From b7606ef2fcb3e9561dedf50f088e3d6340fca266 Mon Sep 17 00:00:00 2001 From: ChiaNing Date: Wed, 20 Nov 2019 16:07:50 +0800 Subject: [PATCH 01/21] node event TRS remove (#5750) * node event TRS remove * transformBit rename & deprecated * notice update --- cocos/core/3d/framework/model-component.ts | 4 +- .../components/ui-base/ui-render-component.ts | 3 +- cocos/core/platform/SubContextView.ts | 2 - .../core/platform/event-manager/deprecated.ts | 17 ++++ .../core/platform/event-manager/event-enum.ts | 36 +++----- cocos/core/platform/event-manager/index.ts | 4 +- cocos/core/scene-graph/index.ts | 2 +- cocos/core/scene-graph/node-enum.ts | 34 +++++++- cocos/core/scene-graph/node.ts | 84 ++++++++++--------- cocos/core/utils/interfaces.ts | 4 +- .../detail/physics-based-component.ts | 4 +- cocos/ui/components/layout-component.ts | 19 +++-- cocos/ui/components/mask-component.ts | 5 +- cocos/ui/components/scroll-view-component.ts | 10 +-- cocos/ui/components/widget-component.ts | 5 +- 15 files changed, 134 insertions(+), 99 deletions(-) create mode 100644 cocos/core/platform/event-manager/deprecated.ts diff --git a/cocos/core/3d/framework/model-component.ts b/cocos/core/3d/framework/model-component.ts index 000d880839..5014652bd4 100644 --- a/cocos/core/3d/framework/model-component.ts +++ b/cocos/core/3d/framework/model-component.ts @@ -30,7 +30,7 @@ import { Material, Mesh } from '../../assets'; import { ccclass, executeInEditMode, executionOrder, menu, property } from '../../data/class-decorator'; import { Model } from '../../renderer/scene/model'; -import { TransformDirtyBit } from '../../scene-graph/node-enum'; +import { TransformBit } from '../../scene-graph/node-enum'; import { Enum } from '../../value-types'; import { builtinResMgr } from '../builtin'; import { RenderableComponent } from './renderable-component'; @@ -249,7 +249,7 @@ export class ModelComponent extends RenderableComponent { if (!this._mesh || !this._model) { return; } - this.node.hasChangedFlags = this._model.transform.hasChangedFlags = TransformDirtyBit.POSITION; + this.node.hasChangedFlags = this._model.transform.hasChangedFlags = TransformBit.POSITION; this._model.isDynamicBatching = this._enableDynamicBatching; // should pass this in before create PSO const meshCount = this._mesh ? this._mesh.subMeshCount : 0; for (let i = 0; i < meshCount; ++i) { diff --git a/cocos/core/components/ui-base/ui-render-component.ts b/cocos/core/components/ui-base/ui-render-component.ts index 3b643e20b1..0c430bf900 100644 --- a/cocos/core/components/ui-base/ui-render-component.ts +++ b/cocos/core/components/ui-base/ui-render-component.ts @@ -45,6 +45,7 @@ import { RenderableComponent } from '../../../core/3d/framework/renderable-compo import { IAssembler, IAssemblerManager } from '../../renderer/ui/base'; import { UIComponent } from './ui-component'; import { UITransformComponent } from './ui-transfrom-component'; +import { TransformBit } from '../../scene-graph/node-enum'; // hack ccenum(GFXBlendFactor); @@ -387,7 +388,7 @@ export class UIRenderComponent extends UIComponent { } // pos, rot, scale changed - protected _nodeStateChange (type: SystemEventType){ + protected _nodeStateChange (type: TransformBit){ if (this._renderData) { this.markForUpdateRenderData(); } diff --git a/cocos/core/platform/SubContextView.ts b/cocos/core/platform/SubContextView.ts index 83b17658f6..8286767c3e 100644 --- a/cocos/core/platform/SubContextView.ts +++ b/cocos/core/platform/SubContextView.ts @@ -207,13 +207,11 @@ export class SubContextView extends Component { private _registerNodeEvent () { this.node.on(Node.EventType.TRANSFORM_CHANGED, this.updateSubContextViewport, this); - this.node.on(Node.EventType.SCALE_PART, this.updateSubContextViewport, this); this.node.on(Node.EventType.SIZE_CHANGED, this.updateSubContextViewport, this); } private _unregisterNodeEvent () { this.node.off(Node.EventType.TRANSFORM_CHANGED, this.updateSubContextViewport, this); - this.node.off(Node.EventType.SCALE_PART, this.updateSubContextViewport, this); this.node.off(Node.EventType.SIZE_CHANGED, this.updateSubContextViewport, this); } diff --git a/cocos/core/platform/event-manager/deprecated.ts b/cocos/core/platform/event-manager/deprecated.ts new file mode 100644 index 0000000000..fda34c3ce9 --- /dev/null +++ b/cocos/core/platform/event-manager/deprecated.ts @@ -0,0 +1,17 @@ +import { replaceProperty } from '../../utils'; +import { SystemEventType } from './event-enum'; + +replaceProperty(SystemEventType, 'Node.EventType', [ + { + name: 'POSITION_PART', + newName: 'TRANSFORM_CHANGED', + }, + { + name: 'ROTATION_PART', + newName: 'TRANSFORM_CHANGED', + }, + { + name: 'SCALE_PART', + newName: 'TRANSFORM_CHANGED', + }, +]); diff --git a/cocos/core/platform/event-manager/event-enum.ts b/cocos/core/platform/event-manager/event-enum.ts index 696fa97956..858b8c1308 100644 --- a/cocos/core/platform/event-manager/event-enum.ts +++ b/cocos/core/platform/event-manager/event-enum.ts @@ -120,37 +120,21 @@ export enum SystemEventType { /** * @en - * The event type for position, rotation, scale changed. + * The event type for position, rotation, scale changed.Use the type parameter as [[Node.TransformBit]] to check which part is changed * * @zh - * 节点改变位置、旋转或缩放事件. + * 节点改变位置、旋转或缩放事件。如果具体需要判断是哪一个事件,可通过判断回调的第一个参数类型是 [[Node.TransformBit]] 中的哪一个来获取 + * @example + * ``` + * this.node.on(Node.EventType.TRANSFORM_CHANGED, (type)=>{ + * if (type & Node.TransformBit.POSITION) { + * //... + * } + * }, this); + * ``` */ TRANSFORM_CHANGED = 'transform-changed', - /** - * @en - * The event type for position changed. - * - * @zh - * 节点位置改变事件 - */ - POSITION_PART = 'position-part', - - /** - * @en - * The event type for rotation changed. - * - * @zh - * 节点旋转事件 - */ - ROTATION_PART = 'rotation-part', - - /** - * @en The event type for scale changed. - * @zh 节点缩放事件 - */ - SCALE_PART = 'scale-part', - /** * @en The event type for press the devicemotion event, you can use its value directly: 'devicemotion'. * @zh diff --git a/cocos/core/platform/event-manager/index.ts b/cocos/core/platform/event-manager/index.ts index 5b15441d6f..4b51b4bef9 100644 --- a/cocos/core/platform/event-manager/index.ts +++ b/cocos/core/platform/event-manager/index.ts @@ -33,4 +33,6 @@ export * from './input-manager'; export * from './system-event'; export * from './events'; export * from './touch'; -export * from './event-enum'; \ No newline at end of file +export * from './event-enum'; + +import './deprecated'; diff --git a/cocos/core/scene-graph/index.ts b/cocos/core/scene-graph/index.ts index b62179a5b8..08e1be2929 100644 --- a/cocos/core/scene-graph/index.ts +++ b/cocos/core/scene-graph/index.ts @@ -36,4 +36,4 @@ export { find } from './find'; export { PrivateNode } from './private-node'; export { default as NodeActivator } from './node-activator'; -import './deprecated'; \ No newline at end of file +import './deprecated'; \ No newline at end of file diff --git a/cocos/core/scene-graph/node-enum.ts b/cocos/core/scene-graph/node-enum.ts index ee11f1dcba..2287dbc4f9 100644 --- a/cocos/core/scene-graph/node-enum.ts +++ b/cocos/core/scene-graph/node-enum.ts @@ -27,17 +27,43 @@ * @category scene-graph */ +import { ccenum } from '../value-types/enum'; + export enum NodeSpace { LOCAL, WORLD, } -export enum TransformDirtyBit { +export enum TransformBit { + /** + * @zh + * 无改变 + */ NONE = 0, + /** + * @zh + * 节点位置改变 + */ POSITION = (1 << 0), + /** + * @zh + * 节点旋转 + */ ROTATION = (1 << 1), + /** + * @zh + * 节点缩放 + */ SCALE = (1 << 2), - RS = TransformDirtyBit.ROTATION | TransformDirtyBit.SCALE, - TRS = TransformDirtyBit.POSITION | TransformDirtyBit.ROTATION | TransformDirtyBit.SCALE, - TRS_MASK = ~TransformDirtyBit.TRS, + /** + * @zh + * 节点旋转及缩放 + */ + RS = TransformBit.ROTATION | TransformBit.SCALE, + /** + * @zh + * 节点平移,旋转及缩放 + */ + TRS = TransformBit.POSITION | TransformBit.ROTATION | TransformBit.SCALE, + TRS_MASK = ~TransformBit.TRS, } diff --git a/cocos/core/scene-graph/node.ts b/cocos/core/scene-graph/node.ts index 4cd580d3ea..8a27cab3ee 100644 --- a/cocos/core/scene-graph/node.ts +++ b/cocos/core/scene-graph/node.ts @@ -35,7 +35,7 @@ import { eventManager } from '../platform/event-manager/event-manager'; import { INode } from '../utils/interfaces'; import { BaseNode, TRANFORM_ON } from './base-node'; import { Layers } from './layers'; -import { NodeSpace, TransformDirtyBit } from './node-enum'; +import { NodeSpace, TransformBit } from './node-enum'; const v3_a = new Vec3(); const q_a = new Quat(); @@ -70,9 +70,15 @@ export class Node extends BaseNode implements INode { public static NodeSpace = NodeSpace; /** * @zh - * 节点变换脏更新的具体部分 + * 节点变换更新的具体部分 + * @deprecated 请使用 [Node.TransformBit] */ - public static TransformDirtyBit = TransformDirtyBit; + public static TransformDirtyBit = TransformBit; + /** + * @zh + * 节点变换更新的具体部分,可用于判断 TRANSFORM_CHANGED 事件的具体类型 + */ + public static TransformBit = TransformBit; // UI 部分的脏数据 public _uiTransfromComp: UITransformComponent | null = null; @@ -99,7 +105,7 @@ export class Node extends BaseNode implements INode { @property protected _euler = new Vec3(); - protected _dirtyFlags = TransformDirtyBit.NONE; // does the world transform need to update? + protected _dirtyFlags = TransformBit.NONE; // does the world transform need to update? protected _eulerDirty = false; /** @@ -208,12 +214,10 @@ export class Node extends BaseNode implements INode { */ public set matrix (val: Readonly) { Mat4.toRTS(val, this._lrot, this._lpos, this._lscale); - this.invalidateChildren(TransformDirtyBit.TRS); + this.invalidateChildren(TransformBit.TRS); this._eulerDirty = true; if (this._eventMask & TRANFORM_ON) { - this.emit(SystemEventType.TRANSFORM_CHANGED, SystemEventType.POSITION_PART); - this.emit(SystemEventType.TRANSFORM_CHANGED, SystemEventType.ROTATION_PART); - this.emit(SystemEventType.TRANSFORM_CHANGED, SystemEventType.SCALE_PART); + this.emit(SystemEventType.TRANSFORM_CHANGED, TransformBit.TRS); } } @@ -339,13 +343,13 @@ export class Node extends BaseNode implements INode { this._eulerDirty = true; } - this.invalidateChildren(TransformDirtyBit.TRS); + this.invalidateChildren(TransformBit.TRS); } public _onBatchCreated () { super._onBatchCreated(); - bookOfChange.set(this._id, TransformDirtyBit.TRS); - this._dirtyFlags = TransformDirtyBit.TRS; + bookOfChange.set(this._id, TransformBit.TRS); + this._dirtyFlags = TransformBit.TRS; const len = this._children.length; for (let i = 0; i < len; ++i) { this._children[i]._onBatchCreated(); @@ -393,9 +397,9 @@ export class Node extends BaseNode implements INode { } } - this.invalidateChildren(TransformDirtyBit.POSITION); + this.invalidateChildren(TransformBit.POSITION); if (this._eventMask & TRANFORM_ON) { - this.emit(SystemEventType.TRANSFORM_CHANGED, SystemEventType.POSITION_PART); + this.emit(SystemEventType.TRANSFORM_CHANGED, TransformBit.POSITION); } } @@ -420,9 +424,9 @@ export class Node extends BaseNode implements INode { } this._eulerDirty = true; - this.invalidateChildren(TransformDirtyBit.ROTATION); + this.invalidateChildren(TransformBit.ROTATION); if (this._eventMask & TRANFORM_ON) { - this.emit(SystemEventType.TRANSFORM_CHANGED, SystemEventType.ROTATION_PART); + this.emit(SystemEventType.TRANSFORM_CHANGED, TransformBit.ROTATION); } } @@ -451,11 +455,11 @@ export class Node extends BaseNode implements INode { * @zh * 递归标记节点世界变换为 dirty */ - public invalidateChildren (dirtyBit: TransformDirtyBit) { + public invalidateChildren (dirtyBit: TransformBit) { if ((this._dirtyFlags & this.hasChangedFlags & dirtyBit) === dirtyBit) { return; } this._dirtyFlags |= dirtyBit; bookOfChange.set(this._id, this.hasChangedFlags | dirtyBit); - dirtyBit |= TransformDirtyBit.POSITION; + dirtyBit |= TransformBit.POSITION; const len = this._children.length; for (let i = 0; i < len; ++i) { this._children[i].invalidateChildren(dirtyBit); @@ -482,16 +486,16 @@ export class Node extends BaseNode implements INode { child = array_a[--i]; dirtyBits |= child._dirtyFlags; if (cur) { - if (dirtyBits & TransformDirtyBit.POSITION) { + if (dirtyBits & TransformBit.POSITION) { Vec3.transformMat4(child._pos, child._lpos, cur._mat); child._mat.m12 = child._pos.x; child._mat.m13 = child._pos.y; child._mat.m14 = child._pos.z; } - if (dirtyBits & TransformDirtyBit.RS) { + if (dirtyBits & TransformBit.RS) { Mat4.fromRTS(child._mat, child._lrot, child._lpos, child._lscale); Mat4.multiply(child._mat, cur._mat, child._mat); - if (dirtyBits & TransformDirtyBit.ROTATION) { + if (dirtyBits & TransformBit.ROTATION) { Quat.multiply(child._rot, cur._rot, child._lrot); } Mat3.fromQuat(m3_1, Quat.conjugate(qt_1, child._rot)); @@ -501,14 +505,14 @@ export class Node extends BaseNode implements INode { child._scale.z = m3_1.m08; } } else { - if (dirtyBits & TransformDirtyBit.POSITION) { + if (dirtyBits & TransformBit.POSITION) { Vec3.copy(child._pos, child._lpos); child._mat.m12 = child._pos.x; child._mat.m13 = child._pos.y; child._mat.m14 = child._pos.z; } - if (dirtyBits & TransformDirtyBit.RS) { - if (dirtyBits & TransformDirtyBit.ROTATION) { + if (dirtyBits & TransformBit.RS) { + if (dirtyBits & TransformBit.ROTATION) { Quat.copy(child._rot, child._lrot); } else { Vec3.copy(child._scale, child._lscale); @@ -516,7 +520,7 @@ export class Node extends BaseNode implements INode { Mat4.fromRTS(child._mat, child._rot, child._pos, child._scale); } } - child._dirtyFlags = TransformDirtyBit.NONE; + child._dirtyFlags = TransformBit.NONE; cur = child; } } @@ -549,9 +553,9 @@ export class Node extends BaseNode implements INode { Vec3.set(this._lpos, val as number, y, z); } - this.invalidateChildren(TransformDirtyBit.POSITION); + this.invalidateChildren(TransformBit.POSITION); if (this._eventMask & TRANFORM_ON) { - this.emit(SystemEventType.TRANSFORM_CHANGED, SystemEventType.POSITION_PART); + this.emit(SystemEventType.TRANSFORM_CHANGED, TransformBit.POSITION); } } @@ -593,9 +597,9 @@ export class Node extends BaseNode implements INode { } this._eulerDirty = true; - this.invalidateChildren(TransformDirtyBit.ROTATION); + this.invalidateChildren(TransformBit.ROTATION); if (this._eventMask & TRANFORM_ON) { - this.emit(SystemEventType.TRANSFORM_CHANGED, SystemEventType.ROTATION_PART); + this.emit(SystemEventType.TRANSFORM_CHANGED, TransformBit.ROTATION); } } @@ -611,9 +615,9 @@ export class Node extends BaseNode implements INode { Quat.fromEuler(this._lrot, x, y, z); this._eulerDirty = false; - this.invalidateChildren(TransformDirtyBit.ROTATION); + this.invalidateChildren(TransformBit.ROTATION); if (this._eventMask & TRANFORM_ON) { - this.emit(SystemEventType.TRANSFORM_CHANGED, SystemEventType.ROTATION_PART); + this.emit(SystemEventType.TRANSFORM_CHANGED, TransformBit.ROTATION); } } @@ -653,9 +657,9 @@ export class Node extends BaseNode implements INode { Vec3.set(this._lscale, val as number, y, z); } - this.invalidateChildren(TransformDirtyBit.SCALE); + this.invalidateChildren(TransformBit.SCALE); if (this._eventMask & TRANFORM_ON) { - this.emit(SystemEventType.TRANSFORM_CHANGED, SystemEventType.SCALE_PART); + this.emit(SystemEventType.TRANSFORM_CHANGED, TransformBit.SCALE); } } @@ -723,9 +727,9 @@ export class Node extends BaseNode implements INode { Vec3.copy(local, this._pos); } - this.invalidateChildren(TransformDirtyBit.POSITION); + this.invalidateChildren(TransformBit.POSITION); if (this._eventMask & TRANFORM_ON) { - this.emit(SystemEventType.TRANSFORM_CHANGED, SystemEventType.POSITION_PART); + this.emit(SystemEventType.TRANSFORM_CHANGED, TransformBit.POSITION); } } @@ -774,9 +778,9 @@ export class Node extends BaseNode implements INode { } this._eulerDirty = true; - this.invalidateChildren(TransformDirtyBit.ROTATION); + this.invalidateChildren(TransformBit.ROTATION); if (this._eventMask & TRANFORM_ON) { - this.emit(SystemEventType.TRANSFORM_CHANGED, SystemEventType.ROTATION_PART); + this.emit(SystemEventType.TRANSFORM_CHANGED, TransformBit.ROTATION); } } @@ -797,9 +801,9 @@ export class Node extends BaseNode implements INode { } this._eulerDirty = true; - this.invalidateChildren(TransformDirtyBit.ROTATION); + this.invalidateChildren(TransformBit.ROTATION); if (this._eventMask & TRANFORM_ON) { - this.emit(SystemEventType.TRANSFORM_CHANGED, SystemEventType.ROTATION_PART); + this.emit(SystemEventType.TRANSFORM_CHANGED, TransformBit.ROTATION); } } @@ -855,9 +859,9 @@ export class Node extends BaseNode implements INode { Vec3.copy(this._lscale, this._scale); } - this.invalidateChildren(TransformDirtyBit.SCALE); + this.invalidateChildren(TransformBit.SCALE); if (this._eventMask & TRANFORM_ON) { - this.emit(SystemEventType.TRANSFORM_CHANGED, SystemEventType.SCALE_PART); + this.emit(SystemEventType.TRANSFORM_CHANGED, TransformBit.SCALE); } } diff --git a/cocos/core/utils/interfaces.ts b/cocos/core/utils/interfaces.ts index a4199cd5e8..1444692ef4 100644 --- a/cocos/core/utils/interfaces.ts +++ b/cocos/core/utils/interfaces.ts @@ -27,7 +27,7 @@ import { Component } from '../components/component'; import { Event } from '../event'; import { Mat4, Quat, Size, Vec2, Vec3 } from '../math'; import { SystemEventType } from '../platform/event-manager/event-enum'; -import { NodeSpace, TransformDirtyBit } from '../scene-graph/node-enum'; +import { NodeSpace, TransformBit } from '../scene-graph/node-enum'; import { NodeEventProcessor } from '../scene-graph/node-event-processor'; import { Scene } from '../scene-graph/scene'; @@ -446,7 +446,7 @@ export interface INode extends IBaseNode { * @zh * 这个节点的空间变换信息在当前帧内是否有变过? */ - hasChangedFlags: Readonly; + hasChangedFlags: Readonly; /** * @zh diff --git a/cocos/physics/components/detail/physics-based-component.ts b/cocos/physics/components/detail/physics-based-component.ts index 4abca0422b..1fe747b562 100644 --- a/cocos/physics/components/detail/physics-based-component.ts +++ b/cocos/physics/components/detail/physics-based-component.ts @@ -11,7 +11,7 @@ import { AfterStepCallback, BeforeStepCallback, PhysicsWorldBase, RigidBodyBase import { createRigidBody } from '../../instance'; import { ERigidBodyType, ETransformSource } from '../../physic-enum'; import { INode } from '../../../core/utils/interfaces'; -import { TransformDirtyBit } from '../../../core/scene-graph/node-enum'; +import { TransformBit } from '../../../core/scene-graph/node-enum'; import { error } from '../../../core/platform/debug'; import { PhysicsSystem } from '../physics-system'; @@ -376,7 +376,7 @@ class SharedRigidBody { // 开始物理计算之前,用户脚本或引擎功能有可能改变节点的Transform,所以需要判断并进行更新 if (this._node.hasChangedFlags) { // scale 进行单独判断,因为目前的物理系统处理后不会改变scale的属性 - if (this._node.hasChangedFlags & TransformDirtyBit.SCALE) { + if (this._node.hasChangedFlags & TransformBit.SCALE) { this._body.scaleAllShapes(this._node.worldScale); } this._syncPhysWithScene(this._node); diff --git a/cocos/ui/components/layout-component.ts b/cocos/ui/components/layout-component.ts index a2ef9d99d9..d7a0ddd9f4 100644 --- a/cocos/ui/components/layout-component.ts +++ b/cocos/ui/components/layout-component.ts @@ -36,6 +36,7 @@ import { UITransformComponent } from '../../core/components/ui-base/ui-transfrom import { SystemEventType } from '../../core/platform/event-manager/event-enum'; import { INode } from '../../core/utils/interfaces'; import { director, Director } from '../../core/director'; +import { TransformBit } from '../../core/scene-graph/node-enum'; const NodeEvent = SystemEventType; /** * @zh @@ -540,7 +541,7 @@ export class LayoutComponent extends Component { private _addChildrenEventListeners () { const children = this.node.children; for (const child of children) { - child.on(NodeEvent.SCALE_PART, this._doScaleDirty, this); + child.on(NodeEvent.TRANSFORM_CHANGED, this._doScaleDirty, this); child.on(NodeEvent.SIZE_CHANGED, this._doLayoutDirty, this); child.on(NodeEvent.TRANSFORM_CHANGED, this._transformDirty, this); child.on(NodeEvent.ANCHOR_CHANGED, this._doLayoutDirty, this); @@ -551,7 +552,7 @@ export class LayoutComponent extends Component { private _removeChildrenEventListeners () { const children = this.node.children; for (const child of children) { - child.off(NodeEvent.SCALE_PART, this._doScaleDirty, this); + child.off(NodeEvent.TRANSFORM_CHANGED, this._doScaleDirty, this); child.off(NodeEvent.SIZE_CHANGED, this._doLayoutDirty, this); child.off(NodeEvent.TRANSFORM_CHANGED, this._transformDirty, this); child.off(NodeEvent.ANCHOR_CHANGED, this._doLayoutDirty, this); @@ -560,7 +561,7 @@ export class LayoutComponent extends Component { } private _childAdded (child: INode) { - child.on(NodeEvent.SCALE_PART, this._doScaleDirty, this); + child.on(NodeEvent.TRANSFORM_CHANGED, this._doScaleDirty, this); child.on(NodeEvent.SIZE_CHANGED, this._doLayoutDirty, this); child.on(NodeEvent.TRANSFORM_CHANGED, this._transformDirty, this); child.on(NodeEvent.ANCHOR_CHANGED, this._doLayoutDirty, this); @@ -570,7 +571,7 @@ export class LayoutComponent extends Component { } private _childRemoved (child: INode) { - child.off(NodeEvent.SCALE_PART, this._doScaleDirty, this); + child.off(NodeEvent.TRANSFORM_CHANGED, this._doScaleDirty, this); child.off(NodeEvent.SIZE_CHANGED, this._doLayoutDirty, this); child.off(NodeEvent.TRANSFORM_CHANGED, this._transformDirty, this); child.off(NodeEvent.ANCHOR_CHANGED, this._doLayoutDirty, this); @@ -1085,8 +1086,8 @@ export class LayoutComponent extends Component { return this._affectedByScale ? Math.abs(value) : 1; } - private _transformDirty(type: SystemEventType){ - if(type !== SystemEventType.POSITION_PART){ + private _transformDirty (type: TransformBit) { + if (!(type & TransformBit.POSITION)){ return; } @@ -1097,8 +1098,10 @@ export class LayoutComponent extends Component { this._layoutDirty = true; } - private _doScaleDirty () { - this._layoutDirty = this._layoutDirty || this._affectedByScale; + private _doScaleDirty (type: TransformBit) { + if (type & TransformBit.SCALE){ + this._layoutDirty = this._layoutDirty || this._affectedByScale; + } } } diff --git a/cocos/ui/components/mask-component.ts b/cocos/ui/components/mask-component.ts index eaf5ec268e..9649eaf7ff 100644 --- a/cocos/ui/components/mask-component.ts +++ b/cocos/ui/components/mask-component.ts @@ -39,6 +39,7 @@ import { UI } from '../../core/renderer/ui/ui'; import { Node } from '../../core/scene-graph'; import { ccenum } from '../../core/value-types/enum'; import { GraphicsComponent } from './graphics-component'; +import { TransformBit } from '../../core/scene-graph/node-enum'; const _worldMatrix = new Mat4(); const _vec2_temp = new Vec2(); @@ -392,8 +393,8 @@ export class MaskComponent extends UIRenderComponent { render.commitComp(this, null, this._postAssembler!); } - protected _nodeStateChange (type: SystemEventType) { - if (type === SystemEventType.POSITION_PART) { + protected _nodeStateChange (type: TransformBit) { + if (type & TransformBit.POSITION) { return; } diff --git a/cocos/ui/components/scroll-view-component.ts b/cocos/ui/components/scroll-view-component.ts index d3b290fef6..d8ec9f9a54 100644 --- a/cocos/ui/components/scroll-view-component.ts +++ b/cocos/ui/components/scroll-view-component.ts @@ -787,10 +787,9 @@ export class ScrollViewComponent extends ViewGroupComponent { this._registerEvent(); if (this.content) { this.content.on(Node.EventType.SIZE_CHANGED, this._calculateBoundary, this); - this.content.on(Node.EventType.SCALE_PART, this._calculateBoundary, this); + this.content.on(Node.EventType.TRANSFORM_CHANGED, this._calculateBoundary, this); if (this.view!) { - this.view!.on(Node.EventType.POSITION_PART, this._calculateBoundary, this); - this.view!.on(Node.EventType.SCALE_PART, this._calculateBoundary, this); + this.view!.on(Node.EventType.TRANSFORM_CHANGED, this._calculateBoundary, this); this.view!.on(Node.EventType.SIZE_CHANGED, this._calculateBoundary, this); } } @@ -809,10 +808,9 @@ export class ScrollViewComponent extends ViewGroupComponent { this._unregisterEvent(); if (this.content) { this.content.off(Node.EventType.SIZE_CHANGED, this._calculateBoundary, this); - this.content.off(Node.EventType.SCALE_PART, this._calculateBoundary, this); + this.content.off(Node.EventType.TRANSFORM_CHANGED, this._calculateBoundary, this); if (this.view!) { - this.view!.off(Node.EventType.POSITION_PART, this._calculateBoundary, this); - this.view!.off(Node.EventType.SCALE_PART, this._calculateBoundary, this); + this.view!.off(Node.EventType.TRANSFORM_CHANGED, this._calculateBoundary, this); this.view!.off(Node.EventType.SIZE_CHANGED, this._calculateBoundary, this); } } diff --git a/cocos/ui/components/widget-component.ts b/cocos/ui/components/widget-component.ts index 05925ccd75..80d1f5f95c 100644 --- a/cocos/ui/components/widget-component.ts +++ b/cocos/ui/components/widget-component.ts @@ -40,6 +40,7 @@ import { Scene } from '../../core/scene-graph'; import { Node } from '../../core/scene-graph/node'; import { INode } from '../../core/utils/interfaces'; import { ccenum } from '../../core/value-types/enum'; +import { TransformBit } from '../../core/scene-graph/node-enum'; const _zeroVec3 = new Vec3(); @@ -727,8 +728,8 @@ export class WidgetComponent extends Component { this._removeParentEvent(); } - public _adjustWidgetToAllowMovingInEditor (eventType: SystemEventType) { - if (/*!CC_EDITOR ||*/ eventType !== SystemEventType.POSITION_PART) { + public _adjustWidgetToAllowMovingInEditor (eventType: TransformBit) { + if (/*!CC_EDITOR ||*/ !(eventType & TransformBit.POSITION)) { return; } From d446a357ce274115e3bad86227c0be1d1564d096 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lelie=20Leight=20=28=E6=9D=8E=E7=9A=84=E5=BA=8F=29?= Date: Sat, 23 Nov 2019 18:17:45 +0800 Subject: [PATCH 02/21] Warn on explicit undefined type (#5770) --- EngineErrorMap.md | 21 ++++++++++++++++++ cocos/core/data/class-decorator.ts | 6 ++++++ cocos/core/data/class.ts | 6 +++++- jest.config.js | 5 ++++- tests/core/ccclass.test.ts | 34 ++++++++++++++++++++++++++++++ tests/init.ts | 11 ++++++++++ 6 files changed, 81 insertions(+), 2 deletions(-) create mode 100644 tests/core/ccclass.test.ts diff --git a/EngineErrorMap.md b/EngineErrorMap.md index 2558b41ff0..e69834f754 100644 --- a/EngineErrorMap.md +++ b/EngineErrorMap.md @@ -632,6 +632,27 @@ browser does not support getters Violation error: extending enumerations shall have non-overlaped member names or member values +### 3660 + +You are explicitly specifying `undefined` type to cc property "%s" of cc class "%s". +Is this intended? If not, this may indicate a circular reference. +For example: +``` +// foo.ts +import { _decorator } from 'cc'; +import { Bar } from './bar'; // Given that './bar' also reference 'foo.ts'. + // When importing './bar', execution of './bar' is hung on to wait execution of 'foo.ts', + // the `Bar` imported here is `undefined` until './bar' finish its execution. + // It leads to that +@_decorator.ccclass // ↓ +export class Foo { // ↓ + @_decorator.type(Bar) // → is equivalent to `@_decorator.type(undefined)` + public bar: Bar; // To eliminate this error, either: + // - Refactor your module structure(recommended), or + // - specify the type as cc class name: `@_decorator.type('Bar'/* or any name you specified for `Bar` */)` +} +``` + ### 3700 internal error: _prefab is undefined diff --git a/cocos/core/data/class-decorator.ts b/cocos/core/data/class-decorator.ts index 49ddba21fa..7bd3014112 100644 --- a/cocos/core/data/class-decorator.ts +++ b/cocos/core/data/class-decorator.ts @@ -346,6 +346,12 @@ export function property (ctorProtoOrOptions?, propName?, desc?) { genProperty(ctorProto.constructor, properties, propName, options, desc, cache); } } + if (ctorProtoOrOptions === undefined) { + // @property(undefined) + return property({ + type: undefined, + }); + } if (typeof propName === 'undefined') { options = ctorProtoOrOptions; return normalized; diff --git a/cocos/core/data/class.ts b/cocos/core/data/class.ts index bd57635501..1eb42be77f 100644 --- a/cocos/core/data/class.ts +++ b/cocos/core/data/class.ts @@ -1,4 +1,4 @@ -/* +/* Copyright (c) 2013-2016 Chukong Technologies Inc. Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. @@ -1118,6 +1118,10 @@ function parseAttributes (constructor: Function, attributes: IAcceptableAttribut tmpAttrs.length = 0; const result: IParsedAttribute[] = tmpAttrs; + if ('type' in attributes && typeof attributes.type === 'undefined') { + warnID(3660, propertyName, className); + } + const type = attributes.type; if (type) { const primitiveType = PrimitiveTypes[type]; diff --git a/jest.config.js b/jest.config.js index ae5c62d503..33b3225d5c 100644 --- a/jest.config.js +++ b/jest.config.js @@ -9,6 +9,9 @@ module.exports = { globals: { CC_DEV: true, CC_TEST: true, - CC_PHYSICS_BUILTIN: true + CC_PHYSICS_BUILTIN: true, + 'ts-jest': { + diagnostics: false + } } }; \ No newline at end of file diff --git a/tests/core/ccclass.test.ts b/tests/core/ccclass.test.ts new file mode 100644 index 0000000000..217d3d83f1 --- /dev/null +++ b/tests/core/ccclass.test.ts @@ -0,0 +1,34 @@ +import { ccclass, property } from '../../cocos/core/data/class-decorator'; +import { warnID } from '../../cocos/core'; + +/** + * Happened when: + * - `@property(undefined)` Explicit `undefined`, it's rare + * - `@property(${some-global}.${some-property})` From a expression which evaluated as `undefined`, + * - `@property(${imported-undefined})` Due to circular reference + */ +test('explicit undefined type', () => { + // @ts-ignore + warnID.mockClear(); + + @ccclass + class Foo { + /** + * `@property(type)` form. + */ + @property(undefined) + public property1 = 0; + + /** + * `@property({ type })` form. + */ + @property({ + type: undefined, + }) + public property2 = 0; + } + + expect(warnID).toHaveBeenCalledTimes(2); + expect(warnID).toHaveBeenNthCalledWith(1, 3660, 'property1', Foo.name); + expect(warnID).toHaveBeenNthCalledWith(2, 3660, 'property2', Foo.name); +}); \ No newline at end of file diff --git a/tests/init.ts b/tests/init.ts index 656f55cb2e..a50ad6edac 100644 --- a/tests/init.ts +++ b/tests/init.ts @@ -1,3 +1,14 @@ +jest.mock('../cocos/core/platform/debug', () => { + const result = { + __esModule: true, // Use it when dealing with esModules + ...jest.requireActual('../cocos/core/platform/debug'), + }; + if (result.warnID) { + result.warnID = jest.fn(result.warnID); + } + return result; +}); + import '../exports/base'; import { DebugMode } from "../cocos/core/platform/debug"; From cda23e5c1450a8b65e6d23543d2f13bbedd342d6 Mon Sep 17 00:00:00 2001 From: zxg0622 <247274249@qq.com> Date: Sat, 23 Nov 2019 18:28:28 +0800 Subject: [PATCH 03/21] refactor model allocation logic (#5689) * refactor model allocation logic * fix ts null check * fix particle system decorator --- cocos/core/3d/framework/camera-component.ts | 45 +++++++---- .../framework/directional-light-component.ts | 9 ++- .../3d/framework/editor-camera-component.ts | 15 +++- cocos/core/3d/framework/light-component.ts | 61 ++++++++++++--- cocos/core/3d/framework/model-component.ts | 54 +++++++------ .../core/3d/framework/renderable-component.ts | 4 +- .../3d/framework/skinning-model-component.ts | 10 ++- .../3d/framework/sphere-light-component.ts | 18 ++--- .../core/3d/framework/spot-light-component.ts | 18 ++--- .../components/ui-base/canvas-component.ts | 21 +++-- cocos/core/pipeline/culling.ts | 4 +- .../core/pipeline/forward/forward-pipeline.ts | 4 +- cocos/core/pipeline/forward/forward-stage.ts | 2 +- cocos/core/pipeline/render-pipeline.ts | 6 +- cocos/core/renderer/models/skinning-model.ts | 19 +++-- cocos/core/renderer/scene/camera.ts | 62 +++++++++------ .../core/renderer/scene/directional-light.ts | 4 +- cocos/core/renderer/scene/light.ts | 31 ++++++-- cocos/core/renderer/scene/model.ts | 40 ++++++---- cocos/core/renderer/scene/planar-shadows.ts | 4 +- cocos/core/renderer/scene/render-scene.ts | 77 ++++++++++--------- cocos/core/renderer/scene/skybox.ts | 8 +- cocos/core/renderer/scene/sphere-light.ts | 4 +- cocos/core/renderer/scene/spot-light.ts | 4 +- cocos/core/renderer/ui/ui-batch-model.ts | 6 +- cocos/core/renderer/ui/ui.ts | 9 ++- cocos/core/root.ts | 73 ++++++++++++++++++ cocos/particle/models/particle-batch-model.ts | 16 ++-- cocos/particle/particle-system-component.ts | 28 +++---- .../renderer/particle-system-renderer.ts | 45 ++++++----- cocos/particle/renderer/trail.ts | 31 +++++--- cocos/ui/components/ui-model-component.ts | 18 ++++- 32 files changed, 491 insertions(+), 259 deletions(-) diff --git a/cocos/core/3d/framework/camera-component.ts b/cocos/core/3d/framework/camera-component.ts index b28295dfac..715459dade 100644 --- a/cocos/core/3d/framework/camera-component.ts +++ b/cocos/core/3d/framework/camera-component.ts @@ -39,6 +39,7 @@ import { SKYBOX_FLAG } from '../../renderer/scene/camera'; import { Layers, Scene } from '../../scene-graph'; import { Enum } from '../../value-types'; import { CameraDefaultMask } from '../../pipeline/define'; +import { director } from '../../director'; /** * The projection type
@@ -376,21 +377,25 @@ export class CameraComponent extends Component { public onLoad () { cc.director.on(cc.Director.EVENT_AFTER_SCENE_LAUNCH, this.onSceneChanged, this); + this._createCamera(); } public onEnable () { - if (this._camera) { this._camera.enabled = true; return; } - this._createCamera(); - this._camera!.enabled = true; + if (this._camera) { + this._attachToScene(); + return; + } } - public onDisable () { - if (this._camera) { this._camera.enabled = false; } + public onDisable() { + if (this._camera) { + this._detachFromScene(); + } } public onDestroy () { if (this._camera) { - this._getRenderScene().destroyCamera(this._camera); + cc.director.root.destroyCamera(this._camera); this._camera = null; } @@ -418,10 +423,8 @@ export class CameraComponent extends Component { } protected _createCamera () { - if (!this.node.scene) { return; } - const scene = this._getRenderScene(); - if (this._camera && scene.cameras.find((c) => c === this._camera)) { return; } - this._camera = scene.createCamera({ + this._camera = director.root!.createCamera(); + this._camera.initialize({ name: this.node.name, node: this.node, projection: this._projection, @@ -449,11 +452,27 @@ export class CameraComponent extends Component { this._updateTargetTexture(); } + protected _attachToScene() { + if (!this.node.scene || !this._camera) { + return; + } + if (this._camera && this._camera.scene) { + this._camera.scene.removeCamera(this._camera); + } + const scene = this._getRenderScene(); + scene.addCamera(this._camera); + } + + protected _detachFromScene() { + if (this._camera && this._camera.scene) { + this._camera.scene.removeCamera(this._camera); + } + } + protected onSceneChanged (scene: Scene) { // to handle scene switch of editor camera - if (this._camera && this._camera.scene !== scene.renderScene) { - this._createCamera(); - this._camera.enabled = true; + if (this._camera && this._camera.scene == null) { + this._attachToScene(); } } diff --git a/cocos/core/3d/framework/directional-light-component.ts b/cocos/core/3d/framework/directional-light-component.ts index ed59cd9aa2..3a3c492566 100644 --- a/cocos/core/3d/framework/directional-light-component.ts +++ b/cocos/core/3d/framework/directional-light-component.ts @@ -62,16 +62,20 @@ export class DirectionalLightComponent extends LightComponent { if (this._light) { this._light.illuminance = this._illuminance; } } + constructor() { + super(); + this._lightType = DirectionalLight; + } + protected _createLight (scene?: RenderScene) { if (!this.node.scene) { return; } scene = scene || this._getRenderScene(); - if (scene.mainLight.node.activeInHierarchy) { + if (scene.mainLight.node!.activeInHierarchy) { console.warn('there can be only one directional(main) light.'); return; } this._light = scene.mainLight; this.illuminance = this._illuminance; - super._createLight(scene); } protected _destroyLight (scene?: RenderScene) { @@ -79,6 +83,5 @@ export class DirectionalLightComponent extends LightComponent { this._light.enabled = false; scene = scene || this._getRenderScene(); this._light.node = scene.defaultMainLightNode; - super._destroyLight(scene); } } diff --git a/cocos/core/3d/framework/editor-camera-component.ts b/cocos/core/3d/framework/editor-camera-component.ts index 9cb7470d9b..84f4c65415 100644 --- a/cocos/core/3d/framework/editor-camera-component.ts +++ b/cocos/core/3d/framework/editor-camera-component.ts @@ -110,16 +110,22 @@ export class EditorCameraComponent extends CameraComponent { public onEnable () { super.onEnable(); + if (this._uiEditorCamera) { + cc.director.root!.ui.renderScene.addCamera(this._uiEditorCamera); + } } - public onDisable () { + public onDisable() { super.onDisable(); + if (this._uiEditorCamera) { + cc.director.root!.ui.renderScene.removeCamera(this._uiEditorCamera); + } } public onDestroy () { super.onDestroy(); if (this._uiEditorCamera) { - cc.director.root!.ui.renderScene.destroyCamera(this._uiEditorCamera); + cc.director.root!.destroyCamera(this._uiEditorCamera); this._uiEditorCamera = null; } } @@ -130,10 +136,11 @@ export class EditorCameraComponent extends CameraComponent { if (this._camera !== priorCamera && this._camera) { if (this._uiEditorCamera) { - cc.director.root!.ui.renderScene.destroyCamera(this._uiEditorCamera); + cc.director.root!.destroyCamera(this._uiEditorCamera); this._uiEditorCamera = null; } - this._uiEditorCamera = cc.director.root!.ui.renderScene.createCamera({ + this._uiEditorCamera = cc.director.root!.createCamera(); + this._uiEditorCamera!.initialize({ name: 'Editor UICamera', node: this._camera.node, projection: this._projection, diff --git a/cocos/core/3d/framework/light-component.ts b/cocos/core/3d/framework/light-component.ts index 643a5ef366..fa77751fc9 100644 --- a/cocos/core/3d/framework/light-component.ts +++ b/cocos/core/3d/framework/light-component.ts @@ -33,7 +33,6 @@ import { Color } from '../../math'; import { Enum } from '../../value-types'; import { Light, LightType } from '../../renderer/scene/light'; -import { RenderScene } from '../../renderer/scene/render-scene'; export const PhotometricTerm = Enum({ LUMINOUS_POWER: 0, @@ -53,6 +52,7 @@ export class LightComponent extends Component { protected _colorTemperature = 6550; protected _type = LightType.UNKNOWN; + protected _lightType : typeof Light; protected _light: Light | null = null; /** @@ -124,29 +124,70 @@ export class LightComponent extends Component { return this._type; } - public onEnable () { - if (this._light) { this._light.enabled = true; return; } + constructor() { + super(); + this._lightType = Light; + } + + public onLoad(){ this._createLight(); } + public onEnable () { + this._attachToScene(); + } + public onDisable () { - if (this._light) { this._light.enabled = false; } + this._detachFromScene(); } public onDestroy () { this._destroyLight(); } - protected _createLight (scene?: RenderScene) { - if (!this._light) { return; } + protected _createLight () { + if (this._light) { + return; + } + this._light = cc.director.root.createLight(this._lightType); this.color = this._color; this.useColorTemperature = this._useColorTemperature; this.colorTemperature = this._colorTemperature; - this._light.node = this.node; - this._light.enabled = this.enabledInHierarchy; + this._light!.node = this.node; + this._light!.enabled = this.enabledInHierarchy; } - protected _destroyLight (scene?: RenderScene) { - this._light = null; + protected _destroyLight () { + if (this._light) { + cc.director.root.destroyLight(this); + this._light = null; + } + } + + protected _attachToScene() { + this._detachFromScene(); + if (this._light && !this._light.scene && !this.node.scene) { + switch (this._type) { + case LightType.SPHERE: + this._getRenderScene().addSphereLight(this._light as any); + break; + case LightType.SPOT: + this._getRenderScene().addSpotLight(this._light as any); + break; + } + } + } + + protected _detachFromScene() { + if (this._light && this._light.scene) { + switch (this._type) { + case LightType.SPHERE: + this._light.scene.removeSphereLight(this._light as any); + break; + case LightType.SPOT: + this._light.scene.removeSpotLight(this._light as any); + break; + } + } } } diff --git a/cocos/core/3d/framework/model-component.ts b/cocos/core/3d/framework/model-component.ts index 5014652bd4..68862fe352 100644 --- a/cocos/core/3d/framework/model-component.ts +++ b/cocos/core/3d/framework/model-component.ts @@ -34,6 +34,7 @@ import { TransformBit } from '../../scene-graph/node-enum'; import { Enum } from '../../value-types'; import { builtinResMgr } from '../builtin'; import { RenderableComponent } from './renderable-component'; +import { Root } from '../../root'; /** * Shadow projection mode
@@ -147,6 +148,8 @@ export class ModelComponent extends RenderableComponent { public static ShadowCastingMode = ModelShadowCastingMode; + protected _modelType : typeof Model; + protected _model: Model | null = null; @property @@ -161,6 +164,11 @@ export class ModelComponent extends RenderableComponent { @property private _receiveShadows = false; + constructor() { + super(); + this._modelType = Model; + } + public onLoad () { this._updateModels(); this._updateCastShadow(); @@ -169,43 +177,32 @@ export class ModelComponent extends RenderableComponent { public onEnable () { if (this._model) { - if (!this._model.inited) { - this._updateModels(); - } - this._model.enabled = true; + this._attachToScene(); } } public onDisable () { if (this._model) { - this._model.enabled = false; + this._detachFromScene(); } } public onDestroy () { if (this._model) { - this._model.scene.destroyModel(this._model); + cc.director.root.destroyModel(this._model); this._model = null; this._models.length = 0; } } - public _changeSceneInModel () { - if (this.isValid) { - if (this._model) { - this._model.destroy(); - this._model.scene.destroyModel(this._model); - this._model = null; - } - this._updateModels(); - } - } - protected _updateModels () { if (!this.enabledInHierarchy || !this._mesh) { return; } + if (this._model) { + cc.director.root.destroyModel(this._model); + } this._createModel(); this._updateModelParams(); @@ -232,17 +229,28 @@ export class ModelComponent extends RenderableComponent { } protected _createModel () { - if (!this.node.scene) { return; } - const scene = this._getRenderScene(); - if (this._model) { scene.destroyModel(this._model); } - this._model = scene.createModel(this._getModelConstructor(), this.node); + this._model = (cc.director.root as Root).createModel(this._modelType); this._model.visFlags = this.visibility; + this._model.initialize(this.node); this._models.length = 0; this._models.push(this._model); } - protected _getModelConstructor () { - return Model; + protected _attachToScene() { + if (!this.node.scene && !this._model) { + return; + } + const scene = this._getRenderScene(); + if (this._model!.scene != null) { + this._detachFromScene(); + } + scene.addModel(this._model!); + } + + protected _detachFromScene() { + if (this._model && this._model.scene) { + this._model.scene.removeModel(this._model); + } } protected _updateModelParams () { diff --git a/cocos/core/3d/framework/renderable-component.ts b/cocos/core/3d/framework/renderable-component.ts index e0ad6ba24b..e14f70b9e4 100644 --- a/cocos/core/3d/framework/renderable-component.ts +++ b/cocos/core/3d/framework/renderable-component.ts @@ -133,8 +133,10 @@ export class RenderableComponent extends Component { return this._models; } - public _changeSceneInModel () { + protected _attachToScene() { + } + protected _detachFromScene() { } protected _onMaterialModified (index: number, material: Material | null) { diff --git a/cocos/core/3d/framework/skinning-model-component.ts b/cocos/core/3d/framework/skinning-model-component.ts index 6f4d128181..74a110c8ba 100644 --- a/cocos/core/3d/framework/skinning-model-component.ts +++ b/cocos/core/3d/framework/skinning-model-component.ts @@ -36,6 +36,7 @@ import { Node } from '../../scene-graph/node'; import { INode } from '../../utils/interfaces'; import { builtinResMgr } from '../builtin'; import { ModelComponent } from './model-component'; +import { Model } from '../../renderer'; /** * @en The Skinning Model Component @@ -90,6 +91,11 @@ export class SkinningModelComponent extends ModelComponent { return (this._model as SkinningModel); } + constructor() { + super(); + this._modelType = SkinningModel; + } + public uploadAnimation (clip: AnimationClip | null) { this._clip = clip; if (this._model) { (this._model as SkinningModel).uploadAnimation(clip); } @@ -101,10 +107,6 @@ export class SkinningModelComponent extends ModelComponent { super._updateModelParams(); } - protected _getModelConstructor () { - return SkinningModel; - } - protected _getBuiltinMaterial () { // classic ugly pink indicating missing material return builtinResMgr.get('missing-skinning-material'); diff --git a/cocos/core/3d/framework/sphere-light-component.ts b/cocos/core/3d/framework/sphere-light-component.ts index a78b54b9d3..e942174445 100644 --- a/cocos/core/3d/framework/sphere-light-component.ts +++ b/cocos/core/3d/framework/sphere-light-component.ts @@ -127,11 +127,13 @@ export class SphereLightComponent extends LightComponent { if (this._light) { this._light.range = val; } } + constructor() { + super(); + this._lightType = SphereLight; + } + protected _createLight (scene?: RenderScene) { - if (!this.node.scene) { return; } - scene = scene || this._getRenderScene(); - if (this._light && scene.sphereLights.find((c) => c === this._light)) { return; } - this._light = scene.createSphereLight(this.name, this.node); + super._createLight(); if (!this._light) { console.warn('we don\'t support this many lights in forward pipeline.'); return; @@ -139,13 +141,5 @@ export class SphereLightComponent extends LightComponent { this._light.luminance = this._luminance; this.size = this._size; this.range = this._range; - super._createLight(scene); - } - - protected _destroyLight (scene?: RenderScene) { - if (!this.node.scene || !this._light) { return; } - if (!scene) { scene = this._getRenderScene(); } - scene.destroySphereLight(this._light); - super._destroyLight(scene); } } diff --git a/cocos/core/3d/framework/spot-light-component.ts b/cocos/core/3d/framework/spot-light-component.ts index 1002d6059a..084f0c4f3b 100644 --- a/cocos/core/3d/framework/spot-light-component.ts +++ b/cocos/core/3d/framework/spot-light-component.ts @@ -150,12 +150,14 @@ export class SpotLightComponent extends LightComponent { this._spotAngle = val; if (this._light) { this._light.spotAngle = toRadian(val); } } + + constructor() { + super(); + this._lightType = SpotLight; + } protected _createLight (scene?: RenderScene) { - if (!this.node.scene) { return; } - if (!scene) { scene = this._getRenderScene(); } - if (this._light && scene.spotLights.find((c) => c === this._light)) { return; } - this._light = scene.createSpotLight(this.name, this.node); + super._createLight(); if (!this._light) { console.warn('we don\'t support this many lights in forward pipeline.'); return; @@ -164,13 +166,5 @@ export class SpotLightComponent extends LightComponent { this.size = this._size; this.range = this._range; this.spotAngle = this._spotAngle; - super._createLight(scene); - } - - protected _destroyLight (scene?: RenderScene) { - if (!this.node.scene || !this._light) { return; } - if (!scene) { scene = this._getRenderScene(); } - scene.destroySpotLight(this._light); - super._destroyLight(scene); } } diff --git a/cocos/core/components/ui-base/canvas-component.ts b/cocos/core/components/ui-base/canvas-component.ts index 341b72f99b..81028f7bd0 100644 --- a/cocos/core/components/ui-base/canvas-component.ts +++ b/cocos/core/components/ui-base/canvas-component.ts @@ -212,7 +212,8 @@ export class CanvasComponent extends Component { const cameraNode = new Node('UICamera_' + this.node.name); cameraNode.setPosition(0, 0, 1000); if (!CC_EDITOR) { - this._camera = director.root!.ui.renderScene.createCamera({ + this._camera = director.root!.createCamera(); + this._camera.initialize({ name: 'ui_' + this.node.name, node: cameraNode as INode, projection: CameraComponent.ProjectionType.ORTHO, @@ -246,17 +247,21 @@ export class CanvasComponent extends Component { director.root!.ui.addScreen(this); } - // public onEnable (){ + public onEnable() { + if (this._camera) { + director.root!.ui.renderScene.addCamera(this._camera); + } + } - // } - - // public onDisable () { - - // } + public onDisable() { + if (this._camera) { + director.root!.ui.renderScene.removeCamera(this._camera); + } + } public onDestroy () { if (this._camera) { - director.root!.ui.renderScene.destroyCamera(this._camera); + director.root!.destroyCamera(this._camera); } if (CC_EDITOR) { diff --git a/cocos/core/pipeline/culling.ts b/cocos/core/pipeline/culling.ts index fe91235acc..f3484076d8 100644 --- a/cocos/core/pipeline/culling.ts +++ b/cocos/core/pipeline/culling.ts @@ -57,7 +57,7 @@ export const calcDirectionalLightCullFrustum = (() => { const minBoxCorner = new Vec3(); const maxBoxCorner = new Vec3(); return (out: frustum, sceneCamera: Camera, light: DirectionalLight, near: number, far: number, nearBias: number) => { - Mat4.fromRT(lightViewMat, light.node.getWorldRotation(lightRot), sceneCamera.node.getWorldPosition(lightPos)); + Mat4.fromRT(lightViewMat, light.node!.getWorldRotation(lightRot), sceneCamera.node.getWorldPosition(lightPos)); Mat4.invert(lightVeiwMatInv, lightViewMat); sceneCamera.getSplitFrustum(camFrustum, near, far); // transform camera frustum to light space @@ -77,7 +77,7 @@ export const calcDirectionalLightCullFrustum = (() => { Vec3.set(lightViewCenter, (minBoxCorner.x + maxBoxCorner.x) / 2, (minBoxCorner.y + maxBoxCorner.y) / 2, maxBoxCorner.z); lightViewCenter.z += nearBias; Vec3.transformMat4(lightPos, lightViewCenter, lightViewMat); - Mat4.fromRT(lightViewMat, light.node.getWorldRotation(lightRot), lightPos); + Mat4.fromRT(lightViewMat, light.node!.getWorldRotation(lightRot), lightPos); // calc the light's frustum frustum.createOrtho(out, maxBoxCorner.x - minBoxCorner.x, maxBoxCorner.y - minBoxCorner.y, 0, minBoxCorner.z - nearBias - maxBoxCorner.z, lightViewMat); }; diff --git a/cocos/core/pipeline/forward/forward-pipeline.ts b/cocos/core/pipeline/forward/forward-pipeline.ts index 74ccdf2687..11b2d8eeb0 100644 --- a/cocos/core/pipeline/forward/forward-pipeline.ts +++ b/cocos/core/pipeline/forward/forward-pipeline.ts @@ -286,7 +286,7 @@ export class ForwardPipeline extends RenderPipeline { protected sceneCulling (view: RenderView) { super.sceneCulling(view); this._validLights.splice(0); - for (const light of view.camera.scene.sphereLights) { + for (const light of view.camera.scene!.sphereLights) { if (light.enabled) { light.update(); sphere.set(_sphere, light.position.x, light.position.y, light.position.z, light.range); @@ -295,7 +295,7 @@ export class ForwardPipeline extends RenderPipeline { } } } - for (const light of view.camera.scene.spotLights) { + for (const light of view.camera.scene!.spotLights) { if (light.enabled) { light.update(); sphere.set(_sphere, light.position.x, light.position.y, light.position.z, light.range); diff --git a/cocos/core/pipeline/forward/forward-stage.ts b/cocos/core/pipeline/forward/forward-stage.ts index 9e5d0822db..a0db786855 100644 --- a/cocos/core/pipeline/forward/forward-stage.ts +++ b/cocos/core/pipeline/forward/forward-stage.ts @@ -204,7 +204,7 @@ export class ForwardStage extends RenderStage { this._framebuffer = view.window!.framebuffer; } - const planarShadow = camera.scene.planarShadows; + const planarShadow = camera.scene!.planarShadows; cmdBuff.begin(); cmdBuff.beginRenderPass(this._framebuffer!, this._renderArea, diff --git a/cocos/core/pipeline/render-pipeline.ts b/cocos/core/pipeline/render-pipeline.ts index 100ff1aa2a..2bb71109a3 100644 --- a/cocos/core/pipeline/render-pipeline.ts +++ b/cocos/core/pipeline/render-pipeline.ts @@ -1119,7 +1119,7 @@ export abstract class RenderPipeline { protected updateUBOs (view: RenderView) { const camera = view.camera; - const scene = camera.scene; + const scene = camera.scene!; const device = this._root.device; const mainLight = scene.mainLight; @@ -1203,7 +1203,7 @@ export abstract class RenderPipeline { protected sceneCulling (view: RenderView) { const camera = view.camera; - const scene = camera.scene; + const scene = camera.scene!; this._renderObjects.splice(0); @@ -1213,7 +1213,7 @@ export abstract class RenderPipeline { } const planarShadows = scene.planarShadows; - if (planarShadows.enabled && mainLight.node.hasChangedFlags) { + if (planarShadows.enabled && mainLight.node!.hasChangedFlags) { planarShadows.updateDirLight(mainLight); } diff --git a/cocos/core/renderer/models/skinning-model.ts b/cocos/core/renderer/models/skinning-model.ts index 25a07bb1c0..3c52382294 100644 --- a/cocos/core/renderer/models/skinning-model.ts +++ b/cocos/core/renderer/models/skinning-model.ts @@ -59,12 +59,11 @@ export class SkinningModel extends Model { private _staticModelBounds: aabb | null = null; private _mesh: Mesh | null = null; - constructor (scene: RenderScene, node: INode) { - super(scene, node); + constructor () { + super(); this._type = 'skinning'; const jointsTextureInfo = new Float32Array(4); - const texture = this._scene.root.dataPoolManager.jointsTexturePool.getDefaultJointsTexture(); - this._jointsMedium = { buffer: null, jointsTextureInfo, texture, animInfo: null, boundsInfo: null }; + this._jointsMedium = { buffer: null, jointsTextureInfo, texture: null, animInfo: null, boundsInfo: null }; } public destroy () { @@ -75,12 +74,18 @@ export class SkinningModel extends Model { } } + public attachToScene(scene: RenderScene) { + super.attachToScene(scene); + const texture = scene.root.dataPoolManager.jointsTexturePool.getDefaultJointsTexture(); + this._jointsMedium.texture = texture; + } + public bindSkeleton (skeleton: Skeleton | null, skinningRoot: INode | null, mesh: Mesh | null) { this._skeleton = skeleton; this._mesh = mesh; if (!skeleton || !skinningRoot || !mesh) { return; } this._transform = skinningRoot; - this._jointsMedium.animInfo = this._scene.root.dataPoolManager.jointsAnimationInfo.get(skinningRoot.uuid); + this._jointsMedium.animInfo = this._scene!.root.dataPoolManager.jointsAnimationInfo.get(skinningRoot.uuid); if (!this._jointsMedium.buffer) { this._jointsMedium.buffer = this._device.createBuffer({ usage: GFXBufferUsageBit.UNIFORM | GFXBufferUsageBit.TRANSFER_DST, @@ -119,7 +124,7 @@ export class SkinningModel extends Model { public uploadAnimation (anim: AnimationClip | null) { if (!this._skeleton || !this._mesh) { return; } this.uploadedAnim = anim; - const resMgr = this._scene.root.dataPoolManager; + const resMgr = this._scene!.root.dataPoolManager; const texture = anim ? resMgr.jointsTexturePool.getJointsTextureWithAnimation(this._skeleton, anim) : resMgr.jointsTexturePool.getDefaultJointsTexture(this._skeleton); resMgr.jointsAnimationInfo.switchClip(this._jointsMedium.animInfo!, anim); @@ -131,7 +136,7 @@ export class SkinningModel extends Model { protected _applyJointsTexture (texture: IJointsTextureHandle | null) { if (!texture) { return; } const oldTex = this._jointsMedium.texture; - if (oldTex && oldTex !== texture) { this._scene.root.dataPoolManager.jointsTexturePool.releaseHandle(oldTex); } + if (oldTex && oldTex !== texture) { this._scene!.root.dataPoolManager.jointsTexturePool.releaseHandle(oldTex); } this._jointsMedium.texture = texture; const { buffer, jointsTextureInfo } = this._jointsMedium; jointsTextureInfo[0] = texture.handle.texture.width; diff --git a/cocos/core/renderer/scene/camera.ts b/cocos/core/renderer/scene/camera.ts index fe1c05ba2d..aeac31537a 100644 --- a/cocos/core/renderer/scene/camera.ts +++ b/cocos/core/renderer/scene/camera.ts @@ -86,10 +86,10 @@ export const SKYBOX_FLAG = GFXClearFlag.STENCIL << 1; export class Camera { - private _scene: RenderScene; - private _name: string; + private _scene: RenderScene | null = null; + private _name: string | null = null; private _enabled: boolean = false; - private _proj: CameraProjection; + private _proj: CameraProjection = -1; private _isWindowSize: boolean = true; private _width: number; private _height: number; @@ -114,7 +114,7 @@ export class Camera { private _forward: Vec3 = new Vec3(); private _position: Vec3 = new Vec3(); private _node: INode | null = null; - private _view: RenderView; + private _view: RenderView | null = null; private _visibility = CameraDefaultMask; private _priority: number = 0; private _aperture: CameraAperture = CameraAperture.F16_0; @@ -126,13 +126,7 @@ export class Camera { private _ec: number = 0.0; private _exposure: number = 0.0; - constructor (scene: RenderScene, info: ICameraInfo) { - this._scene = scene; - this._name = info.name; - this._node = info.node; - this._proj = info.projection; - this._priority = info.priority || 0; - + constructor () { this._apertureValue = FSTOPS[this._aperture]; this._shutterValue = SHUTTERS[this._shutter]; this._isoValue = ISOS[this._iso]; @@ -140,20 +134,37 @@ export class Camera { this._aspect = this._width = this._height = this._screenScale = 1; - this._view = this._scene.root.createView({ + } + + public initialize(info: ICameraInfo) { + this._name = info.name; + this._node = info.node; + this._proj = info.projection; + this._priority = info.priority || 0; + + this._view = cc.director.root.createView({ camera: this, name: this._name, priority: this._priority, flows: info.flows, }); - this.changeTargetWindow(info.window); - console.log('Create Camera: ' + this._name + ' ' + this._width + ' x ' + this._height); + console.log('Alloc Camera: ' + this._name + ' ' + this._width + ' x ' + this._height); } public destroy () { - this._scene.root.destroyView(this._view); + cc.director.root.destroyView(this._view); + this._view = null; + this._name = null; + } + + public attachToScene(scene: RenderScene) { + this._scene = scene; + } + + public detachFromScene() { + this._scene = null; } public resize (width: number, height: number) { @@ -241,7 +252,9 @@ export class Camera { set enabled (val) { this._enabled = val; - this._view.enable(val); + if (this._view) { + this._view.enable(val); + } } get enabled () { @@ -249,7 +262,7 @@ export class Camera { } get view (): RenderView { - return this._view; + return this._view!; } set node (val: INode) { @@ -410,19 +423,21 @@ export class Camera { set visibility (vis) { this._visibility = vis; - this._view.visibility = vis; + if (this._view) + this._view.visibility = vis; } get visibility () { return this._visibility; } - get priority (): number { - return this._view.priority; + get priority(): number { + return this._view ? this._view.priority : -1; } set priority (val: number) { this._priority = val; - this._view.priority = this._priority; + if (this._view) + this._view.priority = this._priority; } set aperture (val: CameraAperture) { @@ -486,9 +501,8 @@ export class Camera { } public changeTargetWindow (window: GFXWindow | null = null) { - const scene = this._scene; - const win = window || scene.root.mainWindow; - if (win) { + const win = window || cc.director.root.mainWindow; + if (win && this._view) { this._view.window = win; this.resize(win.width, win.height); } diff --git a/cocos/core/renderer/scene/directional-light.ts b/cocos/core/renderer/scene/directional-light.ts index 9d75905d29..71af9b7549 100644 --- a/cocos/core/renderer/scene/directional-light.ts +++ b/cocos/core/renderer/scene/directional-light.ts @@ -30,8 +30,8 @@ export class DirectionalLight extends Light { return this._illum; } - constructor (scene: RenderScene, name: string, node: INode) { - super(scene, name, node); + constructor () { + super(); this._type = LightType.DIRECTIONAL; } diff --git a/cocos/core/renderer/scene/light.ts b/cocos/core/renderer/scene/light.ts index c7c7aeae52..99b6f2d3f0 100644 --- a/cocos/core/renderer/scene/light.ts +++ b/cocos/core/renderer/scene/light.ts @@ -92,22 +92,43 @@ export class Light { return this._name; } + get scene() { + return this._scene; + } + protected _enabled = true; protected _color: Vec3 = new Vec3(1, 1, 1); protected _useColorTemp: boolean = false; protected _colorTemp: number = 6550.0; protected _colorTempRGB: Vec3 = new Vec3(1, 1, 1); - protected _scene: RenderScene; - protected _node: INode; + protected _scene: RenderScene | null = null; + protected _node: INode | null = null; protected _type: LightType; - protected _name: string; + protected _name: string | null = null; - constructor (scene: RenderScene, name: string, node: INode) { - this._scene = scene; + constructor () { + this._type = LightType.UNKNOWN; + } + + public initialize(name: string, node: INode) { this._name = name; this._type = LightType.UNKNOWN; this._node = node; } + public attachToScene(scene: RenderScene) { + this._scene = scene; + } + + public detachFromScene() { + this._scene = null; + } + + public destroy() { + this._name = null; + this._type = LightType.UNKNOWN; + this._node = null; + } + public update () {} } diff --git a/cocos/core/renderer/scene/model.ts b/cocos/core/renderer/scene/model.ts index 28730003c6..44d169e4d9 100644 --- a/cocos/core/renderer/scene/model.ts +++ b/cocos/core/renderer/scene/model.ts @@ -39,11 +39,10 @@ export class Model { set scene (scene: RenderScene) { this._scene = scene; - this._id = this._scene.generateModelId(); } get scene () { - return this._scene; + return this._scene!; } get id () { @@ -71,7 +70,7 @@ export class Model { } get node () { - return this._node; + return this._node!; } set node (node: INode) { @@ -79,7 +78,7 @@ export class Model { } get transform () { - return this._transform; + return this._transform!; } set transform (transform: INode) { @@ -143,11 +142,11 @@ export class Model { protected _type: string = 'default'; protected _device: GFXDevice; - protected _scene: RenderScene; - protected _node: INode; - protected _transform: INode; - protected _id: number; - protected _enabled = false; + protected _scene: RenderScene | null = null; + protected _node: INode | null = null; + protected _transform: INode | null = null; + protected _id: number = -1; + protected _enabled: boolean = false; protected _visFlags = Layers.Enum.NONE; protected _cameraID = -1; protected _userKey = -1; @@ -169,11 +168,12 @@ export class Model { /** * Setup a default empty model */ - constructor (scene: RenderScene, node: INode) { + constructor () { this._device = cc.director.root!.device; - this._scene = scene; - this._node = this._transform = node; - this._id = this._scene.generateModelId(); + } + + public initialize(node: INode) { + this._transform = this._node = node; } public destroy () { @@ -202,6 +202,16 @@ export class Model { this._inited = false; } + public attachToScene(scene: RenderScene) { + this._scene = scene; + this._id = this._scene.generateModelId(); + } + + public detachFromScene() { + this._scene = null; + this._id = -1; + } + public getSubModel (idx: number) { return this._subModels[idx]; } @@ -210,7 +220,7 @@ export class Model { const node = this._transform; // @ts-ignore if (node.hasChangedFlags || node._dirtyFlags) { - node.updateWorldTransform(); + node!.updateWorldTransform(); this._transformUpdated = true; if (this._modelBounds && this._worldBounds) { // @ts-ignore TS2339 @@ -256,7 +266,7 @@ export class Model { if (!minPos || !maxPos) { return; } this._modelBounds = aabb.fromPoints(aabb.create(), minPos, maxPos); this._worldBounds = aabb.clone(this._modelBounds); - this._transform.updateWorldTransform(); + this._transform!.updateWorldTransform(); // @ts-ignore this._modelBounds.transform(this._transform._mat, this._transform._pos, this._transform._rot, this._transform._scale, this._worldBounds); } diff --git a/cocos/core/renderer/scene/planar-shadows.ts b/cocos/core/renderer/scene/planar-shadows.ts index d349c4a4bc..9a72c54ff0 100644 --- a/cocos/core/renderer/scene/planar-shadows.ts +++ b/cocos/core/renderer/scene/planar-shadows.ts @@ -102,7 +102,7 @@ export class PlanarShadows { } public updateSphereLight (light: SphereLight) { - light.node.getWorldPosition(_v3); + light.node!.getWorldPosition(_v3); const n = this._normal; const d = this._distance; const NdL = Vec3.dot(n, _v3); const lx = _v3.x; const ly = _v3.y; const lz = _v3.z; @@ -129,7 +129,7 @@ export class PlanarShadows { } public updateDirLight (light: DirectionalLight = this._scene.mainLight) { - light.node.getWorldRotation(_qt); + light.node!.getWorldRotation(_qt); Vec3.transformQuat(_v3, _forward, _qt); const n = this._normal; const d = this._distance; const NdL = Vec3.dot(n, _v3); const scale = 1 / NdL; diff --git a/cocos/core/renderer/scene/render-scene.ts b/cocos/core/renderer/scene/render-scene.ts index ac3f39f5a4..61189e719a 100644 --- a/cocos/core/renderer/scene/render-scene.ts +++ b/cocos/core/renderer/scene/render-scene.ts @@ -128,9 +128,9 @@ export class RenderScene { constructor (root: Root) { this._root = root; - this._ambient = new Ambient(this); this._defaultMainLightNode = new Node('Main Light'); - this._mainLight = new DirectionalLight(this, 'Main Light', this._defaultMainLightNode); + this._mainLight = new DirectionalLight(); + this._mainLight.initialize('Main Light', this._defaultMainLightNode); this._mainLight.illuminance = Ambient.SUN_ILLUM; this._mainLight.enabled = false; // disabled by default this._ambient = new Ambient(this); @@ -144,97 +144,102 @@ export class RenderScene { } public destroy () { - this.destroyCameras(); - this.destroyPointLights(); - this.destroySpotLights(); - this.destroyModels(); + this.removeCameras(); + this.removeSphereLights(); + this.removeSpotLights(); + this.removeModels(); this._skybox.destroy(); this._planarShadows.destroy(); } - public createCamera (info: ICameraInfo): Camera { - const camera = new Camera(this, info); - this._cameras.push(camera); - return camera; + public addCamera (cam: Camera) { + cam.attachToScene(this); + this._cameras.push(cam); } - public destroyCamera (camera: Camera) { + public removeCamera (camera: Camera) { for (let i = 0; i < this._cameras.length; ++i) { if (this._cameras[i] === camera) { - camera.destroy(); this._cameras.splice(i, 1); + camera.detachFromScene(); return; } } } - public destroyCameras () { + public removeCameras () { for (const camera of this._cameras) { - camera.destroy(); + camera.detachFromScene(); } this._cameras.splice(0); } - public createSphereLight (name: string, node: INode): SphereLight | null { - const light = new SphereLight(this, name, node); - this._sphereLights.push(light); - return light; + public addSphereLight (sl:SphereLight) { + sl.attachToScene(this); + this._sphereLights.push(sl); } - public destroySphereLight (light: SphereLight) { + public removeSphereLight (light: SphereLight) { for (let i = 0; i < this._sphereLights.length; ++i) { if (this._sphereLights[i] === light) { + light.detachFromScene(); this._sphereLights.splice(i, 1); return; } } } - public createSpotLight (name: string, node: INode): SpotLight | null { - const light = new SpotLight(this, name, node); - this._spotLights.push(light); - return light; + public addSpotLight (sl:SpotLight) { + sl.attachToScene(this); + this._spotLights.push(sl); } - public destroySpotLight (light: SpotLight) { + public removeSpotLight (light: SpotLight) { for (let i = 0; i < this._spotLights.length; ++i) { if (this._spotLights[i] === light) { + light.detachFromScene(); this._spotLights.splice(i, 1); return; } } } - public destroyPointLights () { - this._sphereLights = []; + public removeSphereLights () { + for (let i = 0; i < this._sphereLights.length; ++i) { + this._sphereLights[i].detachFromScene(); + } + this._sphereLights.length = 0; } - public destroySpotLights () { + public removeSpotLights () { + for (let i = 0; i < this._spotLights.length; ++i) { + this._spotLights[i].detachFromScene(); + } this._spotLights = []; } - public createModel (clazz: new (scene: RenderScene, node: INode) => T, node: INode): T { - const model = new clazz(this, node); - this._models.push(model); - return model; + public addModel (m:Model) { + m.attachToScene(this); + this._models.push(m); } - public destroyModel (model: Model) { + public removeModel (model: Model) { for (let i = 0; i < this._models.length; ++i) { if (this._models[i] === model) { this._planarShadows.destroyShadowModel(model); - this._models.splice(i, 1)[0].destroy(); + model.detachFromScene(); + this._models.splice(i, 1); return; } } } - public destroyModels () { + public removeModels () { for (const m of this._models) { this._planarShadows.destroyShadowModel(m); - m.destroy(); + m.detachFromScene(); } - this._models = []; + this._models.length = 0; } public onPipelineChange () { diff --git a/cocos/core/renderer/scene/skybox.ts b/cocos/core/renderer/scene/skybox.ts index 2e63c23140..1e6dab554e 100644 --- a/cocos/core/renderer/scene/skybox.ts +++ b/cocos/core/renderer/scene/skybox.ts @@ -36,7 +36,7 @@ export class Skybox extends Model { set envmap (val: TextureCube | null) { const newEnvmap = val || this._default; this._envmap = newEnvmap; - this._scene.ambient.groundAlbedo[3] = this._envmap.mipmapLevel; + this._scene!.ambient.groundAlbedo[3] = this._envmap.mipmapLevel; this._updateGlobalBinding(); } get envmap () { @@ -51,7 +51,7 @@ export class Skybox extends Model { protected _globalBinding: IInternalBindingInst; constructor (scene: RenderScene) { - super(scene, null!); + super(); this._scene = scene; this._globalBinding = this._scene.root.pipeline.globalBindings.get(UNIFORM_ENVIRONMENT.name)!; if (!skybox_material) { @@ -64,10 +64,10 @@ export class Skybox extends Model { protected _updatePipeline () { const value = this._useIBL ? this._isRGBE ? 2 : 1 : 0; - const pipeline = this._scene.root.pipeline; + const pipeline = this._scene!.root.pipeline; if (pipeline.macros.CC_USE_IBL === value) { return; } pipeline.macros.CC_USE_IBL = value; - this._scene.onPipelineChange(); + this._scene!.onPipelineChange(); } protected _updateGlobalBinding () { diff --git a/cocos/core/renderer/scene/sphere-light.ts b/cocos/core/renderer/scene/sphere-light.ts index 1dc5edb7b2..a77d4ca8c6 100644 --- a/cocos/core/renderer/scene/sphere-light.ts +++ b/cocos/core/renderer/scene/sphere-light.ts @@ -44,8 +44,8 @@ export class SphereLight extends Light { protected _pos: Vec3; protected _aabb: aabb; - constructor (scene: RenderScene, name: string, node: INode) { - super(scene, name, node); + constructor () { + super(); this._type = LightType.SPHERE; this._aabb = aabb.create(); this._pos = new Vec3(); diff --git a/cocos/core/renderer/scene/spot-light.ts b/cocos/core/renderer/scene/spot-light.ts index c4f12035fd..687e704614 100644 --- a/cocos/core/renderer/scene/spot-light.ts +++ b/cocos/core/renderer/scene/spot-light.ts @@ -72,8 +72,8 @@ export class SpotLight extends Light { return this._frustum; } - constructor (scene: RenderScene, name: string, node: INode) { - super(scene, name, node); + constructor () { + super(); this._type = LightType.SPOT; this._aabb = aabb.create(); this._frustum = frustum.create(); diff --git a/cocos/core/renderer/ui/ui-batch-model.ts b/cocos/core/renderer/ui/ui-batch-model.ts index ba80c9d690..7bbf372364 100644 --- a/cocos/core/renderer/ui/ui-batch-model.ts +++ b/cocos/core/renderer/ui/ui-batch-model.ts @@ -38,8 +38,8 @@ export class UIBatchModel extends Model { private _subModel: UISubModel; - constructor (scene: RenderScene) { - super(scene, null!); + constructor () { + super(); this._subModel = new UISubModel(); } @@ -50,7 +50,7 @@ export class UIBatchModel extends Model { return false; } - public initialize (ia: GFXInputAssembler, batch: UIDrawBatch) { + public directInitialize (ia: GFXInputAssembler, batch: UIDrawBatch) { this._subModel.directInitialize(ia, batch.material!, batch.pipelineState!); this._subModels[0] = this._subModel; } diff --git a/cocos/core/renderer/ui/ui.ts b/cocos/core/renderer/ui/ui.ts index 024aa37c7e..fdb8fed312 100644 --- a/cocos/core/renderer/ui/ui.ts +++ b/cocos/core/renderer/ui/ui.ts @@ -108,7 +108,8 @@ export class UI { name: 'GUIScene', }); this._uiModelPool = new Pool(() => { - const model = this._scene.createModel(UIBatchModel, null!); + const model = cc.director.root.createModel(UIBatchModel); + model.enabled = true; model.visFlags |= Layers.Enum.UI_3D; return model; }, 2); @@ -272,7 +273,7 @@ export class UI { let batchPriority = 0; for (let i = 0; i < this._modelInUse.length; i++) { - this._modelInUse.get(i).enabled = false; + this._scene.removeModel(this._modelInUse.get(i)); this._uiModelPool!.free(this._modelInUse.get(i)); } this._modelInUse.clear(); @@ -302,8 +303,8 @@ export class UI { ia.indexCount = batch.idxCount; const uiModel = this._uiModelPool!.alloc(); - uiModel.initialize(ia, batch); - uiModel.enabled = true; + uiModel.directInitialize(ia, batch); + this._scene.addModel(uiModel); uiModel.getSubModel(0).priority = batchPriority++; if (batch.camera) { uiModel.visFlags = batch.camera.view.visibility; diff --git a/cocos/core/root.ts b/cocos/core/root.ts index 438ccd9b63..1f33865293 100644 --- a/cocos/core/root.ts +++ b/cocos/core/root.ts @@ -11,6 +11,12 @@ import { IRenderViewInfo, RenderView } from './pipeline/render-view'; import { DataPoolManager } from './renderer/data-pool-manager'; import { IRenderSceneInfo, RenderScene } from './renderer/scene/render-scene'; import { UI } from './renderer/ui/ui'; +import { Model, Camera, Light } from './renderer'; +import { Pool } from './memop'; +import { DirectionalLight } from './renderer/scene/directional-light'; +import { SphereLight } from './renderer/scene/sphere-light'; +import { SpotLight } from './renderer/scene/spot-light'; +import { LightType } from './renderer/scene/light'; export let _createSceneFun; export let _createViewFun; @@ -183,6 +189,12 @@ export class Root { private _dataPoolMgr: DataPoolManager; private _scenes: RenderScene[] = []; private _views: RenderView[] = []; + private _modelPools: Map> = new Map>(); + private _cameraPool: Pool | null = null; + private _lightPools: Map> = new Map>(); + private _directLightPool: Pool | null = null; + private _sphereLightPool: Pool | null = null; + private _spotLightPool: Pool | null = null; private _time: number = 0; private _frameTime: number = 0; private _fpsTime: number = 0; @@ -201,6 +213,8 @@ export class Root { RenderScene.registerCreateFunc(this); RenderView.registerCreateFunc(this); + + this._cameraPool = new Pool(() => new Camera, 4); } /** @@ -471,4 +485,63 @@ export class Root { } this._views = []; } + + public createModel(mClass: new () => T): T { + let p = this._modelPools.get(mClass); + if (!p) { + this._modelPools.set(mClass, new Pool(() => new mClass(), 10)); + p = this._modelPools.get(mClass)!; + } + return p.alloc(); + } + + public destroyModel(m: Model) { + const p = this._modelPools.get(m.constructor); + if (p) { + p.free(m); + m.destroy(); + if (m.scene) { + m.scene.removeModel(m); + } + } + } + + public createCamera(): Camera { + return this._cameraPool!.alloc(); + } + + public destroyCamera(c: Camera) { + this._cameraPool!.free(c); + c.destroy(); + if (c.scene) { + c.scene.removeCamera(c); + } + } + + public createLight(lClass: new () => T): T { + let l = this._lightPools.get(lClass); + if (!l) { + this._lightPools.set(lClass, new Pool(() => new lClass(), 4)); + l = this._lightPools.get(lClass)!; + } + return l.alloc(); + } + + public destroyLight(l: Light) { + const p = this._lightPools.get(l.constructor); + l.destroy(); + if (p) { + p.free(l); + if (l.scene) { + switch (l.type) { + case LightType.SPHERE: + l.scene.removeSphereLight(l as SphereLight); + break; + case LightType.SPOT: + l.scene.removeSpotLight(l as SpotLight); + break; + } + } + } + } } diff --git a/cocos/particle/models/particle-batch-model.ts b/cocos/particle/models/particle-batch-model.ts index a4c59d7144..3b108a55b9 100644 --- a/cocos/particle/models/particle-batch-model.ts +++ b/cocos/particle/models/particle-batch-model.ts @@ -31,12 +31,10 @@ import { Material } from '../../core/assets/material'; import { IRenderingSubmesh, Mesh } from '../../core/assets/mesh'; import { GFX_DRAW_INFO_SIZE, GFXBuffer, IGFXIndirectBuffer } from '../../core/gfx/buffer'; import { GFXAttributeName, GFXBufferUsageBit, GFXFormatInfos, - GFXMemoryUsageBit, GFXPrimitiveMode } from '../../core/gfx/define'; + GFXMemoryUsageBit, GFXPrimitiveMode, GFXStatus } from '../../core/gfx/define'; import { IGFXAttribute } from '../../core/gfx/input-assembler'; import { Color } from '../../core/math/color'; import { Model } from '../../core/renderer/scene/model'; -import { RenderScene } from '../../core/renderer/scene/render-scene'; -import { Node } from '../../core/scene-graph'; export default class ParticleBatchModel extends Model { @@ -54,8 +52,8 @@ export default class ParticleBatchModel extends Model { private _vertCount: number = 0; private _indexCount: number = 0; - constructor (scene: RenderScene, node: Node) { - super(scene, node); + constructor () { + super(); this._type = 'particle-batch'; this._capacity = 0; @@ -184,6 +182,14 @@ export default class ParticleBatchModel extends Model { this._iaInfo.drawInfos[0].vertexCount = this._capacity * this._vertCount; this._iaInfo.drawInfos[0].indexCount = this._capacity * this._indexCount; + if (this._iaInfoBuffer.status === GFXStatus.UNREADY) { + this._iaInfoBuffer.initialize({ + usage: GFXBufferUsageBit.INDIRECT, + memUsage: GFXMemoryUsageBit.HOST | GFXMemoryUsageBit.DEVICE, + size: GFX_DRAW_INFO_SIZE, + stride: 1, + }); + } this._iaInfoBuffer.update(this._iaInfo); this._subMeshData = { diff --git a/cocos/particle/particle-system-component.ts b/cocos/particle/particle-system-component.ts index 5cd8d6b8dd..03f77c0cae 100644 --- a/cocos/particle/particle-system-component.ts +++ b/cocos/particle/particle-system-component.ts @@ -501,23 +501,17 @@ export class ParticleSystemComponent extends RenderableComponent { return this._models; } - public _changeSceneInModel () { - if (this.isValid) { - const r = this.renderer as any; - if (r && r._model) { - r._model.scene.destroyModel(r._model); - r._model = null; - r.onEnable(); - r._updateModel(); - r._updateMaterialParams(); - } - const t = this.trailModule as any; - if (t && t._trailModel) { - t._trailModel.scene.destroyModel(t._trailModel); - t._trailModel = null; - t.enable = t._enable; - r._updateTrailMaterial(); - } + protected _attachToScene() { + this.renderer._attachToScene(); + if (this.trailModule.enable) { + this.trailModule._attachToScene(); + } + } + + protected _detachFromScene() { + this.renderer._detachFromScene(); + if (this.trailModule.enable) { + this.trailModule._detachFromScene(); } } diff --git a/cocos/particle/renderer/particle-system-renderer.ts b/cocos/particle/renderer/particle-system-renderer.ts index 9071c75492..a304228f00 100644 --- a/cocos/particle/renderer/particle-system-renderer.ts +++ b/cocos/particle/renderer/particle-system-renderer.ts @@ -137,10 +137,7 @@ export default class ParticleSystemRenderer { }) private _mesh: Mesh | null = null; - @property({ - type: cc.ParticleSystemComponent, - visible: false, - }) + @property private _particleSystem: any = null; /** @@ -236,7 +233,6 @@ export default class ParticleSystemRenderer { return new Particle(this); }, 16); this._setVertexAttrib(); - this.onEnable(); this._updateModel(); this._updateMaterialParams(); this._updateTrailMaterial(); @@ -246,30 +242,37 @@ export default class ParticleSystemRenderer { if (!this._particleSystem) { return; } - if (this._model == null) { - this._model = this._particleSystem._getRenderScene().createModel(ParticleBatchModel, this._particleSystem.node) as ParticleBatchModel; - this._model.visFlags = this._particleSystem.visibility; - } - if (!this._model.inited) { - this._model.setCapacity(this._particleSystem.capacity); - this._model.node = this._particleSystem.node; - } - this._model.enabled = this._particleSystem.enabledInHierarchy; + this._attachToScene(); + this._model!.initialize(this._particleSystem.node); + this._model!.enabled = this._particleSystem.enabledInHierarchy; } public onDisable () { - if (this._model) { - this._model.enabled = this._particleSystem.enabledInHierarchy; - } + this._detachFromScene(); } public onDestroy () { if (this._model) { - this._model.scene.destroyModel(this._model); + cc.director.root.destroyModel(this._model); this._model = null; } } + public _attachToScene() { + if (this._model) { + if (this._model.scene) { + this._detachFromScene(); + } + this._particleSystem._getRenderScene().addModel(this._model); + } + } + + public _detachFromScene() { + if (this._model && this._model.scene) { + this._model.scene.removeModel(this._model); + } + } + public clear () { this._particles!.reset(); this._updateRenderData(); @@ -531,9 +534,11 @@ export default class ParticleSystemRenderer { private _updateModel () { if (!this._model) { - return; + this._model = cc.director.root.createModel(ParticleBatchModel); + this._model!.setCapacity(this._particleSystem.capacity); + this._model!.visFlags = this._particleSystem.visibility; } - this._model.setVertexAttributes(this._renderMode === RenderMode.Mesh ? this._mesh : null, this._vertAttrs); + this._model!.setVertexAttributes(this._renderMode === RenderMode.Mesh ? this._mesh : null, this._vertAttrs); // if (Object.getPrototypeOf(this).constructor.name === 'ParticleSystemGpuRenderer') { // return; // } diff --git a/cocos/particle/renderer/trail.ts b/cocos/particle/renderer/trail.ts index 913d215bb8..02fdac02e0 100644 --- a/cocos/particle/renderer/trail.ts +++ b/cocos/particle/renderer/trail.ts @@ -290,10 +290,7 @@ export default class TrailModule { }) private _space = Space.World; - @property({ - type: cc.ParticleSystemComponent, - visible: false, - }) + @property private _particleSystem: any = null; private _minSquaredDistance: number = 0; @@ -359,20 +356,31 @@ export default class TrailModule { } public onEnable () { - if (this._enable && this._trailModel) { - this._trailModel.enabled = true; - } + this._attachToScene(); } public onDisable () { - if (this._enable && this._trailModel) { - this._trailModel.enabled = false; + this._detachFromScene(); + } + + public _attachToScene() { + if (this._trailModel) { + if (this._trailModel.scene) { + this._detachFromScene(); + } + this._particleSystem._getRenderScene().addModel(this._trailModel); + } + } + + public _detachFromScene() { + if (this._trailModel && this._trailModel.scene) { + this._trailModel.scene.removeModel(this._trailModel); } } public destroy () { if (this._trailModel) { - this._trailModel.scene.destroyModel(this._trailModel); + cc.director.root.destroyModel(this._trailModel); this._trailModel = null; } if (this._trailSegments) { @@ -606,7 +614,8 @@ export default class TrailModule { flatBuffers: [], }; - this._trailModel = this._particleSystem._getRenderScene().createModel(Model, this._particleSystem.node); + this._trailModel = cc.director.root.createModel(Model); + this._trailModel!.initialize(this._particleSystem.node); this._trailModel!.visFlags = this._particleSystem.visibility; this._trailModel!.setSubModelMesh(0, this._subMeshData); this._trailModel!.enabled = true; diff --git a/cocos/ui/components/ui-model-component.ts b/cocos/ui/components/ui-model-component.ts index 4774439a44..5cf6eed877 100644 --- a/cocos/ui/components/ui-model-component.ts +++ b/cocos/ui/components/ui-model-component.ts @@ -63,11 +63,25 @@ export class UIModelComponent extends UIComponent { } this._modelComponent._sceneGetter = director.root!.ui.getRenderSceneGetter(); - this._modelComponent._changeSceneInModel(); this._models = this._modelComponent._collectModels(); } + public onEnable() { + super.onEnable(); + if (this._modelComponent) { + this._modelComponent._attachToScene(); + } + } + + public onDisable() { + super.onDisable(); + if (this._modelComponent) { + this._modelComponent._detachFromScene(); + } + } + public onDestroy () { + super.onDestroy(); this._modelComponent = this.getComponent('cc.RenderableComponent') as RenderableComponent; if (!this._modelComponent) { return; @@ -75,7 +89,7 @@ export class UIModelComponent extends UIComponent { this._modelComponent._sceneGetter = null; if (cc.isValid(this.node, true)) { - this._modelComponent._changeSceneInModel(); + this._modelComponent._attachToScene(); } this._models = null; } From e558f3f0feb996f0b9b19344e240a625cd579b1a Mon Sep 17 00:00:00 2001 From: Yun Hsiao Wu Date: Mon, 25 Nov 2019 16:05:56 +0800 Subject: [PATCH 04/21] filter shader bindings wrt. macros (#5772) * filter shader bindings wrt. macros * fix default joint texture size * empty scene opt --- cocos/core/3d/builtin/effects.ts | 26 +++--- cocos/core/animation/animation-blend-state.ts | 11 ++- cocos/core/assets/simple-texture.ts | 9 +- cocos/core/gfx/webgl/webgl-commands.ts | 50 ++++++---- cocos/core/gfx/webgl2/webgl2-commands.ts | 91 +++++++++++-------- cocos/core/memop/cached-array.ts | 8 -- .../core/pipeline/forward/forward-pipeline.ts | 14 ++- cocos/core/pipeline/render-pipeline.ts | 20 ++-- cocos/core/renderer/core/pass.ts | 40 ++------ cocos/core/renderer/core/program-lib.ts | 63 +++++++++---- cocos/core/renderer/core/sampler-lib.ts | 8 +- .../core/renderer/core/texture-buffer-pool.ts | 4 +- .../models/skeletal-animation-utils.ts | 4 +- .../core/renderer/scene/directional-light.ts | 4 +- 14 files changed, 201 insertions(+), 151 deletions(-) diff --git a/cocos/core/3d/builtin/effects.ts b/cocos/core/3d/builtin/effects.ts index 2e7acf500c..daa3012e3c 100644 --- a/cocos/core/3d/builtin/effects.ts +++ b/cocos/core/3d/builtin/effects.ts @@ -9,21 +9,17 @@ export default [ "shaders": [ { "name": "builtin-billboard|vert:vs_main|tinted-fs:add", - "hash": 3128769502, + "hash": 2541047749, "glsl3": { - "vert": `\nprecision mediump float;\nuniform Constants {\n vec4 mainTiling_Offset;\n vec4 frameTile_velLenScale;\n vec4 scale;\n};\nuniform CCGlobal {\n vec4 cc_time;\n vec4 cc_screenSize;\n vec4 cc_screenScale;\n vec4 cc_nativeSize;\n highp mat4 cc_matView;\n mat4 cc_matViewInv;\n mat4 cc_matProj;\n mat4 cc_matProjInv;\n mat4 cc_matViewProj;\n mat4 cc_matViewProjInv;\n vec4 cc_cameraPos;\n vec4 cc_exposure;\n vec4 cc_mainLitDir;\n vec4 cc_mainLitColor;\n vec4 cc_ambientSky;\n vec4 cc_ambientGround;\n};\nuniform CCLocal {\n highp mat4 cc_matWorld;\n highp mat4 cc_matWorldIT;\n};\nvec4 quaternionFromAxisAngle (float angle, vec3 axis){\n angle /= 2.;\n float s = sin(angle);\n vec4 res;\n res.xyz = s * axis;\n res.w = cos(angle);\n return res;\n}\nvec4 quaternionFromAxis (vec3 xAxis,vec3 yAxis,vec3 zAxis){\n mat3 m = mat3(xAxis,yAxis,zAxis);\n float trace = m[0][0] + m[1][1] + m[2][2];\n vec4 quat;\n if (trace > 0.) {\n float s = 0.5 / sqrt(trace + 1.0);\n quat.w = 0.25 / s;\n quat.x = (m[2][1] - m[1][2]) * s;\n quat.y = (m[0][2] - m[2][0]) * s;\n quat.z = (m[1][0] - m[0][1]) * s;\n } else if ((m[0][0] > m[1][1]) && (m[0][0] > m[2][2])) {\n float s = 2.0 * sqrt(1.0 + m[0][0] - m[1][1] - m[2][2]);\n quat.w = (m[2][1] - m[1][2]) / s;\n quat.x = 0.25 * s;\n quat.y = (m[0][1] + m[1][0]) / s;\n quat.z = (m[0][2] + m[2][0]) / s;\n } else if (m[1][1] > m[2][2]) {\n float s = 2.0 * sqrt(1.0 + m[1][1] - m[0][0] - m[2][2]);\n quat.w = (m[0][2] - m[2][0]) / s;\n quat.x = (m[0][1] + m[1][0]) / s;\n quat.y = 0.25 * s;\n quat.z = (m[1][2] + m[2][1]) / s;\n } else {\n float s = 2.0 * sqrt(1.0 + m[2][2] - m[0][0] - m[1][1]);\n quat.w = (m[1][0] - m[0][1]) / s;\n quat.x = (m[0][2] + m[2][0]) / s;\n quat.y = (m[1][2] + m[2][1]) / s;\n quat.z = 0.25 * s;\n }\n float len = quat.x * quat.x + quat.y * quat.y + quat.z * quat.z + quat.w * quat.w;\n if (len > 0.) {\n len = 1. / sqrt(len);\n quat.x = quat.x * len;\n quat.y = quat.y * len;\n quat.z = quat.z * len;\n quat.w = quat.w * len;\n }\n return quat;\n}\nvec4 quaternionFromEuler (vec3 angle){\n float x = angle.x / 2.;\n float y = angle.y / 2.;\n float z = angle.z / 2.;\n float sx = sin(x);\n float cx = cos(x);\n float sy = sin(y);\n float cy = cos(y);\n float sz = sin(z);\n float cz = cos(z);\n vec4 quat = vec4(0);\n quat.x = sx * cy * cz + cx * sy * sz;\n quat.y = cx * sy * cz + sx * cy * sz;\n quat.z = cx * cy * sz - sx * sy * cz;\n quat.w = cx * cy * cz - sx * sy * sz;\n return quat;\n}\nmat4 matrixFromRT (vec4 q, vec3 p){\n float x2 = q.x + q.x;\n float y2 = q.y + q.y;\n float z2 = q.z + q.z;\n float xx = q.x * x2;\n float xy = q.x * y2;\n float xz = q.x * z2;\n float yy = q.y * y2;\n float yz = q.y * z2;\n float zz = q.z * z2;\n float wx = q.w * x2;\n float wy = q.w * y2;\n float wz = q.w * z2;\n return mat4(\n 1. - (yy + zz), xy + wz, xz - wy, 0,\n xy - wz, 1. - (xx + zz), yz + wx, 0,\n xz + wy, yz - wx, 1. - (xx + yy), 0,\n p.x, p.y, p.z, 1\n );\n}\nmat4 matFromRTS (vec4 q, vec3 t, vec3 s){\n float x = q.x, y = q.y, z = q.z, w = q.w;\n float x2 = x + x;\n float y2 = y + y;\n float z2 = z + z;\n float xx = x * x2;\n float xy = x * y2;\n float xz = x * z2;\n float yy = y * y2;\n float yz = y * z2;\n float zz = z * z2;\n float wx = w * x2;\n float wy = w * y2;\n float wz = w * z2;\n float sx = s.x;\n float sy = s.y;\n float sz = s.z;\n return mat4((1. - (yy + zz)) * sx, (xy + wz) * sx, (xz - wy) * sx, 0,\n (xy - wz) * sy, (1. - (xx + zz)) * sy, (yz + wx) * sy, 0,\n (xz + wy) * sz, (yz - wx) * sz, (1. - (xx + yy)) * sz, 0,\n t.x, t.y, t.z, 1);\n}\nvoid scaleMatrix (inout mat4 m, float s){\n m[0].xyz *= s;\n m[1].xyz *= s;\n m[2].xyz *= s;\n}\nvec4 quatMultiply (vec4 a, vec4 b){\n vec4 quat;\n quat.x = a.x * b.w + a.w * b.x + a.y * b.z - a.z * b.y;\n quat.y = a.y * b.w + a.w * b.y + a.z * b.x - a.x * b.z;\n quat.z = a.z * b.w + a.w * b.z + a.x * b.y - a.y * b.x;\n quat.w = a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z;\n return quat;\n}\nvoid rotateVecFromQuat (inout vec3 v, vec4 q){\n float ix = q.w * v.x + q.y * v.z - q.z * v.y;\n float iy = q.w * v.y + q.z * v.x - q.x * v.z;\n float iz = q.w * v.z + q.x * v.y - q.y * v.x;\n float iw = -q.x * v.x - q.y * v.y - q.z * v.z;\n v.x = ix * q.w + iw * -q.x + iy * -q.z - iz * -q.y;\n v.y = iy * q.w + iw * -q.y + iz * -q.x - ix * -q.z;\n v.z = iz * q.w + iw * -q.z + ix * -q.y - iy * -q.x;\n}\nvec3 rotateVecFromAxis (vec3 v, vec3 axis, float theta){\n return cos(theta) * v + sin(theta) * cross(v, axis) + (1. - cos(theta)) * dot(v, axis) * axis;\n}\nvec3 rotateInLocalSpace (vec3 pos, vec3 xAxis, vec3 yAxis, vec3 zAxis, vec4 q){\n vec4 viewQuat = quaternionFromAxis(xAxis, yAxis, zAxis);\n vec4 rotQuat = quatMultiply(viewQuat, q);\n rotateVecFromQuat(pos, rotQuat);\n return pos;\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}\nout vec2 uv;\nout vec4 color;\nvoid computeVertPos (inout vec4 pos, vec2 vertOffset, vec4 q, vec3 s\n#if 1 || CC_USE_VERTICAL_BILLBOARD\n , mat4 viewInv\n#endif\n#if CC_USE_STRETCHED_BILLBOARD\n , vec3 eye\n , vec4 velocity\n , float velocityScale\n , float lengthScale\n , float xIndex\n#endif\n) {\n#if 1\n vec3 viewSpaceVert = vec3(vertOffset.x * s.x, vertOffset.y * s.y, 0.);\n vec3 camX = normalize(vec3(viewInv[0][0], viewInv[1][0], viewInv[2][0]));\n vec3 camY = normalize(vec3(viewInv[0][1], viewInv[1][1], viewInv[2][1]));\n vec3 camZ = normalize(vec3(viewInv[0][2], viewInv[1][2], viewInv[2][2]));\n pos.xyz += rotateInLocalSpace(viewSpaceVert, camX, camY, camZ, q);\n#elif CC_USE_STRETCHED_BILLBOARD\n vec3 camRight = normalize(cross(pos.xyz - eye, velocity.xyz)) * s.x;\n vec3 camUp = velocity.xyz * velocityScale + normalize(velocity.xyz) * lengthScale * s.y;\n pos.xyz += (camRight * abs(vertOffset.x) * sign(vertOffset.y)) - camUp * xIndex;\n#elif CC_USE_HORIZONTAL_BILLBOARD\n vec3 viewSpaceVert = vec3(vertOffset.x * s.x, vertOffset.y * s.y, 0.);\n vec3 camX = vec3(1, 0, 0);\n vec3 camY = vec3(0, 0, -1);\n pos.xyz += rotateInLocalSpace(viewSpaceVert, camX, camY, cross(camX, camY), q);\n#elif CC_USE_VERTICAL_BILLBOARD\n vec2 viewSpaceVert = vec2(vertOffset.x * s.x, vertOffset.y * s.y);\n rotateCorner(viewSpaceVert, q.z);\n vec3 camX = normalize(vec3(cc_matView[0][0], cc_matView[1][0], cc_matView[2][0]));\n vec3 camY = vec3(0, 1, 0);\n vec3 offset = camX * viewSpaceVert.x + camY * viewSpaceVert.y;\n pos.xyz += offset;\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#if !CC_USE_MESH\n vertIndex.y = 1. - vertIndex.y;\n#endif\n return (aniUV.xy + vertIndex) / vec2(frameTile.x, frameTile.y);\n}\nin vec3 a_position;\nin vec2 a_texCoord;\nin vec4 a_color;\nuniform builtin {\n vec4 cc_size_rotation;\n};\nvec4 vs_main() {\n vec4 pos = vec4(a_position, 1);\n pos = cc_matWorld * pos;\n vec2 vertOffset = a_texCoord.xy - 0.5;\n computeVertPos(pos, vertOffset, quaternionFromEuler(0., 0., cc_size_rotation.z), vec3(cc_size_rotation.xy, 0.), cc_matViewInv);\n pos = cc_matViewProj * pos;\n uv = a_texCoord.xy;\n color = a_color;\n return pos;\n}\nvoid main() { gl_Position = vs_main(); }`, + "vert": `\nprecision mediump float;\nuniform Constants {\n vec4 mainTiling_Offset;\n vec4 frameTile_velLenScale;\n vec4 scale;\n};\nuniform CCGlobal {\n vec4 cc_time;\n vec4 cc_screenSize;\n vec4 cc_screenScale;\n vec4 cc_nativeSize;\n highp mat4 cc_matView;\n mat4 cc_matViewInv;\n mat4 cc_matProj;\n mat4 cc_matProjInv;\n mat4 cc_matViewProj;\n mat4 cc_matViewProjInv;\n vec4 cc_cameraPos;\n vec4 cc_exposure;\n vec4 cc_mainLitDir;\n vec4 cc_mainLitColor;\n vec4 cc_ambientSky;\n vec4 cc_ambientGround;\n};\nuniform CCLocal {\n highp mat4 cc_matWorld;\n highp mat4 cc_matWorldIT;\n};\nvec4 quaternionFromAxisAngle (float angle, vec3 axis){\n angle /= 2.;\n float s = sin(angle);\n vec4 res;\n res.xyz = s * axis;\n res.w = cos(angle);\n return res;\n}\nvec4 quaternionFromAxis (vec3 xAxis,vec3 yAxis,vec3 zAxis){\n mat3 m = mat3(xAxis,yAxis,zAxis);\n float trace = m[0][0] + m[1][1] + m[2][2];\n vec4 quat;\n if (trace > 0.) {\n float s = 0.5 / sqrt(trace + 1.0);\n quat.w = 0.25 / s;\n quat.x = (m[2][1] - m[1][2]) * s;\n quat.y = (m[0][2] - m[2][0]) * s;\n quat.z = (m[1][0] - m[0][1]) * s;\n } else if ((m[0][0] > m[1][1]) && (m[0][0] > m[2][2])) {\n float s = 2.0 * sqrt(1.0 + m[0][0] - m[1][1] - m[2][2]);\n quat.w = (m[2][1] - m[1][2]) / s;\n quat.x = 0.25 * s;\n quat.y = (m[0][1] + m[1][0]) / s;\n quat.z = (m[0][2] + m[2][0]) / s;\n } else if (m[1][1] > m[2][2]) {\n float s = 2.0 * sqrt(1.0 + m[1][1] - m[0][0] - m[2][2]);\n quat.w = (m[0][2] - m[2][0]) / s;\n quat.x = (m[0][1] + m[1][0]) / s;\n quat.y = 0.25 * s;\n quat.z = (m[1][2] + m[2][1]) / s;\n } else {\n float s = 2.0 * sqrt(1.0 + m[2][2] - m[0][0] - m[1][1]);\n quat.w = (m[1][0] - m[0][1]) / s;\n quat.x = (m[0][2] + m[2][0]) / s;\n quat.y = (m[1][2] + m[2][1]) / s;\n quat.z = 0.25 * s;\n }\n float len = quat.x * quat.x + quat.y * quat.y + quat.z * quat.z + quat.w * quat.w;\n if (len > 0.) {\n len = 1. / sqrt(len);\n quat.x = quat.x * len;\n quat.y = quat.y * len;\n quat.z = quat.z * len;\n quat.w = quat.w * len;\n }\n return quat;\n}\nvec4 quaternionFromEuler (vec3 angle){\n float x = angle.x / 2.;\n float y = angle.y / 2.;\n float z = angle.z / 2.;\n float sx = sin(x);\n float cx = cos(x);\n float sy = sin(y);\n float cy = cos(y);\n float sz = sin(z);\n float cz = cos(z);\n vec4 quat = vec4(0);\n quat.x = sx * cy * cz + cx * sy * sz;\n quat.y = cx * sy * cz + sx * cy * sz;\n quat.z = cx * cy * sz - sx * sy * cz;\n quat.w = cx * cy * cz - sx * sy * sz;\n return quat;\n}\nmat4 matrixFromRT (vec4 q, vec3 p){\n float x2 = q.x + q.x;\n float y2 = q.y + q.y;\n float z2 = q.z + q.z;\n float xx = q.x * x2;\n float xy = q.x * y2;\n float xz = q.x * z2;\n float yy = q.y * y2;\n float yz = q.y * z2;\n float zz = q.z * z2;\n float wx = q.w * x2;\n float wy = q.w * y2;\n float wz = q.w * z2;\n return mat4(\n 1. - (yy + zz), xy + wz, xz - wy, 0,\n xy - wz, 1. - (xx + zz), yz + wx, 0,\n xz + wy, yz - wx, 1. - (xx + yy), 0,\n p.x, p.y, p.z, 1\n );\n}\nmat4 matFromRTS (vec4 q, vec3 t, vec3 s){\n float x = q.x, y = q.y, z = q.z, w = q.w;\n float x2 = x + x;\n float y2 = y + y;\n float z2 = z + z;\n float xx = x * x2;\n float xy = x * y2;\n float xz = x * z2;\n float yy = y * y2;\n float yz = y * z2;\n float zz = z * z2;\n float wx = w * x2;\n float wy = w * y2;\n float wz = w * z2;\n float sx = s.x;\n float sy = s.y;\n float sz = s.z;\n return mat4((1. - (yy + zz)) * sx, (xy + wz) * sx, (xz - wy) * sx, 0,\n (xy - wz) * sy, (1. - (xx + zz)) * sy, (yz + wx) * sy, 0,\n (xz + wy) * sz, (yz - wx) * sz, (1. - (xx + yy)) * sz, 0,\n t.x, t.y, t.z, 1);\n}\nvoid scaleMatrix (inout mat4 m, float s){\n m[0].xyz *= s;\n m[1].xyz *= s;\n m[2].xyz *= s;\n}\nvec4 quatMultiply (vec4 a, vec4 b){\n vec4 quat;\n quat.x = a.x * b.w + a.w * b.x + a.y * b.z - a.z * b.y;\n quat.y = a.y * b.w + a.w * b.y + a.z * b.x - a.x * b.z;\n quat.z = a.z * b.w + a.w * b.z + a.x * b.y - a.y * b.x;\n quat.w = a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z;\n return quat;\n}\nvoid rotateVecFromQuat (inout vec3 v, vec4 q){\n float ix = q.w * v.x + q.y * v.z - q.z * v.y;\n float iy = q.w * v.y + q.z * v.x - q.x * v.z;\n float iz = q.w * v.z + q.x * v.y - q.y * v.x;\n float iw = -q.x * v.x - q.y * v.y - q.z * v.z;\n v.x = ix * q.w + iw * -q.x + iy * -q.z - iz * -q.y;\n v.y = iy * q.w + iw * -q.y + iz * -q.x - ix * -q.z;\n v.z = iz * q.w + iw * -q.z + ix * -q.y - iy * -q.x;\n}\nvec3 rotateVecFromAxis (vec3 v, vec3 axis, float theta){\n return cos(theta) * v + sin(theta) * cross(v, axis) + (1. - cos(theta)) * dot(v, axis) * axis;\n}\nvec3 rotateInLocalSpace (vec3 pos, vec3 xAxis, vec3 yAxis, vec3 zAxis, vec4 q){\n vec4 viewQuat = quaternionFromAxis(xAxis, yAxis, zAxis);\n vec4 rotQuat = quatMultiply(viewQuat, q);\n rotateVecFromQuat(pos, rotQuat);\n return pos;\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}\nout vec2 uv;\nout vec4 color;\nvoid computeVertPos (inout vec4 pos, vec2 vertOffset, vec4 q, vec3 s\n , mat4 viewInv\n) {\n vec3 viewSpaceVert = vec3(vertOffset.x * s.x, vertOffset.y * s.y, 0.);\n vec3 camX = normalize(vec3(viewInv[0][0], viewInv[1][0], viewInv[2][0]));\n vec3 camY = normalize(vec3(viewInv[0][1], viewInv[1][1], viewInv[2][1]));\n vec3 camZ = normalize(vec3(viewInv[0][2], viewInv[1][2], viewInv[2][2]));\n pos.xyz += rotateInLocalSpace(viewSpaceVert, camX, camY, camZ, q);\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 vertIndex.y = 1. - vertIndex.y;\n return (aniUV.xy + vertIndex) / vec2(frameTile.x, frameTile.y);\n}\nin vec3 a_position;\nin vec2 a_texCoord;\nin vec4 a_color;\nuniform builtin {\n vec4 cc_size_rotation;\n};\nvec4 vs_main() {\n vec4 pos = vec4(a_position, 1);\n pos = cc_matWorld * pos;\n vec2 vertOffset = a_texCoord.xy - 0.5;\n computeVertPos(pos, vertOffset, quaternionFromEuler(vec3(0., 0., cc_size_rotation.z)), vec3(cc_size_rotation.xy, 0.), cc_matViewInv);\n pos = cc_matViewProj * pos;\n uv = a_texCoord.xy;\n color = a_color;\n return pos;\n}\nvoid main() { gl_Position = vs_main(); }`, "frag": `\nprecision mediump float;\nuniform CCGlobal {\n vec4 cc_time;\n vec4 cc_screenSize;\n vec4 cc_screenScale;\n vec4 cc_nativeSize;\n highp mat4 cc_matView;\n mat4 cc_matViewInv;\n mat4 cc_matProj;\n mat4 cc_matProjInv;\n mat4 cc_matViewProj;\n mat4 cc_matViewProjInv;\n vec4 cc_cameraPos;\n vec4 cc_exposure;\n vec4 cc_mainLitDir;\n vec4 cc_mainLitColor;\n vec4 cc_ambientSky;\n vec4 cc_ambientGround;\n};\nvec3 SRGBToLinear (vec3 gamma) {\n return gamma * gamma;\n}\nvec4 CCFragOutput (vec4 color) {\n #if CC_USE_HDR\n color.rgb = mix(color.rgb, SRGBToLinear(color.rgb) * cc_exposure.w, vec3(cc_exposure.z));\n #endif\n return color;\n}\nin vec2 uv;\nin vec4 color;\nuniform sampler2D mainTexture;\nuniform FragConstants {\n vec4 tintColor;\n};\nvec4 add () {\n vec4 col = 2.0 * color * tintColor * texture(mainTexture, uv);\n return CCFragOutput(col);\n}\nvec4 multiply () {\n vec4 col;\n vec4 texColor = texture(mainTexture, uv);\n col.rgb = tintColor.rgb * texColor.rgb * color.rgb * vec3(2.0);\n col.a = (1.0 - texColor.a) * (tintColor.a * color.a * 2.0);\n return CCFragOutput(col);\n}\nout vec4 cc_FragColor;\nvoid main() { cc_FragColor = add(); }` }, "glsl1": { - "vert": `\nprecision mediump float;\nuniform highp mat4 cc_matView;\nuniform mat4 cc_matViewInv;\nuniform mat4 cc_matViewProj;\nuniform highp mat4 cc_matWorld;\nvec4 quaternionFromAxisAngle (float angle, vec3 axis){\n angle /= 2.;\n float s = sin(angle);\n vec4 res;\n res.xyz = s * axis;\n res.w = cos(angle);\n return res;\n}\nvec4 quaternionFromAxis (vec3 xAxis,vec3 yAxis,vec3 zAxis){\n mat3 m = mat3(xAxis,yAxis,zAxis);\n float trace = m[0][0] + m[1][1] + m[2][2];\n vec4 quat;\n if (trace > 0.) {\n float s = 0.5 / sqrt(trace + 1.0);\n quat.w = 0.25 / s;\n quat.x = (m[2][1] - m[1][2]) * s;\n quat.y = (m[0][2] - m[2][0]) * s;\n quat.z = (m[1][0] - m[0][1]) * s;\n } else if ((m[0][0] > m[1][1]) && (m[0][0] > m[2][2])) {\n float s = 2.0 * sqrt(1.0 + m[0][0] - m[1][1] - m[2][2]);\n quat.w = (m[2][1] - m[1][2]) / s;\n quat.x = 0.25 * s;\n quat.y = (m[0][1] + m[1][0]) / s;\n quat.z = (m[0][2] + m[2][0]) / s;\n } else if (m[1][1] > m[2][2]) {\n float s = 2.0 * sqrt(1.0 + m[1][1] - m[0][0] - m[2][2]);\n quat.w = (m[0][2] - m[2][0]) / s;\n quat.x = (m[0][1] + m[1][0]) / s;\n quat.y = 0.25 * s;\n quat.z = (m[1][2] + m[2][1]) / s;\n } else {\n float s = 2.0 * sqrt(1.0 + m[2][2] - m[0][0] - m[1][1]);\n quat.w = (m[1][0] - m[0][1]) / s;\n quat.x = (m[0][2] + m[2][0]) / s;\n quat.y = (m[1][2] + m[2][1]) / s;\n quat.z = 0.25 * s;\n }\n float len = quat.x * quat.x + quat.y * quat.y + quat.z * quat.z + quat.w * quat.w;\n if (len > 0.) {\n len = 1. / sqrt(len);\n quat.x = quat.x * len;\n quat.y = quat.y * len;\n quat.z = quat.z * len;\n quat.w = quat.w * len;\n }\n return quat;\n}\nvec4 quaternionFromEuler (vec3 angle){\n float x = angle.x / 2.;\n float y = angle.y / 2.;\n float z = angle.z / 2.;\n float sx = sin(x);\n float cx = cos(x);\n float sy = sin(y);\n float cy = cos(y);\n float sz = sin(z);\n float cz = cos(z);\n vec4 quat = vec4(0);\n quat.x = sx * cy * cz + cx * sy * sz;\n quat.y = cx * sy * cz + sx * cy * sz;\n quat.z = cx * cy * sz - sx * sy * cz;\n quat.w = cx * cy * cz - sx * sy * sz;\n return quat;\n}\nmat4 matrixFromRT (vec4 q, vec3 p){\n float x2 = q.x + q.x;\n float y2 = q.y + q.y;\n float z2 = q.z + q.z;\n float xx = q.x * x2;\n float xy = q.x * y2;\n float xz = q.x * z2;\n float yy = q.y * y2;\n float yz = q.y * z2;\n float zz = q.z * z2;\n float wx = q.w * x2;\n float wy = q.w * y2;\n float wz = q.w * z2;\n return mat4(\n 1. - (yy + zz), xy + wz, xz - wy, 0,\n xy - wz, 1. - (xx + zz), yz + wx, 0,\n xz + wy, yz - wx, 1. - (xx + yy), 0,\n p.x, p.y, p.z, 1\n );\n}\nmat4 matFromRTS (vec4 q, vec3 t, vec3 s){\n float x = q.x, y = q.y, z = q.z, w = q.w;\n float x2 = x + x;\n float y2 = y + y;\n float z2 = z + z;\n float xx = x * x2;\n float xy = x * y2;\n float xz = x * z2;\n float yy = y * y2;\n float yz = y * z2;\n float zz = z * z2;\n float wx = w * x2;\n float wy = w * y2;\n float wz = w * z2;\n float sx = s.x;\n float sy = s.y;\n float sz = s.z;\n return mat4((1. - (yy + zz)) * sx, (xy + wz) * sx, (xz - wy) * sx, 0,\n (xy - wz) * sy, (1. - (xx + zz)) * sy, (yz + wx) * sy, 0,\n (xz + wy) * sz, (yz - wx) * sz, (1. - (xx + yy)) * sz, 0,\n t.x, t.y, t.z, 1);\n}\nvoid scaleMatrix (inout mat4 m, float s){\n m[0].xyz *= s;\n m[1].xyz *= s;\n m[2].xyz *= s;\n}\nvec4 quatMultiply (vec4 a, vec4 b){\n vec4 quat;\n quat.x = a.x * b.w + a.w * b.x + a.y * b.z - a.z * b.y;\n quat.y = a.y * b.w + a.w * b.y + a.z * b.x - a.x * b.z;\n quat.z = a.z * b.w + a.w * b.z + a.x * b.y - a.y * b.x;\n quat.w = a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z;\n return quat;\n}\nvoid rotateVecFromQuat (inout vec3 v, vec4 q){\n float ix = q.w * v.x + q.y * v.z - q.z * v.y;\n float iy = q.w * v.y + q.z * v.x - q.x * v.z;\n float iz = q.w * v.z + q.x * v.y - q.y * v.x;\n float iw = -q.x * v.x - q.y * v.y - q.z * v.z;\n v.x = ix * q.w + iw * -q.x + iy * -q.z - iz * -q.y;\n v.y = iy * q.w + iw * -q.y + iz * -q.x - ix * -q.z;\n v.z = iz * q.w + iw * -q.z + ix * -q.y - iy * -q.x;\n}\nvec3 rotateVecFromAxis (vec3 v, vec3 axis, float theta){\n return cos(theta) * v + sin(theta) * cross(v, axis) + (1. - cos(theta)) * dot(v, axis) * axis;\n}\nvec3 rotateInLocalSpace (vec3 pos, vec3 xAxis, vec3 yAxis, vec3 zAxis, vec4 q){\n vec4 viewQuat = quaternionFromAxis(xAxis, yAxis, zAxis);\n vec4 rotQuat = quatMultiply(viewQuat, q);\n rotateVecFromQuat(pos, rotQuat);\n return pos;\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}\nvarying vec2 uv;\nvarying vec4 color;\nvoid computeVertPos (inout vec4 pos, vec2 vertOffset, vec4 q, vec3 s\n#if 1 || CC_USE_VERTICAL_BILLBOARD\n , mat4 viewInv\n#endif\n#if CC_USE_STRETCHED_BILLBOARD\n , vec3 eye\n , vec4 velocity\n , float velocityScale\n , float lengthScale\n , float xIndex\n#endif\n) {\n#if 1\n vec3 viewSpaceVert = vec3(vertOffset.x * s.x, vertOffset.y * s.y, 0.);\n vec3 camX = normalize(vec3(viewInv[0][0], viewInv[1][0], viewInv[2][0]));\n vec3 camY = normalize(vec3(viewInv[0][1], viewInv[1][1], viewInv[2][1]));\n vec3 camZ = normalize(vec3(viewInv[0][2], viewInv[1][2], viewInv[2][2]));\n pos.xyz += rotateInLocalSpace(viewSpaceVert, camX, camY, camZ, q);\n#elif CC_USE_STRETCHED_BILLBOARD\n vec3 camRight = normalize(cross(pos.xyz - eye, velocity.xyz)) * s.x;\n vec3 camUp = velocity.xyz * velocityScale + normalize(velocity.xyz) * lengthScale * s.y;\n pos.xyz += (camRight * abs(vertOffset.x) * sign(vertOffset.y)) - camUp * xIndex;\n#elif CC_USE_HORIZONTAL_BILLBOARD\n vec3 viewSpaceVert = vec3(vertOffset.x * s.x, vertOffset.y * s.y, 0.);\n vec3 camX = vec3(1, 0, 0);\n vec3 camY = vec3(0, 0, -1);\n pos.xyz += rotateInLocalSpace(viewSpaceVert, camX, camY, cross(camX, camY), q);\n#elif CC_USE_VERTICAL_BILLBOARD\n vec2 viewSpaceVert = vec2(vertOffset.x * s.x, vertOffset.y * s.y);\n rotateCorner(viewSpaceVert, q.z);\n vec3 camX = normalize(vec3(cc_matView[0][0], cc_matView[1][0], cc_matView[2][0]));\n vec3 camY = vec3(0, 1, 0);\n vec3 offset = camX * viewSpaceVert.x + camY * viewSpaceVert.y;\n pos.xyz += offset;\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#if !CC_USE_MESH\n vertIndex.y = 1. - vertIndex.y;\n#endif\n return (aniUV.xy + vertIndex) / vec2(frameTile.x, frameTile.y);\n}\nattribute vec3 a_position;\nattribute vec2 a_texCoord;\nattribute vec4 a_color;\nuniform vec4 cc_size_rotation;\nvec4 vs_main() {\n vec4 pos = vec4(a_position, 1);\n pos = cc_matWorld * pos;\n vec2 vertOffset = a_texCoord.xy - 0.5;\n computeVertPos(pos, vertOffset, quaternionFromEuler(0., 0., cc_size_rotation.z), vec3(cc_size_rotation.xy, 0.), cc_matViewInv);\n pos = cc_matViewProj * pos;\n uv = a_texCoord.xy;\n color = a_color;\n return pos;\n}\nvoid main() { gl_Position = vs_main(); }`, - "frag": `\nprecision mediump float;\nuniform vec4 cc_exposure;\nvec3 SRGBToLinear (vec3 gamma) {\n return gamma * gamma;\n}\nvec4 CCFragOutput (vec4 color) {\n #if CC_USE_HDR\n color.rgb = mix(color.rgb, SRGBToLinear(color.rgb) * cc_exposure.w, vec3(cc_exposure.z));\n #endif\n return color;\n}\nvarying vec2 uv;\nvarying vec4 color;\nuniform sampler2D mainTexture;\nuniform vec4 tintColor;\nvec4 add () {\n vec4 col = 2.0 * color * tintColor * texture2D(mainTexture, uv);\n return CCFragOutput(col);\n}\nvec4 multiply () {\n vec4 col;\n vec4 texColor = texture2D(mainTexture, uv);\n col.rgb = tintColor.rgb * texColor.rgb * color.rgb * vec3(2.0);\n col.a = (1.0 - texColor.a) * (tintColor.a * color.a * 2.0);\n return CCFragOutput(col);\n}\nvoid main() { gl_FragColor = add(); }` + "vert": `\nprecision mediump float;\nuniform highp mat4 cc_matView;\nuniform mat4 cc_matViewInv;\nuniform mat4 cc_matViewProj;\nuniform highp mat4 cc_matWorld;\nvec4 quaternionFromAxis (vec3 xAxis,vec3 yAxis,vec3 zAxis){\n mat3 m = mat3(xAxis,yAxis,zAxis);\n float trace = m[0][0] + m[1][1] + m[2][2];\n vec4 quat;\n if (trace > 0.) {\n float s = 0.5 / sqrt(trace + 1.0);\n quat.w = 0.25 / s;\n quat.x = (m[2][1] - m[1][2]) * s;\n quat.y = (m[0][2] - m[2][0]) * s;\n quat.z = (m[1][0] - m[0][1]) * s;\n } else if ((m[0][0] > m[1][1]) && (m[0][0] > m[2][2])) {\n float s = 2.0 * sqrt(1.0 + m[0][0] - m[1][1] - m[2][2]);\n quat.w = (m[2][1] - m[1][2]) / s;\n quat.x = 0.25 * s;\n quat.y = (m[0][1] + m[1][0]) / s;\n quat.z = (m[0][2] + m[2][0]) / s;\n } else if (m[1][1] > m[2][2]) {\n float s = 2.0 * sqrt(1.0 + m[1][1] - m[0][0] - m[2][2]);\n quat.w = (m[0][2] - m[2][0]) / s;\n quat.x = (m[0][1] + m[1][0]) / s;\n quat.y = 0.25 * s;\n quat.z = (m[1][2] + m[2][1]) / s;\n } else {\n float s = 2.0 * sqrt(1.0 + m[2][2] - m[0][0] - m[1][1]);\n quat.w = (m[1][0] - m[0][1]) / s;\n quat.x = (m[0][2] + m[2][0]) / s;\n quat.y = (m[1][2] + m[2][1]) / s;\n quat.z = 0.25 * s;\n }\n float len = quat.x * quat.x + quat.y * quat.y + quat.z * quat.z + quat.w * quat.w;\n if (len > 0.) {\n len = 1. / sqrt(len);\n quat.x = quat.x * len;\n quat.y = quat.y * len;\n quat.z = quat.z * len;\n quat.w = quat.w * len;\n }\n return quat;\n}\nvec4 quaternionFromEuler (vec3 angle){\n float x = angle.x / 2.;\n float y = angle.y / 2.;\n float z = angle.z / 2.;\n float sx = sin(x);\n float cx = cos(x);\n float sy = sin(y);\n float cy = cos(y);\n float sz = sin(z);\n float cz = cos(z);\n vec4 quat = vec4(0);\n quat.x = sx * cy * cz + cx * sy * sz;\n quat.y = cx * sy * cz + sx * cy * sz;\n quat.z = cx * cy * sz - sx * sy * cz;\n quat.w = cx * cy * cz - sx * sy * sz;\n return quat;\n}\nvec4 quatMultiply (vec4 a, vec4 b){\n vec4 quat;\n quat.x = a.x * b.w + a.w * b.x + a.y * b.z - a.z * b.y;\n quat.y = a.y * b.w + a.w * b.y + a.z * b.x - a.x * b.z;\n quat.z = a.z * b.w + a.w * b.z + a.x * b.y - a.y * b.x;\n quat.w = a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z;\n return quat;\n}\nvoid rotateVecFromQuat (inout vec3 v, vec4 q){\n float ix = q.w * v.x + q.y * v.z - q.z * v.y;\n float iy = q.w * v.y + q.z * v.x - q.x * v.z;\n float iz = q.w * v.z + q.x * v.y - q.y * v.x;\n float iw = -q.x * v.x - q.y * v.y - q.z * v.z;\n v.x = ix * q.w + iw * -q.x + iy * -q.z - iz * -q.y;\n v.y = iy * q.w + iw * -q.y + iz * -q.x - ix * -q.z;\n v.z = iz * q.w + iw * -q.z + ix * -q.y - iy * -q.x;\n}\nvec3 rotateInLocalSpace (vec3 pos, vec3 xAxis, vec3 yAxis, vec3 zAxis, vec4 q){\n vec4 viewQuat = quaternionFromAxis(xAxis, yAxis, zAxis);\n vec4 rotQuat = quatMultiply(viewQuat, q);\n rotateVecFromQuat(pos, rotQuat);\n return pos;\n}\nvarying vec2 uv;\nvarying vec4 color;\nvoid computeVertPos (inout vec4 pos, vec2 vertOffset, vec4 q, vec3 s\n , mat4 viewInv\n) {\n vec3 viewSpaceVert = vec3(vertOffset.x * s.x, vertOffset.y * s.y, 0.);\n vec3 camX = normalize(vec3(viewInv[0][0], viewInv[1][0], viewInv[2][0]));\n vec3 camY = normalize(vec3(viewInv[0][1], viewInv[1][1], viewInv[2][1]));\n vec3 camZ = normalize(vec3(viewInv[0][2], viewInv[1][2], viewInv[2][2]));\n pos.xyz += rotateInLocalSpace(viewSpaceVert, camX, camY, camZ, q);\n}\nattribute vec3 a_position;\nattribute vec2 a_texCoord;\nattribute vec4 a_color;\nuniform vec4 cc_size_rotation;\nvec4 vs_main() {\n vec4 pos = vec4(a_position, 1);\n pos = cc_matWorld * pos;\n vec2 vertOffset = a_texCoord.xy - 0.5;\n computeVertPos(pos, vertOffset, quaternionFromEuler(vec3(0., 0., cc_size_rotation.z)), vec3(cc_size_rotation.xy, 0.), cc_matViewInv);\n pos = cc_matViewProj * pos;\n uv = a_texCoord.xy;\n color = a_color;\n return pos;\n}\nvoid main() { gl_Position = vs_main(); }`, + "frag": `\nprecision mediump float;\nuniform vec4 cc_exposure;\nvec3 SRGBToLinear (vec3 gamma) {\n return gamma * gamma;\n}\nvec4 CCFragOutput (vec4 color) {\n #if CC_USE_HDR\n color.rgb = mix(color.rgb, SRGBToLinear(color.rgb) * cc_exposure.w, vec3(cc_exposure.z));\n #endif\n return color;\n}\nvarying vec2 uv;\nvarying vec4 color;\nuniform sampler2D mainTexture;\nuniform vec4 tintColor;\nvec4 add () {\n vec4 col = 2.0 * color * tintColor * texture2D(mainTexture, uv);\n return CCFragOutput(col);\n}\nvoid main() { gl_FragColor = add(); }` }, "builtins": {"globals":{"blocks":[{"name":"CCGlobal", "defines":[]}], "samplers":[]}, "locals":{"blocks":[{"name":"CCLocal", "defines":[]}], "samplers":[]}}, "defines": [ - {"name":"CC_USE_STRETCHED_BILLBOARD", "type":"boolean"}, - {"name":"CC_USE_HORIZONTAL_BILLBOARD", "type":"boolean"}, - {"name":"CC_USE_VERTICAL_BILLBOARD", "type":"boolean"}, - {"name":"CC_USE_MESH", "type":"boolean"}, {"name":"CC_USE_HDR", "type":"boolean"} ], "blocks": [ @@ -59,8 +55,8 @@ export default [ "frag": `\n precision mediump float;\nuniform CCGlobal {\n vec4 cc_time;\n vec4 cc_screenSize;\n vec4 cc_screenScale;\n vec4 cc_nativeSize;\n highp mat4 cc_matView;\n mat4 cc_matViewInv;\n mat4 cc_matProj;\n mat4 cc_matProjInv;\n mat4 cc_matViewProj;\n mat4 cc_matViewProjInv;\n vec4 cc_cameraPos;\n vec4 cc_exposure;\n vec4 cc_mainLitDir;\n vec4 cc_mainLitColor;\n vec4 cc_ambientSky;\n vec4 cc_ambientGround;\n};\nvec3 SRGBToLinear (vec3 gamma) {\n return gamma * gamma;\n}\nvec4 CCFragOutput (vec4 color) {\n #if CC_USE_HDR\n color.rgb = mix(color.rgb, SRGBToLinear(color.rgb) * cc_exposure.w, vec3(cc_exposure.z));\n #endif\n return color;\n}\n in vec2 uv;\n in vec4 color;\n #if CC_DRAW_WIRE_FRAME\n in vec3 vBarycentric;\n #endif\n uniform sampler2D mainTexture;\n uniform FragConstants {\n vec4 tintColor;\n };\n vec4 add () {\n vec4 col = 2.0 * color * tintColor * texture(mainTexture, uv);\n#if CC_DRAW_WIRE_FRAME\n if (any(lessThan(vBarycentric, vec3(0.02)))) {\n col = vec4(0., 1., 1., 1.);\n }\n#endif\n return CCFragOutput(col);\n }\n vec4 multiply () {\n vec4 col;\n vec4 texColor = texture(mainTexture, uv);\n col.rgb = tintColor.rgb * texColor.rgb * color.rgb * vec3(2.0);\n col.a = (1.0 - texColor.a) * (tintColor.a * color.a * 2.0);\n#if CC_DRAW_WIRE_FRAME\n if (any(lessThan(vBarycentric, vec3(0.02)))) {\n col = vec4(0., 1., 1., col.a);\n }\n#endif\n return CCFragOutput(col);\n }\nout vec4 cc_FragColor;\nvoid main() { cc_FragColor = add(); }` }, "glsl1": { - "vert": `\nprecision mediump float;\nuniform vec4 mainTiling_Offset;\nuniform highp mat4 cc_matView;\nuniform mat4 cc_matViewProj;\nuniform vec4 cc_cameraPos;\nuniform highp mat4 cc_matWorld;\nvec4 quaternionFromAxisAngle (float angle, vec3 axis){\n angle /= 2.;\n float s = sin(angle);\n vec4 res;\n res.xyz = s * axis;\n res.w = cos(angle);\n return res;\n}\nvec4 quaternionFromAxis (vec3 xAxis,vec3 yAxis,vec3 zAxis){\n mat3 m = mat3(xAxis,yAxis,zAxis);\n float trace = m[0][0] + m[1][1] + m[2][2];\n vec4 quat;\n if (trace > 0.) {\n float s = 0.5 / sqrt(trace + 1.0);\n quat.w = 0.25 / s;\n quat.x = (m[2][1] - m[1][2]) * s;\n quat.y = (m[0][2] - m[2][0]) * s;\n quat.z = (m[1][0] - m[0][1]) * s;\n } else if ((m[0][0] > m[1][1]) && (m[0][0] > m[2][2])) {\n float s = 2.0 * sqrt(1.0 + m[0][0] - m[1][1] - m[2][2]);\n quat.w = (m[2][1] - m[1][2]) / s;\n quat.x = 0.25 * s;\n quat.y = (m[0][1] + m[1][0]) / s;\n quat.z = (m[0][2] + m[2][0]) / s;\n } else if (m[1][1] > m[2][2]) {\n float s = 2.0 * sqrt(1.0 + m[1][1] - m[0][0] - m[2][2]);\n quat.w = (m[0][2] - m[2][0]) / s;\n quat.x = (m[0][1] + m[1][0]) / s;\n quat.y = 0.25 * s;\n quat.z = (m[1][2] + m[2][1]) / s;\n } else {\n float s = 2.0 * sqrt(1.0 + m[2][2] - m[0][0] - m[1][1]);\n quat.w = (m[1][0] - m[0][1]) / s;\n quat.x = (m[0][2] + m[2][0]) / s;\n quat.y = (m[1][2] + m[2][1]) / s;\n quat.z = 0.25 * s;\n }\n float len = quat.x * quat.x + quat.y * quat.y + quat.z * quat.z + quat.w * quat.w;\n if (len > 0.) {\n len = 1. / sqrt(len);\n quat.x = quat.x * len;\n quat.y = quat.y * len;\n quat.z = quat.z * len;\n quat.w = quat.w * len;\n }\n return quat;\n}\nvec4 quaternionFromEuler (vec3 angle){\n float x = angle.x / 2.;\n float y = angle.y / 2.;\n float z = angle.z / 2.;\n float sx = sin(x);\n float cx = cos(x);\n float sy = sin(y);\n float cy = cos(y);\n float sz = sin(z);\n float cz = cos(z);\n vec4 quat = vec4(0);\n quat.x = sx * cy * cz + cx * sy * sz;\n quat.y = cx * sy * cz + sx * cy * sz;\n quat.z = cx * cy * sz - sx * sy * cz;\n quat.w = cx * cy * cz - sx * sy * sz;\n return quat;\n}\nmat4 matrixFromRT (vec4 q, vec3 p){\n float x2 = q.x + q.x;\n float y2 = q.y + q.y;\n float z2 = q.z + q.z;\n float xx = q.x * x2;\n float xy = q.x * y2;\n float xz = q.x * z2;\n float yy = q.y * y2;\n float yz = q.y * z2;\n float zz = q.z * z2;\n float wx = q.w * x2;\n float wy = q.w * y2;\n float wz = q.w * z2;\n return mat4(\n 1. - (yy + zz), xy + wz, xz - wy, 0,\n xy - wz, 1. - (xx + zz), yz + wx, 0,\n xz + wy, yz - wx, 1. - (xx + yy), 0,\n p.x, p.y, p.z, 1\n );\n}\nmat4 matFromRTS (vec4 q, vec3 t, vec3 s){\n float x = q.x, y = q.y, z = q.z, w = q.w;\n float x2 = x + x;\n float y2 = y + y;\n float z2 = z + z;\n float xx = x * x2;\n float xy = x * y2;\n float xz = x * z2;\n float yy = y * y2;\n float yz = y * z2;\n float zz = z * z2;\n float wx = w * x2;\n float wy = w * y2;\n float wz = w * z2;\n float sx = s.x;\n float sy = s.y;\n float sz = s.z;\n return mat4((1. - (yy + zz)) * sx, (xy + wz) * sx, (xz - wy) * sx, 0,\n (xy - wz) * sy, (1. - (xx + zz)) * sy, (yz + wx) * sy, 0,\n (xz + wy) * sz, (yz - wx) * sz, (1. - (xx + yy)) * sz, 0,\n t.x, t.y, t.z, 1);\n}\nvoid scaleMatrix (inout mat4 m, float s){\n m[0].xyz *= s;\n m[1].xyz *= s;\n m[2].xyz *= s;\n}\nvec4 quatMultiply (vec4 a, vec4 b){\n vec4 quat;\n quat.x = a.x * b.w + a.w * b.x + a.y * b.z - a.z * b.y;\n quat.y = a.y * b.w + a.w * b.y + a.z * b.x - a.x * b.z;\n quat.z = a.z * b.w + a.w * b.z + a.x * b.y - a.y * b.x;\n quat.w = a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z;\n return quat;\n}\nvoid rotateVecFromQuat (inout vec3 v, vec4 q){\n float ix = q.w * v.x + q.y * v.z - q.z * v.y;\n float iy = q.w * v.y + q.z * v.x - q.x * v.z;\n float iz = q.w * v.z + q.x * v.y - q.y * v.x;\n float iw = -q.x * v.x - q.y * v.y - q.z * v.z;\n v.x = ix * q.w + iw * -q.x + iy * -q.z - iz * -q.y;\n v.y = iy * q.w + iw * -q.y + iz * -q.x - ix * -q.z;\n v.z = iz * q.w + iw * -q.z + ix * -q.y - iy * -q.x;\n}\nvec3 rotateVecFromAxis (vec3 v, vec3 axis, float theta){\n return cos(theta) * v + sin(theta) * cross(v, axis) + (1. - cos(theta)) * dot(v, axis) * axis;\n}\nvec3 rotateInLocalSpace (vec3 pos, vec3 xAxis, vec3 yAxis, vec3 zAxis, vec4 q){\n vec4 viewQuat = quaternionFromAxis(xAxis, yAxis, zAxis);\n vec4 rotQuat = quatMultiply(viewQuat, q);\n rotateVecFromQuat(pos, rotQuat);\n return pos;\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}\nvarying vec2 uv;\nvarying vec4 color;\nvoid computeVertPos (inout vec4 pos, vec2 vertOffset, vec4 q, vec3 s\n#if CC_USE_BILLBOARD || CC_USE_VERTICAL_BILLBOARD\n , mat4 viewInv\n#endif\n#if CC_USE_STRETCHED_BILLBOARD\n , vec3 eye\n , vec4 velocity\n , float velocityScale\n , float lengthScale\n , float xIndex\n#endif\n) {\n#if CC_USE_BILLBOARD\n vec3 viewSpaceVert = vec3(vertOffset.x * s.x, vertOffset.y * s.y, 0.);\n vec3 camX = normalize(vec3(viewInv[0][0], viewInv[1][0], viewInv[2][0]));\n vec3 camY = normalize(vec3(viewInv[0][1], viewInv[1][1], viewInv[2][1]));\n vec3 camZ = normalize(vec3(viewInv[0][2], viewInv[1][2], viewInv[2][2]));\n pos.xyz += rotateInLocalSpace(viewSpaceVert, camX, camY, camZ, q);\n#elif CC_USE_STRETCHED_BILLBOARD\n vec3 camRight = normalize(cross(pos.xyz - eye, velocity.xyz)) * s.x;\n vec3 camUp = velocity.xyz * velocityScale + normalize(velocity.xyz) * lengthScale * s.y;\n pos.xyz += (camRight * abs(vertOffset.x) * sign(vertOffset.y)) - camUp * xIndex;\n#elif CC_USE_HORIZONTAL_BILLBOARD\n vec3 viewSpaceVert = vec3(vertOffset.x * s.x, vertOffset.y * s.y, 0.);\n vec3 camX = vec3(1, 0, 0);\n vec3 camY = vec3(0, 0, -1);\n pos.xyz += rotateInLocalSpace(viewSpaceVert, camX, camY, cross(camX, camY), q);\n#elif CC_USE_VERTICAL_BILLBOARD\n vec2 viewSpaceVert = vec2(vertOffset.x * s.x, vertOffset.y * s.y);\n rotateCorner(viewSpaceVert, q.z);\n vec3 camX = normalize(vec3(cc_matView[0][0], cc_matView[1][0], cc_matView[2][0]));\n vec3 camY = vec3(0, 1, 0);\n vec3 offset = camX * viewSpaceVert.x + camY * viewSpaceVert.y;\n pos.xyz += offset;\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#if !CC_USE_MESH\n vertIndex.y = 1. - vertIndex.y;\n#endif\n return (aniUV.xy + vertIndex) / vec2(frameTile.x, frameTile.y);\n}\nattribute vec3 a_position;\nattribute vec4 a_texCoord;\nattribute vec3 a_texCoord1;\nattribute vec3 a_texCoord2;\nattribute vec4 a_color;\n#if CC_DRAW_WIRE_FRAME\n varying vec3 vBarycentric;\n#endif\nvec4 vs_main() {\n highp vec4 pos = vec4(a_position, 1);\n vec4 velocity = vec4(a_texCoord1.xyz, 0);\n #if !CC_USE_WORLD_SPACE\n pos = cc_matWorld * pos;\n velocity = cc_matWorld * velocity;\n #endif\n float vertOffset = (a_texCoord.x - 0.5) * a_texCoord.y;\n vec3 camUp = normalize(cross(pos.xyz - cc_cameraPos.xyz, velocity.xyz));\n pos.xyz += camUp * vertOffset;\n pos = cc_matViewProj * pos;\n uv = a_texCoord.zw * mainTiling_Offset.xy + mainTiling_Offset.zw;;\n color = a_color;\n #if CC_DRAW_WIRE_FRAME\n vBarycentric = a_texCoord2;\n #endif\n return pos;\n}\nvoid main() { gl_Position = vs_main(); }`, - "frag": `\n precision mediump float;\nuniform vec4 cc_exposure;\nvec3 SRGBToLinear (vec3 gamma) {\n return gamma * gamma;\n}\nvec4 CCFragOutput (vec4 color) {\n #if CC_USE_HDR\n color.rgb = mix(color.rgb, SRGBToLinear(color.rgb) * cc_exposure.w, vec3(cc_exposure.z));\n #endif\n return color;\n}\n varying vec2 uv;\n varying vec4 color;\n #if CC_DRAW_WIRE_FRAME\n varying vec3 vBarycentric;\n #endif\n uniform sampler2D mainTexture;\n uniform vec4 tintColor;\n vec4 add () {\n vec4 col = 2.0 * color * tintColor * texture2D(mainTexture, uv);\n#if CC_DRAW_WIRE_FRAME\n if (any(lessThan(vBarycentric, vec3(0.02)))) {\n col = vec4(0., 1., 1., 1.);\n }\n#endif\n return CCFragOutput(col);\n }\n vec4 multiply () {\n vec4 col;\n vec4 texColor = texture2D(mainTexture, uv);\n col.rgb = tintColor.rgb * texColor.rgb * color.rgb * vec3(2.0);\n col.a = (1.0 - texColor.a) * (tintColor.a * color.a * 2.0);\n#if CC_DRAW_WIRE_FRAME\n if (any(lessThan(vBarycentric, vec3(0.02)))) {\n col = vec4(0., 1., 1., col.a);\n }\n#endif\n return CCFragOutput(col);\n }\nvoid main() { gl_FragColor = add(); }` + "vert": `\nprecision mediump float;\nuniform vec4 mainTiling_Offset;\nuniform highp mat4 cc_matView;\nuniform mat4 cc_matViewProj;\nuniform vec4 cc_cameraPos;\nuniform highp mat4 cc_matWorld;\nvec4 quaternionFromAxis (vec3 xAxis,vec3 yAxis,vec3 zAxis){\n mat3 m = mat3(xAxis,yAxis,zAxis);\n float trace = m[0][0] + m[1][1] + m[2][2];\n vec4 quat;\n if (trace > 0.) {\n float s = 0.5 / sqrt(trace + 1.0);\n quat.w = 0.25 / s;\n quat.x = (m[2][1] - m[1][2]) * s;\n quat.y = (m[0][2] - m[2][0]) * s;\n quat.z = (m[1][0] - m[0][1]) * s;\n } else if ((m[0][0] > m[1][1]) && (m[0][0] > m[2][2])) {\n float s = 2.0 * sqrt(1.0 + m[0][0] - m[1][1] - m[2][2]);\n quat.w = (m[2][1] - m[1][2]) / s;\n quat.x = 0.25 * s;\n quat.y = (m[0][1] + m[1][0]) / s;\n quat.z = (m[0][2] + m[2][0]) / s;\n } else if (m[1][1] > m[2][2]) {\n float s = 2.0 * sqrt(1.0 + m[1][1] - m[0][0] - m[2][2]);\n quat.w = (m[0][2] - m[2][0]) / s;\n quat.x = (m[0][1] + m[1][0]) / s;\n quat.y = 0.25 * s;\n quat.z = (m[1][2] + m[2][1]) / s;\n } else {\n float s = 2.0 * sqrt(1.0 + m[2][2] - m[0][0] - m[1][1]);\n quat.w = (m[1][0] - m[0][1]) / s;\n quat.x = (m[0][2] + m[2][0]) / s;\n quat.y = (m[1][2] + m[2][1]) / s;\n quat.z = 0.25 * s;\n }\n float len = quat.x * quat.x + quat.y * quat.y + quat.z * quat.z + quat.w * quat.w;\n if (len > 0.) {\n len = 1. / sqrt(len);\n quat.x = quat.x * len;\n quat.y = quat.y * len;\n quat.z = quat.z * len;\n quat.w = quat.w * len;\n }\n return quat;\n}\nvec4 quatMultiply (vec4 a, vec4 b){\n vec4 quat;\n quat.x = a.x * b.w + a.w * b.x + a.y * b.z - a.z * b.y;\n quat.y = a.y * b.w + a.w * b.y + a.z * b.x - a.x * b.z;\n quat.z = a.z * b.w + a.w * b.z + a.x * b.y - a.y * b.x;\n quat.w = a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z;\n return quat;\n}\nvoid rotateVecFromQuat (inout vec3 v, vec4 q){\n float ix = q.w * v.x + q.y * v.z - q.z * v.y;\n float iy = q.w * v.y + q.z * v.x - q.x * v.z;\n float iz = q.w * v.z + q.x * v.y - q.y * v.x;\n float iw = -q.x * v.x - q.y * v.y - q.z * v.z;\n v.x = ix * q.w + iw * -q.x + iy * -q.z - iz * -q.y;\n v.y = iy * q.w + iw * -q.y + iz * -q.x - ix * -q.z;\n v.z = iz * q.w + iw * -q.z + ix * -q.y - iy * -q.x;\n}\nvec3 rotateInLocalSpace (vec3 pos, vec3 xAxis, vec3 yAxis, vec3 zAxis, vec4 q){\n vec4 viewQuat = quaternionFromAxis(xAxis, yAxis, zAxis);\n vec4 rotQuat = quatMultiply(viewQuat, q);\n rotateVecFromQuat(pos, rotQuat);\n return pos;\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}\nvarying vec2 uv;\nvarying vec4 color;\nattribute vec3 a_position;\nattribute vec4 a_texCoord;\nattribute vec3 a_texCoord1;\nattribute vec3 a_texCoord2;\nattribute vec4 a_color;\n#if CC_DRAW_WIRE_FRAME\n varying vec3 vBarycentric;\n#endif\nvec4 vs_main() {\n highp vec4 pos = vec4(a_position, 1);\n vec4 velocity = vec4(a_texCoord1.xyz, 0);\n #if !CC_USE_WORLD_SPACE\n pos = cc_matWorld * pos;\n velocity = cc_matWorld * velocity;\n #endif\n float vertOffset = (a_texCoord.x - 0.5) * a_texCoord.y;\n vec3 camUp = normalize(cross(pos.xyz - cc_cameraPos.xyz, velocity.xyz));\n pos.xyz += camUp * vertOffset;\n pos = cc_matViewProj * pos;\n uv = a_texCoord.zw * mainTiling_Offset.xy + mainTiling_Offset.zw;;\n color = a_color;\n #if CC_DRAW_WIRE_FRAME\n vBarycentric = a_texCoord2;\n #endif\n return pos;\n}\nvoid main() { gl_Position = vs_main(); }`, + "frag": `\n precision mediump float;\nuniform vec4 cc_exposure;\nvec3 SRGBToLinear (vec3 gamma) {\n return gamma * gamma;\n}\nvec4 CCFragOutput (vec4 color) {\n #if CC_USE_HDR\n color.rgb = mix(color.rgb, SRGBToLinear(color.rgb) * cc_exposure.w, vec3(cc_exposure.z));\n #endif\n return color;\n}\n varying vec2 uv;\n varying vec4 color;\n #if CC_DRAW_WIRE_FRAME\n varying vec3 vBarycentric;\n #endif\n uniform sampler2D mainTexture;\n uniform vec4 tintColor;\n vec4 add () {\n vec4 col = 2.0 * color * tintColor * texture2D(mainTexture, uv);\n#if CC_DRAW_WIRE_FRAME\n if (any(lessThan(vBarycentric, vec3(0.02)))) {\n col = vec4(0., 1., 1., 1.);\n }\n#endif\n return CCFragOutput(col);\n }\nvoid main() { gl_FragColor = add(); }` }, "builtins": {"globals":{"blocks":[{"name":"CCGlobal", "defines":[]}], "samplers":[]}, "locals":{"blocks":[{"name":"CCLocal", "defines":[]}], "samplers":[]}}, "defines": [ @@ -97,14 +93,14 @@ export default [ "shaders": [ { "name": "builtin-particle|particle-vs-legacy:lpvs_main|tinted-fs:add", - "hash": 1910301377, + "hash": 2210001251, "glsl3": { - "vert": `\nprecision highp float;\nvec4 quaternionFromAxisAngle (float angle, vec3 axis){\n angle /= 2.;\n float s = sin(angle);\n vec4 res;\n res.xyz = s * axis;\n res.w = cos(angle);\n return res;\n}\nvec4 quaternionFromAxis (vec3 xAxis,vec3 yAxis,vec3 zAxis){\n mat3 m = mat3(xAxis,yAxis,zAxis);\n float trace = m[0][0] + m[1][1] + m[2][2];\n vec4 quat;\n if (trace > 0.) {\n float s = 0.5 / sqrt(trace + 1.0);\n quat.w = 0.25 / s;\n quat.x = (m[2][1] - m[1][2]) * s;\n quat.y = (m[0][2] - m[2][0]) * s;\n quat.z = (m[1][0] - m[0][1]) * s;\n } else if ((m[0][0] > m[1][1]) && (m[0][0] > m[2][2])) {\n float s = 2.0 * sqrt(1.0 + m[0][0] - m[1][1] - m[2][2]);\n quat.w = (m[2][1] - m[1][2]) / s;\n quat.x = 0.25 * s;\n quat.y = (m[0][1] + m[1][0]) / s;\n quat.z = (m[0][2] + m[2][0]) / s;\n } else if (m[1][1] > m[2][2]) {\n float s = 2.0 * sqrt(1.0 + m[1][1] - m[0][0] - m[2][2]);\n quat.w = (m[0][2] - m[2][0]) / s;\n quat.x = (m[0][1] + m[1][0]) / s;\n quat.y = 0.25 * s;\n quat.z = (m[1][2] + m[2][1]) / s;\n } else {\n float s = 2.0 * sqrt(1.0 + m[2][2] - m[0][0] - m[1][1]);\n quat.w = (m[1][0] - m[0][1]) / s;\n quat.x = (m[0][2] + m[2][0]) / s;\n quat.y = (m[1][2] + m[2][1]) / s;\n quat.z = 0.25 * s;\n }\n float len = quat.x * quat.x + quat.y * quat.y + quat.z * quat.z + quat.w * quat.w;\n if (len > 0.) {\n len = 1. / sqrt(len);\n quat.x = quat.x * len;\n quat.y = quat.y * len;\n quat.z = quat.z * len;\n quat.w = quat.w * len;\n }\n return quat;\n}\nvec4 quaternionFromEuler (vec3 angle){\n float x = angle.x / 2.;\n float y = angle.y / 2.;\n float z = angle.z / 2.;\n float sx = sin(x);\n float cx = cos(x);\n float sy = sin(y);\n float cy = cos(y);\n float sz = sin(z);\n float cz = cos(z);\n vec4 quat = vec4(0);\n quat.x = sx * cy * cz + cx * sy * sz;\n quat.y = cx * sy * cz + sx * cy * sz;\n quat.z = cx * cy * sz - sx * sy * cz;\n quat.w = cx * cy * cz - sx * sy * sz;\n return quat;\n}\nmat4 matrixFromRT (vec4 q, vec3 p){\n float x2 = q.x + q.x;\n float y2 = q.y + q.y;\n float z2 = q.z + q.z;\n float xx = q.x * x2;\n float xy = q.x * y2;\n float xz = q.x * z2;\n float yy = q.y * y2;\n float yz = q.y * z2;\n float zz = q.z * z2;\n float wx = q.w * x2;\n float wy = q.w * y2;\n float wz = q.w * z2;\n return mat4(\n 1. - (yy + zz), xy + wz, xz - wy, 0,\n xy - wz, 1. - (xx + zz), yz + wx, 0,\n xz + wy, yz - wx, 1. - (xx + yy), 0,\n p.x, p.y, p.z, 1\n );\n}\nmat4 matFromRTS (vec4 q, vec3 t, vec3 s){\n float x = q.x, y = q.y, z = q.z, w = q.w;\n float x2 = x + x;\n float y2 = y + y;\n float z2 = z + z;\n float xx = x * x2;\n float xy = x * y2;\n float xz = x * z2;\n float yy = y * y2;\n float yz = y * z2;\n float zz = z * z2;\n float wx = w * x2;\n float wy = w * y2;\n float wz = w * z2;\n float sx = s.x;\n float sy = s.y;\n float sz = s.z;\n return mat4((1. - (yy + zz)) * sx, (xy + wz) * sx, (xz - wy) * sx, 0,\n (xy - wz) * sy, (1. - (xx + zz)) * sy, (yz + wx) * sy, 0,\n (xz + wy) * sz, (yz - wx) * sz, (1. - (xx + yy)) * sz, 0,\n t.x, t.y, t.z, 1);\n}\nvoid scaleMatrix (inout mat4 m, float s){\n m[0].xyz *= s;\n m[1].xyz *= s;\n m[2].xyz *= s;\n}\nvec4 quatMultiply (vec4 a, vec4 b){\n vec4 quat;\n quat.x = a.x * b.w + a.w * b.x + a.y * b.z - a.z * b.y;\n quat.y = a.y * b.w + a.w * b.y + a.z * b.x - a.x * b.z;\n quat.z = a.z * b.w + a.w * b.z + a.x * b.y - a.y * b.x;\n quat.w = a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z;\n return quat;\n}\nvoid rotateVecFromQuat (inout vec3 v, vec4 q){\n float ix = q.w * v.x + q.y * v.z - q.z * v.y;\n float iy = q.w * v.y + q.z * v.x - q.x * v.z;\n float iz = q.w * v.z + q.x * v.y - q.y * v.x;\n float iw = -q.x * v.x - q.y * v.y - q.z * v.z;\n v.x = ix * q.w + iw * -q.x + iy * -q.z - iz * -q.y;\n v.y = iy * q.w + iw * -q.y + iz * -q.x - ix * -q.z;\n v.z = iz * q.w + iw * -q.z + ix * -q.y - iy * -q.x;\n}\nvec3 rotateVecFromAxis (vec3 v, vec3 axis, float theta){\n return cos(theta) * v + sin(theta) * cross(v, axis) + (1. - cos(theta)) * dot(v, axis) * axis;\n}\nvec3 rotateInLocalSpace (vec3 pos, vec3 xAxis, vec3 yAxis, vec3 zAxis, vec4 q){\n vec4 viewQuat = quaternionFromAxis(xAxis, yAxis, zAxis);\n vec4 rotQuat = quatMultiply(viewQuat, q);\n rotateVecFromQuat(pos, rotQuat);\n return pos;\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}\nuniform Constants {\n vec4 mainTiling_Offset;\n vec4 frameTile_velLenScale;\n vec4 scale;\n};\nuniform CCGlobal {\n vec4 cc_time;\n vec4 cc_screenSize;\n vec4 cc_screenScale;\n vec4 cc_nativeSize;\n highp mat4 cc_matView;\n mat4 cc_matViewInv;\n mat4 cc_matProj;\n mat4 cc_matProjInv;\n mat4 cc_matViewProj;\n mat4 cc_matViewProjInv;\n vec4 cc_cameraPos;\n vec4 cc_exposure;\n vec4 cc_mainLitDir;\n vec4 cc_mainLitColor;\n vec4 cc_ambientSky;\n vec4 cc_ambientGround;\n};\nuniform CCLocal {\n highp mat4 cc_matWorld;\n highp mat4 cc_matWorldIT;\n};\nout vec2 uv;\nout vec4 color;\nvoid computeVertPos (inout vec4 pos, vec2 vertOffset, vec4 q, vec3 s\n#if CC_USE_BILLBOARD || CC_USE_VERTICAL_BILLBOARD\n , mat4 viewInv\n#endif\n#if CC_USE_STRETCHED_BILLBOARD\n , vec3 eye\n , vec4 velocity\n , float velocityScale\n , float lengthScale\n , float xIndex\n#endif\n) {\n#if CC_USE_BILLBOARD\n vec3 viewSpaceVert = vec3(vertOffset.x * s.x, vertOffset.y * s.y, 0.);\n vec3 camX = normalize(vec3(viewInv[0][0], viewInv[1][0], viewInv[2][0]));\n vec3 camY = normalize(vec3(viewInv[0][1], viewInv[1][1], viewInv[2][1]));\n vec3 camZ = normalize(vec3(viewInv[0][2], viewInv[1][2], viewInv[2][2]));\n pos.xyz += rotateInLocalSpace(viewSpaceVert, camX, camY, camZ, q);\n#elif CC_USE_STRETCHED_BILLBOARD\n vec3 camRight = normalize(cross(pos.xyz - eye, velocity.xyz)) * s.x;\n vec3 camUp = velocity.xyz * velocityScale + normalize(velocity.xyz) * lengthScale * s.y;\n pos.xyz += (camRight * abs(vertOffset.x) * sign(vertOffset.y)) - camUp * xIndex;\n#elif CC_USE_HORIZONTAL_BILLBOARD\n vec3 viewSpaceVert = vec3(vertOffset.x * s.x, vertOffset.y * s.y, 0.);\n vec3 camX = vec3(1, 0, 0);\n vec3 camY = vec3(0, 0, -1);\n pos.xyz += rotateInLocalSpace(viewSpaceVert, camX, camY, cross(camX, camY), q);\n#elif CC_USE_VERTICAL_BILLBOARD\n vec2 viewSpaceVert = vec2(vertOffset.x * s.x, vertOffset.y * s.y);\n rotateCorner(viewSpaceVert, q.z);\n vec3 camX = normalize(vec3(cc_matView[0][0], cc_matView[1][0], cc_matView[2][0]));\n vec3 camY = vec3(0, 1, 0);\n vec3 offset = camX * viewSpaceVert.x + camY * viewSpaceVert.y;\n pos.xyz += offset;\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#if !CC_USE_MESH\n vertIndex.y = 1. - vertIndex.y;\n#endif\n return (aniUV.xy + vertIndex) / vec2(frameTile.x, frameTile.y);\n}\nin vec3 a_position;\nin vec3 a_texCoord;\nin vec3 a_texCoord1;\nin vec3 a_texCoord2;\nin vec4 a_color;\n#if CC_USE_STRETCHED_BILLBOARD\n in vec3 a_color1;\n#endif\n#if CC_USE_MESH\n in vec3 a_texCoord3;\n in vec3 a_normal;\n in vec4 a_color1;\n#endif\nvec4 lpvs_main () {\n vec3 compScale = scale.xyz * a_texCoord1;\n vec4 pos = vec4(a_position, 1);\n #if CC_USE_STRETCHED_BILLBOARD\n vec4 velocity = vec4(a_color1.xyz, 0);\n #endif\n #if !CC_USE_WORLD_SPACE\n pos = cc_matWorld * pos;\n #if CC_USE_STRETCHED_BILLBOARD\n velocity = cc_matWorld * velocity;\n #endif\n #endif\n #if !CC_USE_MESH\n vec2 cornerOffset = vec2((a_texCoord.xy - 0.5));\n #if CC_USE_BILLBOARD\n vec3 rotEuler = a_texCoord2;\n #elif CC_USE_STRETCHED_BILLBOARD\n vec3 rotEuler = vec3(0.);\n #else\n vec3 rotEuler = vec3(0., 0., a_texCoord2.z);\n #endif\n computeVertPos(pos, cornerOffset, quaternionFromEuler(rotEuler), compScale\n #if CC_USE_BILLBOARD || CC_USE_VERTICAL_BILLBOARD\n , cc_matViewInv\n #endif\n #if CC_USE_STRETCHED_BILLBOARD\n , cc_cameraPos.xyz\n , velocity\n , frameTile_velLenScale.z\n , frameTile_velLenScale.w\n , a_texCoord.x\n #endif\n );\n color = a_color;\n #else\n mat4 xformNoScale = matrixFromRT(quaternionFromEuler(a_texCoord2), pos.xyz);\n mat4 xform = matFromRTS(quaternionFromEuler(a_texCoord2), pos.xyz, compScale);\n pos = xform * vec4(a_texCoord3, 1);\n vec4 normal = xformNoScale * vec4(a_normal, 0);\n color = a_color * a_color1;\n #endif\n uv = computeUV(a_texCoord.z, a_texCoord.xy, frameTile_velLenScale.xy) * mainTiling_Offset.xy + mainTiling_Offset.zw;\n pos = cc_matViewProj * pos;\n return pos;\n}\nvoid main() { gl_Position = lpvs_main(); }`, + "vert": `\nprecision highp float;\nvec4 quaternionFromAxisAngle (float angle, vec3 axis){\n angle /= 2.;\n float s = sin(angle);\n vec4 res;\n res.xyz = s * axis;\n res.w = cos(angle);\n return res;\n}\nvec4 quaternionFromAxis (vec3 xAxis,vec3 yAxis,vec3 zAxis){\n mat3 m = mat3(xAxis,yAxis,zAxis);\n float trace = m[0][0] + m[1][1] + m[2][2];\n vec4 quat;\n if (trace > 0.) {\n float s = 0.5 / sqrt(trace + 1.0);\n quat.w = 0.25 / s;\n quat.x = (m[2][1] - m[1][2]) * s;\n quat.y = (m[0][2] - m[2][0]) * s;\n quat.z = (m[1][0] - m[0][1]) * s;\n } else if ((m[0][0] > m[1][1]) && (m[0][0] > m[2][2])) {\n float s = 2.0 * sqrt(1.0 + m[0][0] - m[1][1] - m[2][2]);\n quat.w = (m[2][1] - m[1][2]) / s;\n quat.x = 0.25 * s;\n quat.y = (m[0][1] + m[1][0]) / s;\n quat.z = (m[0][2] + m[2][0]) / s;\n } else if (m[1][1] > m[2][2]) {\n float s = 2.0 * sqrt(1.0 + m[1][1] - m[0][0] - m[2][2]);\n quat.w = (m[0][2] - m[2][0]) / s;\n quat.x = (m[0][1] + m[1][0]) / s;\n quat.y = 0.25 * s;\n quat.z = (m[1][2] + m[2][1]) / s;\n } else {\n float s = 2.0 * sqrt(1.0 + m[2][2] - m[0][0] - m[1][1]);\n quat.w = (m[1][0] - m[0][1]) / s;\n quat.x = (m[0][2] + m[2][0]) / s;\n quat.y = (m[1][2] + m[2][1]) / s;\n quat.z = 0.25 * s;\n }\n float len = quat.x * quat.x + quat.y * quat.y + quat.z * quat.z + quat.w * quat.w;\n if (len > 0.) {\n len = 1. / sqrt(len);\n quat.x = quat.x * len;\n quat.y = quat.y * len;\n quat.z = quat.z * len;\n quat.w = quat.w * len;\n }\n return quat;\n}\nvec4 quaternionFromEuler (vec3 angle){\n float x = angle.x / 2.;\n float y = angle.y / 2.;\n float z = angle.z / 2.;\n float sx = sin(x);\n float cx = cos(x);\n float sy = sin(y);\n float cy = cos(y);\n float sz = sin(z);\n float cz = cos(z);\n vec4 quat = vec4(0);\n quat.x = sx * cy * cz + cx * sy * sz;\n quat.y = cx * sy * cz + sx * cy * sz;\n quat.z = cx * cy * sz - sx * sy * cz;\n quat.w = cx * cy * cz - sx * sy * sz;\n return quat;\n}\nmat4 matrixFromRT (vec4 q, vec3 p){\n float x2 = q.x + q.x;\n float y2 = q.y + q.y;\n float z2 = q.z + q.z;\n float xx = q.x * x2;\n float xy = q.x * y2;\n float xz = q.x * z2;\n float yy = q.y * y2;\n float yz = q.y * z2;\n float zz = q.z * z2;\n float wx = q.w * x2;\n float wy = q.w * y2;\n float wz = q.w * z2;\n return mat4(\n 1. - (yy + zz), xy + wz, xz - wy, 0,\n xy - wz, 1. - (xx + zz), yz + wx, 0,\n xz + wy, yz - wx, 1. - (xx + yy), 0,\n p.x, p.y, p.z, 1\n );\n}\nmat4 matFromRTS (vec4 q, vec3 t, vec3 s){\n float x = q.x, y = q.y, z = q.z, w = q.w;\n float x2 = x + x;\n float y2 = y + y;\n float z2 = z + z;\n float xx = x * x2;\n float xy = x * y2;\n float xz = x * z2;\n float yy = y * y2;\n float yz = y * z2;\n float zz = z * z2;\n float wx = w * x2;\n float wy = w * y2;\n float wz = w * z2;\n float sx = s.x;\n float sy = s.y;\n float sz = s.z;\n return mat4((1. - (yy + zz)) * sx, (xy + wz) * sx, (xz - wy) * sx, 0,\n (xy - wz) * sy, (1. - (xx + zz)) * sy, (yz + wx) * sy, 0,\n (xz + wy) * sz, (yz - wx) * sz, (1. - (xx + yy)) * sz, 0,\n t.x, t.y, t.z, 1);\n}\nvoid scaleMatrix (inout mat4 m, float s){\n m[0].xyz *= s;\n m[1].xyz *= s;\n m[2].xyz *= s;\n}\nvec4 quatMultiply (vec4 a, vec4 b){\n vec4 quat;\n quat.x = a.x * b.w + a.w * b.x + a.y * b.z - a.z * b.y;\n quat.y = a.y * b.w + a.w * b.y + a.z * b.x - a.x * b.z;\n quat.z = a.z * b.w + a.w * b.z + a.x * b.y - a.y * b.x;\n quat.w = a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z;\n return quat;\n}\nvoid rotateVecFromQuat (inout vec3 v, vec4 q){\n float ix = q.w * v.x + q.y * v.z - q.z * v.y;\n float iy = q.w * v.y + q.z * v.x - q.x * v.z;\n float iz = q.w * v.z + q.x * v.y - q.y * v.x;\n float iw = -q.x * v.x - q.y * v.y - q.z * v.z;\n v.x = ix * q.w + iw * -q.x + iy * -q.z - iz * -q.y;\n v.y = iy * q.w + iw * -q.y + iz * -q.x - ix * -q.z;\n v.z = iz * q.w + iw * -q.z + ix * -q.y - iy * -q.x;\n}\nvec3 rotateVecFromAxis (vec3 v, vec3 axis, float theta){\n return cos(theta) * v + sin(theta) * cross(v, axis) + (1. - cos(theta)) * dot(v, axis) * axis;\n}\nvec3 rotateInLocalSpace (vec3 pos, vec3 xAxis, vec3 yAxis, vec3 zAxis, vec4 q){\n vec4 viewQuat = quaternionFromAxis(xAxis, yAxis, zAxis);\n vec4 rotQuat = quatMultiply(viewQuat, q);\n rotateVecFromQuat(pos, rotQuat);\n return pos;\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}\nuniform Constants {\n vec4 mainTiling_Offset;\n vec4 frameTile_velLenScale;\n vec4 scale;\n};\nuniform CCGlobal {\n vec4 cc_time;\n vec4 cc_screenSize;\n vec4 cc_screenScale;\n vec4 cc_nativeSize;\n highp mat4 cc_matView;\n mat4 cc_matViewInv;\n mat4 cc_matProj;\n mat4 cc_matProjInv;\n mat4 cc_matViewProj;\n mat4 cc_matViewProjInv;\n vec4 cc_cameraPos;\n vec4 cc_exposure;\n vec4 cc_mainLitDir;\n vec4 cc_mainLitColor;\n vec4 cc_ambientSky;\n vec4 cc_ambientGround;\n};\nuniform CCLocal {\n highp mat4 cc_matWorld;\n highp mat4 cc_matWorldIT;\n};\nout vec2 uv;\nout vec4 color;\nvoid computeVertPos (inout vec4 pos, vec2 vertOffset, vec4 q, vec3 s\n#if CC_USE_BILLBOARD || CC_USE_VERTICAL_BILLBOARD\n , mat4 viewInv\n#endif\n#if CC_USE_STRETCHED_BILLBOARD\n , vec3 eye\n , vec4 velocity\n , float velocityScale\n , float lengthScale\n , float xIndex\n#endif\n) {\n#if CC_USE_BILLBOARD\n vec3 viewSpaceVert = vec3(vertOffset.x * s.x, vertOffset.y * s.y, 0.);\n vec3 camX = normalize(vec3(viewInv[0][0], viewInv[1][0], viewInv[2][0]));\n vec3 camY = normalize(vec3(viewInv[0][1], viewInv[1][1], viewInv[2][1]));\n vec3 camZ = normalize(vec3(viewInv[0][2], viewInv[1][2], viewInv[2][2]));\n pos.xyz += rotateInLocalSpace(viewSpaceVert, camX, camY, camZ, q);\n#elif CC_USE_STRETCHED_BILLBOARD\n vec3 camRight = normalize(cross(pos.xyz - eye, velocity.xyz)) * s.x;\n vec3 camUp = velocity.xyz * velocityScale + normalize(velocity.xyz) * lengthScale * s.y;\n pos.xyz += (camRight * abs(vertOffset.x) * sign(vertOffset.y)) - camUp * xIndex;\n#elif CC_USE_HORIZONTAL_BILLBOARD\n vec3 viewSpaceVert = vec3(vertOffset.x * s.x, vertOffset.y * s.y, 0.);\n vec3 camX = vec3(1, 0, 0);\n vec3 camY = vec3(0, 0, -1);\n pos.xyz += rotateInLocalSpace(viewSpaceVert, camX, camY, cross(camX, camY), q);\n#elif CC_USE_VERTICAL_BILLBOARD\n vec2 viewSpaceVert = vec2(vertOffset.x * s.x, vertOffset.y * s.y);\n rotateCorner(viewSpaceVert, q.z);\n vec3 camX = normalize(vec3(cc_matView[0][0], cc_matView[1][0], cc_matView[2][0]));\n vec3 camY = vec3(0, 1, 0);\n vec3 offset = camX * viewSpaceVert.x + camY * viewSpaceVert.y;\n pos.xyz += offset;\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#if !CC_USE_MESH\n vertIndex.y = 1. - vertIndex.y;\n#endif\n return (aniUV.xy + vertIndex) / vec2(frameTile.x, frameTile.y);\n}\nin vec3 a_position;\nin vec3 a_texCoord;\nin vec3 a_texCoord1;\nin vec3 a_texCoord2;\nin vec4 a_color;\n#if CC_USE_MESH\n in vec3 a_texCoord3;\n in vec3 a_normal;\n in vec4 a_color1;\n#elif CC_USE_STRETCHED_BILLBOARD\n in vec3 a_color1;\n#endif\nvec4 lpvs_main () {\n vec3 compScale = scale.xyz * a_texCoord1;\n vec4 pos = vec4(a_position, 1);\n #if CC_USE_STRETCHED_BILLBOARD\n vec4 velocity = vec4(a_color1.xyz, 0);\n #endif\n #if !CC_USE_WORLD_SPACE\n pos = cc_matWorld * pos;\n #if CC_USE_STRETCHED_BILLBOARD\n velocity = cc_matWorld * velocity;\n #endif\n #endif\n #if !CC_USE_MESH\n vec2 cornerOffset = vec2((a_texCoord.xy - 0.5));\n #if CC_USE_BILLBOARD\n vec3 rotEuler = a_texCoord2;\n #elif CC_USE_STRETCHED_BILLBOARD\n vec3 rotEuler = vec3(0.);\n #else\n vec3 rotEuler = vec3(0., 0., a_texCoord2.z);\n #endif\n computeVertPos(pos, cornerOffset, quaternionFromEuler(rotEuler), compScale\n #if CC_USE_BILLBOARD || CC_USE_VERTICAL_BILLBOARD\n , cc_matViewInv\n #endif\n #if CC_USE_STRETCHED_BILLBOARD\n , cc_cameraPos.xyz\n , velocity\n , frameTile_velLenScale.z\n , frameTile_velLenScale.w\n , a_texCoord.x\n #endif\n );\n color = a_color;\n #else\n mat4 xformNoScale = matrixFromRT(quaternionFromEuler(a_texCoord2), pos.xyz);\n mat4 xform = matFromRTS(quaternionFromEuler(a_texCoord2), pos.xyz, compScale);\n pos = xform * vec4(a_texCoord3, 1);\n vec4 normal = xformNoScale * vec4(a_normal, 0);\n color = a_color * a_color1;\n #endif\n uv = computeUV(a_texCoord.z, a_texCoord.xy, frameTile_velLenScale.xy) * mainTiling_Offset.xy + mainTiling_Offset.zw;\n pos = cc_matViewProj * pos;\n return pos;\n}\nvoid main() { gl_Position = lpvs_main(); }`, "frag": `\nprecision highp float;\nuniform CCGlobal {\n vec4 cc_time;\n vec4 cc_screenSize;\n vec4 cc_screenScale;\n vec4 cc_nativeSize;\n highp mat4 cc_matView;\n mat4 cc_matViewInv;\n mat4 cc_matProj;\n mat4 cc_matProjInv;\n mat4 cc_matViewProj;\n mat4 cc_matViewProjInv;\n vec4 cc_cameraPos;\n vec4 cc_exposure;\n vec4 cc_mainLitDir;\n vec4 cc_mainLitColor;\n vec4 cc_ambientSky;\n vec4 cc_ambientGround;\n};\nvec3 SRGBToLinear (vec3 gamma) {\n return gamma * gamma;\n}\nvec4 CCFragOutput (vec4 color) {\n #if CC_USE_HDR\n color.rgb = mix(color.rgb, SRGBToLinear(color.rgb) * cc_exposure.w, vec3(cc_exposure.z));\n #endif\n return color;\n}\nin vec2 uv;\nin vec4 color;\nuniform sampler2D mainTexture;\nuniform FragConstants {\n vec4 tintColor;\n};\nvec4 add () {\n vec4 col = 2.0 * color * tintColor * texture(mainTexture, uv);\n return CCFragOutput(col);\n}\nvec4 multiply () {\n vec4 col;\n vec4 texColor = texture(mainTexture, uv);\n col.rgb = tintColor.rgb * texColor.rgb * color.rgb * vec3(2.0);\n col.a = (1.0 - texColor.a) * (tintColor.a * color.a * 2.0);\n return CCFragOutput(col);\n}\nout vec4 cc_FragColor;\nvoid main() { cc_FragColor = add(); }` }, "glsl1": { - "vert": `\nprecision highp float;\nvec4 quaternionFromAxisAngle (float angle, vec3 axis){\n angle /= 2.;\n float s = sin(angle);\n vec4 res;\n res.xyz = s * axis;\n res.w = cos(angle);\n return res;\n}\nvec4 quaternionFromAxis (vec3 xAxis,vec3 yAxis,vec3 zAxis){\n mat3 m = mat3(xAxis,yAxis,zAxis);\n float trace = m[0][0] + m[1][1] + m[2][2];\n vec4 quat;\n if (trace > 0.) {\n float s = 0.5 / sqrt(trace + 1.0);\n quat.w = 0.25 / s;\n quat.x = (m[2][1] - m[1][2]) * s;\n quat.y = (m[0][2] - m[2][0]) * s;\n quat.z = (m[1][0] - m[0][1]) * s;\n } else if ((m[0][0] > m[1][1]) && (m[0][0] > m[2][2])) {\n float s = 2.0 * sqrt(1.0 + m[0][0] - m[1][1] - m[2][2]);\n quat.w = (m[2][1] - m[1][2]) / s;\n quat.x = 0.25 * s;\n quat.y = (m[0][1] + m[1][0]) / s;\n quat.z = (m[0][2] + m[2][0]) / s;\n } else if (m[1][1] > m[2][2]) {\n float s = 2.0 * sqrt(1.0 + m[1][1] - m[0][0] - m[2][2]);\n quat.w = (m[0][2] - m[2][0]) / s;\n quat.x = (m[0][1] + m[1][0]) / s;\n quat.y = 0.25 * s;\n quat.z = (m[1][2] + m[2][1]) / s;\n } else {\n float s = 2.0 * sqrt(1.0 + m[2][2] - m[0][0] - m[1][1]);\n quat.w = (m[1][0] - m[0][1]) / s;\n quat.x = (m[0][2] + m[2][0]) / s;\n quat.y = (m[1][2] + m[2][1]) / s;\n quat.z = 0.25 * s;\n }\n float len = quat.x * quat.x + quat.y * quat.y + quat.z * quat.z + quat.w * quat.w;\n if (len > 0.) {\n len = 1. / sqrt(len);\n quat.x = quat.x * len;\n quat.y = quat.y * len;\n quat.z = quat.z * len;\n quat.w = quat.w * len;\n }\n return quat;\n}\nvec4 quaternionFromEuler (vec3 angle){\n float x = angle.x / 2.;\n float y = angle.y / 2.;\n float z = angle.z / 2.;\n float sx = sin(x);\n float cx = cos(x);\n float sy = sin(y);\n float cy = cos(y);\n float sz = sin(z);\n float cz = cos(z);\n vec4 quat = vec4(0);\n quat.x = sx * cy * cz + cx * sy * sz;\n quat.y = cx * sy * cz + sx * cy * sz;\n quat.z = cx * cy * sz - sx * sy * cz;\n quat.w = cx * cy * cz - sx * sy * sz;\n return quat;\n}\nmat4 matrixFromRT (vec4 q, vec3 p){\n float x2 = q.x + q.x;\n float y2 = q.y + q.y;\n float z2 = q.z + q.z;\n float xx = q.x * x2;\n float xy = q.x * y2;\n float xz = q.x * z2;\n float yy = q.y * y2;\n float yz = q.y * z2;\n float zz = q.z * z2;\n float wx = q.w * x2;\n float wy = q.w * y2;\n float wz = q.w * z2;\n return mat4(\n 1. - (yy + zz), xy + wz, xz - wy, 0,\n xy - wz, 1. - (xx + zz), yz + wx, 0,\n xz + wy, yz - wx, 1. - (xx + yy), 0,\n p.x, p.y, p.z, 1\n );\n}\nmat4 matFromRTS (vec4 q, vec3 t, vec3 s){\n float x = q.x, y = q.y, z = q.z, w = q.w;\n float x2 = x + x;\n float y2 = y + y;\n float z2 = z + z;\n float xx = x * x2;\n float xy = x * y2;\n float xz = x * z2;\n float yy = y * y2;\n float yz = y * z2;\n float zz = z * z2;\n float wx = w * x2;\n float wy = w * y2;\n float wz = w * z2;\n float sx = s.x;\n float sy = s.y;\n float sz = s.z;\n return mat4((1. - (yy + zz)) * sx, (xy + wz) * sx, (xz - wy) * sx, 0,\n (xy - wz) * sy, (1. - (xx + zz)) * sy, (yz + wx) * sy, 0,\n (xz + wy) * sz, (yz - wx) * sz, (1. - (xx + yy)) * sz, 0,\n t.x, t.y, t.z, 1);\n}\nvoid scaleMatrix (inout mat4 m, float s){\n m[0].xyz *= s;\n m[1].xyz *= s;\n m[2].xyz *= s;\n}\nvec4 quatMultiply (vec4 a, vec4 b){\n vec4 quat;\n quat.x = a.x * b.w + a.w * b.x + a.y * b.z - a.z * b.y;\n quat.y = a.y * b.w + a.w * b.y + a.z * b.x - a.x * b.z;\n quat.z = a.z * b.w + a.w * b.z + a.x * b.y - a.y * b.x;\n quat.w = a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z;\n return quat;\n}\nvoid rotateVecFromQuat (inout vec3 v, vec4 q){\n float ix = q.w * v.x + q.y * v.z - q.z * v.y;\n float iy = q.w * v.y + q.z * v.x - q.x * v.z;\n float iz = q.w * v.z + q.x * v.y - q.y * v.x;\n float iw = -q.x * v.x - q.y * v.y - q.z * v.z;\n v.x = ix * q.w + iw * -q.x + iy * -q.z - iz * -q.y;\n v.y = iy * q.w + iw * -q.y + iz * -q.x - ix * -q.z;\n v.z = iz * q.w + iw * -q.z + ix * -q.y - iy * -q.x;\n}\nvec3 rotateVecFromAxis (vec3 v, vec3 axis, float theta){\n return cos(theta) * v + sin(theta) * cross(v, axis) + (1. - cos(theta)) * dot(v, axis) * axis;\n}\nvec3 rotateInLocalSpace (vec3 pos, vec3 xAxis, vec3 yAxis, vec3 zAxis, vec4 q){\n vec4 viewQuat = quaternionFromAxis(xAxis, yAxis, zAxis);\n vec4 rotQuat = quatMultiply(viewQuat, q);\n rotateVecFromQuat(pos, rotQuat);\n return pos;\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}\nuniform vec4 mainTiling_Offset;\nuniform vec4 frameTile_velLenScale;\nuniform vec4 scale;\nuniform highp mat4 cc_matView;\nuniform mat4 cc_matViewInv;\nuniform mat4 cc_matViewProj;\nuniform vec4 cc_cameraPos;\nuniform highp mat4 cc_matWorld;\nvarying vec2 uv;\nvarying vec4 color;\nvoid computeVertPos (inout vec4 pos, vec2 vertOffset, vec4 q, vec3 s\n#if CC_USE_BILLBOARD || CC_USE_VERTICAL_BILLBOARD\n , mat4 viewInv\n#endif\n#if CC_USE_STRETCHED_BILLBOARD\n , vec3 eye\n , vec4 velocity\n , float velocityScale\n , float lengthScale\n , float xIndex\n#endif\n) {\n#if CC_USE_BILLBOARD\n vec3 viewSpaceVert = vec3(vertOffset.x * s.x, vertOffset.y * s.y, 0.);\n vec3 camX = normalize(vec3(viewInv[0][0], viewInv[1][0], viewInv[2][0]));\n vec3 camY = normalize(vec3(viewInv[0][1], viewInv[1][1], viewInv[2][1]));\n vec3 camZ = normalize(vec3(viewInv[0][2], viewInv[1][2], viewInv[2][2]));\n pos.xyz += rotateInLocalSpace(viewSpaceVert, camX, camY, camZ, q);\n#elif CC_USE_STRETCHED_BILLBOARD\n vec3 camRight = normalize(cross(pos.xyz - eye, velocity.xyz)) * s.x;\n vec3 camUp = velocity.xyz * velocityScale + normalize(velocity.xyz) * lengthScale * s.y;\n pos.xyz += (camRight * abs(vertOffset.x) * sign(vertOffset.y)) - camUp * xIndex;\n#elif CC_USE_HORIZONTAL_BILLBOARD\n vec3 viewSpaceVert = vec3(vertOffset.x * s.x, vertOffset.y * s.y, 0.);\n vec3 camX = vec3(1, 0, 0);\n vec3 camY = vec3(0, 0, -1);\n pos.xyz += rotateInLocalSpace(viewSpaceVert, camX, camY, cross(camX, camY), q);\n#elif CC_USE_VERTICAL_BILLBOARD\n vec2 viewSpaceVert = vec2(vertOffset.x * s.x, vertOffset.y * s.y);\n rotateCorner(viewSpaceVert, q.z);\n vec3 camX = normalize(vec3(cc_matView[0][0], cc_matView[1][0], cc_matView[2][0]));\n vec3 camY = vec3(0, 1, 0);\n vec3 offset = camX * viewSpaceVert.x + camY * viewSpaceVert.y;\n pos.xyz += offset;\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#if !CC_USE_MESH\n vertIndex.y = 1. - vertIndex.y;\n#endif\n return (aniUV.xy + vertIndex) / vec2(frameTile.x, frameTile.y);\n}\nattribute vec3 a_position;\nattribute vec3 a_texCoord;\nattribute vec3 a_texCoord1;\nattribute vec3 a_texCoord2;\nattribute vec4 a_color;\n#if CC_USE_STRETCHED_BILLBOARD\n attribute vec3 a_color1;\n#endif\n#if CC_USE_MESH\n attribute vec3 a_texCoord3;\n attribute vec3 a_normal;\n attribute vec4 a_color1;\n#endif\nvec4 lpvs_main () {\n vec3 compScale = scale.xyz * a_texCoord1;\n vec4 pos = vec4(a_position, 1);\n #if CC_USE_STRETCHED_BILLBOARD\n vec4 velocity = vec4(a_color1.xyz, 0);\n #endif\n #if !CC_USE_WORLD_SPACE\n pos = cc_matWorld * pos;\n #if CC_USE_STRETCHED_BILLBOARD\n velocity = cc_matWorld * velocity;\n #endif\n #endif\n #if !CC_USE_MESH\n vec2 cornerOffset = vec2((a_texCoord.xy - 0.5));\n #if CC_USE_BILLBOARD\n vec3 rotEuler = a_texCoord2;\n #elif CC_USE_STRETCHED_BILLBOARD\n vec3 rotEuler = vec3(0.);\n #else\n vec3 rotEuler = vec3(0., 0., a_texCoord2.z);\n #endif\n computeVertPos(pos, cornerOffset, quaternionFromEuler(rotEuler), compScale\n #if CC_USE_BILLBOARD || CC_USE_VERTICAL_BILLBOARD\n , cc_matViewInv\n #endif\n #if CC_USE_STRETCHED_BILLBOARD\n , cc_cameraPos.xyz\n , velocity\n , frameTile_velLenScale.z\n , frameTile_velLenScale.w\n , a_texCoord.x\n #endif\n );\n color = a_color;\n #else\n mat4 xformNoScale = matrixFromRT(quaternionFromEuler(a_texCoord2), pos.xyz);\n mat4 xform = matFromRTS(quaternionFromEuler(a_texCoord2), pos.xyz, compScale);\n pos = xform * vec4(a_texCoord3, 1);\n vec4 normal = xformNoScale * vec4(a_normal, 0);\n color = a_color * a_color1;\n #endif\n uv = computeUV(a_texCoord.z, a_texCoord.xy, frameTile_velLenScale.xy) * mainTiling_Offset.xy + mainTiling_Offset.zw;\n pos = cc_matViewProj * pos;\n return pos;\n}\nvoid main() { gl_Position = lpvs_main(); }`, - "frag": `\nprecision highp float;\nuniform vec4 cc_exposure;\nvec3 SRGBToLinear (vec3 gamma) {\n return gamma * gamma;\n}\nvec4 CCFragOutput (vec4 color) {\n #if CC_USE_HDR\n color.rgb = mix(color.rgb, SRGBToLinear(color.rgb) * cc_exposure.w, vec3(cc_exposure.z));\n #endif\n return color;\n}\nvarying vec2 uv;\nvarying vec4 color;\nuniform sampler2D mainTexture;\nuniform vec4 tintColor;\nvec4 add () {\n vec4 col = 2.0 * color * tintColor * texture2D(mainTexture, uv);\n return CCFragOutput(col);\n}\nvec4 multiply () {\n vec4 col;\n vec4 texColor = texture2D(mainTexture, uv);\n col.rgb = tintColor.rgb * texColor.rgb * color.rgb * vec3(2.0);\n col.a = (1.0 - texColor.a) * (tintColor.a * color.a * 2.0);\n return CCFragOutput(col);\n}\nvoid main() { gl_FragColor = add(); }` + "vert": `\nprecision highp float;\nvec4 quaternionFromAxis (vec3 xAxis,vec3 yAxis,vec3 zAxis){\n mat3 m = mat3(xAxis,yAxis,zAxis);\n float trace = m[0][0] + m[1][1] + m[2][2];\n vec4 quat;\n if (trace > 0.) {\n float s = 0.5 / sqrt(trace + 1.0);\n quat.w = 0.25 / s;\n quat.x = (m[2][1] - m[1][2]) * s;\n quat.y = (m[0][2] - m[2][0]) * s;\n quat.z = (m[1][0] - m[0][1]) * s;\n } else if ((m[0][0] > m[1][1]) && (m[0][0] > m[2][2])) {\n float s = 2.0 * sqrt(1.0 + m[0][0] - m[1][1] - m[2][2]);\n quat.w = (m[2][1] - m[1][2]) / s;\n quat.x = 0.25 * s;\n quat.y = (m[0][1] + m[1][0]) / s;\n quat.z = (m[0][2] + m[2][0]) / s;\n } else if (m[1][1] > m[2][2]) {\n float s = 2.0 * sqrt(1.0 + m[1][1] - m[0][0] - m[2][2]);\n quat.w = (m[0][2] - m[2][0]) / s;\n quat.x = (m[0][1] + m[1][0]) / s;\n quat.y = 0.25 * s;\n quat.z = (m[1][2] + m[2][1]) / s;\n } else {\n float s = 2.0 * sqrt(1.0 + m[2][2] - m[0][0] - m[1][1]);\n quat.w = (m[1][0] - m[0][1]) / s;\n quat.x = (m[0][2] + m[2][0]) / s;\n quat.y = (m[1][2] + m[2][1]) / s;\n quat.z = 0.25 * s;\n }\n float len = quat.x * quat.x + quat.y * quat.y + quat.z * quat.z + quat.w * quat.w;\n if (len > 0.) {\n len = 1. / sqrt(len);\n quat.x = quat.x * len;\n quat.y = quat.y * len;\n quat.z = quat.z * len;\n quat.w = quat.w * len;\n }\n return quat;\n}\nvec4 quaternionFromEuler (vec3 angle){\n float x = angle.x / 2.;\n float y = angle.y / 2.;\n float z = angle.z / 2.;\n float sx = sin(x);\n float cx = cos(x);\n float sy = sin(y);\n float cy = cos(y);\n float sz = sin(z);\n float cz = cos(z);\n vec4 quat = vec4(0);\n quat.x = sx * cy * cz + cx * sy * sz;\n quat.y = cx * sy * cz + sx * cy * sz;\n quat.z = cx * cy * sz - sx * sy * cz;\n quat.w = cx * cy * cz - sx * sy * sz;\n return quat;\n}\nmat4 matrixFromRT (vec4 q, vec3 p){\n float x2 = q.x + q.x;\n float y2 = q.y + q.y;\n float z2 = q.z + q.z;\n float xx = q.x * x2;\n float xy = q.x * y2;\n float xz = q.x * z2;\n float yy = q.y * y2;\n float yz = q.y * z2;\n float zz = q.z * z2;\n float wx = q.w * x2;\n float wy = q.w * y2;\n float wz = q.w * z2;\n return mat4(\n 1. - (yy + zz), xy + wz, xz - wy, 0,\n xy - wz, 1. - (xx + zz), yz + wx, 0,\n xz + wy, yz - wx, 1. - (xx + yy), 0,\n p.x, p.y, p.z, 1\n );\n}\nmat4 matFromRTS (vec4 q, vec3 t, vec3 s){\n float x = q.x, y = q.y, z = q.z, w = q.w;\n float x2 = x + x;\n float y2 = y + y;\n float z2 = z + z;\n float xx = x * x2;\n float xy = x * y2;\n float xz = x * z2;\n float yy = y * y2;\n float yz = y * z2;\n float zz = z * z2;\n float wx = w * x2;\n float wy = w * y2;\n float wz = w * z2;\n float sx = s.x;\n float sy = s.y;\n float sz = s.z;\n return mat4((1. - (yy + zz)) * sx, (xy + wz) * sx, (xz - wy) * sx, 0,\n (xy - wz) * sy, (1. - (xx + zz)) * sy, (yz + wx) * sy, 0,\n (xz + wy) * sz, (yz - wx) * sz, (1. - (xx + yy)) * sz, 0,\n t.x, t.y, t.z, 1);\n}\nvec4 quatMultiply (vec4 a, vec4 b){\n vec4 quat;\n quat.x = a.x * b.w + a.w * b.x + a.y * b.z - a.z * b.y;\n quat.y = a.y * b.w + a.w * b.y + a.z * b.x - a.x * b.z;\n quat.z = a.z * b.w + a.w * b.z + a.x * b.y - a.y * b.x;\n quat.w = a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z;\n return quat;\n}\nvoid rotateVecFromQuat (inout vec3 v, vec4 q){\n float ix = q.w * v.x + q.y * v.z - q.z * v.y;\n float iy = q.w * v.y + q.z * v.x - q.x * v.z;\n float iz = q.w * v.z + q.x * v.y - q.y * v.x;\n float iw = -q.x * v.x - q.y * v.y - q.z * v.z;\n v.x = ix * q.w + iw * -q.x + iy * -q.z - iz * -q.y;\n v.y = iy * q.w + iw * -q.y + iz * -q.x - ix * -q.z;\n v.z = iz * q.w + iw * -q.z + ix * -q.y - iy * -q.x;\n}\nvec3 rotateInLocalSpace (vec3 pos, vec3 xAxis, vec3 yAxis, vec3 zAxis, vec4 q){\n vec4 viewQuat = quaternionFromAxis(xAxis, yAxis, zAxis);\n vec4 rotQuat = quatMultiply(viewQuat, q);\n rotateVecFromQuat(pos, rotQuat);\n return pos;\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}\nuniform vec4 mainTiling_Offset;\nuniform vec4 frameTile_velLenScale;\nuniform vec4 scale;\nuniform highp mat4 cc_matView;\nuniform mat4 cc_matViewInv;\nuniform mat4 cc_matViewProj;\nuniform vec4 cc_cameraPos;\nuniform highp mat4 cc_matWorld;\nvarying vec2 uv;\nvarying vec4 color;\nvoid computeVertPos (inout vec4 pos, vec2 vertOffset, vec4 q, vec3 s\n#if CC_USE_BILLBOARD || CC_USE_VERTICAL_BILLBOARD\n , mat4 viewInv\n#endif\n#if CC_USE_STRETCHED_BILLBOARD\n , vec3 eye\n , vec4 velocity\n , float velocityScale\n , float lengthScale\n , float xIndex\n#endif\n) {\n#if CC_USE_BILLBOARD\n vec3 viewSpaceVert = vec3(vertOffset.x * s.x, vertOffset.y * s.y, 0.);\n vec3 camX = normalize(vec3(viewInv[0][0], viewInv[1][0], viewInv[2][0]));\n vec3 camY = normalize(vec3(viewInv[0][1], viewInv[1][1], viewInv[2][1]));\n vec3 camZ = normalize(vec3(viewInv[0][2], viewInv[1][2], viewInv[2][2]));\n pos.xyz += rotateInLocalSpace(viewSpaceVert, camX, camY, camZ, q);\n#elif CC_USE_STRETCHED_BILLBOARD\n vec3 camRight = normalize(cross(pos.xyz - eye, velocity.xyz)) * s.x;\n vec3 camUp = velocity.xyz * velocityScale + normalize(velocity.xyz) * lengthScale * s.y;\n pos.xyz += (camRight * abs(vertOffset.x) * sign(vertOffset.y)) - camUp * xIndex;\n#elif CC_USE_HORIZONTAL_BILLBOARD\n vec3 viewSpaceVert = vec3(vertOffset.x * s.x, vertOffset.y * s.y, 0.);\n vec3 camX = vec3(1, 0, 0);\n vec3 camY = vec3(0, 0, -1);\n pos.xyz += rotateInLocalSpace(viewSpaceVert, camX, camY, cross(camX, camY), q);\n#elif CC_USE_VERTICAL_BILLBOARD\n vec2 viewSpaceVert = vec2(vertOffset.x * s.x, vertOffset.y * s.y);\n rotateCorner(viewSpaceVert, q.z);\n vec3 camX = normalize(vec3(cc_matView[0][0], cc_matView[1][0], cc_matView[2][0]));\n vec3 camY = vec3(0, 1, 0);\n vec3 offset = camX * viewSpaceVert.x + camY * viewSpaceVert.y;\n pos.xyz += offset;\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#if !CC_USE_MESH\n vertIndex.y = 1. - vertIndex.y;\n#endif\n return (aniUV.xy + vertIndex) / vec2(frameTile.x, frameTile.y);\n}\nattribute vec3 a_position;\nattribute vec3 a_texCoord;\nattribute vec3 a_texCoord1;\nattribute vec3 a_texCoord2;\nattribute vec4 a_color;\n#if CC_USE_MESH\n attribute vec3 a_texCoord3;\n attribute vec3 a_normal;\n attribute vec4 a_color1;\n#elif CC_USE_STRETCHED_BILLBOARD\n attribute vec3 a_color1;\n#endif\nvec4 lpvs_main () {\n vec3 compScale = scale.xyz * a_texCoord1;\n vec4 pos = vec4(a_position, 1);\n #if CC_USE_STRETCHED_BILLBOARD\n vec4 velocity = vec4(a_color1.xyz, 0);\n #endif\n #if !CC_USE_WORLD_SPACE\n pos = cc_matWorld * pos;\n #if CC_USE_STRETCHED_BILLBOARD\n velocity = cc_matWorld * velocity;\n #endif\n #endif\n #if !CC_USE_MESH\n vec2 cornerOffset = vec2((a_texCoord.xy - 0.5));\n #if CC_USE_BILLBOARD\n vec3 rotEuler = a_texCoord2;\n #elif CC_USE_STRETCHED_BILLBOARD\n vec3 rotEuler = vec3(0.);\n #else\n vec3 rotEuler = vec3(0., 0., a_texCoord2.z);\n #endif\n computeVertPos(pos, cornerOffset, quaternionFromEuler(rotEuler), compScale\n #if CC_USE_BILLBOARD || CC_USE_VERTICAL_BILLBOARD\n , cc_matViewInv\n #endif\n #if CC_USE_STRETCHED_BILLBOARD\n , cc_cameraPos.xyz\n , velocity\n , frameTile_velLenScale.z\n , frameTile_velLenScale.w\n , a_texCoord.x\n #endif\n );\n color = a_color;\n #else\n mat4 xformNoScale = matrixFromRT(quaternionFromEuler(a_texCoord2), pos.xyz);\n mat4 xform = matFromRTS(quaternionFromEuler(a_texCoord2), pos.xyz, compScale);\n pos = xform * vec4(a_texCoord3, 1);\n vec4 normal = xformNoScale * vec4(a_normal, 0);\n color = a_color * a_color1;\n #endif\n uv = computeUV(a_texCoord.z, a_texCoord.xy, frameTile_velLenScale.xy) * mainTiling_Offset.xy + mainTiling_Offset.zw;\n pos = cc_matViewProj * pos;\n return pos;\n}\nvoid main() { gl_Position = lpvs_main(); }`, + "frag": `\nprecision highp float;\nuniform vec4 cc_exposure;\nvec3 SRGBToLinear (vec3 gamma) {\n return gamma * gamma;\n}\nvec4 CCFragOutput (vec4 color) {\n #if CC_USE_HDR\n color.rgb = mix(color.rgb, SRGBToLinear(color.rgb) * cc_exposure.w, vec3(cc_exposure.z));\n #endif\n return color;\n}\nvarying vec2 uv;\nvarying vec4 color;\nuniform sampler2D mainTexture;\nuniform vec4 tintColor;\nvec4 add () {\n vec4 col = 2.0 * color * tintColor * texture2D(mainTexture, uv);\n return CCFragOutput(col);\n}\nvoid main() { gl_FragColor = add(); }` }, "builtins": {"globals":{"blocks":[{"name":"CCGlobal", "defines":[]}], "samplers":[]}, "locals":{"blocks":[{"name":"CCLocal", "defines":[]}], "samplers":[]}}, "defines": [ @@ -177,7 +173,7 @@ export default [ }, "glsl1": { "vert": `\nprecision highp float;\nuniform highp mat4 cc_matView;\nuniform mat4 cc_matProj;\n#if CC_USE_BATCHING\n attribute float a_dyn_batch_id;\n uniform highp mat4 cc_matWorlds[10];\n#else\nuniform highp mat4 cc_matWorld;\nuniform highp mat4 cc_matWorldIT;\n#endif\nstruct StandardVertInput {\n highp vec4 position;\n vec3 normal;\n vec4 tangent;\n};\nattribute vec3 a_position;\nattribute vec3 a_normal;\nattribute vec4 a_tangent;\n#if CC_USE_SKINNING\nattribute vec4 a_weights;\nattribute vec4 a_joints;\nuniform highp vec4 cc_jointsTextureInfo;\nuniform highp vec4 cc_jointsAnimInfo;\nuniform sampler2D cc_jointsTexture;\n#if CC_USE_SKINNING == 1\n highp float decode32 (highp vec4 rgba) {\n rgba = rgba * 255.0;\n highp float Sign = 1.0 - step(128.0, rgba[3]) * 2.0;\n highp float Exponent = 2.0 * mod(rgba[3], 128.0) + step(128.0, rgba[2]) - 127.0;\n highp float Mantissa = mod(rgba[2], 128.0) * 65536.0 + rgba[1] * 256.0 + rgba[0] + 8388608.0;\n return Sign * exp2(Exponent - 23.0) * Mantissa;\n }\n#endif\n#if CC_USE_SKINNING == 1\n mat4 getJointMatrix (float i) {\n highp float j = 12.0 * (cc_jointsAnimInfo.x * i + cc_jointsAnimInfo.y) + cc_jointsTextureInfo.z;\n highp float invSize = cc_jointsTextureInfo.y;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointsTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = vec4(\n decode32(texture2D(cc_jointsTexture, vec2((x + 0.5) * invSize, y))),\n decode32(texture2D(cc_jointsTexture, vec2((x + 1.5) * invSize, y))),\n decode32(texture2D(cc_jointsTexture, vec2((x + 2.5) * invSize, y))),\n decode32(texture2D(cc_jointsTexture, vec2((x + 3.5) * invSize, y)))\n );\n vec4 v2 = vec4(\n decode32(texture2D(cc_jointsTexture, vec2((x + 4.5) * invSize, y))),\n decode32(texture2D(cc_jointsTexture, vec2((x + 5.5) * invSize, y))),\n decode32(texture2D(cc_jointsTexture, vec2((x + 6.5) * invSize, y))),\n decode32(texture2D(cc_jointsTexture, vec2((x + 7.5) * invSize, y)))\n );\n vec4 v3 = vec4(\n decode32(texture2D(cc_jointsTexture, vec2((x + 8.5) * invSize, y))),\n decode32(texture2D(cc_jointsTexture, vec2((x + 9.5) * invSize, y))),\n decode32(texture2D(cc_jointsTexture, vec2((x + 10.5) * invSize, y))),\n decode32(texture2D(cc_jointsTexture, vec2((x + 11.5) * invSize, y)))\n );\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n#elif CC_USE_SKINNING == 2\n mat4 getJointMatrix (float i) {\n highp float j = 3.0 * (cc_jointsAnimInfo.x * i + cc_jointsAnimInfo.y) + cc_jointsTextureInfo.z;\n highp float invSize = cc_jointsTextureInfo.y;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointsTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = texture2D(cc_jointsTexture, vec2((x + 0.5) * invSize, y));\n vec4 v2 = texture2D(cc_jointsTexture, vec2((x + 1.5) * invSize, y));\n vec4 v3 = texture2D(cc_jointsTexture, vec2((x + 2.5) * invSize, y));\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n#endif\nmat4 skinMatrix () {\n return getJointMatrix(a_joints.x) * a_weights.x\n + getJointMatrix(a_joints.y) * a_weights.y;\n + getJointMatrix(a_joints.z) * a_weights.z;\n + getJointMatrix(a_joints.w) * a_weights.w;\n}\nvoid CCSkin (inout vec4 position) {\n mat4 m = skinMatrix();\n position = m * position;\n}\nvoid CCSkin (inout StandardVertInput attr) {\n mat4 m = skinMatrix();\n attr.position = m * attr.position;\n attr.normal = (m * vec4(attr.normal, 0.0)).xyz;\n attr.tangent.xyz = (m * vec4(attr.tangent.xyz, 0.0)).xyz;\n}\n#endif\nuniform vec4 tilingOffset;\n#if USE_VERTEX_COLOR\n attribute vec3 a_color;\n varying vec3 v_color;\n#endif\nvarying vec3 v_position;\nvarying vec3 v_normal;\n#if USE_NORMAL_MAP\n varying vec3 v_tangent;\n varying vec3 v_bitangent;\n#endif\nattribute vec2 a_texCoord;\nvarying vec2 v_uv;\nattribute vec2 a_texCoord1;\nvarying vec2 v_uv1;\nhighp vec4 vert () {\n StandardVertInput In;\n In.position = vec4(a_position, 1.0);\n In.normal = a_normal;\n In.tangent = a_tangent;\n #if CC_USE_SKINNING\n CCSkin(In);\n #endif\n highp mat4 matWorld, matWorldIT;\n #if CC_USE_BATCHING\n matWorld = cc_matWorlds[int(a_dyn_batch_id + 0.5)];\n matWorldIT = matWorld;\n #else\n matWorld = cc_matWorld;\n matWorldIT = cc_matWorldIT;\n #endif\n highp vec4 pos = matWorld * In.position;\n v_position = pos.xyz;\n v_normal = normalize((matWorldIT * vec4(In.normal, 0.0)).xyz);\n #if USE_NORMAL_MAP\n v_tangent = normalize((matWorldIT * vec4(In.tangent.xyz, 0.0)).xyz);\n v_bitangent = cross(v_normal, v_tangent) * In.tangent.w;\n #endif\n v_uv = a_texCoord * tilingOffset.xy + tilingOffset.zw;\n v_uv1 = a_texCoord1 * tilingOffset.xy + tilingOffset.zw;\n #if USE_VERTEX_COLOR\n v_color = a_color;\n #endif\n return cc_matProj * (cc_matView * matWorld) * In.position;\n}\nvoid main() { gl_Position = vert(); }`, - "frag": `\n#if CC_USE_IBL\n #ifdef GL_EXT_shader_texture_lod\n #extension GL_EXT_shader_texture_lod : enable\n #endif\n#endif\nprecision highp float;\nuniform vec4 cc_cameraPos;\nuniform vec4 cc_exposure;\nuniform vec4 cc_mainLitDir;\nuniform vec4 cc_mainLitColor;\nuniform vec4 cc_ambientSky;\nuniform vec4 cc_ambientGround;\n#if CC_USE_IBL\nuniform samplerCube cc_environment;\nvec3 unpackRGBE (vec4 rgbe) {\n return rgbe.rgb * pow(2.0, rgbe.a * 255.0 - 128.0);\n}\n#endif\nvec3 SRGBToLinear (vec3 gamma) {\n return gamma * gamma;\n}\nuniform highp vec4 cc_sphereLitPos[2];\nuniform vec4 cc_sphereLitSizeRange[2];\nuniform vec4 cc_sphereLitColor[2];\nuniform highp vec4 cc_spotLitPos[2];\nuniform vec4 cc_spotLitSizeRangeAngle[2];\nuniform vec4 cc_spotLitDir[2];\nuniform vec4 cc_spotLitColor[2];\nfloat SmoothDistAtt2 (float distSqr, float invSqrAttRadius) {\n float factor = distSqr * invSqrAttRadius;\n float factor2 = factor * factor;\n float factor3 = factor2 * factor2;\n float smoothFactor = clamp(1.0 - factor3 * factor3, 0.0, 1.0);\n return smoothFactor * smoothFactor;\n}\nfloat SmoothDistAtt (float distSqr, float invSqrAttRadius) {\n float factor = distSqr * invSqrAttRadius;\n float smoothFactor = clamp(1.0 - factor * factor, 0.0, 1.0);\n return smoothFactor * smoothFactor;\n}\nfloat GetDistAtt (float distSqr, float invSqrAttRadius) {\n float attenuation = 1.0 / max(distSqr, 0.01*0.01);\n attenuation *= SmoothDistAtt(distSqr , invSqrAttRadius);\n return attenuation;\n}\nfloat GetAngleAtt (vec3 L, vec3 litDir, float litAngleScale, float litAngleOffset) {\n float cd = dot(litDir, L);\n float attenuation = clamp(cd * litAngleScale + litAngleOffset, 0.0, 1.0);\n return (attenuation * attenuation);\n}\nfloat GGXMobile (float roughness, float NoH, vec3 H, vec3 N) {\n vec3 NxH = cross(N, H);\n float OneMinusNoHSqr = dot(NxH, NxH);\n float a = roughness * roughness;\n float n = NoH * a;\n float p = a / (OneMinusNoHSqr + n * n);\n return p * p;\n}\nfloat CalcSpecular (float roughness, float NoH, vec3 H, vec3 N) {\n return (roughness*0.25 + 0.25) * GGXMobile(roughness, NoH, H, N);\n}\nvec3 BRDFApprox (vec3 specular, float roughness, float NoV) {\n const vec4 c0 = vec4(-1.0, -0.0275, -0.572, 0.022);\n const vec4 c1 = vec4(1.0, 0.0425, 1.04, -0.04);\n vec4 r = roughness * c0 + c1;\n float a004 = min( r.x * r.x, exp2( -9.28 * NoV ) ) * r.x + r.y;\n vec2 AB = vec2( -1.04, 1.04 ) * a004 + r.zw;\n AB.y *= clamp(50.0 * specular.g, 0.0, 1.0);\n return specular * AB.x + AB.y;\n}\nvec3 CalcDynamicLighting (vec3 worldPos, vec3 N, vec3 V, vec3 diffuse, vec3 specular, float roughness) {\n vec3 lighting = vec3(0.0);\n vec3 diffuseContrib = diffuse / 3.14159265359;\n for (int i = 0; i < 2; i++) {\n vec3 PLU = cc_sphereLitPos[i].xyz - worldPos;\n vec3 PL = normalize(PLU);\n vec3 PH = normalize(PL + V);\n float PNL = max(dot(N, PL), 0.001);\n float PNH = max(dot(N, PH), 0.0);\n float distSqr = dot(PLU, PLU);\n float litRadius = cc_sphereLitSizeRange[i].x;\n float litRadiusSqr = litRadius * litRadius;\n float illum = 3.14159265359 * (litRadiusSqr / max(litRadiusSqr , distSqr));\n float attRadiusSqrInv = 1.0 / max(cc_sphereLitSizeRange[i].y, 0.01);\n attRadiusSqrInv *= attRadiusSqrInv;\n float att = GetDistAtt(distSqr, attRadiusSqrInv);\n vec3 lspec = specular * CalcSpecular(roughness, PNH, PH, N);\n lighting += PNL * cc_sphereLitColor[i].rgb * cc_sphereLitColor[i].w * illum * att * (diffuseContrib + lspec);\n }\n for (int i = 0; i < 2; i++) {\n vec3 SLU = cc_spotLitPos[i].xyz - worldPos;\n vec3 SL = normalize(SLU);\n vec3 SH = normalize(SL + V);\n float SNL = max(dot(N, SL), 0.001);\n float SNH = max(dot(N, SH), 0.0);\n float distSqr = dot(SLU, SLU);\n float litRadius = cc_spotLitSizeRangeAngle[i].x;\n float litRadiusSqr = litRadius * litRadius;\n float illum = 3.14159265359 * (litRadiusSqr / max(litRadiusSqr , distSqr));\n float attRadiusSqrInv = 1.0 / max(cc_spotLitSizeRangeAngle[i].y, 0.01);\n attRadiusSqrInv *= attRadiusSqrInv;\n float cosInner = max(dot(-cc_spotLitDir[i].xyz, SL), 0.01);\n float cosOuter = cc_spotLitSizeRangeAngle[i].z;\n float litAngleScale = 1.0 / max(0.001, cosInner - cosOuter);\n float litAngleOffset = -cosOuter * litAngleScale;\n float att = GetDistAtt(distSqr, attRadiusSqrInv);\n att *= GetAngleAtt(SL, -cc_spotLitDir[i].xyz, litAngleScale, litAngleOffset);\n vec3 lspec = specular * CalcSpecular(roughness, SNH, SH, N);\n lighting += SNL * cc_spotLitColor[i].rgb * cc_spotLitColor[i].w * illum * att * (diffuseContrib + lspec);\n }\n return lighting;\n}\nstruct StandardSurface {\n vec4 albedo;\n vec3 position;\n vec3 normal;\n vec3 emissive;\n float roughness;\n float metallic;\n float occlusion;\n};\nvec4 CCStandardShading (StandardSurface s) {\n vec3 diffuse = s.albedo.rgb * (1.0 - s.metallic);\n vec3 specular = mix(vec3(0.04), s.albedo.rgb, s.metallic);\n vec3 N = normalize(s.normal);\n vec3 V = normalize(cc_cameraPos.xyz - s.position);\n vec3 L = normalize(-cc_mainLitDir.xyz);\n vec3 H = normalize(L+V);\n float NV = max(abs(dot(N, V)), 0.001);\n float NL = max(dot(N, L), 0.001);\n float NH = max(dot(N, H), 0.0);\n specular = BRDFApprox(specular, s.roughness, NV);\n vec3 diffuseContrib = diffuse / 3.14159265359;\n vec3 specularContrib = specular * CalcSpecular(s.roughness, NH, H, N);\n vec3 finalColor = NL * cc_mainLitColor.rgb * cc_mainLitColor.w * (diffuseContrib + specularContrib);\n finalColor += CalcDynamicLighting(s.position, N, V, diffuse, specular, s.roughness);\n float fAmb = 0.5 - N.y * 0.5;\n vec3 ambDiff = mix(cc_ambientSky.rgb, cc_ambientGround.rgb, fAmb) * cc_ambientSky.w;\n finalColor += (ambDiff.rgb * diffuse);\n #if CC_USE_IBL\n vec3 R = normalize(reflect(-V, N));\n #ifdef GL_EXT_shader_texture_lod\n vec4 envmap = textureCubeLodEXT(cc_environment, R, s.roughness * cc_ambientGround.w);\n #else\n vec4 envmap = textureCube(cc_environment, R);\n #endif\n #if CC_USE_IBL == 2\n vec3 env = unpackRGBE(envmap);\n #else\n vec3 env = SRGBToLinear(envmap.rgb) * cc_ambientSky.w;\n #endif\n finalColor += env * specular;\n #endif\n finalColor = finalColor * s.occlusion;\n #if CC_USE_HDR\n s.emissive *= cc_exposure.w;\n #endif\n finalColor += s.emissive;\n return vec4(finalColor, s.albedo.a);\n}\nvec3 ACESToneMap (vec3 color) {\n const float A = 2.51;\n const float B = 0.03;\n const float C = 2.43;\n const float D = 0.59;\n const float E = 0.14;\n return (color * (A * color + B)) / (color * (C * color + D) + E);\n}\nvec4 CCFragOutput (vec4 color) {\n #if !CC_USE_HDR\n color.rgb = sqrt(ACESToneMap(color.rgb));\n #endif\n return color;\n}\nuniform vec4 albedo;\nuniform vec4 albedoScaleAndCutoff;\nuniform vec4 pbrParams;\nuniform vec4 emissive;\nuniform vec4 emissiveScale;\nvarying vec3 v_position;\nvarying vec2 v_uv;\nvarying vec2 v_uv1;\nvarying vec3 v_normal;\n#if USE_VERTEX_COLOR\n varying vec3 v_color;\n#endif\n#if USE_ALBEDO_MAP\n uniform sampler2D albedoMap;\n#endif\n#if USE_NORMAL_MAP\n varying vec3 v_tangent;\n varying vec3 v_bitangent;\n uniform sampler2D normalMap;\n#endif\n#if USE_PBR_MAP\n uniform sampler2D pbrMap;\n#endif\n#if USE_METALLIC_ROUGHNESS_MAP\n uniform sampler2D metallicRoughnessMap;\n#endif\n#if USE_OCCLUSION_MAP\n uniform sampler2D occlusionMap;\n#endif\n#if USE_EMISSIVE_MAP\n uniform sampler2D emissiveMap;\n#endif\n#if USE_ALPHA_TEST\n#endif\nvoid surf (out StandardSurface s) {\n vec4 baseColor = albedo;\n #if USE_VERTEX_COLOR\n baseColor.rgb *= v_color;\n #endif\n #if USE_ALBEDO_MAP\n vec4 texColor = texture2D(albedoMap, ALBEDO_UV);\n texColor.rgb = SRGBToLinear(texColor.rgb);\n baseColor *= texColor;\n #endif\n s.albedo = baseColor;\n s.albedo.rgb *= albedoScaleAndCutoff.xyz;\n #if USE_ALPHA_TEST\n if (s.albedo.ALPHA_TEST_CHANNEL < albedoScaleAndCutoff.w) discard;\n #endif\n s.normal = v_normal;\n #if USE_NORMAL_MAP\n vec3 nmmp = texture2D(normalMap, v_uv).xyz - vec3(0.5);\n s.normal =\n (nmmp.x * pbrParams.w) * normalize(v_tangent) +\n (nmmp.y * pbrParams.w) * normalize(v_bitangent) +\n nmmp.z * normalize(s.normal);\n #endif\n s.position = v_position;\n vec4 pbr = pbrParams;\n #if USE_PBR_MAP\n vec4 res = texture2D(pbrMap, v_uv);\n pbr.x *= res.OCCLUSION_CHANNEL;\n pbr.y *= res.ROUGHNESS_CHANNEL;\n pbr.z *= res.METALLIC_CHANNEL;\n #endif\n #if USE_METALLIC_ROUGHNESS_MAP\n vec4 metallicRoughness = texture2D(metallicRoughnessMap, v_uv);\n pbr.z *= metallicRoughness.METALLIC_CHANNEL;\n pbr.y *= metallicRoughness.ROUGHNESS_CHANNEL;\n #endif\n #if USE_OCCLUSION_MAP\n pbr.x *= texture2D(occlusionMap, v_uv).OCCLUSION_CHANNEL;\n #endif\n s.occlusion = clamp(pbr.x, 0.0, 0.96);\n s.roughness = clamp(pbr.y, 0.04, 1.0);\n s.metallic = pbr.z;\n s.emissive = emissive.rgb * emissiveScale.xyz;\n #if USE_EMISSIVE_MAP\n s.emissive *= SRGBToLinear(texture2D(emissiveMap, EMISSIVE_UV).rgb);\n #endif\n}\nvec4 frag () {\n StandardSurface s; surf(s);\n vec4 color = CCStandardShading(s);\n return CCFragOutput(color);\n}\nvoid main() { gl_FragColor = frag(); }` + "frag": `\n#if CC_USE_IBL\n #ifdef GL_EXT_shader_texture_lod\n #extension GL_EXT_shader_texture_lod : enable\n #endif\n#endif\nprecision highp float;\nuniform vec4 cc_cameraPos;\nuniform vec4 cc_exposure;\nuniform vec4 cc_mainLitDir;\nuniform vec4 cc_mainLitColor;\nuniform vec4 cc_ambientSky;\nuniform vec4 cc_ambientGround;\n#if CC_USE_IBL\nuniform samplerCube cc_environment;\nvec3 unpackRGBE (vec4 rgbe) {\n return rgbe.rgb * pow(2.0, rgbe.a * 255.0 - 128.0);\n}\n#endif\nvec3 SRGBToLinear (vec3 gamma) {\n return gamma * gamma;\n}\nuniform highp vec4 cc_sphereLitPos[2];\nuniform vec4 cc_sphereLitSizeRange[2];\nuniform vec4 cc_sphereLitColor[2];\nuniform highp vec4 cc_spotLitPos[2];\nuniform vec4 cc_spotLitSizeRangeAngle[2];\nuniform vec4 cc_spotLitDir[2];\nuniform vec4 cc_spotLitColor[2];\nfloat SmoothDistAtt (float distSqr, float invSqrAttRadius) {\n float factor = distSqr * invSqrAttRadius;\n float smoothFactor = clamp(1.0 - factor * factor, 0.0, 1.0);\n return smoothFactor * smoothFactor;\n}\nfloat GetDistAtt (float distSqr, float invSqrAttRadius) {\n float attenuation = 1.0 / max(distSqr, 0.01*0.01);\n attenuation *= SmoothDistAtt(distSqr , invSqrAttRadius);\n return attenuation;\n}\nfloat GetAngleAtt (vec3 L, vec3 litDir, float litAngleScale, float litAngleOffset) {\n float cd = dot(litDir, L);\n float attenuation = clamp(cd * litAngleScale + litAngleOffset, 0.0, 1.0);\n return (attenuation * attenuation);\n}\nfloat GGXMobile (float roughness, float NoH, vec3 H, vec3 N) {\n vec3 NxH = cross(N, H);\n float OneMinusNoHSqr = dot(NxH, NxH);\n float a = roughness * roughness;\n float n = NoH * a;\n float p = a / (OneMinusNoHSqr + n * n);\n return p * p;\n}\nfloat CalcSpecular (float roughness, float NoH, vec3 H, vec3 N) {\n return (roughness*0.25 + 0.25) * GGXMobile(roughness, NoH, H, N);\n}\nvec3 BRDFApprox (vec3 specular, float roughness, float NoV) {\n const vec4 c0 = vec4(-1.0, -0.0275, -0.572, 0.022);\n const vec4 c1 = vec4(1.0, 0.0425, 1.04, -0.04);\n vec4 r = roughness * c0 + c1;\n float a004 = min( r.x * r.x, exp2( -9.28 * NoV ) ) * r.x + r.y;\n vec2 AB = vec2( -1.04, 1.04 ) * a004 + r.zw;\n AB.y *= clamp(50.0 * specular.g, 0.0, 1.0);\n return specular * AB.x + AB.y;\n}\nvec3 CalcDynamicLighting (vec3 worldPos, vec3 N, vec3 V, vec3 diffuse, vec3 specular, float roughness) {\n vec3 lighting = vec3(0.0);\n vec3 diffuseContrib = diffuse / 3.14159265359;\n for (int i = 0; i < 2; i++) {\n vec3 PLU = cc_sphereLitPos[i].xyz - worldPos;\n vec3 PL = normalize(PLU);\n vec3 PH = normalize(PL + V);\n float PNL = max(dot(N, PL), 0.001);\n float PNH = max(dot(N, PH), 0.0);\n float distSqr = dot(PLU, PLU);\n float litRadius = cc_sphereLitSizeRange[i].x;\n float litRadiusSqr = litRadius * litRadius;\n float illum = 3.14159265359 * (litRadiusSqr / max(litRadiusSqr , distSqr));\n float attRadiusSqrInv = 1.0 / max(cc_sphereLitSizeRange[i].y, 0.01);\n attRadiusSqrInv *= attRadiusSqrInv;\n float att = GetDistAtt(distSqr, attRadiusSqrInv);\n vec3 lspec = specular * CalcSpecular(roughness, PNH, PH, N);\n lighting += PNL * cc_sphereLitColor[i].rgb * cc_sphereLitColor[i].w * illum * att * (diffuseContrib + lspec);\n }\n for (int i = 0; i < 2; i++) {\n vec3 SLU = cc_spotLitPos[i].xyz - worldPos;\n vec3 SL = normalize(SLU);\n vec3 SH = normalize(SL + V);\n float SNL = max(dot(N, SL), 0.001);\n float SNH = max(dot(N, SH), 0.0);\n float distSqr = dot(SLU, SLU);\n float litRadius = cc_spotLitSizeRangeAngle[i].x;\n float litRadiusSqr = litRadius * litRadius;\n float illum = 3.14159265359 * (litRadiusSqr / max(litRadiusSqr , distSqr));\n float attRadiusSqrInv = 1.0 / max(cc_spotLitSizeRangeAngle[i].y, 0.01);\n attRadiusSqrInv *= attRadiusSqrInv;\n float cosInner = max(dot(-cc_spotLitDir[i].xyz, SL), 0.01);\n float cosOuter = cc_spotLitSizeRangeAngle[i].z;\n float litAngleScale = 1.0 / max(0.001, cosInner - cosOuter);\n float litAngleOffset = -cosOuter * litAngleScale;\n float att = GetDistAtt(distSqr, attRadiusSqrInv);\n att *= GetAngleAtt(SL, -cc_spotLitDir[i].xyz, litAngleScale, litAngleOffset);\n vec3 lspec = specular * CalcSpecular(roughness, SNH, SH, N);\n lighting += SNL * cc_spotLitColor[i].rgb * cc_spotLitColor[i].w * illum * att * (diffuseContrib + lspec);\n }\n return lighting;\n}\nstruct StandardSurface {\n vec4 albedo;\n vec3 position;\n vec3 normal;\n vec3 emissive;\n float roughness;\n float metallic;\n float occlusion;\n};\nvec4 CCStandardShading (StandardSurface s) {\n vec3 diffuse = s.albedo.rgb * (1.0 - s.metallic);\n vec3 specular = mix(vec3(0.04), s.albedo.rgb, s.metallic);\n vec3 N = normalize(s.normal);\n vec3 V = normalize(cc_cameraPos.xyz - s.position);\n vec3 L = normalize(-cc_mainLitDir.xyz);\n vec3 H = normalize(L+V);\n float NV = max(abs(dot(N, V)), 0.001);\n float NL = max(dot(N, L), 0.001);\n float NH = max(dot(N, H), 0.0);\n specular = BRDFApprox(specular, s.roughness, NV);\n vec3 diffuseContrib = diffuse / 3.14159265359;\n vec3 specularContrib = specular * CalcSpecular(s.roughness, NH, H, N);\n vec3 finalColor = NL * cc_mainLitColor.rgb * cc_mainLitColor.w * (diffuseContrib + specularContrib);\n finalColor += CalcDynamicLighting(s.position, N, V, diffuse, specular, s.roughness);\n float fAmb = 0.5 - N.y * 0.5;\n vec3 ambDiff = mix(cc_ambientSky.rgb, cc_ambientGround.rgb, fAmb) * cc_ambientSky.w;\n finalColor += (ambDiff.rgb * diffuse);\n #if CC_USE_IBL\n vec3 R = normalize(reflect(-V, N));\n #ifdef GL_EXT_shader_texture_lod\n vec4 envmap = textureCubeLodEXT(cc_environment, R, s.roughness * cc_ambientGround.w);\n #else\n vec4 envmap = textureCube(cc_environment, R);\n #endif\n #if CC_USE_IBL == 2\n vec3 env = unpackRGBE(envmap);\n #else\n vec3 env = SRGBToLinear(envmap.rgb) * cc_ambientSky.w;\n #endif\n finalColor += env * specular;\n #endif\n finalColor = finalColor * s.occlusion;\n #if CC_USE_HDR\n s.emissive *= cc_exposure.w;\n #endif\n finalColor += s.emissive;\n return vec4(finalColor, s.albedo.a);\n}\nvec3 ACESToneMap (vec3 color) {\n const float A = 2.51;\n const float B = 0.03;\n const float C = 2.43;\n const float D = 0.59;\n const float E = 0.14;\n return (color * (A * color + B)) / (color * (C * color + D) + E);\n}\nvec4 CCFragOutput (vec4 color) {\n #if !CC_USE_HDR\n color.rgb = sqrt(ACESToneMap(color.rgb));\n #endif\n return color;\n}\nuniform vec4 albedo;\nuniform vec4 albedoScaleAndCutoff;\nuniform vec4 pbrParams;\nuniform vec4 emissive;\nuniform vec4 emissiveScale;\nvarying vec3 v_position;\nvarying vec2 v_uv;\nvarying vec2 v_uv1;\nvarying vec3 v_normal;\n#if USE_VERTEX_COLOR\n varying vec3 v_color;\n#endif\n#if USE_ALBEDO_MAP\n uniform sampler2D albedoMap;\n#endif\n#if USE_NORMAL_MAP\n varying vec3 v_tangent;\n varying vec3 v_bitangent;\n uniform sampler2D normalMap;\n#endif\n#if USE_PBR_MAP\n uniform sampler2D pbrMap;\n#endif\n#if USE_METALLIC_ROUGHNESS_MAP\n uniform sampler2D metallicRoughnessMap;\n#endif\n#if USE_OCCLUSION_MAP\n uniform sampler2D occlusionMap;\n#endif\n#if USE_EMISSIVE_MAP\n uniform sampler2D emissiveMap;\n#endif\n#if USE_ALPHA_TEST\n#endif\nvoid surf (out StandardSurface s) {\n vec4 baseColor = albedo;\n #if USE_VERTEX_COLOR\n baseColor.rgb *= v_color;\n #endif\n #if USE_ALBEDO_MAP\n vec4 texColor = texture2D(albedoMap, ALBEDO_UV);\n texColor.rgb = SRGBToLinear(texColor.rgb);\n baseColor *= texColor;\n #endif\n s.albedo = baseColor;\n s.albedo.rgb *= albedoScaleAndCutoff.xyz;\n #if USE_ALPHA_TEST\n if (s.albedo.ALPHA_TEST_CHANNEL < albedoScaleAndCutoff.w) discard;\n #endif\n s.normal = v_normal;\n #if USE_NORMAL_MAP\n vec3 nmmp = texture2D(normalMap, v_uv).xyz - vec3(0.5);\n s.normal =\n (nmmp.x * pbrParams.w) * normalize(v_tangent) +\n (nmmp.y * pbrParams.w) * normalize(v_bitangent) +\n nmmp.z * normalize(s.normal);\n #endif\n s.position = v_position;\n vec4 pbr = pbrParams;\n #if USE_PBR_MAP\n vec4 res = texture2D(pbrMap, v_uv);\n pbr.x *= res.OCCLUSION_CHANNEL;\n pbr.y *= res.ROUGHNESS_CHANNEL;\n pbr.z *= res.METALLIC_CHANNEL;\n #endif\n #if USE_METALLIC_ROUGHNESS_MAP\n vec4 metallicRoughness = texture2D(metallicRoughnessMap, v_uv);\n pbr.z *= metallicRoughness.METALLIC_CHANNEL;\n pbr.y *= metallicRoughness.ROUGHNESS_CHANNEL;\n #endif\n #if USE_OCCLUSION_MAP\n pbr.x *= texture2D(occlusionMap, v_uv).OCCLUSION_CHANNEL;\n #endif\n s.occlusion = clamp(pbr.x, 0.0, 0.96);\n s.roughness = clamp(pbr.y, 0.04, 1.0);\n s.metallic = pbr.z;\n s.emissive = emissive.rgb * emissiveScale.xyz;\n #if USE_EMISSIVE_MAP\n s.emissive *= SRGBToLinear(texture2D(emissiveMap, EMISSIVE_UV).rgb);\n #endif\n}\nvec4 frag () {\n StandardSurface s; surf(s);\n vec4 color = CCStandardShading(s);\n return CCFragOutput(color);\n}\nvoid main() { gl_FragColor = frag(); }` }, "builtins": {"globals":{"blocks":[{"name":"CCGlobal", "defines":[]}], "samplers":[{"name":"cc_environment", "defines":["CC_USE_IBL"]}]}, "locals":{"blocks":[{"name":"CCLocalBatched", "defines":["CC_USE_BATCHING"]}, {"name":"CCLocal", "defines":[]}, {"name":"CCSkinningTexture", "defines":["CC_USE_SKINNING"]}, {"name":"CCSkinningAnimation", "defines":["CC_USE_SKINNING"]}, {"name":"CCForwardLight", "defines":[]}], "samplers":[{"name":"cc_jointsTexture", "defines":["CC_USE_SKINNING"]}]}}, "defines": [ diff --git a/cocos/core/animation/animation-blend-state.ts b/cocos/core/animation/animation-blend-state.ts index 68bc25e212..8253a7c1fb 100644 --- a/cocos/core/animation/animation-blend-state.ts +++ b/cocos/core/animation/animation-blend-state.ts @@ -66,10 +66,13 @@ export class AnimationBlendState { } public apply () { - for (const targetState of this._blendTargets) { + const targets = this._blendTargets; + for (let i = 0; i < targets.length; i++) { + const targetState = targets[i]; const target = targetState.target; const propertyStates = targetState.properties; - for (const p of propertyStates) { + for (let j = 0; j < propertyStates.length; j++) { + const p = propertyStates[j]; if (p.weight !== 0) { if (target instanceof Node) { if (p.name === 'position') { @@ -88,7 +91,9 @@ export class AnimationBlendState { } public clear () { - for (const targetState of this._blendTargets) { + const targets = this._blendTargets; + for (let i = 0; i < targets.length; i++) { + const targetState = targets[i]; const propertyStates = targetState.properties; for (const p of propertyStates) { p.weight = 0; diff --git a/cocos/core/assets/simple-texture.ts b/cocos/core/assets/simple-texture.ts index a0c510a935..a9c3c89dd9 100644 --- a/cocos/core/assets/simple-texture.ts +++ b/cocos/core/assets/simple-texture.ts @@ -4,7 +4,7 @@ import { ccclass } from '../data/class-decorator'; import { GFXBufferTextureCopy, GFXTextureFlagBit, GFXTextureUsageBit } from '../gfx/define'; -import { GFXDevice } from '../gfx/device'; +import { GFXAPI, GFXDevice } from '../gfx/device'; import { GFXTexture, IGFXTextureInfo } from '../gfx/texture'; import { GFXTextureView, IGFXTextureViewInfo } from '../gfx/texture-view'; import { error } from '../platform/debug'; @@ -46,6 +46,11 @@ function getMipLevel (width: number, height: number) { } function isPOT (n: number) { return n && (n & (n - 1)) === 0; } +function canGenerateMipmap (device: GFXDevice, w: number, h: number) { + const needCheckPOT = device.gfxAPI === GFXAPI.WEBGL; + if (needCheckPOT) { return isPOT(w) && isPOT(h); } + return true; +} /** * 简单贴图基类。 @@ -213,7 +218,7 @@ export class SimpleTexture extends TextureBase { protected _createTexture (device: GFXDevice) { let flags = GFXTextureFlagBit.NONE; - if (this._mipFilter !== Filter.NONE && isPOT(this._width) && isPOT(this._height)) { + if (this._mipFilter !== Filter.NONE && canGenerateMipmap(device, this._width, this._height)) { this._mipmapLevel = getMipLevel(this._width, this._height); flags = GFXTextureFlagBit.GEN_MIPMAP; } diff --git a/cocos/core/gfx/webgl/webgl-commands.ts b/cocos/core/gfx/webgl/webgl-commands.ts index 56b3451f9e..8b8a23d37e 100644 --- a/cocos/core/gfx/webgl/webgl-commands.ts +++ b/cocos/core/gfx/webgl/webgl-commands.ts @@ -424,7 +424,7 @@ export class WebGLCmdBeginRenderPass extends WebGLCmdObject { public clear () { this.gpuFramebuffer = null; - this.clearColors = []; + this.clearColors.length = 0; } } @@ -529,7 +529,7 @@ export class WebGLCmdCopyBufferToTexture extends WebGLCmdObject { this.gpuBuffer = null; this.gpuTexture = null; this.dstLayout = null; - this.regions = []; + this.regions.length = 0; } } @@ -1138,7 +1138,8 @@ export function WebGLCmdFuncDestroyFramebuffer (device: WebGLGFXDevice, gpuFrame export function WebGLCmdFuncCreateShader (device: WebGLGFXDevice, gpuShader: WebGLGPUShader) { const gl = device.gl; - for (const gpuStage of gpuShader.gpuStages) { + for (let k = 0; k < gpuShader.gpuStages.length; k++) { + const gpuStage = gpuShader.gpuStages[k]; let glShaderType: GLenum = 0; let shaderTypeStr = ''; @@ -1187,7 +1188,8 @@ export function WebGLCmdFuncCreateShader (device: WebGLGFXDevice, gpuShader: Web gpuShader.glProgram = glProgram; // link program - for (const gpuStage of gpuShader.gpuStages) { + for (let k = 0; k < gpuShader.gpuStages.length; k++) { + const gpuStage = gpuShader.gpuStages[k]; gl.attachShader(gpuShader.glProgram, gpuStage.glShader!); } @@ -1198,7 +1200,8 @@ export function WebGLCmdFuncCreateShader (device: WebGLGFXDevice, gpuShader: Web console.error('Failed to link shader \'' + gpuShader.name + '\'.'); console.error(gl.getProgramInfoLog(gpuShader.glProgram)); - for (const gpuStage of gpuShader.gpuStages) { + for (let k = 0; k < gpuShader.gpuStages.length; k++) { + const gpuStage = gpuShader.gpuStages[k]; if (gpuStage.glShader) { gl.deleteShader(gpuStage.glShader); gpuStage.glShader = null; @@ -1288,7 +1291,8 @@ export function WebGLCmdFuncCreateShader (device: WebGLGFXDevice, gpuShader: Web /* glBlock.buffer = new ArrayBuffer(glBlock.size); - for (const glUniform of glBlock.glUniforms) { + for (let k = 0; k < glBlock.glUniforms.length; k++) { + const glUniform = glBlock.glUniforms[k]; switch (glUniform.glType) { case gl.BOOL: case gl.BOOL_VEC2: @@ -1355,9 +1359,11 @@ export function WebGLCmdFuncCreateShader (device: WebGLGFXDevice, gpuShader: Web // let stride = WebGLGetTypeSize(info.type); // build uniform block mapping - for (const glBlock of gpuShader.glBlocks) { + for (let j = 0; j < gpuShader.glBlocks.length; j++) { + const glBlock = gpuShader.glBlocks[j]; - for (const glUniform of glBlock.glUniforms) { + for (let k = 0; k < glBlock.glUniforms.length; k++) { + const glUniform = glBlock.glUniforms[k]; if (glUniform.name === varName) { // let varSize = stride * info.size; @@ -1370,7 +1376,8 @@ export function WebGLCmdFuncCreateShader (device: WebGLGFXDevice, gpuShader: Web } // for } else { - for (const glSampler of gpuShader.glSamplers) { + for (let j = 0; j < gpuShader.glSamplers.length; j++) { + const glSampler = gpuShader.glSamplers[j]; if (glSampler.name === varName) { // let varSize = stride * uniformInfo.size; @@ -1397,7 +1404,8 @@ export function WebGLCmdFuncCreateShader (device: WebGLGFXDevice, gpuShader: Web device.stateCache.glProgram = gpuShader.glProgram; } - for (const glSampler of glActiveSamplers) { + for (let i = 0; i < glActiveSamplers.length; i++) { + const glSampler = glActiveSamplers[i]; gl.uniform1iv(glSampler.glLoc, glSampler.units); } } @@ -1405,7 +1413,8 @@ export function WebGLCmdFuncCreateShader (device: WebGLGFXDevice, gpuShader: Web export function WebGLCmdFuncDestroyShader (device: WebGLGFXDevice, gpuShader: WebGLGPUShader) { - for (const gpuStage of gpuShader.gpuStages) { + for (let i = 0; i < gpuShader.gpuStages.length; i++) { + const gpuStage = gpuShader.gpuStages[i]; if (gpuStage.glShader) { device.gl.deleteShader(gpuStage.glShader); gpuStage.glShader = null; @@ -1454,8 +1463,11 @@ export function WebGLCmdFuncCreateInputAssember (device: WebGLGFXDevice, gpuInpu } export function WebGLCmdFuncDestroyInputAssembler (device: WebGLGFXDevice, gpuInputAssembler: IWebGLGPUInputAssembler) { - for (const vao of gpuInputAssembler.glVAOs) { - device.OES_vertex_array_object!.deleteVertexArrayOES(vao[1]); + const it = gpuInputAssembler.glVAOs.values(); + let res = it.next(); + while (!res.done) { + device.OES_vertex_array_object!.deleteVertexArrayOES(res.value); + res = it.next(); } gpuInputAssembler.glVAOs.clear(); } @@ -2558,7 +2570,8 @@ export function WebGLCmdFuncCopyTexImagesToTexture ( switch (gpuTexture.glTarget) { case gl.TEXTURE_2D: { - for (const region of regions) { + for (let i = 0; i < regions.length; i++) { + const region = regions[i]; // console.debug('Copying image to texture 2D: ' + region.texExtent.width + ' x ' + region.texExtent.height); for (m = region.texSubres.baseMipLevel; m < region.texSubres.levelCount; ++m) { gl.texSubImage2D(gl.TEXTURE_2D, m, @@ -2569,7 +2582,8 @@ export function WebGLCmdFuncCopyTexImagesToTexture ( break; } case gl.TEXTURE_CUBE_MAP: { - for (const region of regions) { + for (let i = 0; i < regions.length; i++) { + const region = regions[i]; // console.debug('Copying image to texture cube: ' + region.texExtent.width + ' x ' + region.texExtent.height); const fcount = region.texSubres.baseArrayLayer + region.texSubres.layerCount; for (f = region.texSubres.baseArrayLayer; f < fcount; ++f) { @@ -2617,7 +2631,8 @@ export function WebGLCmdFuncCopyBuffersToTexture ( const isCompressed = fmtInfo.isCompressed; switch (gpuTexture.glTarget) { case gl.TEXTURE_2D: { - for (const region of regions) { + for (let i = 0; i < regions.length; i++) { + const region = regions[i]; w = region.texExtent.width; h = region.texExtent.height; // console.debug('Copying buffer to texture 2D: ' + w + ' x ' + h); @@ -2647,7 +2662,8 @@ export function WebGLCmdFuncCopyBuffersToTexture ( break; } case gl.TEXTURE_CUBE_MAP: { - for (const region of regions) { + for (let i = 0; i < regions.length; i++) { + const region = regions[i]; n = 0; const fcount = region.texSubres.baseArrayLayer + region.texSubres.layerCount; for (f = region.texSubres.baseArrayLayer; f < fcount; ++f) { diff --git a/cocos/core/gfx/webgl2/webgl2-commands.ts b/cocos/core/gfx/webgl2/webgl2-commands.ts index 9ce2e56c51..f8558d1ba8 100644 --- a/cocos/core/gfx/webgl2/webgl2-commands.ts +++ b/cocos/core/gfx/webgl2/webgl2-commands.ts @@ -575,7 +575,7 @@ export class WebGL2CmdBeginRenderPass extends WebGL2CmdObject { public clear () { this.gpuFramebuffer = null; - this.clearColors = []; + this.clearColors.length = 0; } } @@ -679,7 +679,7 @@ export class WebGL2CmdCopyBufferToTexture extends WebGL2CmdObject { this.gpuBuffer = null; this.gpuTexture = null; this.dstLayout = null; - this.regions = []; + this.regions.length = 0; } } @@ -928,18 +928,11 @@ export function WebGL2CmdFuncUpdateBuffer (device: WebGL2GFXDevice, gpuBuffer: W cache.glUniformBuffer = gpuBuffer.glBuffer; } - let buf: Float32Array; - if (buffer instanceof Float32Array) { - buf = buffer; - } else { - buf = new Float32Array(buff, 0, size / 4); - } - - if (size === buf.byteLength) { - gl.bufferSubData(gpuBuffer.glTarget, offset, buf); + if (size === buff.byteLength) { + gl.bufferSubData(gpuBuffer.glTarget, offset, buff); // if (gl.getBufferParameter(gl.UNIFORM_BUFFER, gl.BUFFER_SIZE) !== buff.length * 4) { debugger; } } else { - gl.bufferSubData(gpuBuffer.glTarget, offset, new Float32Array(buf.buffer, 0, size / 4)); + gl.bufferSubData(gpuBuffer.glTarget, offset, new Float32Array(buff, 0, size / 4)); } break; } @@ -1387,7 +1380,8 @@ export function WebGL2CmdFuncDestroyFramebuffer (device: WebGL2GFXDevice, gpuFra export function WebGL2CmdFuncCreateShader (device: WebGL2GFXDevice, gpuShader: WebGL2GPUShader) { const gl = device.gl; - for (const gpuStage of gpuShader.gpuStages) { + for (let k = 0; k < gpuShader.gpuStages.length; k++) { + const gpuStage = gpuShader.gpuStages[k]; let glShaderType: GLenum = 0; let shaderTypeStr = ''; @@ -1436,7 +1430,8 @@ export function WebGL2CmdFuncCreateShader (device: WebGL2GFXDevice, gpuShader: W gpuShader.glProgram = glProgram; // link program - for (const gpuStage of gpuShader.gpuStages) { + for (let k = 0; k < gpuShader.gpuStages.length; k++) { + const gpuStage = gpuShader.gpuStages[k]; gl.attachShader(gpuShader.glProgram, gpuStage.glShader!); } @@ -1447,7 +1442,8 @@ export function WebGL2CmdFuncCreateShader (device: WebGL2GFXDevice, gpuShader: W console.error('Failed to link shader \'' + gpuShader.name + '\'.'); console.error(gl.getProgramInfoLog(gpuShader.glProgram)); - for (const gpuStage of gpuShader.gpuStages) { + for (let k = 0; k < gpuShader.gpuStages.length; k++) { + const gpuStage = gpuShader.gpuStages[k]; if (gpuStage.glShader) { gl.deleteShader(gpuStage.glShader); gpuStage.glShader = null; @@ -1518,7 +1514,8 @@ export function WebGL2CmdFuncCreateShader (device: WebGL2GFXDevice, gpuShader: W // blockIdx = gl.getUniformBlockIndex(gpuShader.glProgram, blockName); blockBinding = -1; - for (const block of gpuShader.blocks) { + for (let k = 0; k < gpuShader.blocks.length; k++) { + const block = gpuShader.blocks[k]; if (block.name === blockName) { blockBinding = block.binding; break; @@ -1625,7 +1622,8 @@ export function WebGL2CmdFuncCreateShader (device: WebGL2GFXDevice, gpuShader: W (uniformInfo.type === gl.SAMPLER_CUBE); if (isSampler) { - for (const glSampler of gpuShader.glSamplers) { + for (let k = 0; k < gpuShader.glSamplers.length; k++) { + const glSampler = gpuShader.glSamplers[k]; if (glSampler.name === varName) { // let varSize = stride * uniformInfo.size; @@ -1652,7 +1650,8 @@ export function WebGL2CmdFuncCreateShader (device: WebGL2GFXDevice, gpuShader: W device.stateCache.glProgram = gpuShader.glProgram; } - for (const glSampler of glActiveSamplers) { + for (let k = 0; k < glActiveSamplers.length; k++) { + const glSampler = glActiveSamplers[k]; gl.uniform1iv(glSampler.glLoc, glSampler.units); } } @@ -1660,7 +1659,8 @@ export function WebGL2CmdFuncCreateShader (device: WebGL2GFXDevice, gpuShader: W export function WebGL2CmdFuncDestroyShader (device: WebGL2GFXDevice, gpuShader: WebGL2GPUShader) { - for (const gpuStage of gpuShader.gpuStages) { + for (let k = 0; k < gpuShader.gpuStages.length; k++) { + const gpuStage = gpuShader.gpuStages[k]; if (gpuStage.glShader) { device.gl.deleteShader(gpuStage.glShader); gpuStage.glShader = null; @@ -1710,8 +1710,11 @@ export function WebGL2CmdFuncCreateInputAssember (device: WebGL2GFXDevice, gpuIn } export function WebGL2CmdFuncDestroyInputAssembler (device: WebGL2GFXDevice, gpuInputAssembler: IWebGL2GPUInputAssembler) { - for (const vao of gpuInputAssembler.glVAOs) { - device.gl.deleteVertexArray(vao[1]); + const it = gpuInputAssembler.glVAOs.values(); + let res = it.next(); + while (!res.done) { + device.gl.deleteVertexArray(res.value); + res = it.next(); } gpuInputAssembler.glVAOs.clear(); } @@ -1906,7 +1909,7 @@ export function WebGL2CmdFuncExecuteCmds (device: WebGL2GFXDevice, cmdPackage: W break; } case WebGL2Cmd.END_RENDER_PASS: { - // WebGL 1.0 doesn't support store operation of attachments. + // WebGL 2.0 doesn't support store operation of attachments. // GFXStoreOp.Store is the default GL behaviour. break; } @@ -2160,13 +2163,16 @@ export function WebGL2CmdFuncExecuteCmds (device: WebGL2GFXDevice, cmdPackage: W } // bind pso if (cmd2.gpuBindingLayout && gpuShader) { - for (const gpuBinding of cmd2.gpuBindingLayout.gpuBindings) { + const gpuBindings = cmd2.gpuBindingLayout.gpuBindings; + for (let j = 0; j < gpuBindings.length; j++) { + const gpuBinding = gpuBindings[j]; switch (gpuBinding.type) { case GFXBindingType.UNIFORM_BUFFER: { if (gpuBinding.gpuBuffer) { - for (const glBlock of gpuShader.glBlocks) { + for (let k = 0; k < gpuShader.glBlocks.length; k++) { + const glBlock = gpuShader.glBlocks[k]; if (glBlock.binding === gpuBinding.binding) { if (cache.glBindUBOs[glBlock.binding] !== gpuBinding.gpuBuffer.glBuffer) { gl.bindBufferBase(gl.UNIFORM_BUFFER, glBlock.binding, gpuBinding.gpuBuffer.glBuffer); @@ -2187,7 +2193,8 @@ export function WebGL2CmdFuncExecuteCmds (device: WebGL2GFXDevice, cmdPackage: W let glSampler: WebGL2GPUUniformSampler | null = null; - for (const sampler of gpuShader.glSamplers) { + for (let k = 0; k < gpuShader.glSamplers.length; k++) { + const sampler = gpuShader.glSamplers[k]; if (sampler.binding === gpuBinding.binding) { glSampler = sampler; break; @@ -2195,7 +2202,8 @@ export function WebGL2CmdFuncExecuteCmds (device: WebGL2GFXDevice, cmdPackage: W } if (glSampler) { - for (const texUnit of glSampler.units) { + for (let k = 0; k < glSampler.units.length; k++) { + const texUnit = glSampler.units[k]; const glTexUnit = cache.glTexUnits[texUnit]; @@ -2250,10 +2258,12 @@ export function WebGL2CmdFuncExecuteCmds (device: WebGL2GFXDevice, cmdPackage: W gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null); let glAttrib: WebGL2Attrib | null; - for (const glInput of gpuShader.glInputs) { + for (let j = 0; j < gpuShader.glInputs.length; j++) { + const glInput = gpuShader.glInputs[j]; glAttrib = null; - for (const attrib of gpuInputAssembler.glAttribs) { + for (let k = 0; k < gpuInputAssembler.glAttribs.length; k++) { + const attrib = gpuInputAssembler.glAttribs[k]; if (attrib.name === glInput.name) { glAttrib = attrib; break; @@ -2297,10 +2307,12 @@ export function WebGL2CmdFuncExecuteCmds (device: WebGL2GFXDevice, cmdPackage: W cache.glCurrentAttribLocs[a] = false; } - for (const glInput of gpuShader.glInputs) { + for (let j = 0; j < gpuShader.glInputs.length; j++) { + const glInput = gpuShader.glInputs[j]; let glAttrib: WebGL2Attrib | null = null; - for (const attrib of gpuInputAssembler.glAttribs) { + for (let k = 0; k < gpuInputAssembler.glAttribs.length; k++) { + const attrib = gpuInputAssembler.glAttribs[k]; if (attrib.name === glInput.name) { glAttrib = attrib; break; @@ -2346,7 +2358,8 @@ export function WebGL2CmdFuncExecuteCmds (device: WebGL2GFXDevice, cmdPackage: W } if (gpuPipelineState) { - for (const dynamicState of gpuPipelineState.dynamicStates) { + for (let k = 0; k < gpuPipelineState.dynamicStates.length; k++) { + const dynamicState = gpuPipelineState.dynamicStates[k]; switch (dynamicState) { case GFXDynamicState.VIEWPORT: { if (cmd2.viewport) { @@ -2517,7 +2530,9 @@ export function WebGL2CmdFuncExecuteCmds (device: WebGL2GFXDevice, cmdPackage: W } } else { if (gpuInputAssembler.gpuIndirectBuffer) { - for (const drawInfo of gpuInputAssembler.gpuIndirectBuffer.indirects) { + const indirects = gpuInputAssembler.gpuIndirectBuffer.indirects; + for (let k = 0; k < indirects.length; k++) { + const drawInfo = indirects[k]; const gpuBuffer = gpuInputAssembler.gpuIndexBuffer; if (gpuBuffer && drawInfo.indexCount > -1) { const offset = drawInfo.firstIndex * gpuBuffer.stride; @@ -2574,7 +2589,8 @@ export function WebGL2CmdFuncCopyTexImagesToTexture ( let f = 0; switch (gpuTexture.glTarget) { case gl.TEXTURE_2D: { - for (const region of regions) { + for (let k = 0; k < regions.length; k++) { + const region = regions[k]; for (m = region.texSubres.baseMipLevel; m < region.texSubres.levelCount; ++m) { gl.texSubImage2D(gl.TEXTURE_2D, m, region.texOffset.x, region.texOffset.y, @@ -2584,7 +2600,8 @@ export function WebGL2CmdFuncCopyTexImagesToTexture ( break; } case gl.TEXTURE_CUBE_MAP: { - for (const region of regions) { + for (let k = 0; k < regions.length; k++) { + const region = regions[k]; const fcount = region.texSubres.baseArrayLayer + region.texSubres.layerCount; for (f = region.texSubres.baseArrayLayer; f < fcount; ++f) { const mcount = region.texSubres.baseMipLevel + region.texSubres.levelCount; @@ -2629,7 +2646,8 @@ export function WebGL2CmdFuncCopyBuffersToTexture ( const isCompressed = fmtInfo.isCompressed; switch (gpuTexture.glTarget) { case gl.TEXTURE_2D: { - for (const region of regions) { + for (let k = 0; k < regions.length; k++) { + const region = regions[k]; w = region.texExtent.width; h = region.texExtent.height; for (m = region.texSubres.baseMipLevel; m < region.texSubres.levelCount; ++m) { @@ -2655,7 +2673,8 @@ export function WebGL2CmdFuncCopyBuffersToTexture ( break; } case gl.TEXTURE_CUBE_MAP: { - for (const region of regions) { + for (let k = 0; k < regions.length; k++) { + const region = regions[k]; n = 0; const fcount = region.texSubres.baseArrayLayer + region.texSubres.layerCount; for (f = region.texSubres.baseArrayLayer; f < fcount; ++f) { diff --git a/cocos/core/memop/cached-array.ts b/cocos/core/memop/cached-array.ts index c857ec39fc..816113099c 100644 --- a/cocos/core/memop/cached-array.ts +++ b/cocos/core/memop/cached-array.ts @@ -22,12 +22,6 @@ export class CachedArray { */ public length: number = 0; - /** - * @zh - * 指向缓存数组的引用 - */ - private cache: Array; - /** * @zh * 比较函数 @@ -41,7 +35,6 @@ export class CachedArray { */ constructor (length: number, compareFn?: (a: T, b: T) => number) { this.array = new Array(length); - this.cache = this.array; this.length = 0; if (compareFn !== undefined) { @@ -83,7 +76,6 @@ export class CachedArray { * 清空数组所有元素 */ public clear () { - this.cache.fill(null); this.length = 0; } diff --git a/cocos/core/pipeline/forward/forward-pipeline.ts b/cocos/core/pipeline/forward/forward-pipeline.ts index 11b2d8eeb0..20b86e2e1b 100644 --- a/cocos/core/pipeline/forward/forward-pipeline.ts +++ b/cocos/core/pipeline/forward/forward-pipeline.ts @@ -285,8 +285,10 @@ export class ForwardPipeline extends RenderPipeline { */ protected sceneCulling (view: RenderView) { super.sceneCulling(view); - this._validLights.splice(0); - for (const light of view.camera.scene!.sphereLights) { + this._validLights.length = 0; + const sphereLights = view.camera.scene!.sphereLights; + for (let i = 0; i < sphereLights.length; i++) { + const light = sphereLights[i]; if (light.enabled) { light.update(); sphere.set(_sphere, light.position.x, light.position.y, light.position.z, light.range); @@ -295,7 +297,9 @@ export class ForwardPipeline extends RenderPipeline { } } } - for (const light of view.camera.scene!.spotLights) { + const spotLights = view.camera.scene!.spotLights; + for (let i = 0; i < spotLights.length; i++) { + const light = spotLights[i]; if (light.enabled) { light.update(); sphere.set(_sphere, light.position.x, light.position.y, light.position.z, light.range); @@ -305,8 +309,8 @@ export class ForwardPipeline extends RenderPipeline { } } - this._lightIndexOffset.splice(0); - this._lightIndices.splice(0); + this._lightIndexOffset.length = 0; + this._lightIndices.length = 0; for (let i = 0; i < this._renderObjects.length; i++) { this._lightIndexOffset[i] = this._lightIndices.length; if (this._renderObjects[i].model.localBindings.get(UBOForwardLight.BLOCK.name)) { diff --git a/cocos/core/pipeline/render-pipeline.ts b/cocos/core/pipeline/render-pipeline.ts index 2bb71109a3..469de3ab56 100644 --- a/cocos/core/pipeline/render-pipeline.ts +++ b/cocos/core/pipeline/render-pipeline.ts @@ -848,9 +848,9 @@ export abstract class RenderPipeline { } } - this._shadingTexViews.splice(0); - this._shadingTextures.splice(0); - this._shadingFBOs.splice(0); + this._shadingTexViews.length = 0; + this._shadingTextures.length = 0; + this._shadingFBOs.length = 0; if (this._depthStencilTexView) { this._depthStencilTexView.destroy(); @@ -1181,13 +1181,13 @@ export abstract class RenderPipeline { Vec4.toArray(fv, _v4Zero, UBOGlobal.MAIN_LIT_COLOR_OFFSET); } - _vec4Array.set(ambient.skyColor); + const skyColor = ambient.skyColor; if (this._isHDR) { - _vec4Array[3] = ambient.skyIllum * this._fpScale; + skyColor[3] = ambient.skyIllum * this._fpScale; } else { - _vec4Array[3] = ambient.skyIllum * exposure; + skyColor[3] = ambient.skyIllum * exposure; } - this._uboGlobal.view.set(_vec4Array, UBOGlobal.AMBIENT_SKY_OFFSET); + this._uboGlobal.view.set(skyColor, UBOGlobal.AMBIENT_SKY_OFFSET); this._uboGlobal.view.set(ambient.groundAlbedo, UBOGlobal.AMBIENT_GROUND_OFFSET); @@ -1205,7 +1205,7 @@ export abstract class RenderPipeline { const camera = view.camera; const scene = camera.scene!; - this._renderObjects.splice(0); + this._renderObjects.length = 0; const mainLight = scene.mainLight; if (mainLight && mainLight.enabled) { @@ -1221,7 +1221,9 @@ export abstract class RenderPipeline { this.addVisibleModel(scene.skybox, camera); } - for (const model of scene.models) { + const models = scene.models; + for (let i = 0; i < models.length; i++) { + const model = models[i]; model._resetUBOUpdateFlag(); diff --git a/cocos/core/renderer/core/pass.ts b/cocos/core/renderer/core/pass.ts index b06b343bdc..5e97a78459 100644 --- a/cocos/core/renderer/core/pass.ts +++ b/cocos/core/renderer/core/pass.ts @@ -542,34 +542,10 @@ export class Pass { if (saveOverrides) { Object.assign(this._defines, defineOverrides); } else { Object.assign(defineOverrides, this._defines); defines = defineOverrides; } } - const shader = programLib.getGFXShader(this._device, this._programName, defines, pipeline); - if (!shader) { console.warn(`create shader ${this._programName} failed`); return null; } - if (saveOverrides) { this._shader = shader; } - - const { blocks, samplers } = this._shaderInfo; - this._bindings.length = 0; - let lastBinding = -1; - blocks: - for (let i = 0; i < blocks.length; i++) { - const block = blocks[i]; - if (block.binding === lastBinding) { continue; } - for (let j = 0; j < block.defines.length; j++) { - if (!defines[block.defines[j]]) { continue blocks; } - } - lastBinding = block.binding; - this._bindings.push(block); - } - samplers: - for (let i = 0; i < samplers.length; i++) { - const sampler = samplers[i]; - if (sampler.binding === lastBinding) { continue; } - for (let j = 0; j < sampler.defines.length; j++) { - if (!defines[sampler.defines[j]]) { continue samplers; } - } - lastBinding = sampler.binding; - this._bindings.push(sampler); - } - return shader; + const res = programLib.getGFXShader(this._device, this._programName, defines, pipeline); + if (!res.shader) { console.warn(`create shader ${this._programName} failed`); return null; } + if (saveOverrides) { this._shader = res.shader; this._bindings = res.bindings; } + return res; } /** @@ -581,10 +557,12 @@ export class Pass { console.warn(`pass resources not complete, create PSO failed`); return null; } - let shader = this._shader!; - if (defineOverrides) { shader = this.tryCompile(defineOverrides, false)!; } + let shader = this._shader!; _blInfo.bindings = this._bindings; + if (defineOverrides) { + const res = this.tryCompile(defineOverrides, false); + if (res) { shader = res.shader; _blInfo.bindings = res.bindings; } + } // bind resources - _blInfo.bindings = this._bindings; const bindingLayout = this._device.createBindingLayout(_blInfo); for (const b in this._buffers) { bindingLayout.bindBuffer(parseInt(b), this._buffers[b]); diff --git a/cocos/core/renderer/core/program-lib.ts b/cocos/core/renderer/core/program-lib.ts index 30f584ecb6..57bb279aae 100644 --- a/cocos/core/renderer/core/program-lib.ts +++ b/cocos/core/renderer/core/program-lib.ts @@ -138,13 +138,44 @@ function genHandles (tmpl: IProgramInfo) { return handleMap; } +function dependencyCheck (dependencies: string[], defines: IDefineMap) { + for (let i = 0; i < dependencies.length; i++) { + if (!defines[dependencies[i]]) { return false; } + } + return true; +} +function getShaderBindings ( + tmpl: IProgramInfo, defines: IDefineMap, outBlocks: IBlockInfoRT[], outSamplers: ISamplerInfoRT[], bindings: IGFXBinding[]) { + const { blocks, samplers } = tmpl; + let lastBinding = -1; + for (let i = 0; i < blocks.length; i++) { + const block = blocks[i]; + if (block.binding === lastBinding || !dependencyCheck(block.defines, defines)) { continue; } + lastBinding = block.binding; + outBlocks.push(block); + bindings.push(block); + } + for (let i = 0; i < samplers.length; i++) { + const sampler = samplers[i]; + if (sampler.binding === lastBinding || !dependencyCheck(sampler.defines, defines)) { continue; } + lastBinding = sampler.binding; + outSamplers.push(sampler); + bindings.push(sampler); + } +} + +interface IShaderResources { + shader: GFXShader; + bindings: IGFXBinding[]; +} + /** * @zh * 维护 shader 资源实例的全局管理器。 */ class ProgramLib { protected _templates: Record; - protected _cache: Record; + protected _cache: Record; constructor () { this._templates = {}; @@ -232,10 +263,11 @@ class ProgramLib { if (typeof val === 'boolean') { val = val ? '1' : '0'; } return new RegExp(cur + val); }); - const keys = Object.keys(this._cache).filter((k) => regexes.every((re) => re.test(this._cache[k].name))); + const keys = Object.keys(this._cache).filter((k) => regexes.every((re) => re.test(this._cache[k].shader.name))); for (const k of keys) { - console.log(`destroyed shader ${this._cache[k].name}`); - this._cache[k].destroy(); + const prog = this._cache[k].shader; + console.log(`destroyed shader ${prog.name}`); + prog.destroy(); delete this._cache[k]; } } @@ -251,19 +283,15 @@ class ProgramLib { public getGFXShader (device: GFXDevice, name: string, defines: IDefineMap, pipeline: RenderPipeline) { Object.assign(defines, pipeline.macros); const key = this.getKey(name, defines); - let program = this._cache[key]; - if (program !== undefined) { - return program; - } + const res = this._cache[key]; + if (res) { return res; } // get template const tmpl = this._templates[name]; if (!tmpl.globalsInited) { insertBuiltinBindings(tmpl, pipeline.globalBindings, 'globals'); tmpl.globalsInited = true; } const macroArray = prepareDefines(defines, tmpl.defines); - const customDef = macroArray.reduce((acc, cur) => { - return `${acc}#define ${cur.name} ${cur.value}\n`; - }, ''); + const customDef = macroArray.reduce((acc, cur) => `${acc}#define ${cur.name} ${cur.value}\n`, ''); let vert: string = ''; let frag: string = ''; @@ -275,17 +303,20 @@ class ProgramLib { frag = `#version 100\n${customDef}\n${tmpl.glsl1.frag}`; } - program = device.createShader({ + const blocks: IBlockInfoRT[] = []; + const samplers: ISamplerInfoRT[] = []; + const bindings: IGFXBinding[] = []; + getShaderBindings(tmpl, defines, blocks, samplers, bindings); + + const shader = device.createShader({ name: getShaderInstanceName(name, macroArray), - blocks: tmpl.blocks, - samplers: tmpl.samplers, + blocks, samplers, stages: [ { type: GFXShaderType.VERTEX, source: vert }, { type: GFXShaderType.FRAGMENT, source: frag }, ], }); - this._cache[key] = program; - return program; + return this._cache[key] = { shader, bindings }; } } diff --git a/cocos/core/renderer/core/sampler-lib.ts b/cocos/core/renderer/core/sampler-lib.ts index 7a7afd5ab8..e03744933c 100644 --- a/cocos/core/renderer/core/sampler-lib.ts +++ b/cocos/core/renderer/core/sampler-lib.ts @@ -43,8 +43,7 @@ export enum SamplerInfoIndex { minLOD, maxLOD, mipLODBias, - borderColor, - total = borderColor + 4, + total, } const defaultInfo = [ @@ -57,10 +56,11 @@ const defaultInfo = [ 8, GFXComparisonFunc.NEVER, 0, 0, 0, - 0, 0, 0, 0, ]; const defaultHash = genSamplerHash(defaultInfo); +const borderColor = { r: 0, g: 0, b: 0, a: 0 }; + const gfxInfo: IGFXSamplerInfo = {}; export function genSamplerHash (info: Array): number { @@ -115,7 +115,7 @@ class SamplerLib { gfxInfo.minLOD = ((hash >> 20) & 15); gfxInfo.maxLOD = ((hash >> 24) & 15); gfxInfo.mipLODBias = ((hash >> 28) & 15); - gfxInfo.borderColor = { r: 0, g: 0, b: 0, a: 0 }; + gfxInfo.borderColor = borderColor; const sampler = this._cache[hash] = device.createSampler(gfxInfo); return sampler; diff --git a/cocos/core/renderer/core/texture-buffer-pool.ts b/cocos/core/renderer/core/texture-buffer-pool.ts index 31d4efc2ab..831e7e2822 100644 --- a/cocos/core/renderer/core/texture-buffer-pool.ts +++ b/cocos/core/renderer/core/texture-buffer-pool.ts @@ -7,7 +7,7 @@ import { GFXDevice } from '../../gfx/device'; import { GFXTexture } from '../../gfx/texture'; import { GFXTextureView } from '../../gfx/texture-view'; -function nearestPO2 (num: number): number { +export function nearestPOT (num: number): number { --num; num |= num >> 16; num |= num >> 8; @@ -145,7 +145,7 @@ export class TextureBufferPool { // create a new one const targetSize = Math.sqrt(size / this._formatSize); - const texWidth = this._roundUpFn && this._roundUpFn(targetSize, this._formatSize) || Math.max(1024, nearestPO2(targetSize)); + const texWidth = this._roundUpFn && this._roundUpFn(targetSize, this._formatSize) || Math.max(1024, nearestPOT(targetSize)); const texSize = texWidth * texWidth * this._formatSize; console.info('TextureBufferPool: Allocate chunk ' + this._chunkCount + ', size: ' + texSize); diff --git a/cocos/core/renderer/models/skeletal-animation-utils.ts b/cocos/core/renderer/models/skeletal-animation-utils.ts index 7b63576dc2..2dde663e9b 100644 --- a/cocos/core/renderer/models/skeletal-animation-utils.ts +++ b/cocos/core/renderer/models/skeletal-animation-utils.ts @@ -38,7 +38,7 @@ import { GFXDevice, GFXFeature } from '../../gfx/device'; import { Mat4, Quat, Vec3 } from '../../math'; import { UBOSkinningAnimation } from '../../pipeline/define'; import { genSamplerHash } from '../core/sampler-lib'; -import { ITextureBufferHandle, TextureBufferPool } from '../core/texture-buffer-pool'; +import { ITextureBufferHandle, nearestPOT, TextureBufferPool } from '../core/texture-buffer-pool'; // change here and cc-skinning.chunk to use other skinning algorithms const uploadJointData = uploadJointDataLBS; @@ -175,7 +175,7 @@ export class JointsTexturePool { this._identityBuffer.readyToBeDeleted = true; this.releaseHandle(this._identityBuffer, false); } - this._maxIdentityJoints *= 2; + this._maxIdentityJoints = nearestPOT(len); this._identityBuffer = this._allocIdentityBuffer(); } if (!this._identityBuffer) { return null; } diff --git a/cocos/core/renderer/scene/directional-light.ts b/cocos/core/renderer/scene/directional-light.ts index 71af9b7549..b522274a2f 100644 --- a/cocos/core/renderer/scene/directional-light.ts +++ b/cocos/core/renderer/scene/directional-light.ts @@ -1,4 +1,5 @@ import { Quat, Vec3 } from '../../math'; +import { TransformBit } from '../../scene-graph/node-enum'; import { INode } from '../../utils/interfaces'; import { Light, LightType } from './light'; import { RenderScene } from './render-scene'; @@ -33,10 +34,11 @@ export class DirectionalLight extends Light { constructor () { super(); this._type = LightType.DIRECTIONAL; + this._node.hasChangedFlags = TransformBit.ROTATION; } public update () { - if (this._node) { + if (this._node && this._node.hasChangedFlags) { this._dir = Vec3.transformQuat(_v3, _forward, this._node.getWorldRotation(_qt)); Vec3.normalize(this._dir, this._dir); } From e4f0efd2ccc7c1a153b51d397daf2d42201e7547 Mon Sep 17 00:00:00 2001 From: JoneLau <32630749+JoneLau@users.noreply.github.com> Date: Tue, 26 Nov 2019 10:02:01 +0800 Subject: [PATCH 05/21] remove uicomponent's priority to uitransform and canvas sort in event (#5762) --- EngineErrorMap.md | 4 + .../components/ui-base/canvas-component.ts | 4 + cocos/core/components/ui-base/ui-component.ts | 119 +----------------- .../components/ui-base/ui-render-component.ts | 4 - .../ui-base/ui-transfrom-component.ts | 117 +++++++++++++---- cocos/core/platform/SubContextView.ts | 2 +- .../platform/event-manager/event-manager.ts | 10 +- cocos/core/renderer/ui/ui.ts | 44 ++++--- cocos/ui/components/editbox/edit-box-impl.ts | 19 +-- cocos/ui/components/mask-component.ts | 34 ++--- cocos/ui/components/ui-model-component.ts | 4 + cocos/ui/components/ui-reorder-component.ts | 1 + cocos/ui/components/widget-manager.ts | 19 +-- 13 files changed, 167 insertions(+), 214 deletions(-) diff --git a/EngineErrorMap.md b/EngineErrorMap.md index e69834f754..b41c587dd6 100644 --- a/EngineErrorMap.md +++ b/EngineErrorMap.md @@ -1960,3 +1960,7 @@ Stencil manager is already empty, cannot pop any mask ### 9100 texture size exceeds current device limits %d/%d + +### 9200 + +Priority can't be set in Canvas node diff --git a/cocos/core/components/ui-base/canvas-component.ts b/cocos/core/components/ui-base/canvas-component.ts index 81028f7bd0..4c421a4a86 100644 --- a/cocos/core/components/ui-base/canvas-component.ts +++ b/cocos/core/components/ui-base/canvas-component.ts @@ -137,6 +137,10 @@ export class CanvasComponent extends Component { if (this._camera) { this._camera.priority = this._getViewPriority(); } + + if(director.root && director.root.ui){ + director.root.ui.sortScreens(); + } } /** diff --git a/cocos/core/components/ui-base/ui-component.ts b/cocos/core/components/ui-base/ui-component.ts index 8336abbeaf..e94b9cc5a5 100644 --- a/cocos/core/components/ui-base/ui-component.ts +++ b/cocos/core/components/ui-base/ui-component.ts @@ -27,82 +27,34 @@ * @category ui */ -import { ccclass, disallowMultiple, executeInEditMode, executionOrder, property } from '../../../core/data/class-decorator'; -import { SystemEventType } from '../../../core/platform/event-manager/event-enum'; +import { ccclass, disallowMultiple, executeInEditMode, executionOrder, property, requireComponent } from '../../../core/data/class-decorator'; import { INode } from '../../../core/utils/interfaces'; import { UI } from '../../renderer/ui/ui'; import { Component } from '../component'; -import { CanvasComponent } from './canvas-component'; +import { UITransformComponent } from './ui-transfrom-component'; /** * @zh * UI 及 UI 模型渲染基类。 */ @ccclass('cc.UIComponent') +@requireComponent(UITransformComponent) @executionOrder(110) @disallowMultiple @executeInEditMode export class UIComponent extends Component { - /** - * @zh - * 渲染先后顺序,按照广度渲染排列,按同级节点下进行一次排列。 - */ - @property({ - tooltip:'渲染排序优先级' - }) - get priority () { - return this._priority; - } - - set priority (value) { - if (this._priority === value) { - return; - } - - this._priority = value; - this._sortSiblings(); - } - - /** - * @zh - * 查找被渲染相机。 - */ - get visibility () { - if (!this._screen){ - return -1; - } - - return this._screen.visibility; - } - - get _screen (){ - return this._followScreen; - } - - @property - protected _priority = 0; - - protected _followScreen: CanvasComponent | null = null; - - private _lastParent: INode | null = null; + protected _lastParent: INode | null = null; public __preload () { this.node._uiComp = this; } public onEnable () { - this._lastParent = this.node.parent; - this._updateVisibility(); - - if (this._lastParent) { - this.node.on(SystemEventType.CHILD_REMOVED, this._parentChanged, this); - } - this._sortSiblings(); } public onDisable () { - this._cancelEventFromParent(); + } public onDestroy () { @@ -116,65 +68,4 @@ export class UIComponent extends Component { public postUpdateAssembler (render: UI) { } - - public _setScreen (value: CanvasComponent){ - this._followScreen = value; - } - - protected _parentChanged (node: INode) { - if (node === this.node) { - this._updateVisibility(); - this._cancelEventFromParent(); - this._lastParent = this.node.parent; - this._sortSiblings(); - return true; - } - - return false; - } - - private _sortSiblings () { - const siblings = this.node.parent && this.node.parent.children as Mutable; - if (siblings) { - siblings.sort((a: INode, b: INode) => { - const aComp = a._uiComp; - const bComp = b._uiComp; - const ca = aComp ? aComp.priority : 0; - const cb = bComp ? bComp.priority : 0; - const diff = ca - cb; - if(diff === 0){ - return a.getSiblingIndex() - b.getSiblingIndex(); - } - return diff; - }); - - this.node.parent!._updateSiblingIndex(); - } - } - - private _updateVisibility () { - let parent = this.node; - // 获取被渲染相机的 visibility - while (parent) { - if (parent) { - const canvasComp = parent.getComponent(CanvasComponent); - if (canvasComp) { - this._followScreen = canvasComp; - break; - } - } - - // @ts-ignore - parent = parent.parent; - } - } - - private _cancelEventFromParent () { - if (this._lastParent) { - this._lastParent.off(SystemEventType.CHILD_REMOVED, this._parentChanged, this); - this._lastParent = null; - } - - this._followScreen = null; - } } diff --git a/cocos/core/components/ui-base/ui-render-component.ts b/cocos/core/components/ui-base/ui-render-component.ts index 0c430bf900..355af06d40 100644 --- a/cocos/core/components/ui-base/ui-render-component.ts +++ b/cocos/core/components/ui-base/ui-render-component.ts @@ -32,7 +32,6 @@ import { executeInEditMode, executionOrder, property, - requireComponent, } from '../../../core/data/class-decorator'; import { SystemEventType } from '../../../core/platform/event-manager/event-enum'; import { Color } from '../../../core/math'; @@ -80,9 +79,6 @@ export enum InstanceMaterialType { * 可通过 cc.UIRenderComponent 获得该组件。 */ @ccclass('cc.UIRenderComponent') -@executionOrder(110) -@requireComponent(UITransformComponent) -@executeInEditMode export class UIRenderComponent extends UIComponent { /** diff --git a/cocos/core/components/ui-base/ui-transfrom-component.ts b/cocos/core/components/ui-base/ui-transfrom-component.ts index ddec903c56..95b4164792 100644 --- a/cocos/core/components/ui-base/ui-transfrom-component.ts +++ b/cocos/core/components/ui-base/ui-transfrom-component.ts @@ -35,7 +35,7 @@ import { Mat4, Rect, Size, Vec2, Vec3 } from '../../../core/math'; import { aabb } from '../../geom-utils'; import { CanvasComponent } from './canvas-component'; import { director } from '../../director'; -import { Layers } from '../../scene-graph/layers'; +import { INode } from '../../utils/interfaces'; const _vec2a = new Vec2(); const _vec2b = new Vec2(); @@ -181,16 +181,75 @@ export class UITransformComponent extends Component { this.node.emit(SystemEventType.ANCHOR_CHANGED, this._anchorPoint); } + /** + * @zh + * 渲染先后顺序,按照广度渲染排列,按同级节点下进行一次排列。 + */ + @property({ + tooltip: '渲染排序优先级' + }) + get priority() { + return this._priority; + } + + set priority(value) { + if (this._priority === value) { + return; + } + + if (this._canvas && this._canvas.node === this.node) { + cc.warn(9200); + return; + } + + this._priority = value; + this._sortSiblings(); + } + + @property + protected _priority = 0; + + /** + * @zh + * 查找被渲染相机。 + */ + get visibility() { + if (!this._screen) { + return -1; + } + + return this._screen.visibility; + } + + get _screen() { + return this._canvas; + } + public static EventType = SystemEventType; @property - private _contentSize = new Size(100, 100); + protected _contentSize = new Size(100, 100); @property - private _anchorPoint = new Vec2(0.5, 0.5); + protected _anchorPoint = new Vec2(0.5, 0.5); + + public _canvas: CanvasComponent | null = null; public __preload () { this.node.uiTransfromComp = this; } + public onEnable(){ + this._updateVisibility(); + + this.node.on(SystemEventType.PARENT_CHANGED, this._parentChanged, this); + + this._sortSiblings(); + } + + public onDisable(){ + this.node.off(SystemEventType.PARENT_CHANGED, this._parentChanged, this); + this._canvas = null; + } + public onDestroy () { this.node.uiTransfromComp = null; } @@ -292,22 +351,12 @@ export class UITransformComponent extends Component { * @param listener - 事件监听器。 */ public isHit (point: Vec2, listener?: EventListener) { - // console.log('click point ' + point.toString()); const w = this._contentSize.width; const h = this._contentSize.height; const cameraPt = _vec2a; const testPt = _vec2b; - // hack: discuss how to distribute 3D event - let visibility = -1; - const renderComp = this.node.getComponent(cc.UIRenderComponent) as any; - if (!renderComp) { - visibility = this._getVisibility(); - } else { - visibility = renderComp.visibility; - } - - const canvas = director.root!.ui.getScreen(visibility); + const canvas = this._canvas; if (!canvas) { return; } @@ -360,7 +409,7 @@ export class UITransformComponent extends Component { * @returns - 返回与目标节点的相对位置。 * @example * ```typescript - * var newVec3 = uiTransform.convertToNodeSpaceAR(cc.v3(100, 100, 0)); + * const newVec3 = uiTransform.convertToNodeSpaceAR(cc.v3(100, 100, 0)); * ``` */ public convertToNodeSpaceAR (worldPoint: Vec3, out?: Vec3) { @@ -382,7 +431,7 @@ export class UITransformComponent extends Component { * @returns - 返回 UI 世界坐标系。 * @example * ```typescript - * var newVec3 = uiTransform.convertToWorldSpaceAR(3(100, 100, 0)); + * const newVec3 = uiTransform.convertToWorldSpaceAR(3(100, 100, 0)); * ``` */ public convertToWorldSpaceAR (nodePoint: Vec3, out?: Vec3) { @@ -401,7 +450,7 @@ export class UITransformComponent extends Component { * @return - 节点大小的包围盒 * @example * ```typescript - * var boundingBox = uiTransform.getBoundingBox(); + * const boundingBox = uiTransform.getBoundingBox(); * ``` */ public getBoundingBox () { @@ -425,7 +474,7 @@ export class UITransformComponent extends Component { * @returns - 返回世界坐标系下包围盒。 * @example * ```typescript - * var newRect = uiTransform.getBoundingBoxToWorld(); + * const newRect = uiTransform.getBoundingBoxToWorld(); * ``` */ public getBoundingBoxToWorld () { @@ -506,15 +555,14 @@ export class UITransformComponent extends Component { } } - private _getVisibility () { - let visibility = -1; + public _updateVisibility() { let parent = this.node; // 获取被渲染相机的 visibility while (parent) { if (parent) { const canvasComp = parent.getComponent('cc.CanvasComponent') as CanvasComponent; if (canvasComp) { - visibility = canvasComp.visibility; + this._canvas = canvasComp; break; } } @@ -522,8 +570,33 @@ export class UITransformComponent extends Component { // @ts-ignore parent = parent.parent; } + } - return visibility; + protected _parentChanged(node: INode) { + if (this._canvas && this._canvas.node === this.node) { + return; + } + + this._sortSiblings(); + } + + protected _sortSiblings() { + const siblings = this.node.parent && this.node.parent.children as Mutable; + if (siblings) { + siblings.sort((a: INode, b: INode) => { + const aComp = a.uiTransfromComp; + const bComp = b.uiTransfromComp; + const ca = aComp ? aComp.priority : 0; + const cb = bComp ? bComp.priority : 0; + const diff = ca - cb; + if (diff === 0) { + return a.getSiblingIndex() - b.getSiblingIndex(); + } + return diff; + }); + + this.node.parent!._updateSiblingIndex(); + } } } diff --git a/cocos/core/platform/SubContextView.ts b/cocos/core/platform/SubContextView.ts index 8286767c3e..a049faab90 100644 --- a/cocos/core/platform/SubContextView.ts +++ b/cocos/core/platform/SubContextView.ts @@ -91,7 +91,7 @@ export class SubContextView extends Component { public onLoad () { // Setup subcontext canvas size - if (wx.getOpenDataContext) { + if (wx && wx.getOpenDataContext) { this._updateInterval = 1000 / this._fps; this._context = wx.getOpenDataContext(); // reset sharedCanvas width and height diff --git a/cocos/core/platform/event-manager/event-manager.ts b/cocos/core/platform/event-manager/event-manager.ts index b2fe506b9b..2082aa6187 100644 --- a/cocos/core/platform/event-manager/event-manager.ts +++ b/cocos/core/platform/event-manager/event-manager.ts @@ -768,14 +768,18 @@ class EventManager { const node1 = l1._getSceneGraphPriority(); const node2 = l2._getSceneGraphPriority(); // Event manager should only care about ui node in the current scene hierarchy - if (!l2 || !node2 || !node2._activeInHierarchy) { + if (!l2 || !node2 || !node2._activeInHierarchy || !(node2 as INode).uiTransfromComp) { return -1; } - else if (!l1 || !node1 || !node1._activeInHierarchy) { + else if (!l1 || !node1 || !node1._activeInHierarchy || !(node1 as INode).uiTransfromComp) { return 1; } - let p1 = node1; let p2 = node2; let ex = false; + let p1 = node1; let p2 = node2; let trans1 = (node1 as INode).uiTransfromComp; let trans2 = (node2 as INode).uiTransfromComp; let ex = false; + if (trans1.visibility !== trans2.visibility) { + return trans2.visibility - trans1.visibility; + } + while (p1.parent._id !== p2.parent._id) { p1 = p1.parent.parent === null ? (ex = true) && node2 : p1.parent; p2 = p2.parent.parent === null ? (ex = true) && node1 : p2.parent; diff --git a/cocos/core/renderer/ui/ui.ts b/cocos/core/renderer/ui/ui.ts index fdb8fed312..8bb3748f84 100644 --- a/cocos/core/renderer/ui/ui.ts +++ b/cocos/core/renderer/ui/ui.ts @@ -98,7 +98,7 @@ export class UI { private _emptyMaterial = new Material(); private _currMaterial: Material = this._emptyMaterial; private _currTexView: GFXTextureView | null = null; - private _currCanvas = -1; + private _currCanvas: CanvasComponent | null = null; private _currMeshBuffer: MeshBuffer | null = null; private _currStaticRoot: UIStaticBatchComponent | null = null; @@ -190,12 +190,17 @@ export class UI { */ public addScreen (comp: CanvasComponent) { this._screens.push(comp); - if (comp.camera) { - comp.camera.view.visibility = Layers.BitMask.UI_2D | this._screens.length; - this._canvasMaterials.set(comp.camera.view.visibility, new Map()); - } - this._screens.sort(this._screenSort); + const screens = this._screens; + for (let i = 0; i < screens.length; i++) { + const element = screens[i]; + if(element.camera){ + element.camera.view.visibility = Layers.BitMask.UI_2D | (i + 1); + if (!this._canvasMaterials.has(element.camera.view.visibility)){ + this._canvasMaterials.set(element.camera.view.visibility, new Map()); + } + } + } } /** @@ -268,6 +273,10 @@ export class UI { this._reset(); } + public sortScreens(){ + this._screens.sort(this._screenSort); + } + public render () { let batchPriority = 0; @@ -332,13 +341,11 @@ export class UI { const renderComp = comp; const texView = frame; if (this._currMaterial.hash !== renderComp.material!.hash || - this._currTexView !== texView || - this._currCanvas !== renderComp.visibility + this._currTexView !== texView ) { this.autoMergeBatches(); this._currMaterial = renderComp.material!; this._currTexView = texView; - this._currCanvas = renderComp.visibility; } if (assembler) { @@ -369,7 +376,7 @@ export class UI { } } - const uiCanvas = this.getScreen(comp.visibility); + const uiCanvas = this.getScreen(comp.node.uiTransfromComp.visibility); const curDrawBatch = this._drawBatchPool.alloc(); curDrawBatch.camera = uiCanvas && uiCanvas.camera; curDrawBatch.model = model; @@ -385,7 +392,6 @@ export class UI { // reset current render state to null this._currMaterial = this._emptyMaterial; this._currTexView = null; - this._currCanvas = comp.visibility; this._batches.push(curDrawBatch); } @@ -408,7 +414,7 @@ export class UI { return; } - const uiCanvas = this.getScreen(this._currCanvas); + const uiCanvas = this._currCanvas; StencilManager.sharedManager!.handleMaterial(mat); @@ -491,11 +497,18 @@ export class UI { continue; } + this._currCanvas = screen; this._recursiveScreenNode(screen.node); } } private _preprocess (c: INode) { + if(!c.uiTransfromComp){ + return; + } + + // parent changed can flush child visibility + c.uiTransfromComp._canvas = this._currCanvas; const render = c._uiComp; if (render && render.enabledInHierarchy) { render.updateAssembler(this); @@ -528,7 +541,7 @@ export class UI { this._batches.clear(); this._currMaterial = this._emptyMaterial; - this._currCanvas = -1; + this._currCanvas = null; this._currTexView = null; this._meshBufferUseCount = 0; this._requireBufferBatch(); @@ -555,7 +568,8 @@ export class UI { } } - private _screenSort (a: CanvasComponent, b: CanvasComponent){ - return a.priority - b.priority; + private _screenSort(a: CanvasComponent, b: CanvasComponent) { + const delta = a.priority - b.priority; + return delta === 0 ? a.node.getSiblingIndex() - b.node.getSiblingIndex() : delta; } } diff --git a/cocos/ui/components/editbox/edit-box-impl.ts b/cocos/ui/components/editbox/edit-box-impl.ts index 85ad5936c7..10f53cba30 100644 --- a/cocos/ui/components/editbox/edit-box-impl.ts +++ b/cocos/ui/components/editbox/edit-box-impl.ts @@ -421,13 +421,13 @@ export class EditBoxImpl { public _updateMatrix () { if (!this._edTxt) { return; } - const node = this._node; + const node = this._node!; let scaleX = view.getScaleX(); let scaleY = view.getScaleY(); const viewport = view.getViewportRect(); const dpr = view.getDevicePixelRatio(); - node!.getWorldMatrix(_matrix); + node.getWorldMatrix(_matrix); const transform = node!.uiTransfromComp; if (transform) { Vec3.set(_vec3, -transform.anchorX * transform.width, -transform.anchorY * transform.height, _vec3.z); @@ -435,20 +435,11 @@ export class EditBoxImpl { Mat4.transform(_matrix, _matrix, _vec3); - // let camera; - // can't find camera in editor - // if (CC_EDITOR) { - // camera = cc.Camera.main; - // } - // else { - // camera = cc.Camera.findCamera(node); - // } - const renderComp:UIRenderComponent = node!.getComponent(UIRenderComponent); - if (!renderComp) { + if (!node.uiTransfromComp) { return false; } - // let canvas = cc.CanvasComponent.findView(renderComp); - const canvas = director.root!.ui.getScreen(renderComp.visibility); + + const canvas = director.root!.ui.getScreen(node.uiTransfromComp.visibility); if (!canvas) { return; } diff --git a/cocos/ui/components/mask-component.ts b/cocos/ui/components/mask-component.ts index 9649eaf7ff..0cfeab99ad 100644 --- a/cocos/ui/components/mask-component.ts +++ b/cocos/ui/components/mask-component.ts @@ -39,6 +39,8 @@ import { UI } from '../../core/renderer/ui/ui'; import { Node } from '../../core/scene-graph'; import { ccenum } from '../../core/value-types/enum'; import { GraphicsComponent } from './graphics-component'; +import { UITransformComponent, CanvasComponent } from '../../core'; +import { INode } from '../../core/utils/interfaces'; import { TransformBit } from '../../core/scene-graph/node-enum'; const _worldMatrix = new Mat4(); @@ -260,7 +262,7 @@ export class MaskComponent extends UIRenderComponent { // private _spriteFrame: SpriteFrame | null = null; @property - private _type = MaskType.RECT; + protected _type = MaskType.RECT; // @property // private _alphaThreshold = 0; @@ -269,10 +271,10 @@ export class MaskComponent extends UIRenderComponent { // private _inverted = false; @property - private _segments = 64; + protected _segments = 64; - private _graphics: GraphicsComponent | null = null; - private _clearGraphics: GraphicsComponent | null = null; + protected _graphics: GraphicsComponent | null = null; + protected _clearGraphics: GraphicsComponent | null = null; constructor () { super(); @@ -299,7 +301,6 @@ export class MaskComponent extends UIRenderComponent { public onEnable () { super.onEnable(); - this._flushVisibility(); // if (this._type === MaskType.IMAGE_STENCIL) { // if (!this._spriteFrame || !this._spriteFrame.textureLoaded()) { // if (this._spriteFrame) { @@ -437,15 +438,6 @@ export class MaskComponent extends UIRenderComponent { } } - protected _parentChanged (node: Node) { - if (super._parentChanged(node)) { - this._flushVisibility(); - return true; - } - - return false; - } - private _onTextureLoaded () { // Mark render data dirty if (this._renderData) { @@ -475,8 +467,8 @@ export class MaskComponent extends UIRenderComponent { private _createGraphics () { if (!this._clearGraphics) { - const clearGraphics = this._clearGraphics = new GraphicsComponent(); - clearGraphics.node = new Node('clear-graphics'); + const node = new Node('clear-graphics'); + const clearGraphics = this._clearGraphics = node.addComponent(GraphicsComponent)!; clearGraphics.helpInstanceMaterial(); clearGraphics._activateMaterial(); clearGraphics.lineWidth = 0; @@ -567,16 +559,6 @@ export class MaskComponent extends UIRenderComponent { } } - private _flushVisibility () { - if (this._clearGraphics) { - this._clearGraphics._setScreen(this._screen!); - } - - if (this._graphics) { - this._graphics._setScreen(this._screen!); - } - } - private _activateMaterial () { // if (this._type === MaskType.IMAGE_STENCIL && (!this.spriteFrame || !this.spriteFrame.textureLoaded())) { // this._renderPermit = false; diff --git a/cocos/ui/components/ui-model-component.ts b/cocos/ui/components/ui-model-component.ts index 5cf6eed877..ffceb60ce9 100644 --- a/cocos/ui/components/ui-model-component.ts +++ b/cocos/ui/components/ui-model-component.ts @@ -56,6 +56,10 @@ export class UIModelComponent extends UIComponent { private _modelComponent: RenderableComponent | null = null; public onLoad () { + if(!this.node.uiTransfromComp){ + this.node.addComponent('cc.UITransformComponent'); + } + this._modelComponent = this.getComponent('cc.RenderableComponent') as RenderableComponent; if (!this._modelComponent) { console.warn(`node '${this.node && this.node.name}' doesn't have any renderable component`); diff --git a/cocos/ui/components/ui-reorder-component.ts b/cocos/ui/components/ui-reorder-component.ts index 5c177a14c7..fa4eb2d0b8 100644 --- a/cocos/ui/components/ui-reorder-component.ts +++ b/cocos/ui/components/ui-reorder-component.ts @@ -33,6 +33,7 @@ import { UIComponent } from '../../core/components/ui-base/ui-component'; /** * @zh * UI 及 UI 模型渲染基类。 + * @deprecated 会在 1.2 的版本移除 */ @ccclass('cc.UIReorderComponent') @menu('UI/Reorder') diff --git a/cocos/ui/components/widget-manager.ts b/cocos/ui/components/widget-manager.ts index 2e491c10c7..66ee58a358 100644 --- a/cocos/ui/components/widget-manager.ts +++ b/cocos/ui/components/widget-manager.ts @@ -370,21 +370,14 @@ export const widgetManager = cc._widgetManager = { }, add (widget: WidgetComponent) { this._nodesOrderDirty = true; - // if (CC_EDITOR && !cc.engine.isPlaying) { - const renderComp: UIRenderComponent = widget.node.getComponent(UIRenderComponent); - if (renderComp) { - const canvasComp = director.root!.ui.getScreen(renderComp.visibility); - if (canvasComp && canvasList.indexOf(canvasComp) === -1) { - canvasList.push(canvasComp); - canvasComp.node.on('design-resolution-changed', this.onResized, this); - } + const canvasComp = director.root!.ui.getScreen(widget.node.uiTransfromComp.visibility); + if (canvasComp && canvasList.indexOf(canvasComp) === -1) { + canvasList.push(canvasComp); + canvasComp.node.on('design-resolution-changed', this.onResized, this); } - // } }, remove (widget: WidgetComponent) { this._activeWidgetsIterator.remove(widget); - // if (CC_EDITOR && !cc.engine.isPlaying) { - // } }, onResized () { const scene = director.getScene(); @@ -395,11 +388,7 @@ export const widgetManager = cc._widgetManager = { refreshWidgetOnResized (node: Node) { if (Node.isNode(node)){ const widget = node.getComponent(WidgetComponent); - // const widget: WidgetComponent | null = null; if (widget && widget.alignFlags === AlignMode.ALWAYS) { - // if (widget!.alignMode === AlignMode.ON_WINDOW_RESIZE) { - // widget!.enabled = true; - // } return; } } From 687742f0c33c86e04b8a6aff146e44617ec755db Mon Sep 17 00:00:00 2001 From: JoneLau <32630749+JoneLau@users.noreply.github.com> Date: Tue, 26 Nov 2019 11:57:05 +0800 Subject: [PATCH 06/21] add component what 3d node convert to 2d, similar to perspective camera in 3d (#5771) --- .../block-input-events-component.ts | 2 +- cocos/core/components/index.ts | 1 + .../ui-coodinate-tracker-component.ts | 177 ++++++++++++++++++ 3 files changed, 179 insertions(+), 1 deletion(-) create mode 100644 cocos/core/components/ui-coodinate-tracker-component.ts diff --git a/cocos/core/components/block-input-events-component.ts b/cocos/core/components/block-input-events-component.ts index 1b4de3195d..04bf29cd4d 100644 --- a/cocos/core/components/block-input-events-component.ts +++ b/cocos/core/components/block-input-events-component.ts @@ -49,7 +49,7 @@ const BlockEvents = [SystemEventType.TOUCH_START, SystemEventType.TOUCH_END, Sys SystemEventType.MOUSE_ENTER, SystemEventType.MOUSE_LEAVE, SystemEventType.MOUSE_WHEEL]; function stopPropagation(event: Event) { - event.propagationStopped = true;; + event.propagationStopped = true; } @ccclass('cc.BlockInputEventsComponent') diff --git a/cocos/core/components/index.ts b/cocos/core/components/index.ts index cc56f38260..d3dab7cb52 100644 --- a/cocos/core/components/index.ts +++ b/cocos/core/components/index.ts @@ -33,3 +33,4 @@ export { default as MissingScript } from './missing-script'; export { BlockInputEventsComponent } from './block-input-events-component'; export { default as System } from './system'; export * from './ui-base'; +export { UICoordinateTrackerComponent } from './ui-coodinate-tracker-component'; diff --git a/cocos/core/components/ui-coodinate-tracker-component.ts b/cocos/core/components/ui-coodinate-tracker-component.ts new file mode 100644 index 0000000000..7b5aa08e3b --- /dev/null +++ b/cocos/core/components/ui-coodinate-tracker-component.ts @@ -0,0 +1,177 @@ +/* + 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 { Component, EventHandler } from '../../core/components'; +import { ccclass, property, menu, executionOrder } from '../data/class-decorator'; +import { Node } from '../scene-graph'; +import { convertUtils } from '../utils'; +import { CameraComponent } from '../3d'; +import { Vec3 } from '../math'; + +/** + * @zh 3D 节点映射 UI 节点组件 + * 主要提供映射后的转换世界坐标以及模拟透视相机远近比。 + */ +@ccclass('cc.UICoordinateTrackerComponent') +@menu('Components/UICoordinateTracker') +@executionOrder(110) +export class UICoordinateTrackerComponent extends Component { + /** + * @zh + * 目标对象。 + */ + @property({ + type: Node, + tooltip: '目标对象' + }) + get target() { + return this._target; + } + + set target(value) { + if (this._target === value) { + return; + } + + this._target = value; + this._checkCanMove(); + } + + /** + * @zh + * 照射相机。 + */ + @property({ + type: CameraComponent, + tooltip: '照射相机' + }) + get camera() { + return this._camera; + } + + set camera(value) { + if (this._camera === value) { + return; + } + + this._camera = value; + this._checkCanMove(); + } + + /** + * @zh + * 是否是缩放映射。 + */ + @property({ + tooltip: '是否是缩放映射' + }) + get useScale() { + return this._useScale; + } + + set useScale(value) { + if (this._useScale === value) { + return; + } + + this._useScale = value; + } + + /** + * @zh + * 距相机多少距离为正常显示计算大小。 + */ + @property({ + tooltip: '距相机多少距离为正常显示计算大小' + }) + get distance() { + return this._distance; + } + + set distance(value) { + if (this._distance === value) { + return; + } + + this._distance = value; + } + + /** + * @zh + * 映射数据事件。回调的第一个参数是映射后的本地坐标,第二个是距相机距离比。 + */ + @property({ + type: [EventHandler], + tooltip: '映射数据事件。回调的第一个参数是映射后的本地坐标,第二个是距相机距离比' + }) + public syncEvents: EventHandler[] = []; + + @property + protected _target: Node | null = null; + @property + protected _camera: CameraComponent | null = null; + @property + protected _useScale = true; + @property + protected _distance = 1; + + protected _transformPos = new Vec3(); + protected _viewPos = new Vec3(); + protected _canMove = true; + protected _lastWpos = new Vec3(); + + public onEnable() { + this._checkCanMove(); + } + + public update() { + const wpos = this.node.worldPosition; + // @ts-ignore + if (!this._canMove || !this._camera!._camera || this._lastWpos.equals(wpos)) { + return; + } + + this._lastWpos.set(wpos); + const camera = this._camera!; + // [HACK] + // @ts-ignore + camera._camera.update(); + convertUtils.WorldNode3DToLocalNodeUI(camera, wpos, this._target!, this._transformPos); + if (this._useScale) { + // @ts-ignore + Vec3.transformMat4(this._viewPos, this.node.worldPosition, camera._camera!.matView); + } + + if (this.syncEvents.length > 0) { + const data = this._distance / Math.abs(this._viewPos.z); + EventHandler.emitEvents(this.syncEvents, this._transformPos, data); + } + } + + protected _checkCanMove() { + this._canMove = !!(this._camera && this._target); + } +} From 14bcb2e49eda789a163cd7bf9c272d250484a2ee Mon Sep 17 00:00:00 2001 From: JoneLau <32630749+JoneLau@users.noreply.github.com> Date: Tue, 26 Nov 2019 13:48:29 +0800 Subject: [PATCH 07/21] add tiled mode in spritecomponent (#5784) --- cocos/core/renderer/ui/render-data.ts | 2 - cocos/ui/assembler/sprite/index.ts | 7 +- cocos/ui/assembler/sprite/tiled.ts | 265 +++++++++--------------- cocos/ui/components/sprite-component.ts | 34 +-- 4 files changed, 112 insertions(+), 196 deletions(-) diff --git a/cocos/core/renderer/ui/render-data.ts b/cocos/core/renderer/ui/render-data.ts index 5fe751b517..1545f0738f 100644 --- a/cocos/core/renderer/ui/render-data.ts +++ b/cocos/core/renderer/ui/render-data.ts @@ -30,8 +30,6 @@ import { Pool, RecyclePool } from '../../memop'; import { Material } from '../../assets'; import { Color } from '../../math'; -import { GFXTextureView } from '../../gfx'; -import { MeshBuffer } from '../../../ui'; export interface IRenderData { x: number; diff --git a/cocos/ui/assembler/sprite/index.ts b/cocos/ui/assembler/sprite/index.ts index 24e7946bdf..81e04f3969 100644 --- a/cocos/ui/assembler/sprite/index.ts +++ b/cocos/ui/assembler/sprite/index.ts @@ -34,6 +34,7 @@ import { barFilled } from './bar-filled'; import { radialFilled } from './radial-filled'; import { simple } from './simple'; import { sliced } from './sliced'; +import { tilled } from './tiled'; const SpriteType = SpriteComponent.Type; const FillType = SpriteComponent.FillType; @@ -49,9 +50,9 @@ const spriteAssembler: IAssemblerManager = { case SpriteType.SLICED: util = sliced; break; - // case SpriteType.TILED: - // util = tilled; - // break; + case SpriteType.TILED: + util = tilled; + break; case SpriteType.FILLED: if (comp.fillType === FillType.RADIAL) { util = radialFilled; diff --git a/cocos/ui/assembler/sprite/tiled.ts b/cocos/ui/assembler/sprite/tiled.ts index 395194a74c..d4fa0f489b 100644 --- a/cocos/ui/assembler/sprite/tiled.ts +++ b/cocos/ui/assembler/sprite/tiled.ts @@ -23,23 +23,19 @@ THE SOFTWARE. */ -import { Mat4, Vec3 } from '../../../core/math'; -import { RenderData } from '../../../core/renderer/ui/render-data'; +import { Mat4, Vec3, Color } from '../../../core/math'; +import { RenderData, IRenderData } from '../../../core/renderer/ui/render-data'; import { UI } from '../../../core/renderer/ui/ui'; import { SpriteComponent } from '../../components/sprite-component'; import { UIRenderComponent } from '../../../core/components/ui-base/ui-render-component'; import { IAssembler } from '../../../core/renderer/ui/base'; -const matrix = new Mat4(); - const vec3_temps: Vec3[] = []; for (let i = 0; i < 4; i++) { vec3_temps.push(new Vec3()); } -const _tempVertexOffset = 6; -const _tempUvOffset = 3; -const _tempColorOffset = 5; +const _perVertextLength = 9; export const tilled: IAssembler = { useModel: false, @@ -49,33 +45,17 @@ export const tilled: IAssembler = { }, updateRenderData (sprite: SpriteComponent) { - const frame = sprite.spriteFrame; - - // TODO: Material API design and export from editor could affect the material activation process - // need to update the logic here - // if (frame) { - // if (!frame._original && dynamicAtlasManager) { - // dynamicAtlasManager.insertSpriteFrame(frame); - // } - // if (sprite._material._texture !== frame._texture) { - // sprite._activateMaterial(); - // } - // } - - const renderData = sprite.renderData; - if (!frame || !renderData || - !(renderData.uvDirty || renderData.vertDirty)) { + const renderData = sprite.renderData!; + const frame = sprite.spriteFrame!; + if (!frame || !renderData || !(renderData.uvDirty || renderData.vertDirty)){ return; } const node = sprite.node; - // contentWidth = Math.abs(node.width), - // contentHeight = Math.abs(node.height), const contentWidth = Math.abs(node.width); const contentHeight = Math.abs(node.height); const appx = node.anchorX * contentWidth; const appy = node.anchorY * contentHeight; - // node._updateWorldMatrix(); const rect = frame.getRect(); const rectWidth = rect.width; @@ -85,14 +65,14 @@ export const tilled: IAssembler = { const row = Math.ceil(vRepeat); const col = Math.ceil(hRepeat); - const data = renderData.datas; + const datas = renderData.datas; renderData.dataLength = Math.max(8, row + 1, col + 1); for (let i = 0; i <= col; ++i) { - data[i].x = Math.min(rectWidth * i, contentWidth) - appx; + datas[i].x = Math.min(rectWidth * i, contentWidth) - appx; } for (let i = 0; i <= row; ++i) { - data[i].y = Math.min(rectHeight * i, contentHeight) - appy; + datas[i].y = Math.min(rectHeight * i, contentHeight) - appy; } // update data property @@ -103,28 +83,32 @@ export const tilled: IAssembler = { }, fillBuffers (sprite: SpriteComponent, renderer: UI) { - const buffer = renderer.currBufferBatch!; - const node = sprite.node; - const color = sprite.color; - const renderData = sprite.renderData; - const datas = renderData!.datas; + const renderData = sprite.renderData!; // buffer - let vertexOffset = buffer.byteOffset >> 2; - let indiceOffset = buffer.indiceOffset; - let vertexId = buffer.vertexOffset; - - buffer.request(renderData!.vertexCount, renderData!.indiceCount); - + let buffer = renderer.currBufferBatch!; // buffer data may be realloc, need get reference after request. - const vbuf = buffer.vData; - // uintbuf = buffer._uintVData, - const ibuf = buffer.iData; + let indiceOffset = buffer.indiceOffset; + let vertexOffset = buffer.byteOffset >> 2; + let vertexId = buffer.vertexOffset; + const vertexCount = renderData!.vertexCount; + const indiceCount = renderData.indiceCount; + const vbuf = buffer.vData!; + const ibuf = buffer.iData!; - const rotated = sprite.spriteFrame!.isRotated; - const uv = sprite.spriteFrame!.uv; - const rect = sprite.spriteFrame!.getRect(); + const isRecreate = buffer.request(vertexCount, indiceCount); + if (!isRecreate) { + buffer = renderer.currBufferBatch!; + vertexOffset = 0; + indiceOffset = 0; + vertexId = 0; + } + + const frame = sprite.spriteFrame!; + const rotated = frame.isRotated(); + const uv = frame.uv; + const rect = frame.getRect(); const contentWidth = Math.abs(node.width); const contentHeight = Math.abs(node.height); const hRepeat = contentWidth / rect.width; @@ -132,14 +116,72 @@ export const tilled: IAssembler = { const row = Math.ceil(vRepeat); const col = Math.ceil(hRepeat); - // const matrix = node._worldMatrix; + const matrix = node.worldMatrix; - // this.updateVerts(vbuf, vertexOffset, matrix, row, col, datas); - // updataVerts - let x = 0; - let x1 = 0; - let y = 0; - let y1 = 0; + this.fillVertices(vbuf, vertexOffset, matrix, row, col, renderData.datas); + + const offset = _perVertextLength; + const offset1 = offset; const offset2 = offset * 2; const offset3 = offset * 3; const offset4 = offset * 4; + let coefu = 0; let coefv = 0; + for (let yindex = 0, ylength = row; yindex < ylength; ++yindex) { + coefv = Math.min(1, vRepeat - yindex); + for (let xindex = 0, xlength = col; xindex < xlength; ++xindex) { + coefu = Math.min(1, hRepeat - xindex); + + const vertexOffsetU = vertexOffset + 3; + const vertexOffsetV = vertexOffsetU + 1; + // UV + if (rotated) { + // lb + vbuf[vertexOffsetU] = uv[0]; + vbuf[vertexOffsetV] = uv[1]; + // rb + vbuf[vertexOffsetU + offset1] = uv[0]; + vbuf[vertexOffsetV + offset1] = uv[1] + (uv[7] - uv[1]) * coefu; + // lt + vbuf[vertexOffsetU + offset2] = uv[0] + (uv[6] - uv[0]) * coefv; + vbuf[vertexOffsetV + offset2] = uv[1]; + // rt + vbuf[vertexOffsetU + offset3] = vbuf[vertexOffsetU + offset2]; + vbuf[vertexOffsetV + offset3] = vbuf[vertexOffsetV + offset1]; + } + else { + // lb + vbuf[vertexOffsetU] = uv[0]; + vbuf[vertexOffsetV] = uv[1]; + // rb + vbuf[vertexOffsetU + offset1] = uv[0] + (uv[6] - uv[0]) * coefu; + vbuf[vertexOffsetV + offset1] = uv[1]; + // lt + vbuf[vertexOffsetU + offset2] = uv[0]; + vbuf[vertexOffsetV + offset2] = uv[1] + (uv[7] - uv[1]) * coefv; + // rt + vbuf[vertexOffsetU + offset3] = vbuf[vertexOffsetU + offset1]; + vbuf[vertexOffsetV + offset3] = vbuf[vertexOffsetV + offset2]; + } + // color + Color.toArray(vbuf!, sprite.color, vertexOffsetV + 1); + Color.toArray(vbuf!, sprite.color, vertexOffsetV + offset1 + 1); + Color.toArray(vbuf!, sprite.color, vertexOffsetV + offset2 + 1); + Color.toArray(vbuf!, sprite.color, vertexOffsetV + offset3 + 1); + vertexOffset += offset4; + } + } + + // update indices + for (let i = 0; i < indiceCount; i += 6) { + ibuf[indiceOffset++] = vertexId; + ibuf[indiceOffset++] = vertexId + 1; + ibuf[indiceOffset++] = vertexId + 2; + ibuf[indiceOffset++] = vertexId + 1; + ibuf[indiceOffset++] = vertexId + 3; + ibuf[indiceOffset++] = vertexId + 2; + vertexId += 4; + } + }, + + fillVertices (vbuf: Float32Array, vertexOffset: number, matrix: Mat4, row: number, col: number, datas: IRenderData[]) { + let x = 0; let x1 = 0; let y = 0; let y1 = 0; for (let yindex = 0, ylength = row; yindex < ylength; ++yindex) { y = datas[yindex].y; y1 = datas[yindex + 1].y; @@ -155,121 +197,14 @@ export const tilled: IAssembler = { for (let i = 0; i < 4; i++) { const vec3_temp = vec3_temps[i]; Vec3.transformMat4(vec3_temp, vec3_temp, matrix); - const move = i * 6; - vbuf![vertexOffset + move] = vec3_temp.x; - vbuf![vertexOffset + move + 1] = vec3_temp.y; - vbuf![vertexOffset + move + 2] = vec3_temp.z; + const offset = i * _perVertextLength; + vbuf[vertexOffset + offset] = vec3_temp.x; + vbuf[vertexOffset + offset + 1] = vec3_temp.y; + vbuf[vertexOffset + offset + 2] = vec3_temp.z; } - vertexOffset += 24; + vertexOffset += 36; } } - - const offset = _tempVertexOffset; - const uvOffset = _tempUvOffset; - const colorOffset = _tempColorOffset; - const offset1 = offset; - const offset2 = offset * 2; - const offset3 = offset * 3; - const offset4 = offset * 4; - let coefu = 0; - let coefv = 0; - for (let yindex = 0, ylength = row; yindex < ylength; ++yindex) { - coefv = Math.min(1, vRepeat - yindex); - for (let xindex = 0, xlength = col; xindex < xlength; ++xindex) { - coefu = Math.min(1, hRepeat - xindex); - - const vertexOffsetU = vertexOffset + uvOffset; - const vertexOffsetV = vertexOffsetU + 1; - // UV - if (rotated) { - // lb - vbuf![vertexOffsetU] = uv[0]; - vbuf![vertexOffsetV] = uv[1]; - // rb - vbuf![vertexOffsetU + offset1] = uv[0]; - vbuf![vertexOffsetV + offset1] = uv[1] + (uv[7] - uv[1]) * coefu; - // lt - vbuf![vertexOffsetU + offset2] = uv[0] + (uv[6] - uv[0]) * coefv; - vbuf![vertexOffsetV + offset2] = uv[1]; - // rt - vbuf![vertexOffsetU + offset3] = vbuf![vertexOffsetU + offset2]; - vbuf![vertexOffsetV + offset3] = vbuf![vertexOffsetV + offset1]; - } else { - // lb - vbuf![vertexOffsetU] = uv[0]; - vbuf![vertexOffsetV] = uv[1]; - // rb - vbuf![vertexOffsetU + offset1] = uv[0] + (uv[6] - uv[0]) * coefu; - vbuf![vertexOffsetV + offset1] = uv[1]; - // lt - vbuf![vertexOffsetU + offset2] = uv[0]; - vbuf![vertexOffsetV + offset2] = uv[1] + (uv[7] - uv[1]) * coefv; - // rt - vbuf![vertexOffsetU + offset3] = vbuf![vertexOffsetU + offset1]; - vbuf![vertexOffsetV + offset3] = vbuf![vertexOffsetV + offset2]; - } - - vbuf![vertexOffset + colorOffset] = color.x; - vbuf![vertexOffset + colorOffset + offset1] = color.y; - vbuf![vertexOffset + colorOffset + offset2] = color.z; - vbuf![vertexOffset + colorOffset + offset3] = color.w; - // TODO: addColor - // color - // uintbuf[vertexOffset + colorOffset] = color; - // uintbuf[vertexOffset + colorOffset + offset1] = color; - // uintbuf[vertexOffset + colorOffset + offset2] = color; - // uintbuf[vertexOffset + colorOffset + offset3] = color; - vertexOffset += offset4; - } - } - - // update indices - const length = renderData!.indiceCount; - for (let i = 0; i < length; i += 6) { - ibuf![indiceOffset++] = vertexId; - ibuf![indiceOffset++] = vertexId + 1; - ibuf![indiceOffset++] = vertexId + 2; - ibuf![indiceOffset++] = vertexId + 1; - ibuf![indiceOffset++] = vertexId + 3; - ibuf![indiceOffset++] = vertexId + 2; - vertexId += 4; - } - }, - - updateVerts (sprite: SpriteComponent) { - // const renderData = sprite.renderData; - // const datas = renderData!.datas; - // const vbuf; - // const vertexOffset; - // sprite.node.getWorldMatrix(matrix); - // const row; - // const col; - // const data; - // let x, x1, y, y1; - // for (let yindex = 0, ylength = row; yindex < ylength; ++yindex) { - // y = data[yindex].y; - // y1 = data[yindex + 1].y; - // for (let xindex = 0, xlength = col; xindex < xlength; ++xindex) { - // x = data[xindex].x; - // x1 = data[xindex + 1].x; - - // vec3.set(vec3_temps[0], x, y, 0); - // vec3.set(vec3_temps[1], x1, y, 0); - // vec3.set(vec3_temps[2], x, y1, 0); - // vec3.set(vec3_temps[3], x1, y1, 0); - - // for (let i = 0; i < 4; i++) { - // let 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; - // } - - // vertexOffset += 24; - // } - // } }, }; diff --git a/cocos/ui/components/sprite-component.ts b/cocos/ui/components/sprite-component.ts index 2ee30c9ef6..da48b0e5f7 100644 --- a/cocos/ui/components/sprite-component.ts +++ b/cocos/ui/components/sprite-component.ts @@ -28,7 +28,7 @@ * @category ui */ -import { SpriteAtlas, SpriteFrame, AssetLibrary } from '../../core/assets'; +import { SpriteAtlas, SpriteFrame } from '../../core/assets'; import { ccclass, executionOrder, menu, property } from '../../core/data/class-decorator'; import { SystemEventType } from '../../core/platform/event-manager/event-enum'; import { Vec2 } from '../../core/math'; @@ -52,11 +52,10 @@ enum SpriteType { * 切片(九宫格)类型。 */ SLICED = 1, - // /** - // * @zh 平铺类型 - // * @property {Number} TILED - // */ - // TILED = 2, + /** + * @zh 平铺类型 + */ + TILED = 2, /** * @zh * 填充类型。 @@ -87,11 +86,9 @@ enum FillType { * 垂直方向填充。 */ VERTICAL = 1, - // /** - // * @en The radial fill. - // * @zh 径向填充 - // * @property {Number} RADIAL - // */ + /** + * @zh 径向填充 + */ RADIAL = 2, } @@ -121,21 +118,6 @@ enum SizeMode { ccenum(SizeMode); -// var State = cc.Enum({ -// /** -// * @en The normal state -// * @zh 正常状态 -// * @property {Number} NORMAL -// */ -// NORMAL: 0, -// /** -// * @en The gray state, all color will be modified to grayscale value. -// * @zh 灰色状态,所有颜色会被转换成灰度值 -// * @property {Number} GRAY -// */ -// GRAY: 1 -// }); - /** * @zh * 渲染精灵组件。 From 53ed7da2db52fffced1246e78475ea515213891a Mon Sep 17 00:00:00 2001 From: zxg0622 <247274249@qq.com> Date: Tue, 26 Nov 2019 15:04:16 +0800 Subject: [PATCH 08/21] fix render scene error (#5790) --- .../framework/directional-light-component.ts | 1 - cocos/core/3d/framework/light-component.ts | 8 ++++- .../core/pipeline/forward/forward-pipeline.ts | 22 +++++------- cocos/core/pipeline/render-pipeline.ts | 4 +-- cocos/core/renderer/models/skinning-model.ts | 6 ++-- .../core/renderer/scene/directional-light.ts | 2 -- cocos/core/renderer/scene/light.ts | 12 +++---- cocos/core/renderer/scene/model.ts | 2 +- cocos/core/renderer/scene/render-scene.ts | 1 - cocos/core/renderer/ui/ui.ts | 2 +- .../graphics/webgl/graphics-assembler.ts | 12 +++---- cocos/ui/components/graphics-component.ts | 34 ++++++++++++++----- 12 files changed, 57 insertions(+), 49 deletions(-) diff --git a/cocos/core/3d/framework/directional-light-component.ts b/cocos/core/3d/framework/directional-light-component.ts index 3a3c492566..e208b45ef9 100644 --- a/cocos/core/3d/framework/directional-light-component.ts +++ b/cocos/core/3d/framework/directional-light-component.ts @@ -80,7 +80,6 @@ export class DirectionalLightComponent extends LightComponent { protected _destroyLight (scene?: RenderScene) { if (!this.node.scene || !this._light) { return; } - this._light.enabled = false; scene = scene || this._getRenderScene(); this._light.node = scene.defaultMainLightNode; } diff --git a/cocos/core/3d/framework/light-component.ts b/cocos/core/3d/framework/light-component.ts index fa77751fc9..db60637706 100644 --- a/cocos/core/3d/framework/light-component.ts +++ b/cocos/core/3d/framework/light-component.ts @@ -166,8 +166,11 @@ export class LightComponent extends Component { protected _attachToScene() { this._detachFromScene(); - if (this._light && !this._light.scene && !this.node.scene) { + if (this._light && !this._light.scene && this.node.scene) { switch (this._type) { + case LightType.DIRECTIONAL: + this._light.attachToScene(this._getRenderScene()); + break; case LightType.SPHERE: this._getRenderScene().addSphereLight(this._light as any); break; @@ -181,6 +184,9 @@ export class LightComponent extends Component { protected _detachFromScene() { if (this._light && this._light.scene) { switch (this._type) { + case LightType.DIRECTIONAL: + this._light.detachFromScene(); + break; case LightType.SPHERE: this._light.scene.removeSphereLight(this._light as any); break; diff --git a/cocos/core/pipeline/forward/forward-pipeline.ts b/cocos/core/pipeline/forward/forward-pipeline.ts index 20b86e2e1b..5f8742abc1 100644 --- a/cocos/core/pipeline/forward/forward-pipeline.ts +++ b/cocos/core/pipeline/forward/forward-pipeline.ts @@ -205,7 +205,7 @@ export class ForwardPipeline extends RenderPipeline { let spotNum = 0; for (let l = this._lightIndexOffset[i]; l < nextLightIndex; l++) { const light = this._validLights[this._lightIndices[l]]; - if (light && light.enabled) { + if (light) { switch (light.type) { case LightType.SPHERE: if (sphereNum >= UBOForwardLight.MAX_SPHERE_LIGHTS) { @@ -289,23 +289,19 @@ export class ForwardPipeline extends RenderPipeline { const sphereLights = view.camera.scene!.sphereLights; for (let i = 0; i < sphereLights.length; i++) { const light = sphereLights[i]; - if (light.enabled) { - light.update(); - sphere.set(_sphere, light.position.x, light.position.y, light.position.z, light.range); - if (intersect.sphere_frustum(_sphere, view.camera.frustum)) { - this._validLights.push(light); - } + light.update(); + sphere.set(_sphere, light.position.x, light.position.y, light.position.z, light.range); + if (intersect.sphere_frustum(_sphere, view.camera.frustum)) { + this._validLights.push(light); } } const spotLights = view.camera.scene!.spotLights; for (let i = 0; i < spotLights.length; i++) { const light = spotLights[i]; - if (light.enabled) { - light.update(); - sphere.set(_sphere, light.position.x, light.position.y, light.position.z, light.range); - if (intersect.sphere_frustum(_sphere, view.camera.frustum)) { - this._validLights.push(light); - } + light.update(); + sphere.set(_sphere, light.position.x, light.position.y, light.position.z, light.range); + if (intersect.sphere_frustum(_sphere, view.camera.frustum)) { + this._validLights.push(light); } } diff --git a/cocos/core/pipeline/render-pipeline.ts b/cocos/core/pipeline/render-pipeline.ts index 469de3ab56..5d8aa39ce3 100644 --- a/cocos/core/pipeline/render-pipeline.ts +++ b/cocos/core/pipeline/render-pipeline.ts @@ -1163,7 +1163,7 @@ export abstract class RenderPipeline { Vec3.toArray(fv, mainLight.direction, UBOGlobal.MAIN_LIT_DIR_OFFSET); - if (mainLight.enabled) { + if (mainLight.scene) { Vec3.toArray(fv, mainLight.color, UBOGlobal.MAIN_LIT_COLOR_OFFSET); if (mainLight.useColorTemperature) { const colorTempRGB = mainLight.colorTemperatureRGB; @@ -1208,7 +1208,7 @@ export abstract class RenderPipeline { this._renderObjects.length = 0; const mainLight = scene.mainLight; - if (mainLight && mainLight.enabled) { + if (mainLight && mainLight.scene) { mainLight.update(); } diff --git a/cocos/core/renderer/models/skinning-model.ts b/cocos/core/renderer/models/skinning-model.ts index 3c52382294..e9321d6646 100644 --- a/cocos/core/renderer/models/skinning-model.ts +++ b/cocos/core/renderer/models/skinning-model.ts @@ -85,7 +85,7 @@ export class SkinningModel extends Model { this._mesh = mesh; if (!skeleton || !skinningRoot || !mesh) { return; } this._transform = skinningRoot; - this._jointsMedium.animInfo = this._scene!.root.dataPoolManager.jointsAnimationInfo.get(skinningRoot.uuid); + this._jointsMedium.animInfo = cc.director.root.dataPoolManager.jointsAnimationInfo.get(skinningRoot.uuid); if (!this._jointsMedium.buffer) { this._jointsMedium.buffer = this._device.createBuffer({ usage: GFXBufferUsageBit.UNIFORM | GFXBufferUsageBit.TRANSFER_DST, @@ -124,7 +124,7 @@ export class SkinningModel extends Model { public uploadAnimation (anim: AnimationClip | null) { if (!this._skeleton || !this._mesh) { return; } this.uploadedAnim = anim; - const resMgr = this._scene!.root.dataPoolManager; + const resMgr = cc.director.root.dataPoolManager; const texture = anim ? resMgr.jointsTexturePool.getJointsTextureWithAnimation(this._skeleton, anim) : resMgr.jointsTexturePool.getDefaultJointsTexture(this._skeleton); resMgr.jointsAnimationInfo.switchClip(this._jointsMedium.animInfo!, anim); @@ -136,7 +136,7 @@ export class SkinningModel extends Model { protected _applyJointsTexture (texture: IJointsTextureHandle | null) { if (!texture) { return; } const oldTex = this._jointsMedium.texture; - if (oldTex && oldTex !== texture) { this._scene!.root.dataPoolManager.jointsTexturePool.releaseHandle(oldTex); } + if (oldTex && oldTex !== texture) { cc.director.root.dataPoolManager.jointsTexturePool.releaseHandle(oldTex); } this._jointsMedium.texture = texture; const { buffer, jointsTextureInfo } = this._jointsMedium; jointsTextureInfo[0] = texture.handle.texture.width; diff --git a/cocos/core/renderer/scene/directional-light.ts b/cocos/core/renderer/scene/directional-light.ts index b522274a2f..c3bd1986df 100644 --- a/cocos/core/renderer/scene/directional-light.ts +++ b/cocos/core/renderer/scene/directional-light.ts @@ -1,5 +1,4 @@ import { Quat, Vec3 } from '../../math'; -import { TransformBit } from '../../scene-graph/node-enum'; import { INode } from '../../utils/interfaces'; import { Light, LightType } from './light'; import { RenderScene } from './render-scene'; @@ -34,7 +33,6 @@ export class DirectionalLight extends Light { constructor () { super(); this._type = LightType.DIRECTIONAL; - this._node.hasChangedFlags = TransformBit.ROTATION; } public update () { diff --git a/cocos/core/renderer/scene/light.ts b/cocos/core/renderer/scene/light.ts index 99b6f2d3f0..1e7e7c6e03 100644 --- a/cocos/core/renderer/scene/light.ts +++ b/cocos/core/renderer/scene/light.ts @@ -1,6 +1,7 @@ import { Vec3 } from '../../math'; import { INode } from '../../utils/interfaces'; import { RenderScene } from './render-scene'; +import { TransformBit } from '../../scene-graph/node-enum'; // Color temperature (in Kelvin) to RGB export function ColorTemperatureToRGB (rgb: Vec3, kelvin: number) { @@ -40,13 +41,6 @@ export const nt2lm = (size: number) => 4 * Math.PI * Math.PI * size * size; export class Light { - set enabled (val) { - this._enabled = val; - } - get enabled () { - return this._enabled; - } - set color (color: Vec3) { this._color.set(color); } @@ -78,6 +72,9 @@ export class Light { set node (n) { this._node = n; + if (this._node) { + this._node.hasChangedFlags = TransformBit.ROTATION; + } } get node () { @@ -96,7 +93,6 @@ export class Light { return this._scene; } - protected _enabled = true; protected _color: Vec3 = new Vec3(1, 1, 1); protected _useColorTemp: boolean = false; protected _colorTemp: number = 6550.0; diff --git a/cocos/core/renderer/scene/model.ts b/cocos/core/renderer/scene/model.ts index 44d169e4d9..d8b2e432a4 100644 --- a/cocos/core/renderer/scene/model.ts +++ b/cocos/core/renderer/scene/model.ts @@ -146,7 +146,7 @@ export class Model { protected _node: INode | null = null; protected _transform: INode | null = null; protected _id: number = -1; - protected _enabled: boolean = false; + protected _enabled: boolean = true; protected _visFlags = Layers.Enum.NONE; protected _cameraID = -1; protected _userKey = -1; diff --git a/cocos/core/renderer/scene/render-scene.ts b/cocos/core/renderer/scene/render-scene.ts index 61189e719a..611bbc8cd9 100644 --- a/cocos/core/renderer/scene/render-scene.ts +++ b/cocos/core/renderer/scene/render-scene.ts @@ -132,7 +132,6 @@ export class RenderScene { this._mainLight = new DirectionalLight(); this._mainLight.initialize('Main Light', this._defaultMainLightNode); this._mainLight.illuminance = Ambient.SUN_ILLUM; - this._mainLight.enabled = false; // disabled by default this._ambient = new Ambient(this); this._skybox = new Skybox(this); this._planarShadows = new PlanarShadows(this); diff --git a/cocos/core/renderer/ui/ui.ts b/cocos/core/renderer/ui/ui.ts index 8bb3748f84..a45cfc3c09 100644 --- a/cocos/core/renderer/ui/ui.ts +++ b/cocos/core/renderer/ui/ui.ts @@ -376,7 +376,7 @@ export class UI { } } - const uiCanvas = this.getScreen(comp.node.uiTransfromComp.visibility); + const uiCanvas = this._currCanvas; const curDrawBatch = this._drawBatchPool.alloc(); curDrawBatch.camera = uiCanvas && uiCanvas.camera; curDrawBatch.model = model; diff --git a/cocos/ui/assembler/graphics/webgl/graphics-assembler.ts b/cocos/ui/assembler/graphics/webgl/graphics-assembler.ts index f20bb9793e..0301fc58c4 100644 --- a/cocos/ui/assembler/graphics/webgl/graphics-assembler.ts +++ b/cocos/ui/assembler/graphics/webgl/graphics-assembler.ts @@ -176,11 +176,10 @@ export const graphicsAssembler: IAssembler = { }, end (graphics: GraphicsComponent){ - const scene = director.root!.ui.renderScene as RenderScene; - if (graphics.model){ + if (graphics.model) { graphics.model.destroy(); - scene.destroyModel(graphics.model); - graphics.model = null; + } else { + graphics.model = new Model(); } const impl = graphics.impl; @@ -226,9 +225,8 @@ export const graphicsAssembler: IAssembler = { indices, }, undefined, { calculateBounds: false }); - graphics.model = scene.createModel(Model, graphics.node); - graphics.model.initSubModel(0, mesh.getSubMesh(0), graphics.material!); - graphics.model.enabled = true; + graphics.model!.initialize(graphics.node); + graphics.model!.initSubModel(0, mesh.getSubMesh(0), graphics.material!); graphics.markForUpdateRenderData(); }, diff --git a/cocos/ui/components/graphics-component.ts b/cocos/ui/components/graphics-component.ts index 154e5fb20e..0a599dba65 100644 --- a/cocos/ui/components/graphics-component.ts +++ b/cocos/ui/components/graphics-component.ts @@ -214,22 +214,21 @@ export class GraphicsComponent extends UIRenderComponent { public onLoad (){ this._sceneGetter = director.root!.ui.getRenderSceneGetter(); + if (!this.model) { + this.model = new Model(); + } } public onEnable () { super.onEnable(); - if (this.model){ - this.model.enabled = true; - } + this._attachToScene(); this._activateMaterial(); } public onDisable (){ - if (this.model){ - this.model.enabled = false; - } + this._detachFromScene(); } public onDestroy () { @@ -237,7 +236,7 @@ export class GraphicsComponent extends UIRenderComponent { this._sceneGetter = null; if (this.model) { - this._getRenderScene().destroyModel(this.model); + this.model.destroy(); this.model = null; } @@ -249,6 +248,23 @@ export class GraphicsComponent extends UIRenderComponent { this.impl = null; } + protected _attachToScene(){ + const scene = director.root!.ui.renderScene; + if (!this.model) { + return; + } + if (this.model!.scene != null) { + this._detachFromScene(); + } + scene.addModel(this.model!); + } + + protected _detachFromScene() { + if (this.model && this.model.scene) { + this.model.scene.removeModel(this.model); + } + } + public _activateMaterial () { if (!this._material) { return; @@ -435,8 +451,8 @@ export class GraphicsComponent extends UIRenderComponent { this.impl.clear(clean); if (this.model) { - this.model.scene.destroyModel(this.model); - this.model = null; + this._detachFromScene(); + this.model.destroy(); } this.markForUpdateRenderData(); From f18becae2836f7107674db5076526e81f39a9e84 Mon Sep 17 00:00:00 2001 From: Yun Hsiao Wu Date: Wed, 27 Nov 2019 16:53:22 +0800 Subject: [PATCH 09/21] fix main light (#5793) * fix main light * linter --- cocos/core/3d/builtin/effects.ts | 31 +++++------ cocos/core/3d/framework/camera-component.ts | 44 ++++++++-------- .../framework/directional-light-component.ts | 21 ++------ cocos/core/3d/framework/light-component.ts | 40 +++++++------- cocos/core/3d/framework/model-component.ts | 15 +++--- .../3d/framework/skinning-model-component.ts | 3 +- .../3d/framework/sphere-light-component.ts | 22 ++++---- .../core/3d/framework/spot-light-component.ts | 26 ++++------ .../components/ui-base/canvas-component.ts | 52 +++++++++---------- .../ui-coodinate-tracker-component.ts | 41 ++++++++------- cocos/core/pipeline/render-flow.ts | 3 +- cocos/core/pipeline/render-pipeline.ts | 30 +++++------ cocos/core/renderer/models/skinning-model.ts | 2 +- cocos/core/renderer/scene/camera.ts | 18 ++++--- .../core/renderer/scene/directional-light.ts | 5 +- cocos/core/renderer/scene/light.ts | 12 ++--- cocos/core/renderer/scene/model.ts | 6 +-- cocos/core/renderer/scene/planar-shadows.ts | 10 ++-- cocos/core/renderer/scene/render-scene.ts | 47 +++++++++-------- cocos/core/root.ts | 34 ++++++------ 20 files changed, 222 insertions(+), 240 deletions(-) diff --git a/cocos/core/3d/builtin/effects.ts b/cocos/core/3d/builtin/effects.ts index daa3012e3c..bdfe9609b5 100644 --- a/cocos/core/3d/builtin/effects.ts +++ b/cocos/core/3d/builtin/effects.ts @@ -9,13 +9,13 @@ export default [ "shaders": [ { "name": "builtin-billboard|vert:vs_main|tinted-fs:add", - "hash": 2541047749, + "hash": 1190489539, "glsl3": { - "vert": `\nprecision mediump float;\nuniform Constants {\n vec4 mainTiling_Offset;\n vec4 frameTile_velLenScale;\n vec4 scale;\n};\nuniform CCGlobal {\n vec4 cc_time;\n vec4 cc_screenSize;\n vec4 cc_screenScale;\n vec4 cc_nativeSize;\n highp mat4 cc_matView;\n mat4 cc_matViewInv;\n mat4 cc_matProj;\n mat4 cc_matProjInv;\n mat4 cc_matViewProj;\n mat4 cc_matViewProjInv;\n vec4 cc_cameraPos;\n vec4 cc_exposure;\n vec4 cc_mainLitDir;\n vec4 cc_mainLitColor;\n vec4 cc_ambientSky;\n vec4 cc_ambientGround;\n};\nuniform CCLocal {\n highp mat4 cc_matWorld;\n highp mat4 cc_matWorldIT;\n};\nvec4 quaternionFromAxisAngle (float angle, vec3 axis){\n angle /= 2.;\n float s = sin(angle);\n vec4 res;\n res.xyz = s * axis;\n res.w = cos(angle);\n return res;\n}\nvec4 quaternionFromAxis (vec3 xAxis,vec3 yAxis,vec3 zAxis){\n mat3 m = mat3(xAxis,yAxis,zAxis);\n float trace = m[0][0] + m[1][1] + m[2][2];\n vec4 quat;\n if (trace > 0.) {\n float s = 0.5 / sqrt(trace + 1.0);\n quat.w = 0.25 / s;\n quat.x = (m[2][1] - m[1][2]) * s;\n quat.y = (m[0][2] - m[2][0]) * s;\n quat.z = (m[1][0] - m[0][1]) * s;\n } else if ((m[0][0] > m[1][1]) && (m[0][0] > m[2][2])) {\n float s = 2.0 * sqrt(1.0 + m[0][0] - m[1][1] - m[2][2]);\n quat.w = (m[2][1] - m[1][2]) / s;\n quat.x = 0.25 * s;\n quat.y = (m[0][1] + m[1][0]) / s;\n quat.z = (m[0][2] + m[2][0]) / s;\n } else if (m[1][1] > m[2][2]) {\n float s = 2.0 * sqrt(1.0 + m[1][1] - m[0][0] - m[2][2]);\n quat.w = (m[0][2] - m[2][0]) / s;\n quat.x = (m[0][1] + m[1][0]) / s;\n quat.y = 0.25 * s;\n quat.z = (m[1][2] + m[2][1]) / s;\n } else {\n float s = 2.0 * sqrt(1.0 + m[2][2] - m[0][0] - m[1][1]);\n quat.w = (m[1][0] - m[0][1]) / s;\n quat.x = (m[0][2] + m[2][0]) / s;\n quat.y = (m[1][2] + m[2][1]) / s;\n quat.z = 0.25 * s;\n }\n float len = quat.x * quat.x + quat.y * quat.y + quat.z * quat.z + quat.w * quat.w;\n if (len > 0.) {\n len = 1. / sqrt(len);\n quat.x = quat.x * len;\n quat.y = quat.y * len;\n quat.z = quat.z * len;\n quat.w = quat.w * len;\n }\n return quat;\n}\nvec4 quaternionFromEuler (vec3 angle){\n float x = angle.x / 2.;\n float y = angle.y / 2.;\n float z = angle.z / 2.;\n float sx = sin(x);\n float cx = cos(x);\n float sy = sin(y);\n float cy = cos(y);\n float sz = sin(z);\n float cz = cos(z);\n vec4 quat = vec4(0);\n quat.x = sx * cy * cz + cx * sy * sz;\n quat.y = cx * sy * cz + sx * cy * sz;\n quat.z = cx * cy * sz - sx * sy * cz;\n quat.w = cx * cy * cz - sx * sy * sz;\n return quat;\n}\nmat4 matrixFromRT (vec4 q, vec3 p){\n float x2 = q.x + q.x;\n float y2 = q.y + q.y;\n float z2 = q.z + q.z;\n float xx = q.x * x2;\n float xy = q.x * y2;\n float xz = q.x * z2;\n float yy = q.y * y2;\n float yz = q.y * z2;\n float zz = q.z * z2;\n float wx = q.w * x2;\n float wy = q.w * y2;\n float wz = q.w * z2;\n return mat4(\n 1. - (yy + zz), xy + wz, xz - wy, 0,\n xy - wz, 1. - (xx + zz), yz + wx, 0,\n xz + wy, yz - wx, 1. - (xx + yy), 0,\n p.x, p.y, p.z, 1\n );\n}\nmat4 matFromRTS (vec4 q, vec3 t, vec3 s){\n float x = q.x, y = q.y, z = q.z, w = q.w;\n float x2 = x + x;\n float y2 = y + y;\n float z2 = z + z;\n float xx = x * x2;\n float xy = x * y2;\n float xz = x * z2;\n float yy = y * y2;\n float yz = y * z2;\n float zz = z * z2;\n float wx = w * x2;\n float wy = w * y2;\n float wz = w * z2;\n float sx = s.x;\n float sy = s.y;\n float sz = s.z;\n return mat4((1. - (yy + zz)) * sx, (xy + wz) * sx, (xz - wy) * sx, 0,\n (xy - wz) * sy, (1. - (xx + zz)) * sy, (yz + wx) * sy, 0,\n (xz + wy) * sz, (yz - wx) * sz, (1. - (xx + yy)) * sz, 0,\n t.x, t.y, t.z, 1);\n}\nvoid scaleMatrix (inout mat4 m, float s){\n m[0].xyz *= s;\n m[1].xyz *= s;\n m[2].xyz *= s;\n}\nvec4 quatMultiply (vec4 a, vec4 b){\n vec4 quat;\n quat.x = a.x * b.w + a.w * b.x + a.y * b.z - a.z * b.y;\n quat.y = a.y * b.w + a.w * b.y + a.z * b.x - a.x * b.z;\n quat.z = a.z * b.w + a.w * b.z + a.x * b.y - a.y * b.x;\n quat.w = a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z;\n return quat;\n}\nvoid rotateVecFromQuat (inout vec3 v, vec4 q){\n float ix = q.w * v.x + q.y * v.z - q.z * v.y;\n float iy = q.w * v.y + q.z * v.x - q.x * v.z;\n float iz = q.w * v.z + q.x * v.y - q.y * v.x;\n float iw = -q.x * v.x - q.y * v.y - q.z * v.z;\n v.x = ix * q.w + iw * -q.x + iy * -q.z - iz * -q.y;\n v.y = iy * q.w + iw * -q.y + iz * -q.x - ix * -q.z;\n v.z = iz * q.w + iw * -q.z + ix * -q.y - iy * -q.x;\n}\nvec3 rotateVecFromAxis (vec3 v, vec3 axis, float theta){\n return cos(theta) * v + sin(theta) * cross(v, axis) + (1. - cos(theta)) * dot(v, axis) * axis;\n}\nvec3 rotateInLocalSpace (vec3 pos, vec3 xAxis, vec3 yAxis, vec3 zAxis, vec4 q){\n vec4 viewQuat = quaternionFromAxis(xAxis, yAxis, zAxis);\n vec4 rotQuat = quatMultiply(viewQuat, q);\n rotateVecFromQuat(pos, rotQuat);\n return pos;\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}\nout vec2 uv;\nout vec4 color;\nvoid computeVertPos (inout vec4 pos, vec2 vertOffset, vec4 q, vec3 s\n , mat4 viewInv\n) {\n vec3 viewSpaceVert = vec3(vertOffset.x * s.x, vertOffset.y * s.y, 0.);\n vec3 camX = normalize(vec3(viewInv[0][0], viewInv[1][0], viewInv[2][0]));\n vec3 camY = normalize(vec3(viewInv[0][1], viewInv[1][1], viewInv[2][1]));\n vec3 camZ = normalize(vec3(viewInv[0][2], viewInv[1][2], viewInv[2][2]));\n pos.xyz += rotateInLocalSpace(viewSpaceVert, camX, camY, camZ, q);\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 vertIndex.y = 1. - vertIndex.y;\n return (aniUV.xy + vertIndex) / vec2(frameTile.x, frameTile.y);\n}\nin vec3 a_position;\nin vec2 a_texCoord;\nin vec4 a_color;\nuniform builtin {\n vec4 cc_size_rotation;\n};\nvec4 vs_main() {\n vec4 pos = vec4(a_position, 1);\n pos = cc_matWorld * pos;\n vec2 vertOffset = a_texCoord.xy - 0.5;\n computeVertPos(pos, vertOffset, quaternionFromEuler(vec3(0., 0., cc_size_rotation.z)), vec3(cc_size_rotation.xy, 0.), cc_matViewInv);\n pos = cc_matViewProj * pos;\n uv = a_texCoord.xy;\n color = a_color;\n return pos;\n}\nvoid main() { gl_Position = vs_main(); }`, - "frag": `\nprecision mediump float;\nuniform CCGlobal {\n vec4 cc_time;\n vec4 cc_screenSize;\n vec4 cc_screenScale;\n vec4 cc_nativeSize;\n highp mat4 cc_matView;\n mat4 cc_matViewInv;\n mat4 cc_matProj;\n mat4 cc_matProjInv;\n mat4 cc_matViewProj;\n mat4 cc_matViewProjInv;\n vec4 cc_cameraPos;\n vec4 cc_exposure;\n vec4 cc_mainLitDir;\n vec4 cc_mainLitColor;\n vec4 cc_ambientSky;\n vec4 cc_ambientGround;\n};\nvec3 SRGBToLinear (vec3 gamma) {\n return gamma * gamma;\n}\nvec4 CCFragOutput (vec4 color) {\n #if CC_USE_HDR\n color.rgb = mix(color.rgb, SRGBToLinear(color.rgb) * cc_exposure.w, vec3(cc_exposure.z));\n #endif\n return color;\n}\nin vec2 uv;\nin vec4 color;\nuniform sampler2D mainTexture;\nuniform FragConstants {\n vec4 tintColor;\n};\nvec4 add () {\n vec4 col = 2.0 * color * tintColor * texture(mainTexture, uv);\n return CCFragOutput(col);\n}\nvec4 multiply () {\n vec4 col;\n vec4 texColor = texture(mainTexture, uv);\n col.rgb = tintColor.rgb * texColor.rgb * color.rgb * vec3(2.0);\n col.a = (1.0 - texColor.a) * (tintColor.a * color.a * 2.0);\n return CCFragOutput(col);\n}\nout vec4 cc_FragColor;\nvoid main() { cc_FragColor = add(); }` + "vert": `\nprecision mediump float;\nuniform Constants {\n vec4 mainTiling_Offset;\n vec4 frameTile_velLenScale;\n vec4 scale;\n};\nuniform CCGlobal {\n vec4 cc_time;\n vec4 cc_screenSize;\n vec4 cc_screenScale;\n vec4 cc_nativeSize;\n highp mat4 cc_matView;\n mat4 cc_matViewInv;\n mat4 cc_matProj;\n mat4 cc_matProjInv;\n mat4 cc_matViewProj;\n mat4 cc_matViewProjInv;\n vec4 cc_cameraPos;\n vec4 cc_exposure;\n vec4 cc_mainLitDir;\n vec4 cc_mainLitColor;\n vec4 cc_ambientSky;\n vec4 cc_ambientGround;\n};\nuniform CCLocal {\n highp mat4 cc_matWorld;\n highp mat4 cc_matWorldIT;\n};\nvec4 quaternionFromAxis (vec3 xAxis,vec3 yAxis,vec3 zAxis){\n mat3 m = mat3(xAxis,yAxis,zAxis);\n float trace = m[0][0] + m[1][1] + m[2][2];\n vec4 quat;\n if (trace > 0.) {\n float s = 0.5 / sqrt(trace + 1.0);\n quat.w = 0.25 / s;\n quat.x = (m[2][1] - m[1][2]) * s;\n quat.y = (m[0][2] - m[2][0]) * s;\n quat.z = (m[1][0] - m[0][1]) * s;\n } else if ((m[0][0] > m[1][1]) && (m[0][0] > m[2][2])) {\n float s = 2.0 * sqrt(1.0 + m[0][0] - m[1][1] - m[2][2]);\n quat.w = (m[2][1] - m[1][2]) / s;\n quat.x = 0.25 * s;\n quat.y = (m[0][1] + m[1][0]) / s;\n quat.z = (m[0][2] + m[2][0]) / s;\n } else if (m[1][1] > m[2][2]) {\n float s = 2.0 * sqrt(1.0 + m[1][1] - m[0][0] - m[2][2]);\n quat.w = (m[0][2] - m[2][0]) / s;\n quat.x = (m[0][1] + m[1][0]) / s;\n quat.y = 0.25 * s;\n quat.z = (m[1][2] + m[2][1]) / s;\n } else {\n float s = 2.0 * sqrt(1.0 + m[2][2] - m[0][0] - m[1][1]);\n quat.w = (m[1][0] - m[0][1]) / s;\n quat.x = (m[0][2] + m[2][0]) / s;\n quat.y = (m[1][2] + m[2][1]) / s;\n quat.z = 0.25 * s;\n }\n float len = quat.x * quat.x + quat.y * quat.y + quat.z * quat.z + quat.w * quat.w;\n if (len > 0.) {\n len = 1. / sqrt(len);\n quat.x = quat.x * len;\n quat.y = quat.y * len;\n quat.z = quat.z * len;\n quat.w = quat.w * len;\n }\n return quat;\n}\nvec4 quaternionFromEuler (vec3 angle){\n float x = angle.x / 2.;\n float y = angle.y / 2.;\n float z = angle.z / 2.;\n float sx = sin(x);\n float cx = cos(x);\n float sy = sin(y);\n float cy = cos(y);\n float sz = sin(z);\n float cz = cos(z);\n vec4 quat = vec4(0);\n quat.x = sx * cy * cz + cx * sy * sz;\n quat.y = cx * sy * cz + sx * cy * sz;\n quat.z = cx * cy * sz - sx * sy * cz;\n quat.w = cx * cy * cz - sx * sy * sz;\n return quat;\n}\nvec4 quatMultiply (vec4 a, vec4 b){\n vec4 quat;\n quat.x = a.x * b.w + a.w * b.x + a.y * b.z - a.z * b.y;\n quat.y = a.y * b.w + a.w * b.y + a.z * b.x - a.x * b.z;\n quat.z = a.z * b.w + a.w * b.z + a.x * b.y - a.y * b.x;\n quat.w = a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z;\n return quat;\n}\nvoid rotateVecFromQuat (inout vec3 v, vec4 q){\n float ix = q.w * v.x + q.y * v.z - q.z * v.y;\n float iy = q.w * v.y + q.z * v.x - q.x * v.z;\n float iz = q.w * v.z + q.x * v.y - q.y * v.x;\n float iw = -q.x * v.x - q.y * v.y - q.z * v.z;\n v.x = ix * q.w + iw * -q.x + iy * -q.z - iz * -q.y;\n v.y = iy * q.w + iw * -q.y + iz * -q.x - ix * -q.z;\n v.z = iz * q.w + iw * -q.z + ix * -q.y - iy * -q.x;\n}\nvec3 rotateInLocalSpace (vec3 pos, vec3 xAxis, vec3 yAxis, vec3 zAxis, vec4 q){\n vec4 viewQuat = quaternionFromAxis(xAxis, yAxis, zAxis);\n vec4 rotQuat = quatMultiply(viewQuat, q);\n rotateVecFromQuat(pos, rotQuat);\n return pos;\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}\nout vec2 uv;\nout vec4 color;\nvoid computeVertPos (inout vec4 pos, vec2 vertOffset, vec4 q, vec3 s\n , mat4 viewInv\n) {\n vec3 viewSpaceVert = vec3(vertOffset.x * s.x, vertOffset.y * s.y, 0.);\n vec3 camX = normalize(vec3(viewInv[0][0], viewInv[1][0], viewInv[2][0]));\n vec3 camY = normalize(vec3(viewInv[0][1], viewInv[1][1], viewInv[2][1]));\n vec3 camZ = normalize(vec3(viewInv[0][2], viewInv[1][2], viewInv[2][2]));\n pos.xyz += rotateInLocalSpace(viewSpaceVert, camX, camY, camZ, q);\n}\nin vec3 a_position;\nin vec2 a_texCoord;\nin vec4 a_color;\nuniform builtin {\n vec4 cc_size_rotation;\n};\nvec4 vs_main() {\n vec4 pos = vec4(a_position, 1);\n pos = cc_matWorld * pos;\n vec2 vertOffset = a_texCoord.xy - 0.5;\n computeVertPos(pos, vertOffset, quaternionFromEuler(vec3(0., 0., cc_size_rotation.z)), vec3(cc_size_rotation.xy, 0.), cc_matViewInv);\n pos = cc_matViewProj * pos;\n uv = a_texCoord.xy;\n color = a_color;\n return pos;\n}\nvoid main() { gl_Position = vs_main(); }`, + "frag": `\nprecision mediump float;\nuniform CCGlobal {\n vec4 cc_time;\n vec4 cc_screenSize;\n vec4 cc_screenScale;\n vec4 cc_nativeSize;\n highp mat4 cc_matView;\n mat4 cc_matViewInv;\n mat4 cc_matProj;\n mat4 cc_matProjInv;\n mat4 cc_matViewProj;\n mat4 cc_matViewProjInv;\n vec4 cc_cameraPos;\n vec4 cc_exposure;\n vec4 cc_mainLitDir;\n vec4 cc_mainLitColor;\n vec4 cc_ambientSky;\n vec4 cc_ambientGround;\n};\nvec3 SRGBToLinear (vec3 gamma) {\n return gamma * gamma;\n}\nvec4 CCFragOutput (vec4 color) {\n #if CC_USE_HDR\n color.rgb = mix(color.rgb, SRGBToLinear(color.rgb) * cc_exposure.w, vec3(cc_exposure.z));\n #endif\n return color;\n}\nin vec2 uv;\nin vec4 color;\nuniform sampler2D mainTexture;\nuniform FragConstants {\n vec4 tintColor;\n};\nvec4 add () {\n vec4 col = 2.0 * color * tintColor * texture(mainTexture, uv);\n return CCFragOutput(col);\n}\nout vec4 cc_FragColor;\nvoid main() { cc_FragColor = add(); }` }, "glsl1": { - "vert": `\nprecision mediump float;\nuniform highp mat4 cc_matView;\nuniform mat4 cc_matViewInv;\nuniform mat4 cc_matViewProj;\nuniform highp mat4 cc_matWorld;\nvec4 quaternionFromAxis (vec3 xAxis,vec3 yAxis,vec3 zAxis){\n mat3 m = mat3(xAxis,yAxis,zAxis);\n float trace = m[0][0] + m[1][1] + m[2][2];\n vec4 quat;\n if (trace > 0.) {\n float s = 0.5 / sqrt(trace + 1.0);\n quat.w = 0.25 / s;\n quat.x = (m[2][1] - m[1][2]) * s;\n quat.y = (m[0][2] - m[2][0]) * s;\n quat.z = (m[1][0] - m[0][1]) * s;\n } else if ((m[0][0] > m[1][1]) && (m[0][0] > m[2][2])) {\n float s = 2.0 * sqrt(1.0 + m[0][0] - m[1][1] - m[2][2]);\n quat.w = (m[2][1] - m[1][2]) / s;\n quat.x = 0.25 * s;\n quat.y = (m[0][1] + m[1][0]) / s;\n quat.z = (m[0][2] + m[2][0]) / s;\n } else if (m[1][1] > m[2][2]) {\n float s = 2.0 * sqrt(1.0 + m[1][1] - m[0][0] - m[2][2]);\n quat.w = (m[0][2] - m[2][0]) / s;\n quat.x = (m[0][1] + m[1][0]) / s;\n quat.y = 0.25 * s;\n quat.z = (m[1][2] + m[2][1]) / s;\n } else {\n float s = 2.0 * sqrt(1.0 + m[2][2] - m[0][0] - m[1][1]);\n quat.w = (m[1][0] - m[0][1]) / s;\n quat.x = (m[0][2] + m[2][0]) / s;\n quat.y = (m[1][2] + m[2][1]) / s;\n quat.z = 0.25 * s;\n }\n float len = quat.x * quat.x + quat.y * quat.y + quat.z * quat.z + quat.w * quat.w;\n if (len > 0.) {\n len = 1. / sqrt(len);\n quat.x = quat.x * len;\n quat.y = quat.y * len;\n quat.z = quat.z * len;\n quat.w = quat.w * len;\n }\n return quat;\n}\nvec4 quaternionFromEuler (vec3 angle){\n float x = angle.x / 2.;\n float y = angle.y / 2.;\n float z = angle.z / 2.;\n float sx = sin(x);\n float cx = cos(x);\n float sy = sin(y);\n float cy = cos(y);\n float sz = sin(z);\n float cz = cos(z);\n vec4 quat = vec4(0);\n quat.x = sx * cy * cz + cx * sy * sz;\n quat.y = cx * sy * cz + sx * cy * sz;\n quat.z = cx * cy * sz - sx * sy * cz;\n quat.w = cx * cy * cz - sx * sy * sz;\n return quat;\n}\nvec4 quatMultiply (vec4 a, vec4 b){\n vec4 quat;\n quat.x = a.x * b.w + a.w * b.x + a.y * b.z - a.z * b.y;\n quat.y = a.y * b.w + a.w * b.y + a.z * b.x - a.x * b.z;\n quat.z = a.z * b.w + a.w * b.z + a.x * b.y - a.y * b.x;\n quat.w = a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z;\n return quat;\n}\nvoid rotateVecFromQuat (inout vec3 v, vec4 q){\n float ix = q.w * v.x + q.y * v.z - q.z * v.y;\n float iy = q.w * v.y + q.z * v.x - q.x * v.z;\n float iz = q.w * v.z + q.x * v.y - q.y * v.x;\n float iw = -q.x * v.x - q.y * v.y - q.z * v.z;\n v.x = ix * q.w + iw * -q.x + iy * -q.z - iz * -q.y;\n v.y = iy * q.w + iw * -q.y + iz * -q.x - ix * -q.z;\n v.z = iz * q.w + iw * -q.z + ix * -q.y - iy * -q.x;\n}\nvec3 rotateInLocalSpace (vec3 pos, vec3 xAxis, vec3 yAxis, vec3 zAxis, vec4 q){\n vec4 viewQuat = quaternionFromAxis(xAxis, yAxis, zAxis);\n vec4 rotQuat = quatMultiply(viewQuat, q);\n rotateVecFromQuat(pos, rotQuat);\n return pos;\n}\nvarying vec2 uv;\nvarying vec4 color;\nvoid computeVertPos (inout vec4 pos, vec2 vertOffset, vec4 q, vec3 s\n , mat4 viewInv\n) {\n vec3 viewSpaceVert = vec3(vertOffset.x * s.x, vertOffset.y * s.y, 0.);\n vec3 camX = normalize(vec3(viewInv[0][0], viewInv[1][0], viewInv[2][0]));\n vec3 camY = normalize(vec3(viewInv[0][1], viewInv[1][1], viewInv[2][1]));\n vec3 camZ = normalize(vec3(viewInv[0][2], viewInv[1][2], viewInv[2][2]));\n pos.xyz += rotateInLocalSpace(viewSpaceVert, camX, camY, camZ, q);\n}\nattribute vec3 a_position;\nattribute vec2 a_texCoord;\nattribute vec4 a_color;\nuniform vec4 cc_size_rotation;\nvec4 vs_main() {\n vec4 pos = vec4(a_position, 1);\n pos = cc_matWorld * pos;\n vec2 vertOffset = a_texCoord.xy - 0.5;\n computeVertPos(pos, vertOffset, quaternionFromEuler(vec3(0., 0., cc_size_rotation.z)), vec3(cc_size_rotation.xy, 0.), cc_matViewInv);\n pos = cc_matViewProj * pos;\n uv = a_texCoord.xy;\n color = a_color;\n return pos;\n}\nvoid main() { gl_Position = vs_main(); }`, + "vert": `\nprecision mediump float;\nuniform highp mat4 cc_matView;\nuniform mat4 cc_matViewInv;\nuniform mat4 cc_matViewProj;\nuniform highp mat4 cc_matWorld;\nvec4 quaternionFromAxis (vec3 xAxis,vec3 yAxis,vec3 zAxis){\n mat3 m = mat3(xAxis,yAxis,zAxis);\n float trace = m[0][0] + m[1][1] + m[2][2];\n vec4 quat;\n if (trace > 0.) {\n float s = 0.5 / sqrt(trace + 1.0);\n quat.w = 0.25 / s;\n quat.x = (m[2][1] - m[1][2]) * s;\n quat.y = (m[0][2] - m[2][0]) * s;\n quat.z = (m[1][0] - m[0][1]) * s;\n } else if ((m[0][0] > m[1][1]) && (m[0][0] > m[2][2])) {\n float s = 2.0 * sqrt(1.0 + m[0][0] - m[1][1] - m[2][2]);\n quat.w = (m[2][1] - m[1][2]) / s;\n quat.x = 0.25 * s;\n quat.y = (m[0][1] + m[1][0]) / s;\n quat.z = (m[0][2] + m[2][0]) / s;\n } else if (m[1][1] > m[2][2]) {\n float s = 2.0 * sqrt(1.0 + m[1][1] - m[0][0] - m[2][2]);\n quat.w = (m[0][2] - m[2][0]) / s;\n quat.x = (m[0][1] + m[1][0]) / s;\n quat.y = 0.25 * s;\n quat.z = (m[1][2] + m[2][1]) / s;\n } else {\n float s = 2.0 * sqrt(1.0 + m[2][2] - m[0][0] - m[1][1]);\n quat.w = (m[1][0] - m[0][1]) / s;\n quat.x = (m[0][2] + m[2][0]) / s;\n quat.y = (m[1][2] + m[2][1]) / s;\n quat.z = 0.25 * s;\n }\n float len = quat.x * quat.x + quat.y * quat.y + quat.z * quat.z + quat.w * quat.w;\n if (len > 0.) {\n len = 1. / sqrt(len);\n quat.x = quat.x * len;\n quat.y = quat.y * len;\n quat.z = quat.z * len;\n quat.w = quat.w * len;\n }\n return quat;\n}\nvec4 quaternionFromEuler (vec3 angle){\n float x = angle.x / 2.;\n float y = angle.y / 2.;\n float z = angle.z / 2.;\n float sx = sin(x);\n float cx = cos(x);\n float sy = sin(y);\n float cy = cos(y);\n float sz = sin(z);\n float cz = cos(z);\n vec4 quat = vec4(0);\n quat.x = sx * cy * cz + cx * sy * sz;\n quat.y = cx * sy * cz + sx * cy * sz;\n quat.z = cx * cy * sz - sx * sy * cz;\n quat.w = cx * cy * cz - sx * sy * sz;\n return quat;\n}\nvec4 quatMultiply (vec4 a, vec4 b){\n vec4 quat;\n quat.x = a.x * b.w + a.w * b.x + a.y * b.z - a.z * b.y;\n quat.y = a.y * b.w + a.w * b.y + a.z * b.x - a.x * b.z;\n quat.z = a.z * b.w + a.w * b.z + a.x * b.y - a.y * b.x;\n quat.w = a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z;\n return quat;\n}\nvoid rotateVecFromQuat (inout vec3 v, vec4 q){\n float ix = q.w * v.x + q.y * v.z - q.z * v.y;\n float iy = q.w * v.y + q.z * v.x - q.x * v.z;\n float iz = q.w * v.z + q.x * v.y - q.y * v.x;\n float iw = -q.x * v.x - q.y * v.y - q.z * v.z;\n v.x = ix * q.w + iw * -q.x + iy * -q.z - iz * -q.y;\n v.y = iy * q.w + iw * -q.y + iz * -q.x - ix * -q.z;\n v.z = iz * q.w + iw * -q.z + ix * -q.y - iy * -q.x;\n}\nvec3 rotateInLocalSpace (vec3 pos, vec3 xAxis, vec3 yAxis, vec3 zAxis, vec4 q){\n vec4 viewQuat = quaternionFromAxis(xAxis, yAxis, zAxis);\n vec4 rotQuat = quatMultiply(viewQuat, q);\n rotateVecFromQuat(pos, rotQuat);\n return pos;\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}\nvarying vec2 uv;\nvarying vec4 color;\nvoid computeVertPos (inout vec4 pos, vec2 vertOffset, vec4 q, vec3 s\n , mat4 viewInv\n) {\n vec3 viewSpaceVert = vec3(vertOffset.x * s.x, vertOffset.y * s.y, 0.);\n vec3 camX = normalize(vec3(viewInv[0][0], viewInv[1][0], viewInv[2][0]));\n vec3 camY = normalize(vec3(viewInv[0][1], viewInv[1][1], viewInv[2][1]));\n vec3 camZ = normalize(vec3(viewInv[0][2], viewInv[1][2], viewInv[2][2]));\n pos.xyz += rotateInLocalSpace(viewSpaceVert, camX, camY, camZ, q);\n}\nattribute vec3 a_position;\nattribute vec2 a_texCoord;\nattribute vec4 a_color;\nuniform vec4 cc_size_rotation;\nvec4 vs_main() {\n vec4 pos = vec4(a_position, 1);\n pos = cc_matWorld * pos;\n vec2 vertOffset = a_texCoord.xy - 0.5;\n computeVertPos(pos, vertOffset, quaternionFromEuler(vec3(0., 0., cc_size_rotation.z)), vec3(cc_size_rotation.xy, 0.), cc_matViewInv);\n pos = cc_matViewProj * pos;\n uv = a_texCoord.xy;\n color = a_color;\n return pos;\n}\nvoid main() { gl_Position = vs_main(); }`, "frag": `\nprecision mediump float;\nuniform vec4 cc_exposure;\nvec3 SRGBToLinear (vec3 gamma) {\n return gamma * gamma;\n}\nvec4 CCFragOutput (vec4 color) {\n #if CC_USE_HDR\n color.rgb = mix(color.rgb, SRGBToLinear(color.rgb) * cc_exposure.w, vec3(cc_exposure.z));\n #endif\n return color;\n}\nvarying vec2 uv;\nvarying vec4 color;\nuniform sampler2D mainTexture;\nuniform vec4 tintColor;\nvec4 add () {\n vec4 col = 2.0 * color * tintColor * texture2D(mainTexture, uv);\n return CCFragOutput(col);\n}\nvoid main() { gl_FragColor = add(); }` }, "builtins": {"globals":{"blocks":[{"name":"CCGlobal", "defines":[]}], "samplers":[]}, "locals":{"blocks":[{"name":"CCLocal", "defines":[]}], "samplers":[]}}, @@ -49,22 +49,17 @@ export default [ "shaders": [ { "name": "builtin-particle-trail|particle-trail:vs_main|tinted-fs:add", - "hash": 2489155218, + "hash": 3301971983, "glsl3": { - "vert": `\nprecision mediump float;\nuniform Constants {\n vec4 mainTiling_Offset;\n vec4 frameTile_velLenScale;\n vec4 scale;\n};\nuniform CCGlobal {\n vec4 cc_time;\n vec4 cc_screenSize;\n vec4 cc_screenScale;\n vec4 cc_nativeSize;\n highp mat4 cc_matView;\n mat4 cc_matViewInv;\n mat4 cc_matProj;\n mat4 cc_matProjInv;\n mat4 cc_matViewProj;\n mat4 cc_matViewProjInv;\n vec4 cc_cameraPos;\n vec4 cc_exposure;\n vec4 cc_mainLitDir;\n vec4 cc_mainLitColor;\n vec4 cc_ambientSky;\n vec4 cc_ambientGround;\n};\nuniform CCLocal {\n highp mat4 cc_matWorld;\n highp mat4 cc_matWorldIT;\n};\nvec4 quaternionFromAxisAngle (float angle, vec3 axis){\n angle /= 2.;\n float s = sin(angle);\n vec4 res;\n res.xyz = s * axis;\n res.w = cos(angle);\n return res;\n}\nvec4 quaternionFromAxis (vec3 xAxis,vec3 yAxis,vec3 zAxis){\n mat3 m = mat3(xAxis,yAxis,zAxis);\n float trace = m[0][0] + m[1][1] + m[2][2];\n vec4 quat;\n if (trace > 0.) {\n float s = 0.5 / sqrt(trace + 1.0);\n quat.w = 0.25 / s;\n quat.x = (m[2][1] - m[1][2]) * s;\n quat.y = (m[0][2] - m[2][0]) * s;\n quat.z = (m[1][0] - m[0][1]) * s;\n } else if ((m[0][0] > m[1][1]) && (m[0][0] > m[2][2])) {\n float s = 2.0 * sqrt(1.0 + m[0][0] - m[1][1] - m[2][2]);\n quat.w = (m[2][1] - m[1][2]) / s;\n quat.x = 0.25 * s;\n quat.y = (m[0][1] + m[1][0]) / s;\n quat.z = (m[0][2] + m[2][0]) / s;\n } else if (m[1][1] > m[2][2]) {\n float s = 2.0 * sqrt(1.0 + m[1][1] - m[0][0] - m[2][2]);\n quat.w = (m[0][2] - m[2][0]) / s;\n quat.x = (m[0][1] + m[1][0]) / s;\n quat.y = 0.25 * s;\n quat.z = (m[1][2] + m[2][1]) / s;\n } else {\n float s = 2.0 * sqrt(1.0 + m[2][2] - m[0][0] - m[1][1]);\n quat.w = (m[1][0] - m[0][1]) / s;\n quat.x = (m[0][2] + m[2][0]) / s;\n quat.y = (m[1][2] + m[2][1]) / s;\n quat.z = 0.25 * s;\n }\n float len = quat.x * quat.x + quat.y * quat.y + quat.z * quat.z + quat.w * quat.w;\n if (len > 0.) {\n len = 1. / sqrt(len);\n quat.x = quat.x * len;\n quat.y = quat.y * len;\n quat.z = quat.z * len;\n quat.w = quat.w * len;\n }\n return quat;\n}\nvec4 quaternionFromEuler (vec3 angle){\n float x = angle.x / 2.;\n float y = angle.y / 2.;\n float z = angle.z / 2.;\n float sx = sin(x);\n float cx = cos(x);\n float sy = sin(y);\n float cy = cos(y);\n float sz = sin(z);\n float cz = cos(z);\n vec4 quat = vec4(0);\n quat.x = sx * cy * cz + cx * sy * sz;\n quat.y = cx * sy * cz + sx * cy * sz;\n quat.z = cx * cy * sz - sx * sy * cz;\n quat.w = cx * cy * cz - sx * sy * sz;\n return quat;\n}\nmat4 matrixFromRT (vec4 q, vec3 p){\n float x2 = q.x + q.x;\n float y2 = q.y + q.y;\n float z2 = q.z + q.z;\n float xx = q.x * x2;\n float xy = q.x * y2;\n float xz = q.x * z2;\n float yy = q.y * y2;\n float yz = q.y * z2;\n float zz = q.z * z2;\n float wx = q.w * x2;\n float wy = q.w * y2;\n float wz = q.w * z2;\n return mat4(\n 1. - (yy + zz), xy + wz, xz - wy, 0,\n xy - wz, 1. - (xx + zz), yz + wx, 0,\n xz + wy, yz - wx, 1. - (xx + yy), 0,\n p.x, p.y, p.z, 1\n );\n}\nmat4 matFromRTS (vec4 q, vec3 t, vec3 s){\n float x = q.x, y = q.y, z = q.z, w = q.w;\n float x2 = x + x;\n float y2 = y + y;\n float z2 = z + z;\n float xx = x * x2;\n float xy = x * y2;\n float xz = x * z2;\n float yy = y * y2;\n float yz = y * z2;\n float zz = z * z2;\n float wx = w * x2;\n float wy = w * y2;\n float wz = w * z2;\n float sx = s.x;\n float sy = s.y;\n float sz = s.z;\n return mat4((1. - (yy + zz)) * sx, (xy + wz) * sx, (xz - wy) * sx, 0,\n (xy - wz) * sy, (1. - (xx + zz)) * sy, (yz + wx) * sy, 0,\n (xz + wy) * sz, (yz - wx) * sz, (1. - (xx + yy)) * sz, 0,\n t.x, t.y, t.z, 1);\n}\nvoid scaleMatrix (inout mat4 m, float s){\n m[0].xyz *= s;\n m[1].xyz *= s;\n m[2].xyz *= s;\n}\nvec4 quatMultiply (vec4 a, vec4 b){\n vec4 quat;\n quat.x = a.x * b.w + a.w * b.x + a.y * b.z - a.z * b.y;\n quat.y = a.y * b.w + a.w * b.y + a.z * b.x - a.x * b.z;\n quat.z = a.z * b.w + a.w * b.z + a.x * b.y - a.y * b.x;\n quat.w = a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z;\n return quat;\n}\nvoid rotateVecFromQuat (inout vec3 v, vec4 q){\n float ix = q.w * v.x + q.y * v.z - q.z * v.y;\n float iy = q.w * v.y + q.z * v.x - q.x * v.z;\n float iz = q.w * v.z + q.x * v.y - q.y * v.x;\n float iw = -q.x * v.x - q.y * v.y - q.z * v.z;\n v.x = ix * q.w + iw * -q.x + iy * -q.z - iz * -q.y;\n v.y = iy * q.w + iw * -q.y + iz * -q.x - ix * -q.z;\n v.z = iz * q.w + iw * -q.z + ix * -q.y - iy * -q.x;\n}\nvec3 rotateVecFromAxis (vec3 v, vec3 axis, float theta){\n return cos(theta) * v + sin(theta) * cross(v, axis) + (1. - cos(theta)) * dot(v, axis) * axis;\n}\nvec3 rotateInLocalSpace (vec3 pos, vec3 xAxis, vec3 yAxis, vec3 zAxis, vec4 q){\n vec4 viewQuat = quaternionFromAxis(xAxis, yAxis, zAxis);\n vec4 rotQuat = quatMultiply(viewQuat, q);\n rotateVecFromQuat(pos, rotQuat);\n return pos;\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}\nout vec2 uv;\nout vec4 color;\nvoid computeVertPos (inout vec4 pos, vec2 vertOffset, vec4 q, vec3 s\n#if CC_USE_BILLBOARD || CC_USE_VERTICAL_BILLBOARD\n , mat4 viewInv\n#endif\n#if CC_USE_STRETCHED_BILLBOARD\n , vec3 eye\n , vec4 velocity\n , float velocityScale\n , float lengthScale\n , float xIndex\n#endif\n) {\n#if CC_USE_BILLBOARD\n vec3 viewSpaceVert = vec3(vertOffset.x * s.x, vertOffset.y * s.y, 0.);\n vec3 camX = normalize(vec3(viewInv[0][0], viewInv[1][0], viewInv[2][0]));\n vec3 camY = normalize(vec3(viewInv[0][1], viewInv[1][1], viewInv[2][1]));\n vec3 camZ = normalize(vec3(viewInv[0][2], viewInv[1][2], viewInv[2][2]));\n pos.xyz += rotateInLocalSpace(viewSpaceVert, camX, camY, camZ, q);\n#elif CC_USE_STRETCHED_BILLBOARD\n vec3 camRight = normalize(cross(pos.xyz - eye, velocity.xyz)) * s.x;\n vec3 camUp = velocity.xyz * velocityScale + normalize(velocity.xyz) * lengthScale * s.y;\n pos.xyz += (camRight * abs(vertOffset.x) * sign(vertOffset.y)) - camUp * xIndex;\n#elif CC_USE_HORIZONTAL_BILLBOARD\n vec3 viewSpaceVert = vec3(vertOffset.x * s.x, vertOffset.y * s.y, 0.);\n vec3 camX = vec3(1, 0, 0);\n vec3 camY = vec3(0, 0, -1);\n pos.xyz += rotateInLocalSpace(viewSpaceVert, camX, camY, cross(camX, camY), q);\n#elif CC_USE_VERTICAL_BILLBOARD\n vec2 viewSpaceVert = vec2(vertOffset.x * s.x, vertOffset.y * s.y);\n rotateCorner(viewSpaceVert, q.z);\n vec3 camX = normalize(vec3(cc_matView[0][0], cc_matView[1][0], cc_matView[2][0]));\n vec3 camY = vec3(0, 1, 0);\n vec3 offset = camX * viewSpaceVert.x + camY * viewSpaceVert.y;\n pos.xyz += offset;\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#if !CC_USE_MESH\n vertIndex.y = 1. - vertIndex.y;\n#endif\n return (aniUV.xy + vertIndex) / vec2(frameTile.x, frameTile.y);\n}\nin vec3 a_position;\nin vec4 a_texCoord;\nin vec3 a_texCoord1;\nin vec3 a_texCoord2;\nin vec4 a_color;\n#if CC_DRAW_WIRE_FRAME\n out vec3 vBarycentric;\n#endif\nvec4 vs_main() {\n highp vec4 pos = vec4(a_position, 1);\n vec4 velocity = vec4(a_texCoord1.xyz, 0);\n #if !CC_USE_WORLD_SPACE\n pos = cc_matWorld * pos;\n velocity = cc_matWorld * velocity;\n #endif\n float vertOffset = (a_texCoord.x - 0.5) * a_texCoord.y;\n vec3 camUp = normalize(cross(pos.xyz - cc_cameraPos.xyz, velocity.xyz));\n pos.xyz += camUp * vertOffset;\n pos = cc_matViewProj * pos;\n uv = a_texCoord.zw * mainTiling_Offset.xy + mainTiling_Offset.zw;;\n color = a_color;\n #if CC_DRAW_WIRE_FRAME\n vBarycentric = a_texCoord2;\n #endif\n return pos;\n}\nvoid main() { gl_Position = vs_main(); }`, - "frag": `\n precision mediump float;\nuniform CCGlobal {\n vec4 cc_time;\n vec4 cc_screenSize;\n vec4 cc_screenScale;\n vec4 cc_nativeSize;\n highp mat4 cc_matView;\n mat4 cc_matViewInv;\n mat4 cc_matProj;\n mat4 cc_matProjInv;\n mat4 cc_matViewProj;\n mat4 cc_matViewProjInv;\n vec4 cc_cameraPos;\n vec4 cc_exposure;\n vec4 cc_mainLitDir;\n vec4 cc_mainLitColor;\n vec4 cc_ambientSky;\n vec4 cc_ambientGround;\n};\nvec3 SRGBToLinear (vec3 gamma) {\n return gamma * gamma;\n}\nvec4 CCFragOutput (vec4 color) {\n #if CC_USE_HDR\n color.rgb = mix(color.rgb, SRGBToLinear(color.rgb) * cc_exposure.w, vec3(cc_exposure.z));\n #endif\n return color;\n}\n in vec2 uv;\n in vec4 color;\n #if CC_DRAW_WIRE_FRAME\n in vec3 vBarycentric;\n #endif\n uniform sampler2D mainTexture;\n uniform FragConstants {\n vec4 tintColor;\n };\n vec4 add () {\n vec4 col = 2.0 * color * tintColor * texture(mainTexture, uv);\n#if CC_DRAW_WIRE_FRAME\n if (any(lessThan(vBarycentric, vec3(0.02)))) {\n col = vec4(0., 1., 1., 1.);\n }\n#endif\n return CCFragOutput(col);\n }\n vec4 multiply () {\n vec4 col;\n vec4 texColor = texture(mainTexture, uv);\n col.rgb = tintColor.rgb * texColor.rgb * color.rgb * vec3(2.0);\n col.a = (1.0 - texColor.a) * (tintColor.a * color.a * 2.0);\n#if CC_DRAW_WIRE_FRAME\n if (any(lessThan(vBarycentric, vec3(0.02)))) {\n col = vec4(0., 1., 1., col.a);\n }\n#endif\n return CCFragOutput(col);\n }\nout vec4 cc_FragColor;\nvoid main() { cc_FragColor = add(); }` + "vert": `\nprecision mediump float;\nuniform Constants {\n vec4 mainTiling_Offset;\n vec4 frameTile_velLenScale;\n vec4 scale;\n};\nuniform CCGlobal {\n vec4 cc_time;\n vec4 cc_screenSize;\n vec4 cc_screenScale;\n vec4 cc_nativeSize;\n highp mat4 cc_matView;\n mat4 cc_matViewInv;\n mat4 cc_matProj;\n mat4 cc_matProjInv;\n mat4 cc_matViewProj;\n mat4 cc_matViewProjInv;\n vec4 cc_cameraPos;\n vec4 cc_exposure;\n vec4 cc_mainLitDir;\n vec4 cc_mainLitColor;\n vec4 cc_ambientSky;\n vec4 cc_ambientGround;\n};\nuniform CCLocal {\n highp mat4 cc_matWorld;\n highp mat4 cc_matWorldIT;\n};\nout vec2 uv;\nout vec4 color;\nin vec3 a_position;\nin vec4 a_texCoord;\nin vec3 a_texCoord1;\nin vec3 a_texCoord2;\nin vec4 a_color;\n#if CC_DRAW_WIRE_FRAME\n out vec3 vBarycentric;\n#endif\nvec4 vs_main() {\n highp vec4 pos = vec4(a_position, 1);\n vec4 velocity = vec4(a_texCoord1.xyz, 0);\n #if !CC_USE_WORLD_SPACE\n pos = cc_matWorld * pos;\n velocity = cc_matWorld * velocity;\n #endif\n float vertOffset = (a_texCoord.x - 0.5) * a_texCoord.y;\n vec3 camUp = normalize(cross(pos.xyz - cc_cameraPos.xyz, velocity.xyz));\n pos.xyz += camUp * vertOffset;\n pos = cc_matViewProj * pos;\n uv = a_texCoord.zw * mainTiling_Offset.xy + mainTiling_Offset.zw;;\n color = a_color;\n #if CC_DRAW_WIRE_FRAME\n vBarycentric = a_texCoord2;\n #endif\n return pos;\n}\nvoid main() { gl_Position = vs_main(); }`, + "frag": `\n precision mediump float;\nuniform CCGlobal {\n vec4 cc_time;\n vec4 cc_screenSize;\n vec4 cc_screenScale;\n vec4 cc_nativeSize;\n highp mat4 cc_matView;\n mat4 cc_matViewInv;\n mat4 cc_matProj;\n mat4 cc_matProjInv;\n mat4 cc_matViewProj;\n mat4 cc_matViewProjInv;\n vec4 cc_cameraPos;\n vec4 cc_exposure;\n vec4 cc_mainLitDir;\n vec4 cc_mainLitColor;\n vec4 cc_ambientSky;\n vec4 cc_ambientGround;\n};\nvec3 SRGBToLinear (vec3 gamma) {\n return gamma * gamma;\n}\nvec4 CCFragOutput (vec4 color) {\n #if CC_USE_HDR\n color.rgb = mix(color.rgb, SRGBToLinear(color.rgb) * cc_exposure.w, vec3(cc_exposure.z));\n #endif\n return color;\n}\n in vec2 uv;\n in vec4 color;\n #if CC_DRAW_WIRE_FRAME\n in vec3 vBarycentric;\n #endif\n uniform sampler2D mainTexture;\n uniform FragConstants {\n vec4 tintColor;\n };\n vec4 add () {\n vec4 col = 2.0 * color * tintColor * texture(mainTexture, uv);\n#if CC_DRAW_WIRE_FRAME\n if (any(lessThan(vBarycentric, vec3(0.02)))) {\n col = vec4(0., 1., 1., 1.);\n }\n#endif\n return CCFragOutput(col);\n }\nout vec4 cc_FragColor;\nvoid main() { cc_FragColor = add(); }` }, "glsl1": { - "vert": `\nprecision mediump float;\nuniform vec4 mainTiling_Offset;\nuniform highp mat4 cc_matView;\nuniform mat4 cc_matViewProj;\nuniform vec4 cc_cameraPos;\nuniform highp mat4 cc_matWorld;\nvec4 quaternionFromAxis (vec3 xAxis,vec3 yAxis,vec3 zAxis){\n mat3 m = mat3(xAxis,yAxis,zAxis);\n float trace = m[0][0] + m[1][1] + m[2][2];\n vec4 quat;\n if (trace > 0.) {\n float s = 0.5 / sqrt(trace + 1.0);\n quat.w = 0.25 / s;\n quat.x = (m[2][1] - m[1][2]) * s;\n quat.y = (m[0][2] - m[2][0]) * s;\n quat.z = (m[1][0] - m[0][1]) * s;\n } else if ((m[0][0] > m[1][1]) && (m[0][0] > m[2][2])) {\n float s = 2.0 * sqrt(1.0 + m[0][0] - m[1][1] - m[2][2]);\n quat.w = (m[2][1] - m[1][2]) / s;\n quat.x = 0.25 * s;\n quat.y = (m[0][1] + m[1][0]) / s;\n quat.z = (m[0][2] + m[2][0]) / s;\n } else if (m[1][1] > m[2][2]) {\n float s = 2.0 * sqrt(1.0 + m[1][1] - m[0][0] - m[2][2]);\n quat.w = (m[0][2] - m[2][0]) / s;\n quat.x = (m[0][1] + m[1][0]) / s;\n quat.y = 0.25 * s;\n quat.z = (m[1][2] + m[2][1]) / s;\n } else {\n float s = 2.0 * sqrt(1.0 + m[2][2] - m[0][0] - m[1][1]);\n quat.w = (m[1][0] - m[0][1]) / s;\n quat.x = (m[0][2] + m[2][0]) / s;\n quat.y = (m[1][2] + m[2][1]) / s;\n quat.z = 0.25 * s;\n }\n float len = quat.x * quat.x + quat.y * quat.y + quat.z * quat.z + quat.w * quat.w;\n if (len > 0.) {\n len = 1. / sqrt(len);\n quat.x = quat.x * len;\n quat.y = quat.y * len;\n quat.z = quat.z * len;\n quat.w = quat.w * len;\n }\n return quat;\n}\nvec4 quatMultiply (vec4 a, vec4 b){\n vec4 quat;\n quat.x = a.x * b.w + a.w * b.x + a.y * b.z - a.z * b.y;\n quat.y = a.y * b.w + a.w * b.y + a.z * b.x - a.x * b.z;\n quat.z = a.z * b.w + a.w * b.z + a.x * b.y - a.y * b.x;\n quat.w = a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z;\n return quat;\n}\nvoid rotateVecFromQuat (inout vec3 v, vec4 q){\n float ix = q.w * v.x + q.y * v.z - q.z * v.y;\n float iy = q.w * v.y + q.z * v.x - q.x * v.z;\n float iz = q.w * v.z + q.x * v.y - q.y * v.x;\n float iw = -q.x * v.x - q.y * v.y - q.z * v.z;\n v.x = ix * q.w + iw * -q.x + iy * -q.z - iz * -q.y;\n v.y = iy * q.w + iw * -q.y + iz * -q.x - ix * -q.z;\n v.z = iz * q.w + iw * -q.z + ix * -q.y - iy * -q.x;\n}\nvec3 rotateInLocalSpace (vec3 pos, vec3 xAxis, vec3 yAxis, vec3 zAxis, vec4 q){\n vec4 viewQuat = quaternionFromAxis(xAxis, yAxis, zAxis);\n vec4 rotQuat = quatMultiply(viewQuat, q);\n rotateVecFromQuat(pos, rotQuat);\n return pos;\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}\nvarying vec2 uv;\nvarying vec4 color;\nattribute vec3 a_position;\nattribute vec4 a_texCoord;\nattribute vec3 a_texCoord1;\nattribute vec3 a_texCoord2;\nattribute vec4 a_color;\n#if CC_DRAW_WIRE_FRAME\n varying vec3 vBarycentric;\n#endif\nvec4 vs_main() {\n highp vec4 pos = vec4(a_position, 1);\n vec4 velocity = vec4(a_texCoord1.xyz, 0);\n #if !CC_USE_WORLD_SPACE\n pos = cc_matWorld * pos;\n velocity = cc_matWorld * velocity;\n #endif\n float vertOffset = (a_texCoord.x - 0.5) * a_texCoord.y;\n vec3 camUp = normalize(cross(pos.xyz - cc_cameraPos.xyz, velocity.xyz));\n pos.xyz += camUp * vertOffset;\n pos = cc_matViewProj * pos;\n uv = a_texCoord.zw * mainTiling_Offset.xy + mainTiling_Offset.zw;;\n color = a_color;\n #if CC_DRAW_WIRE_FRAME\n vBarycentric = a_texCoord2;\n #endif\n return pos;\n}\nvoid main() { gl_Position = vs_main(); }`, + "vert": `\nprecision mediump float;\nuniform vec4 mainTiling_Offset;\nuniform mat4 cc_matViewProj;\nuniform vec4 cc_cameraPos;\nuniform highp mat4 cc_matWorld;\nvarying vec2 uv;\nvarying vec4 color;\nattribute vec3 a_position;\nattribute vec4 a_texCoord;\nattribute vec3 a_texCoord1;\nattribute vec3 a_texCoord2;\nattribute vec4 a_color;\n#if CC_DRAW_WIRE_FRAME\n varying vec3 vBarycentric;\n#endif\nvec4 vs_main() {\n highp vec4 pos = vec4(a_position, 1);\n vec4 velocity = vec4(a_texCoord1.xyz, 0);\n #if !CC_USE_WORLD_SPACE\n pos = cc_matWorld * pos;\n velocity = cc_matWorld * velocity;\n #endif\n float vertOffset = (a_texCoord.x - 0.5) * a_texCoord.y;\n vec3 camUp = normalize(cross(pos.xyz - cc_cameraPos.xyz, velocity.xyz));\n pos.xyz += camUp * vertOffset;\n pos = cc_matViewProj * pos;\n uv = a_texCoord.zw * mainTiling_Offset.xy + mainTiling_Offset.zw;;\n color = a_color;\n #if CC_DRAW_WIRE_FRAME\n vBarycentric = a_texCoord2;\n #endif\n return pos;\n}\nvoid main() { gl_Position = vs_main(); }`, "frag": `\n precision mediump float;\nuniform vec4 cc_exposure;\nvec3 SRGBToLinear (vec3 gamma) {\n return gamma * gamma;\n}\nvec4 CCFragOutput (vec4 color) {\n #if CC_USE_HDR\n color.rgb = mix(color.rgb, SRGBToLinear(color.rgb) * cc_exposure.w, vec3(cc_exposure.z));\n #endif\n return color;\n}\n varying vec2 uv;\n varying vec4 color;\n #if CC_DRAW_WIRE_FRAME\n varying vec3 vBarycentric;\n #endif\n uniform sampler2D mainTexture;\n uniform vec4 tintColor;\n vec4 add () {\n vec4 col = 2.0 * color * tintColor * texture2D(mainTexture, uv);\n#if CC_DRAW_WIRE_FRAME\n if (any(lessThan(vBarycentric, vec3(0.02)))) {\n col = vec4(0., 1., 1., 1.);\n }\n#endif\n return CCFragOutput(col);\n }\nvoid main() { gl_FragColor = add(); }` }, "builtins": {"globals":{"blocks":[{"name":"CCGlobal", "defines":[]}], "samplers":[]}, "locals":{"blocks":[{"name":"CCLocal", "defines":[]}], "samplers":[]}}, "defines": [ - {"name":"CC_USE_BILLBOARD", "type":"boolean"}, - {"name":"CC_USE_STRETCHED_BILLBOARD", "type":"boolean"}, - {"name":"CC_USE_HORIZONTAL_BILLBOARD", "type":"boolean"}, - {"name":"CC_USE_VERTICAL_BILLBOARD", "type":"boolean"}, - {"name":"CC_USE_MESH", "type":"boolean"}, {"name":"CC_DRAW_WIRE_FRAME", "type":"boolean"}, {"name":"CC_USE_WORLD_SPACE", "type":"boolean"}, {"name":"CC_USE_HDR", "type":"boolean"} @@ -93,10 +88,10 @@ export default [ "shaders": [ { "name": "builtin-particle|particle-vs-legacy:lpvs_main|tinted-fs:add", - "hash": 2210001251, + "hash": 3128424677, "glsl3": { - "vert": `\nprecision highp float;\nvec4 quaternionFromAxisAngle (float angle, vec3 axis){\n angle /= 2.;\n float s = sin(angle);\n vec4 res;\n res.xyz = s * axis;\n res.w = cos(angle);\n return res;\n}\nvec4 quaternionFromAxis (vec3 xAxis,vec3 yAxis,vec3 zAxis){\n mat3 m = mat3(xAxis,yAxis,zAxis);\n float trace = m[0][0] + m[1][1] + m[2][2];\n vec4 quat;\n if (trace > 0.) {\n float s = 0.5 / sqrt(trace + 1.0);\n quat.w = 0.25 / s;\n quat.x = (m[2][1] - m[1][2]) * s;\n quat.y = (m[0][2] - m[2][0]) * s;\n quat.z = (m[1][0] - m[0][1]) * s;\n } else if ((m[0][0] > m[1][1]) && (m[0][0] > m[2][2])) {\n float s = 2.0 * sqrt(1.0 + m[0][0] - m[1][1] - m[2][2]);\n quat.w = (m[2][1] - m[1][2]) / s;\n quat.x = 0.25 * s;\n quat.y = (m[0][1] + m[1][0]) / s;\n quat.z = (m[0][2] + m[2][0]) / s;\n } else if (m[1][1] > m[2][2]) {\n float s = 2.0 * sqrt(1.0 + m[1][1] - m[0][0] - m[2][2]);\n quat.w = (m[0][2] - m[2][0]) / s;\n quat.x = (m[0][1] + m[1][0]) / s;\n quat.y = 0.25 * s;\n quat.z = (m[1][2] + m[2][1]) / s;\n } else {\n float s = 2.0 * sqrt(1.0 + m[2][2] - m[0][0] - m[1][1]);\n quat.w = (m[1][0] - m[0][1]) / s;\n quat.x = (m[0][2] + m[2][0]) / s;\n quat.y = (m[1][2] + m[2][1]) / s;\n quat.z = 0.25 * s;\n }\n float len = quat.x * quat.x + quat.y * quat.y + quat.z * quat.z + quat.w * quat.w;\n if (len > 0.) {\n len = 1. / sqrt(len);\n quat.x = quat.x * len;\n quat.y = quat.y * len;\n quat.z = quat.z * len;\n quat.w = quat.w * len;\n }\n return quat;\n}\nvec4 quaternionFromEuler (vec3 angle){\n float x = angle.x / 2.;\n float y = angle.y / 2.;\n float z = angle.z / 2.;\n float sx = sin(x);\n float cx = cos(x);\n float sy = sin(y);\n float cy = cos(y);\n float sz = sin(z);\n float cz = cos(z);\n vec4 quat = vec4(0);\n quat.x = sx * cy * cz + cx * sy * sz;\n quat.y = cx * sy * cz + sx * cy * sz;\n quat.z = cx * cy * sz - sx * sy * cz;\n quat.w = cx * cy * cz - sx * sy * sz;\n return quat;\n}\nmat4 matrixFromRT (vec4 q, vec3 p){\n float x2 = q.x + q.x;\n float y2 = q.y + q.y;\n float z2 = q.z + q.z;\n float xx = q.x * x2;\n float xy = q.x * y2;\n float xz = q.x * z2;\n float yy = q.y * y2;\n float yz = q.y * z2;\n float zz = q.z * z2;\n float wx = q.w * x2;\n float wy = q.w * y2;\n float wz = q.w * z2;\n return mat4(\n 1. - (yy + zz), xy + wz, xz - wy, 0,\n xy - wz, 1. - (xx + zz), yz + wx, 0,\n xz + wy, yz - wx, 1. - (xx + yy), 0,\n p.x, p.y, p.z, 1\n );\n}\nmat4 matFromRTS (vec4 q, vec3 t, vec3 s){\n float x = q.x, y = q.y, z = q.z, w = q.w;\n float x2 = x + x;\n float y2 = y + y;\n float z2 = z + z;\n float xx = x * x2;\n float xy = x * y2;\n float xz = x * z2;\n float yy = y * y2;\n float yz = y * z2;\n float zz = z * z2;\n float wx = w * x2;\n float wy = w * y2;\n float wz = w * z2;\n float sx = s.x;\n float sy = s.y;\n float sz = s.z;\n return mat4((1. - (yy + zz)) * sx, (xy + wz) * sx, (xz - wy) * sx, 0,\n (xy - wz) * sy, (1. - (xx + zz)) * sy, (yz + wx) * sy, 0,\n (xz + wy) * sz, (yz - wx) * sz, (1. - (xx + yy)) * sz, 0,\n t.x, t.y, t.z, 1);\n}\nvoid scaleMatrix (inout mat4 m, float s){\n m[0].xyz *= s;\n m[1].xyz *= s;\n m[2].xyz *= s;\n}\nvec4 quatMultiply (vec4 a, vec4 b){\n vec4 quat;\n quat.x = a.x * b.w + a.w * b.x + a.y * b.z - a.z * b.y;\n quat.y = a.y * b.w + a.w * b.y + a.z * b.x - a.x * b.z;\n quat.z = a.z * b.w + a.w * b.z + a.x * b.y - a.y * b.x;\n quat.w = a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z;\n return quat;\n}\nvoid rotateVecFromQuat (inout vec3 v, vec4 q){\n float ix = q.w * v.x + q.y * v.z - q.z * v.y;\n float iy = q.w * v.y + q.z * v.x - q.x * v.z;\n float iz = q.w * v.z + q.x * v.y - q.y * v.x;\n float iw = -q.x * v.x - q.y * v.y - q.z * v.z;\n v.x = ix * q.w + iw * -q.x + iy * -q.z - iz * -q.y;\n v.y = iy * q.w + iw * -q.y + iz * -q.x - ix * -q.z;\n v.z = iz * q.w + iw * -q.z + ix * -q.y - iy * -q.x;\n}\nvec3 rotateVecFromAxis (vec3 v, vec3 axis, float theta){\n return cos(theta) * v + sin(theta) * cross(v, axis) + (1. - cos(theta)) * dot(v, axis) * axis;\n}\nvec3 rotateInLocalSpace (vec3 pos, vec3 xAxis, vec3 yAxis, vec3 zAxis, vec4 q){\n vec4 viewQuat = quaternionFromAxis(xAxis, yAxis, zAxis);\n vec4 rotQuat = quatMultiply(viewQuat, q);\n rotateVecFromQuat(pos, rotQuat);\n return pos;\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}\nuniform Constants {\n vec4 mainTiling_Offset;\n vec4 frameTile_velLenScale;\n vec4 scale;\n};\nuniform CCGlobal {\n vec4 cc_time;\n vec4 cc_screenSize;\n vec4 cc_screenScale;\n vec4 cc_nativeSize;\n highp mat4 cc_matView;\n mat4 cc_matViewInv;\n mat4 cc_matProj;\n mat4 cc_matProjInv;\n mat4 cc_matViewProj;\n mat4 cc_matViewProjInv;\n vec4 cc_cameraPos;\n vec4 cc_exposure;\n vec4 cc_mainLitDir;\n vec4 cc_mainLitColor;\n vec4 cc_ambientSky;\n vec4 cc_ambientGround;\n};\nuniform CCLocal {\n highp mat4 cc_matWorld;\n highp mat4 cc_matWorldIT;\n};\nout vec2 uv;\nout vec4 color;\nvoid computeVertPos (inout vec4 pos, vec2 vertOffset, vec4 q, vec3 s\n#if CC_USE_BILLBOARD || CC_USE_VERTICAL_BILLBOARD\n , mat4 viewInv\n#endif\n#if CC_USE_STRETCHED_BILLBOARD\n , vec3 eye\n , vec4 velocity\n , float velocityScale\n , float lengthScale\n , float xIndex\n#endif\n) {\n#if CC_USE_BILLBOARD\n vec3 viewSpaceVert = vec3(vertOffset.x * s.x, vertOffset.y * s.y, 0.);\n vec3 camX = normalize(vec3(viewInv[0][0], viewInv[1][0], viewInv[2][0]));\n vec3 camY = normalize(vec3(viewInv[0][1], viewInv[1][1], viewInv[2][1]));\n vec3 camZ = normalize(vec3(viewInv[0][2], viewInv[1][2], viewInv[2][2]));\n pos.xyz += rotateInLocalSpace(viewSpaceVert, camX, camY, camZ, q);\n#elif CC_USE_STRETCHED_BILLBOARD\n vec3 camRight = normalize(cross(pos.xyz - eye, velocity.xyz)) * s.x;\n vec3 camUp = velocity.xyz * velocityScale + normalize(velocity.xyz) * lengthScale * s.y;\n pos.xyz += (camRight * abs(vertOffset.x) * sign(vertOffset.y)) - camUp * xIndex;\n#elif CC_USE_HORIZONTAL_BILLBOARD\n vec3 viewSpaceVert = vec3(vertOffset.x * s.x, vertOffset.y * s.y, 0.);\n vec3 camX = vec3(1, 0, 0);\n vec3 camY = vec3(0, 0, -1);\n pos.xyz += rotateInLocalSpace(viewSpaceVert, camX, camY, cross(camX, camY), q);\n#elif CC_USE_VERTICAL_BILLBOARD\n vec2 viewSpaceVert = vec2(vertOffset.x * s.x, vertOffset.y * s.y);\n rotateCorner(viewSpaceVert, q.z);\n vec3 camX = normalize(vec3(cc_matView[0][0], cc_matView[1][0], cc_matView[2][0]));\n vec3 camY = vec3(0, 1, 0);\n vec3 offset = camX * viewSpaceVert.x + camY * viewSpaceVert.y;\n pos.xyz += offset;\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#if !CC_USE_MESH\n vertIndex.y = 1. - vertIndex.y;\n#endif\n return (aniUV.xy + vertIndex) / vec2(frameTile.x, frameTile.y);\n}\nin vec3 a_position;\nin vec3 a_texCoord;\nin vec3 a_texCoord1;\nin vec3 a_texCoord2;\nin vec4 a_color;\n#if CC_USE_MESH\n in vec3 a_texCoord3;\n in vec3 a_normal;\n in vec4 a_color1;\n#elif CC_USE_STRETCHED_BILLBOARD\n in vec3 a_color1;\n#endif\nvec4 lpvs_main () {\n vec3 compScale = scale.xyz * a_texCoord1;\n vec4 pos = vec4(a_position, 1);\n #if CC_USE_STRETCHED_BILLBOARD\n vec4 velocity = vec4(a_color1.xyz, 0);\n #endif\n #if !CC_USE_WORLD_SPACE\n pos = cc_matWorld * pos;\n #if CC_USE_STRETCHED_BILLBOARD\n velocity = cc_matWorld * velocity;\n #endif\n #endif\n #if !CC_USE_MESH\n vec2 cornerOffset = vec2((a_texCoord.xy - 0.5));\n #if CC_USE_BILLBOARD\n vec3 rotEuler = a_texCoord2;\n #elif CC_USE_STRETCHED_BILLBOARD\n vec3 rotEuler = vec3(0.);\n #else\n vec3 rotEuler = vec3(0., 0., a_texCoord2.z);\n #endif\n computeVertPos(pos, cornerOffset, quaternionFromEuler(rotEuler), compScale\n #if CC_USE_BILLBOARD || CC_USE_VERTICAL_BILLBOARD\n , cc_matViewInv\n #endif\n #if CC_USE_STRETCHED_BILLBOARD\n , cc_cameraPos.xyz\n , velocity\n , frameTile_velLenScale.z\n , frameTile_velLenScale.w\n , a_texCoord.x\n #endif\n );\n color = a_color;\n #else\n mat4 xformNoScale = matrixFromRT(quaternionFromEuler(a_texCoord2), pos.xyz);\n mat4 xform = matFromRTS(quaternionFromEuler(a_texCoord2), pos.xyz, compScale);\n pos = xform * vec4(a_texCoord3, 1);\n vec4 normal = xformNoScale * vec4(a_normal, 0);\n color = a_color * a_color1;\n #endif\n uv = computeUV(a_texCoord.z, a_texCoord.xy, frameTile_velLenScale.xy) * mainTiling_Offset.xy + mainTiling_Offset.zw;\n pos = cc_matViewProj * pos;\n return pos;\n}\nvoid main() { gl_Position = lpvs_main(); }`, - "frag": `\nprecision highp float;\nuniform CCGlobal {\n vec4 cc_time;\n vec4 cc_screenSize;\n vec4 cc_screenScale;\n vec4 cc_nativeSize;\n highp mat4 cc_matView;\n mat4 cc_matViewInv;\n mat4 cc_matProj;\n mat4 cc_matProjInv;\n mat4 cc_matViewProj;\n mat4 cc_matViewProjInv;\n vec4 cc_cameraPos;\n vec4 cc_exposure;\n vec4 cc_mainLitDir;\n vec4 cc_mainLitColor;\n vec4 cc_ambientSky;\n vec4 cc_ambientGround;\n};\nvec3 SRGBToLinear (vec3 gamma) {\n return gamma * gamma;\n}\nvec4 CCFragOutput (vec4 color) {\n #if CC_USE_HDR\n color.rgb = mix(color.rgb, SRGBToLinear(color.rgb) * cc_exposure.w, vec3(cc_exposure.z));\n #endif\n return color;\n}\nin vec2 uv;\nin vec4 color;\nuniform sampler2D mainTexture;\nuniform FragConstants {\n vec4 tintColor;\n};\nvec4 add () {\n vec4 col = 2.0 * color * tintColor * texture(mainTexture, uv);\n return CCFragOutput(col);\n}\nvec4 multiply () {\n vec4 col;\n vec4 texColor = texture(mainTexture, uv);\n col.rgb = tintColor.rgb * texColor.rgb * color.rgb * vec3(2.0);\n col.a = (1.0 - texColor.a) * (tintColor.a * color.a * 2.0);\n return CCFragOutput(col);\n}\nout vec4 cc_FragColor;\nvoid main() { cc_FragColor = add(); }` + "vert": `\nprecision highp float;\nvec4 quaternionFromAxis (vec3 xAxis,vec3 yAxis,vec3 zAxis){\n mat3 m = mat3(xAxis,yAxis,zAxis);\n float trace = m[0][0] + m[1][1] + m[2][2];\n vec4 quat;\n if (trace > 0.) {\n float s = 0.5 / sqrt(trace + 1.0);\n quat.w = 0.25 / s;\n quat.x = (m[2][1] - m[1][2]) * s;\n quat.y = (m[0][2] - m[2][0]) * s;\n quat.z = (m[1][0] - m[0][1]) * s;\n } else if ((m[0][0] > m[1][1]) && (m[0][0] > m[2][2])) {\n float s = 2.0 * sqrt(1.0 + m[0][0] - m[1][1] - m[2][2]);\n quat.w = (m[2][1] - m[1][2]) / s;\n quat.x = 0.25 * s;\n quat.y = (m[0][1] + m[1][0]) / s;\n quat.z = (m[0][2] + m[2][0]) / s;\n } else if (m[1][1] > m[2][2]) {\n float s = 2.0 * sqrt(1.0 + m[1][1] - m[0][0] - m[2][2]);\n quat.w = (m[0][2] - m[2][0]) / s;\n quat.x = (m[0][1] + m[1][0]) / s;\n quat.y = 0.25 * s;\n quat.z = (m[1][2] + m[2][1]) / s;\n } else {\n float s = 2.0 * sqrt(1.0 + m[2][2] - m[0][0] - m[1][1]);\n quat.w = (m[1][0] - m[0][1]) / s;\n quat.x = (m[0][2] + m[2][0]) / s;\n quat.y = (m[1][2] + m[2][1]) / s;\n quat.z = 0.25 * s;\n }\n float len = quat.x * quat.x + quat.y * quat.y + quat.z * quat.z + quat.w * quat.w;\n if (len > 0.) {\n len = 1. / sqrt(len);\n quat.x = quat.x * len;\n quat.y = quat.y * len;\n quat.z = quat.z * len;\n quat.w = quat.w * len;\n }\n return quat;\n}\nvec4 quaternionFromEuler (vec3 angle){\n float x = angle.x / 2.;\n float y = angle.y / 2.;\n float z = angle.z / 2.;\n float sx = sin(x);\n float cx = cos(x);\n float sy = sin(y);\n float cy = cos(y);\n float sz = sin(z);\n float cz = cos(z);\n vec4 quat = vec4(0);\n quat.x = sx * cy * cz + cx * sy * sz;\n quat.y = cx * sy * cz + sx * cy * sz;\n quat.z = cx * cy * sz - sx * sy * cz;\n quat.w = cx * cy * cz - sx * sy * sz;\n return quat;\n}\nmat4 matrixFromRT (vec4 q, vec3 p){\n float x2 = q.x + q.x;\n float y2 = q.y + q.y;\n float z2 = q.z + q.z;\n float xx = q.x * x2;\n float xy = q.x * y2;\n float xz = q.x * z2;\n float yy = q.y * y2;\n float yz = q.y * z2;\n float zz = q.z * z2;\n float wx = q.w * x2;\n float wy = q.w * y2;\n float wz = q.w * z2;\n return mat4(\n 1. - (yy + zz), xy + wz, xz - wy, 0,\n xy - wz, 1. - (xx + zz), yz + wx, 0,\n xz + wy, yz - wx, 1. - (xx + yy), 0,\n p.x, p.y, p.z, 1\n );\n}\nmat4 matFromRTS (vec4 q, vec3 t, vec3 s){\n float x = q.x, y = q.y, z = q.z, w = q.w;\n float x2 = x + x;\n float y2 = y + y;\n float z2 = z + z;\n float xx = x * x2;\n float xy = x * y2;\n float xz = x * z2;\n float yy = y * y2;\n float yz = y * z2;\n float zz = z * z2;\n float wx = w * x2;\n float wy = w * y2;\n float wz = w * z2;\n float sx = s.x;\n float sy = s.y;\n float sz = s.z;\n return mat4((1. - (yy + zz)) * sx, (xy + wz) * sx, (xz - wy) * sx, 0,\n (xy - wz) * sy, (1. - (xx + zz)) * sy, (yz + wx) * sy, 0,\n (xz + wy) * sz, (yz - wx) * sz, (1. - (xx + yy)) * sz, 0,\n t.x, t.y, t.z, 1);\n}\nvec4 quatMultiply (vec4 a, vec4 b){\n vec4 quat;\n quat.x = a.x * b.w + a.w * b.x + a.y * b.z - a.z * b.y;\n quat.y = a.y * b.w + a.w * b.y + a.z * b.x - a.x * b.z;\n quat.z = a.z * b.w + a.w * b.z + a.x * b.y - a.y * b.x;\n quat.w = a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z;\n return quat;\n}\nvoid rotateVecFromQuat (inout vec3 v, vec4 q){\n float ix = q.w * v.x + q.y * v.z - q.z * v.y;\n float iy = q.w * v.y + q.z * v.x - q.x * v.z;\n float iz = q.w * v.z + q.x * v.y - q.y * v.x;\n float iw = -q.x * v.x - q.y * v.y - q.z * v.z;\n v.x = ix * q.w + iw * -q.x + iy * -q.z - iz * -q.y;\n v.y = iy * q.w + iw * -q.y + iz * -q.x - ix * -q.z;\n v.z = iz * q.w + iw * -q.z + ix * -q.y - iy * -q.x;\n}\nvec3 rotateInLocalSpace (vec3 pos, vec3 xAxis, vec3 yAxis, vec3 zAxis, vec4 q){\n vec4 viewQuat = quaternionFromAxis(xAxis, yAxis, zAxis);\n vec4 rotQuat = quatMultiply(viewQuat, q);\n rotateVecFromQuat(pos, rotQuat);\n return pos;\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}\nuniform Constants {\n vec4 mainTiling_Offset;\n vec4 frameTile_velLenScale;\n vec4 scale;\n};\nuniform CCGlobal {\n vec4 cc_time;\n vec4 cc_screenSize;\n vec4 cc_screenScale;\n vec4 cc_nativeSize;\n highp mat4 cc_matView;\n mat4 cc_matViewInv;\n mat4 cc_matProj;\n mat4 cc_matProjInv;\n mat4 cc_matViewProj;\n mat4 cc_matViewProjInv;\n vec4 cc_cameraPos;\n vec4 cc_exposure;\n vec4 cc_mainLitDir;\n vec4 cc_mainLitColor;\n vec4 cc_ambientSky;\n vec4 cc_ambientGround;\n};\nuniform CCLocal {\n highp mat4 cc_matWorld;\n highp mat4 cc_matWorldIT;\n};\nout vec2 uv;\nout vec4 color;\nvoid computeVertPos (inout vec4 pos, vec2 vertOffset, vec4 q, vec3 s\n#if CC_USE_BILLBOARD || CC_USE_VERTICAL_BILLBOARD\n , mat4 viewInv\n#endif\n#if CC_USE_STRETCHED_BILLBOARD\n , vec3 eye\n , vec4 velocity\n , float velocityScale\n , float lengthScale\n , float xIndex\n#endif\n) {\n#if CC_USE_BILLBOARD\n vec3 viewSpaceVert = vec3(vertOffset.x * s.x, vertOffset.y * s.y, 0.);\n vec3 camX = normalize(vec3(viewInv[0][0], viewInv[1][0], viewInv[2][0]));\n vec3 camY = normalize(vec3(viewInv[0][1], viewInv[1][1], viewInv[2][1]));\n vec3 camZ = normalize(vec3(viewInv[0][2], viewInv[1][2], viewInv[2][2]));\n pos.xyz += rotateInLocalSpace(viewSpaceVert, camX, camY, camZ, q);\n#elif CC_USE_STRETCHED_BILLBOARD\n vec3 camRight = normalize(cross(pos.xyz - eye, velocity.xyz)) * s.x;\n vec3 camUp = velocity.xyz * velocityScale + normalize(velocity.xyz) * lengthScale * s.y;\n pos.xyz += (camRight * abs(vertOffset.x) * sign(vertOffset.y)) - camUp * xIndex;\n#elif CC_USE_HORIZONTAL_BILLBOARD\n vec3 viewSpaceVert = vec3(vertOffset.x * s.x, vertOffset.y * s.y, 0.);\n vec3 camX = vec3(1, 0, 0);\n vec3 camY = vec3(0, 0, -1);\n pos.xyz += rotateInLocalSpace(viewSpaceVert, camX, camY, cross(camX, camY), q);\n#elif CC_USE_VERTICAL_BILLBOARD\n vec2 viewSpaceVert = vec2(vertOffset.x * s.x, vertOffset.y * s.y);\n rotateCorner(viewSpaceVert, q.z);\n vec3 camX = normalize(vec3(cc_matView[0][0], cc_matView[1][0], cc_matView[2][0]));\n vec3 camY = vec3(0, 1, 0);\n vec3 offset = camX * viewSpaceVert.x + camY * viewSpaceVert.y;\n pos.xyz += offset;\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#if !CC_USE_MESH\n vertIndex.y = 1. - vertIndex.y;\n#endif\n return (aniUV.xy + vertIndex) / vec2(frameTile.x, frameTile.y);\n}\nin vec3 a_position;\nin vec3 a_texCoord;\nin vec3 a_texCoord1;\nin vec3 a_texCoord2;\nin vec4 a_color;\n#if CC_USE_MESH\n in vec3 a_texCoord3;\n in vec3 a_normal;\n in vec4 a_color1;\n#elif CC_USE_STRETCHED_BILLBOARD\n in vec3 a_color1;\n#endif\nvec4 lpvs_main () {\n vec3 compScale = scale.xyz * a_texCoord1;\n vec4 pos = vec4(a_position, 1);\n #if CC_USE_STRETCHED_BILLBOARD\n vec4 velocity = vec4(a_color1.xyz, 0);\n #endif\n #if !CC_USE_WORLD_SPACE\n pos = cc_matWorld * pos;\n #if CC_USE_STRETCHED_BILLBOARD\n velocity = cc_matWorld * velocity;\n #endif\n #endif\n #if !CC_USE_MESH\n vec2 cornerOffset = vec2((a_texCoord.xy - 0.5));\n #if CC_USE_BILLBOARD\n vec3 rotEuler = a_texCoord2;\n #elif CC_USE_STRETCHED_BILLBOARD\n vec3 rotEuler = vec3(0.);\n #else\n vec3 rotEuler = vec3(0., 0., a_texCoord2.z);\n #endif\n computeVertPos(pos, cornerOffset, quaternionFromEuler(rotEuler), compScale\n #if CC_USE_BILLBOARD || CC_USE_VERTICAL_BILLBOARD\n , cc_matViewInv\n #endif\n #if CC_USE_STRETCHED_BILLBOARD\n , cc_cameraPos.xyz\n , velocity\n , frameTile_velLenScale.z\n , frameTile_velLenScale.w\n , a_texCoord.x\n #endif\n );\n color = a_color;\n #else\n mat4 xformNoScale = matrixFromRT(quaternionFromEuler(a_texCoord2), pos.xyz);\n mat4 xform = matFromRTS(quaternionFromEuler(a_texCoord2), pos.xyz, compScale);\n pos = xform * vec4(a_texCoord3, 1);\n vec4 normal = xformNoScale * vec4(a_normal, 0);\n color = a_color * a_color1;\n #endif\n uv = computeUV(a_texCoord.z, a_texCoord.xy, frameTile_velLenScale.xy) * mainTiling_Offset.xy + mainTiling_Offset.zw;\n pos = cc_matViewProj * pos;\n return pos;\n}\nvoid main() { gl_Position = lpvs_main(); }`, + "frag": `\nprecision highp float;\nuniform CCGlobal {\n vec4 cc_time;\n vec4 cc_screenSize;\n vec4 cc_screenScale;\n vec4 cc_nativeSize;\n highp mat4 cc_matView;\n mat4 cc_matViewInv;\n mat4 cc_matProj;\n mat4 cc_matProjInv;\n mat4 cc_matViewProj;\n mat4 cc_matViewProjInv;\n vec4 cc_cameraPos;\n vec4 cc_exposure;\n vec4 cc_mainLitDir;\n vec4 cc_mainLitColor;\n vec4 cc_ambientSky;\n vec4 cc_ambientGround;\n};\nvec3 SRGBToLinear (vec3 gamma) {\n return gamma * gamma;\n}\nvec4 CCFragOutput (vec4 color) {\n #if CC_USE_HDR\n color.rgb = mix(color.rgb, SRGBToLinear(color.rgb) * cc_exposure.w, vec3(cc_exposure.z));\n #endif\n return color;\n}\nin vec2 uv;\nin vec4 color;\nuniform sampler2D mainTexture;\nuniform FragConstants {\n vec4 tintColor;\n};\nvec4 add () {\n vec4 col = 2.0 * color * tintColor * texture(mainTexture, uv);\n return CCFragOutput(col);\n}\nout vec4 cc_FragColor;\nvoid main() { cc_FragColor = add(); }` }, "glsl1": { "vert": `\nprecision highp float;\nvec4 quaternionFromAxis (vec3 xAxis,vec3 yAxis,vec3 zAxis){\n mat3 m = mat3(xAxis,yAxis,zAxis);\n float trace = m[0][0] + m[1][1] + m[2][2];\n vec4 quat;\n if (trace > 0.) {\n float s = 0.5 / sqrt(trace + 1.0);\n quat.w = 0.25 / s;\n quat.x = (m[2][1] - m[1][2]) * s;\n quat.y = (m[0][2] - m[2][0]) * s;\n quat.z = (m[1][0] - m[0][1]) * s;\n } else if ((m[0][0] > m[1][1]) && (m[0][0] > m[2][2])) {\n float s = 2.0 * sqrt(1.0 + m[0][0] - m[1][1] - m[2][2]);\n quat.w = (m[2][1] - m[1][2]) / s;\n quat.x = 0.25 * s;\n quat.y = (m[0][1] + m[1][0]) / s;\n quat.z = (m[0][2] + m[2][0]) / s;\n } else if (m[1][1] > m[2][2]) {\n float s = 2.0 * sqrt(1.0 + m[1][1] - m[0][0] - m[2][2]);\n quat.w = (m[0][2] - m[2][0]) / s;\n quat.x = (m[0][1] + m[1][0]) / s;\n quat.y = 0.25 * s;\n quat.z = (m[1][2] + m[2][1]) / s;\n } else {\n float s = 2.0 * sqrt(1.0 + m[2][2] - m[0][0] - m[1][1]);\n quat.w = (m[1][0] - m[0][1]) / s;\n quat.x = (m[0][2] + m[2][0]) / s;\n quat.y = (m[1][2] + m[2][1]) / s;\n quat.z = 0.25 * s;\n }\n float len = quat.x * quat.x + quat.y * quat.y + quat.z * quat.z + quat.w * quat.w;\n if (len > 0.) {\n len = 1. / sqrt(len);\n quat.x = quat.x * len;\n quat.y = quat.y * len;\n quat.z = quat.z * len;\n quat.w = quat.w * len;\n }\n return quat;\n}\nvec4 quaternionFromEuler (vec3 angle){\n float x = angle.x / 2.;\n float y = angle.y / 2.;\n float z = angle.z / 2.;\n float sx = sin(x);\n float cx = cos(x);\n float sy = sin(y);\n float cy = cos(y);\n float sz = sin(z);\n float cz = cos(z);\n vec4 quat = vec4(0);\n quat.x = sx * cy * cz + cx * sy * sz;\n quat.y = cx * sy * cz + sx * cy * sz;\n quat.z = cx * cy * sz - sx * sy * cz;\n quat.w = cx * cy * cz - sx * sy * sz;\n return quat;\n}\nmat4 matrixFromRT (vec4 q, vec3 p){\n float x2 = q.x + q.x;\n float y2 = q.y + q.y;\n float z2 = q.z + q.z;\n float xx = q.x * x2;\n float xy = q.x * y2;\n float xz = q.x * z2;\n float yy = q.y * y2;\n float yz = q.y * z2;\n float zz = q.z * z2;\n float wx = q.w * x2;\n float wy = q.w * y2;\n float wz = q.w * z2;\n return mat4(\n 1. - (yy + zz), xy + wz, xz - wy, 0,\n xy - wz, 1. - (xx + zz), yz + wx, 0,\n xz + wy, yz - wx, 1. - (xx + yy), 0,\n p.x, p.y, p.z, 1\n );\n}\nmat4 matFromRTS (vec4 q, vec3 t, vec3 s){\n float x = q.x, y = q.y, z = q.z, w = q.w;\n float x2 = x + x;\n float y2 = y + y;\n float z2 = z + z;\n float xx = x * x2;\n float xy = x * y2;\n float xz = x * z2;\n float yy = y * y2;\n float yz = y * z2;\n float zz = z * z2;\n float wx = w * x2;\n float wy = w * y2;\n float wz = w * z2;\n float sx = s.x;\n float sy = s.y;\n float sz = s.z;\n return mat4((1. - (yy + zz)) * sx, (xy + wz) * sx, (xz - wy) * sx, 0,\n (xy - wz) * sy, (1. - (xx + zz)) * sy, (yz + wx) * sy, 0,\n (xz + wy) * sz, (yz - wx) * sz, (1. - (xx + yy)) * sz, 0,\n t.x, t.y, t.z, 1);\n}\nvec4 quatMultiply (vec4 a, vec4 b){\n vec4 quat;\n quat.x = a.x * b.w + a.w * b.x + a.y * b.z - a.z * b.y;\n quat.y = a.y * b.w + a.w * b.y + a.z * b.x - a.x * b.z;\n quat.z = a.z * b.w + a.w * b.z + a.x * b.y - a.y * b.x;\n quat.w = a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z;\n return quat;\n}\nvoid rotateVecFromQuat (inout vec3 v, vec4 q){\n float ix = q.w * v.x + q.y * v.z - q.z * v.y;\n float iy = q.w * v.y + q.z * v.x - q.x * v.z;\n float iz = q.w * v.z + q.x * v.y - q.y * v.x;\n float iw = -q.x * v.x - q.y * v.y - q.z * v.z;\n v.x = ix * q.w + iw * -q.x + iy * -q.z - iz * -q.y;\n v.y = iy * q.w + iw * -q.y + iz * -q.x - ix * -q.z;\n v.z = iz * q.w + iw * -q.z + ix * -q.y - iy * -q.x;\n}\nvec3 rotateInLocalSpace (vec3 pos, vec3 xAxis, vec3 yAxis, vec3 zAxis, vec4 q){\n vec4 viewQuat = quaternionFromAxis(xAxis, yAxis, zAxis);\n vec4 rotQuat = quatMultiply(viewQuat, q);\n rotateVecFromQuat(pos, rotQuat);\n return pos;\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}\nuniform vec4 mainTiling_Offset;\nuniform vec4 frameTile_velLenScale;\nuniform vec4 scale;\nuniform highp mat4 cc_matView;\nuniform mat4 cc_matViewInv;\nuniform mat4 cc_matViewProj;\nuniform vec4 cc_cameraPos;\nuniform highp mat4 cc_matWorld;\nvarying vec2 uv;\nvarying vec4 color;\nvoid computeVertPos (inout vec4 pos, vec2 vertOffset, vec4 q, vec3 s\n#if CC_USE_BILLBOARD || CC_USE_VERTICAL_BILLBOARD\n , mat4 viewInv\n#endif\n#if CC_USE_STRETCHED_BILLBOARD\n , vec3 eye\n , vec4 velocity\n , float velocityScale\n , float lengthScale\n , float xIndex\n#endif\n) {\n#if CC_USE_BILLBOARD\n vec3 viewSpaceVert = vec3(vertOffset.x * s.x, vertOffset.y * s.y, 0.);\n vec3 camX = normalize(vec3(viewInv[0][0], viewInv[1][0], viewInv[2][0]));\n vec3 camY = normalize(vec3(viewInv[0][1], viewInv[1][1], viewInv[2][1]));\n vec3 camZ = normalize(vec3(viewInv[0][2], viewInv[1][2], viewInv[2][2]));\n pos.xyz += rotateInLocalSpace(viewSpaceVert, camX, camY, camZ, q);\n#elif CC_USE_STRETCHED_BILLBOARD\n vec3 camRight = normalize(cross(pos.xyz - eye, velocity.xyz)) * s.x;\n vec3 camUp = velocity.xyz * velocityScale + normalize(velocity.xyz) * lengthScale * s.y;\n pos.xyz += (camRight * abs(vertOffset.x) * sign(vertOffset.y)) - camUp * xIndex;\n#elif CC_USE_HORIZONTAL_BILLBOARD\n vec3 viewSpaceVert = vec3(vertOffset.x * s.x, vertOffset.y * s.y, 0.);\n vec3 camX = vec3(1, 0, 0);\n vec3 camY = vec3(0, 0, -1);\n pos.xyz += rotateInLocalSpace(viewSpaceVert, camX, camY, cross(camX, camY), q);\n#elif CC_USE_VERTICAL_BILLBOARD\n vec2 viewSpaceVert = vec2(vertOffset.x * s.x, vertOffset.y * s.y);\n rotateCorner(viewSpaceVert, q.z);\n vec3 camX = normalize(vec3(cc_matView[0][0], cc_matView[1][0], cc_matView[2][0]));\n vec3 camY = vec3(0, 1, 0);\n vec3 offset = camX * viewSpaceVert.x + camY * viewSpaceVert.y;\n pos.xyz += offset;\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#if !CC_USE_MESH\n vertIndex.y = 1. - vertIndex.y;\n#endif\n return (aniUV.xy + vertIndex) / vec2(frameTile.x, frameTile.y);\n}\nattribute vec3 a_position;\nattribute vec3 a_texCoord;\nattribute vec3 a_texCoord1;\nattribute vec3 a_texCoord2;\nattribute vec4 a_color;\n#if CC_USE_MESH\n attribute vec3 a_texCoord3;\n attribute vec3 a_normal;\n attribute vec4 a_color1;\n#elif CC_USE_STRETCHED_BILLBOARD\n attribute vec3 a_color1;\n#endif\nvec4 lpvs_main () {\n vec3 compScale = scale.xyz * a_texCoord1;\n vec4 pos = vec4(a_position, 1);\n #if CC_USE_STRETCHED_BILLBOARD\n vec4 velocity = vec4(a_color1.xyz, 0);\n #endif\n #if !CC_USE_WORLD_SPACE\n pos = cc_matWorld * pos;\n #if CC_USE_STRETCHED_BILLBOARD\n velocity = cc_matWorld * velocity;\n #endif\n #endif\n #if !CC_USE_MESH\n vec2 cornerOffset = vec2((a_texCoord.xy - 0.5));\n #if CC_USE_BILLBOARD\n vec3 rotEuler = a_texCoord2;\n #elif CC_USE_STRETCHED_BILLBOARD\n vec3 rotEuler = vec3(0.);\n #else\n vec3 rotEuler = vec3(0., 0., a_texCoord2.z);\n #endif\n computeVertPos(pos, cornerOffset, quaternionFromEuler(rotEuler), compScale\n #if CC_USE_BILLBOARD || CC_USE_VERTICAL_BILLBOARD\n , cc_matViewInv\n #endif\n #if CC_USE_STRETCHED_BILLBOARD\n , cc_cameraPos.xyz\n , velocity\n , frameTile_velLenScale.z\n , frameTile_velLenScale.w\n , a_texCoord.x\n #endif\n );\n color = a_color;\n #else\n mat4 xformNoScale = matrixFromRT(quaternionFromEuler(a_texCoord2), pos.xyz);\n mat4 xform = matFromRTS(quaternionFromEuler(a_texCoord2), pos.xyz, compScale);\n pos = xform * vec4(a_texCoord3, 1);\n vec4 normal = xformNoScale * vec4(a_normal, 0);\n color = a_color * a_color1;\n #endif\n uv = computeUV(a_texCoord.z, a_texCoord.xy, frameTile_velLenScale.xy) * mainTiling_Offset.xy + mainTiling_Offset.zw;\n pos = cc_matViewProj * pos;\n return pos;\n}\nvoid main() { gl_Position = lpvs_main(); }`, @@ -166,10 +161,10 @@ export default [ "shaders": [ { "name": "builtin-standard|standard-vs:vert|standard-fs:frag", - "hash": 339559055, + "hash": 2119024206, "glsl3": { "vert": `\nprecision highp float;\nuniform CCGlobal {\n vec4 cc_time;\n vec4 cc_screenSize;\n vec4 cc_screenScale;\n vec4 cc_nativeSize;\n highp mat4 cc_matView;\n mat4 cc_matViewInv;\n mat4 cc_matProj;\n mat4 cc_matProjInv;\n mat4 cc_matViewProj;\n mat4 cc_matViewProjInv;\n vec4 cc_cameraPos;\n vec4 cc_exposure;\n vec4 cc_mainLitDir;\n vec4 cc_mainLitColor;\n vec4 cc_ambientSky;\n vec4 cc_ambientGround;\n};\n#if CC_USE_BATCHING\n in float a_dyn_batch_id;\n uniform CCLocalBatched {\n highp mat4 cc_matWorlds[10];\n };\n#else\nuniform CCLocal {\n highp mat4 cc_matWorld;\n highp mat4 cc_matWorldIT;\n};\n#endif\nstruct StandardVertInput {\n highp vec4 position;\n vec3 normal;\n vec4 tangent;\n};\nin vec3 a_position;\nin vec3 a_normal;\nin vec4 a_tangent;\n#if CC_USE_SKINNING\nin vec4 a_weights;\nin vec4 a_joints;\nuniform CCSkinningTexture {\n highp vec4 cc_jointsTextureInfo;\n};\nuniform CCSkinningAnimation {\n highp vec4 cc_jointsAnimInfo;\n};\nuniform sampler2D cc_jointsTexture;\n#if CC_USE_SKINNING == 1\n highp float decode32 (highp vec4 rgba) {\n rgba = rgba * 255.0;\n highp float Sign = 1.0 - step(128.0, rgba[3]) * 2.0;\n highp float Exponent = 2.0 * mod(rgba[3], 128.0) + step(128.0, rgba[2]) - 127.0;\n highp float Mantissa = mod(rgba[2], 128.0) * 65536.0 + rgba[1] * 256.0 + rgba[0] + 8388608.0;\n return Sign * exp2(Exponent - 23.0) * Mantissa;\n }\n#endif\n#if CC_USE_SKINNING == 1\n mat4 getJointMatrix (float i) {\n highp float j = 12.0 * (cc_jointsAnimInfo.x * i + cc_jointsAnimInfo.y) + cc_jointsTextureInfo.z;\n highp float invSize = cc_jointsTextureInfo.y;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointsTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = vec4(\n decode32(texture(cc_jointsTexture, vec2((x + 0.5) * invSize, y))),\n decode32(texture(cc_jointsTexture, vec2((x + 1.5) * invSize, y))),\n decode32(texture(cc_jointsTexture, vec2((x + 2.5) * invSize, y))),\n decode32(texture(cc_jointsTexture, vec2((x + 3.5) * invSize, y)))\n );\n vec4 v2 = vec4(\n decode32(texture(cc_jointsTexture, vec2((x + 4.5) * invSize, y))),\n decode32(texture(cc_jointsTexture, vec2((x + 5.5) * invSize, y))),\n decode32(texture(cc_jointsTexture, vec2((x + 6.5) * invSize, y))),\n decode32(texture(cc_jointsTexture, vec2((x + 7.5) * invSize, y)))\n );\n vec4 v3 = vec4(\n decode32(texture(cc_jointsTexture, vec2((x + 8.5) * invSize, y))),\n decode32(texture(cc_jointsTexture, vec2((x + 9.5) * invSize, y))),\n decode32(texture(cc_jointsTexture, vec2((x + 10.5) * invSize, y))),\n decode32(texture(cc_jointsTexture, vec2((x + 11.5) * invSize, y)))\n );\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n#elif CC_USE_SKINNING == 2\n mat4 getJointMatrix (float i) {\n highp float j = 3.0 * (cc_jointsAnimInfo.x * i + cc_jointsAnimInfo.y) + cc_jointsTextureInfo.z;\n highp float invSize = cc_jointsTextureInfo.y;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointsTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = texture(cc_jointsTexture, vec2((x + 0.5) * invSize, y));\n vec4 v2 = texture(cc_jointsTexture, vec2((x + 1.5) * invSize, y));\n vec4 v3 = texture(cc_jointsTexture, vec2((x + 2.5) * invSize, y));\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n#endif\nmat4 skinMatrix () {\n return getJointMatrix(a_joints.x) * a_weights.x\n + getJointMatrix(a_joints.y) * a_weights.y;\n + getJointMatrix(a_joints.z) * a_weights.z;\n + getJointMatrix(a_joints.w) * a_weights.w;\n}\nvoid CCSkin (inout vec4 position) {\n mat4 m = skinMatrix();\n position = m * position;\n}\nvoid CCSkin (inout StandardVertInput attr) {\n mat4 m = skinMatrix();\n attr.position = m * attr.position;\n attr.normal = (m * vec4(attr.normal, 0.0)).xyz;\n attr.tangent.xyz = (m * vec4(attr.tangent.xyz, 0.0)).xyz;\n}\n#endif\nuniform Constants {\n vec4 tilingOffset;\n vec4 albedo;\n vec4 albedoScaleAndCutoff;\n vec4 pbrParams;\n vec4 emissive;\n vec4 emissiveScale;\n};\n#if USE_VERTEX_COLOR\n in vec3 a_color;\n out vec3 v_color;\n#endif\nout vec3 v_position;\nout vec3 v_normal;\n#if USE_NORMAL_MAP\n out vec3 v_tangent;\n out vec3 v_bitangent;\n#endif\nin vec2 a_texCoord;\nout vec2 v_uv;\nin vec2 a_texCoord1;\nout vec2 v_uv1;\nhighp vec4 vert () {\n StandardVertInput In;\n In.position = vec4(a_position, 1.0);\n In.normal = a_normal;\n In.tangent = a_tangent;\n #if CC_USE_SKINNING\n CCSkin(In);\n #endif\n highp mat4 matWorld, matWorldIT;\n #if CC_USE_BATCHING\n matWorld = cc_matWorlds[int(a_dyn_batch_id + 0.5)];\n matWorldIT = matWorld;\n #else\n matWorld = cc_matWorld;\n matWorldIT = cc_matWorldIT;\n #endif\n highp vec4 pos = matWorld * In.position;\n v_position = pos.xyz;\n v_normal = normalize((matWorldIT * vec4(In.normal, 0.0)).xyz);\n #if USE_NORMAL_MAP\n v_tangent = normalize((matWorldIT * vec4(In.tangent.xyz, 0.0)).xyz);\n v_bitangent = cross(v_normal, v_tangent) * In.tangent.w;\n #endif\n v_uv = a_texCoord * tilingOffset.xy + tilingOffset.zw;\n v_uv1 = a_texCoord1 * tilingOffset.xy + tilingOffset.zw;\n #if USE_VERTEX_COLOR\n v_color = a_color;\n #endif\n return cc_matProj * (cc_matView * matWorld) * In.position;\n}\nvoid main() { gl_Position = vert(); }`, - "frag": `\nprecision highp float;\nuniform CCGlobal {\n vec4 cc_time;\n vec4 cc_screenSize;\n vec4 cc_screenScale;\n vec4 cc_nativeSize;\n highp mat4 cc_matView;\n mat4 cc_matViewInv;\n mat4 cc_matProj;\n mat4 cc_matProjInv;\n mat4 cc_matViewProj;\n mat4 cc_matViewProjInv;\n vec4 cc_cameraPos;\n vec4 cc_exposure;\n vec4 cc_mainLitDir;\n vec4 cc_mainLitColor;\n vec4 cc_ambientSky;\n vec4 cc_ambientGround;\n};\n#if CC_USE_IBL\nuniform samplerCube cc_environment;\nvec3 unpackRGBE (vec4 rgbe) {\n return rgbe.rgb * pow(2.0, rgbe.a * 255.0 - 128.0);\n}\n#endif\nvec3 SRGBToLinear (vec3 gamma) {\n return gamma * gamma;\n}\nuniform CCForwardLight {\n highp vec4 cc_sphereLitPos[2];\n vec4 cc_sphereLitSizeRange[2];\n vec4 cc_sphereLitColor[2];\n highp vec4 cc_spotLitPos[2];\n vec4 cc_spotLitSizeRangeAngle[2];\n vec4 cc_spotLitDir[2];\n vec4 cc_spotLitColor[2];\n};\nfloat SmoothDistAtt2 (float distSqr, float invSqrAttRadius) {\n float factor = distSqr * invSqrAttRadius;\n float factor2 = factor * factor;\n float factor3 = factor2 * factor2;\n float smoothFactor = clamp(1.0 - factor3 * factor3, 0.0, 1.0);\n return smoothFactor * smoothFactor;\n}\nfloat SmoothDistAtt (float distSqr, float invSqrAttRadius) {\n float factor = distSqr * invSqrAttRadius;\n float smoothFactor = clamp(1.0 - factor * factor, 0.0, 1.0);\n return smoothFactor * smoothFactor;\n}\nfloat GetDistAtt (float distSqr, float invSqrAttRadius) {\n float attenuation = 1.0 / max(distSqr, 0.01*0.01);\n attenuation *= SmoothDistAtt(distSqr , invSqrAttRadius);\n return attenuation;\n}\nfloat GetAngleAtt (vec3 L, vec3 litDir, float litAngleScale, float litAngleOffset) {\n float cd = dot(litDir, L);\n float attenuation = clamp(cd * litAngleScale + litAngleOffset, 0.0, 1.0);\n return (attenuation * attenuation);\n}\nfloat GGXMobile (float roughness, float NoH, vec3 H, vec3 N) {\n vec3 NxH = cross(N, H);\n float OneMinusNoHSqr = dot(NxH, NxH);\n float a = roughness * roughness;\n float n = NoH * a;\n float p = a / (OneMinusNoHSqr + n * n);\n return p * p;\n}\nfloat CalcSpecular (float roughness, float NoH, vec3 H, vec3 N) {\n return (roughness*0.25 + 0.25) * GGXMobile(roughness, NoH, H, N);\n}\nvec3 BRDFApprox (vec3 specular, float roughness, float NoV) {\n const vec4 c0 = vec4(-1.0, -0.0275, -0.572, 0.022);\n const vec4 c1 = vec4(1.0, 0.0425, 1.04, -0.04);\n vec4 r = roughness * c0 + c1;\n float a004 = min( r.x * r.x, exp2( -9.28 * NoV ) ) * r.x + r.y;\n vec2 AB = vec2( -1.04, 1.04 ) * a004 + r.zw;\n AB.y *= clamp(50.0 * specular.g, 0.0, 1.0);\n return specular * AB.x + AB.y;\n}\nvec3 CalcDynamicLighting (vec3 worldPos, vec3 N, vec3 V, vec3 diffuse, vec3 specular, float roughness) {\n vec3 lighting = vec3(0.0);\n vec3 diffuseContrib = diffuse / 3.14159265359;\n for (int i = 0; i < 2; i++) {\n vec3 PLU = cc_sphereLitPos[i].xyz - worldPos;\n vec3 PL = normalize(PLU);\n vec3 PH = normalize(PL + V);\n float PNL = max(dot(N, PL), 0.001);\n float PNH = max(dot(N, PH), 0.0);\n float distSqr = dot(PLU, PLU);\n float litRadius = cc_sphereLitSizeRange[i].x;\n float litRadiusSqr = litRadius * litRadius;\n float illum = 3.14159265359 * (litRadiusSqr / max(litRadiusSqr , distSqr));\n float attRadiusSqrInv = 1.0 / max(cc_sphereLitSizeRange[i].y, 0.01);\n attRadiusSqrInv *= attRadiusSqrInv;\n float att = GetDistAtt(distSqr, attRadiusSqrInv);\n vec3 lspec = specular * CalcSpecular(roughness, PNH, PH, N);\n lighting += PNL * cc_sphereLitColor[i].rgb * cc_sphereLitColor[i].w * illum * att * (diffuseContrib + lspec);\n }\n for (int i = 0; i < 2; i++) {\n vec3 SLU = cc_spotLitPos[i].xyz - worldPos;\n vec3 SL = normalize(SLU);\n vec3 SH = normalize(SL + V);\n float SNL = max(dot(N, SL), 0.001);\n float SNH = max(dot(N, SH), 0.0);\n float distSqr = dot(SLU, SLU);\n float litRadius = cc_spotLitSizeRangeAngle[i].x;\n float litRadiusSqr = litRadius * litRadius;\n float illum = 3.14159265359 * (litRadiusSqr / max(litRadiusSqr , distSqr));\n float attRadiusSqrInv = 1.0 / max(cc_spotLitSizeRangeAngle[i].y, 0.01);\n attRadiusSqrInv *= attRadiusSqrInv;\n float cosInner = max(dot(-cc_spotLitDir[i].xyz, SL), 0.01);\n float cosOuter = cc_spotLitSizeRangeAngle[i].z;\n float litAngleScale = 1.0 / max(0.001, cosInner - cosOuter);\n float litAngleOffset = -cosOuter * litAngleScale;\n float att = GetDistAtt(distSqr, attRadiusSqrInv);\n att *= GetAngleAtt(SL, -cc_spotLitDir[i].xyz, litAngleScale, litAngleOffset);\n vec3 lspec = specular * CalcSpecular(roughness, SNH, SH, N);\n lighting += SNL * cc_spotLitColor[i].rgb * cc_spotLitColor[i].w * illum * att * (diffuseContrib + lspec);\n }\n return lighting;\n}\nstruct StandardSurface {\n vec4 albedo;\n vec3 position;\n vec3 normal;\n vec3 emissive;\n float roughness;\n float metallic;\n float occlusion;\n};\nvec4 CCStandardShading (StandardSurface s) {\n vec3 diffuse = s.albedo.rgb * (1.0 - s.metallic);\n vec3 specular = mix(vec3(0.04), s.albedo.rgb, s.metallic);\n vec3 N = normalize(s.normal);\n vec3 V = normalize(cc_cameraPos.xyz - s.position);\n vec3 L = normalize(-cc_mainLitDir.xyz);\n vec3 H = normalize(L+V);\n float NV = max(abs(dot(N, V)), 0.001);\n float NL = max(dot(N, L), 0.001);\n float NH = max(dot(N, H), 0.0);\n specular = BRDFApprox(specular, s.roughness, NV);\n vec3 diffuseContrib = diffuse / 3.14159265359;\n vec3 specularContrib = specular * CalcSpecular(s.roughness, NH, H, N);\n vec3 finalColor = NL * cc_mainLitColor.rgb * cc_mainLitColor.w * (diffuseContrib + specularContrib);\n finalColor += CalcDynamicLighting(s.position, N, V, diffuse, specular, s.roughness);\n float fAmb = 0.5 - N.y * 0.5;\n vec3 ambDiff = mix(cc_ambientSky.rgb, cc_ambientGround.rgb, fAmb) * cc_ambientSky.w;\n finalColor += (ambDiff.rgb * diffuse);\n #if CC_USE_IBL\n vec3 R = normalize(reflect(-V, N));\n vec4 envmap = textureLod(cc_environment, R, s.roughness * cc_ambientGround.w);\n #if CC_USE_IBL == 2\n vec3 env = unpackRGBE(envmap);\n #else\n vec3 env = SRGBToLinear(envmap.rgb) * cc_ambientSky.w;\n #endif\n finalColor += env * specular;\n #endif\n finalColor = finalColor * s.occlusion;\n #if CC_USE_HDR\n s.emissive *= cc_exposure.w;\n #endif\n finalColor += s.emissive;\n return vec4(finalColor, s.albedo.a);\n}\nvec3 ACESToneMap (vec3 color) {\n const float A = 2.51;\n const float B = 0.03;\n const float C = 2.43;\n const float D = 0.59;\n const float E = 0.14;\n return (color * (A * color + B)) / (color * (C * color + D) + E);\n}\nvec4 CCFragOutput (vec4 color) {\n #if !CC_USE_HDR\n color.rgb = sqrt(ACESToneMap(color.rgb));\n #endif\n return color;\n}\nuniform Constants {\n vec4 tilingOffset;\n vec4 albedo;\n vec4 albedoScaleAndCutoff;\n vec4 pbrParams;\n vec4 emissive;\n vec4 emissiveScale;\n};\nin vec3 v_position;\nin vec2 v_uv;\nin vec2 v_uv1;\nin vec3 v_normal;\n#if USE_VERTEX_COLOR\n in vec3 v_color;\n#endif\n#if USE_ALBEDO_MAP\n uniform sampler2D albedoMap;\n#endif\n#if USE_NORMAL_MAP\n in vec3 v_tangent;\n in vec3 v_bitangent;\n uniform sampler2D normalMap;\n#endif\n#if USE_PBR_MAP\n uniform sampler2D pbrMap;\n#endif\n#if USE_METALLIC_ROUGHNESS_MAP\n uniform sampler2D metallicRoughnessMap;\n#endif\n#if USE_OCCLUSION_MAP\n uniform sampler2D occlusionMap;\n#endif\n#if USE_EMISSIVE_MAP\n uniform sampler2D emissiveMap;\n#endif\n#if USE_ALPHA_TEST\n#endif\nvoid surf (out StandardSurface s) {\n vec4 baseColor = albedo;\n #if USE_VERTEX_COLOR\n baseColor.rgb *= v_color;\n #endif\n #if USE_ALBEDO_MAP\n vec4 texColor = texture(albedoMap, ALBEDO_UV);\n texColor.rgb = SRGBToLinear(texColor.rgb);\n baseColor *= texColor;\n #endif\n s.albedo = baseColor;\n s.albedo.rgb *= albedoScaleAndCutoff.xyz;\n #if USE_ALPHA_TEST\n if (s.albedo.ALPHA_TEST_CHANNEL < albedoScaleAndCutoff.w) discard;\n #endif\n s.normal = v_normal;\n #if USE_NORMAL_MAP\n vec3 nmmp = texture(normalMap, v_uv).xyz - vec3(0.5);\n s.normal =\n (nmmp.x * pbrParams.w) * normalize(v_tangent) +\n (nmmp.y * pbrParams.w) * normalize(v_bitangent) +\n nmmp.z * normalize(s.normal);\n #endif\n s.position = v_position;\n vec4 pbr = pbrParams;\n #if USE_PBR_MAP\n vec4 res = texture(pbrMap, v_uv);\n pbr.x *= res.OCCLUSION_CHANNEL;\n pbr.y *= res.ROUGHNESS_CHANNEL;\n pbr.z *= res.METALLIC_CHANNEL;\n #endif\n #if USE_METALLIC_ROUGHNESS_MAP\n vec4 metallicRoughness = texture(metallicRoughnessMap, v_uv);\n pbr.z *= metallicRoughness.METALLIC_CHANNEL;\n pbr.y *= metallicRoughness.ROUGHNESS_CHANNEL;\n #endif\n #if USE_OCCLUSION_MAP\n pbr.x *= texture(occlusionMap, v_uv).OCCLUSION_CHANNEL;\n #endif\n s.occlusion = clamp(pbr.x, 0.0, 0.96);\n s.roughness = clamp(pbr.y, 0.04, 1.0);\n s.metallic = pbr.z;\n s.emissive = emissive.rgb * emissiveScale.xyz;\n #if USE_EMISSIVE_MAP\n s.emissive *= SRGBToLinear(texture(emissiveMap, EMISSIVE_UV).rgb);\n #endif\n}\nvec4 frag () {\n StandardSurface s; surf(s);\n vec4 color = CCStandardShading(s);\n return CCFragOutput(color);\n}\nout vec4 cc_FragColor;\nvoid main() { cc_FragColor = frag(); }` + "frag": `\nprecision highp float;\nuniform CCGlobal {\n vec4 cc_time;\n vec4 cc_screenSize;\n vec4 cc_screenScale;\n vec4 cc_nativeSize;\n highp mat4 cc_matView;\n mat4 cc_matViewInv;\n mat4 cc_matProj;\n mat4 cc_matProjInv;\n mat4 cc_matViewProj;\n mat4 cc_matViewProjInv;\n vec4 cc_cameraPos;\n vec4 cc_exposure;\n vec4 cc_mainLitDir;\n vec4 cc_mainLitColor;\n vec4 cc_ambientSky;\n vec4 cc_ambientGround;\n};\n#if CC_USE_IBL\nuniform samplerCube cc_environment;\nvec3 unpackRGBE (vec4 rgbe) {\n return rgbe.rgb * pow(2.0, rgbe.a * 255.0 - 128.0);\n}\n#endif\nvec3 SRGBToLinear (vec3 gamma) {\n return gamma * gamma;\n}\nuniform CCForwardLight {\n highp vec4 cc_sphereLitPos[2];\n vec4 cc_sphereLitSizeRange[2];\n vec4 cc_sphereLitColor[2];\n highp vec4 cc_spotLitPos[2];\n vec4 cc_spotLitSizeRangeAngle[2];\n vec4 cc_spotLitDir[2];\n vec4 cc_spotLitColor[2];\n};\nfloat SmoothDistAtt (float distSqr, float invSqrAttRadius) {\n float factor = distSqr * invSqrAttRadius;\n float smoothFactor = clamp(1.0 - factor * factor, 0.0, 1.0);\n return smoothFactor * smoothFactor;\n}\nfloat GetDistAtt (float distSqr, float invSqrAttRadius) {\n float attenuation = 1.0 / max(distSqr, 0.01*0.01);\n attenuation *= SmoothDistAtt(distSqr , invSqrAttRadius);\n return attenuation;\n}\nfloat GetAngleAtt (vec3 L, vec3 litDir, float litAngleScale, float litAngleOffset) {\n float cd = dot(litDir, L);\n float attenuation = clamp(cd * litAngleScale + litAngleOffset, 0.0, 1.0);\n return (attenuation * attenuation);\n}\nfloat GGXMobile (float roughness, float NoH, vec3 H, vec3 N) {\n vec3 NxH = cross(N, H);\n float OneMinusNoHSqr = dot(NxH, NxH);\n float a = roughness * roughness;\n float n = NoH * a;\n float p = a / (OneMinusNoHSqr + n * n);\n return p * p;\n}\nfloat CalcSpecular (float roughness, float NoH, vec3 H, vec3 N) {\n return (roughness*0.25 + 0.25) * GGXMobile(roughness, NoH, H, N);\n}\nvec3 BRDFApprox (vec3 specular, float roughness, float NoV) {\n const vec4 c0 = vec4(-1.0, -0.0275, -0.572, 0.022);\n const vec4 c1 = vec4(1.0, 0.0425, 1.04, -0.04);\n vec4 r = roughness * c0 + c1;\n float a004 = min( r.x * r.x, exp2( -9.28 * NoV ) ) * r.x + r.y;\n vec2 AB = vec2( -1.04, 1.04 ) * a004 + r.zw;\n AB.y *= clamp(50.0 * specular.g, 0.0, 1.0);\n return specular * AB.x + AB.y;\n}\nvec3 CalcDynamicLighting (vec3 worldPos, vec3 N, vec3 V, vec3 diffuse, vec3 specular, float roughness) {\n vec3 lighting = vec3(0.0);\n vec3 diffuseContrib = diffuse / 3.14159265359;\n for (int i = 0; i < 2; i++) {\n vec3 PLU = cc_sphereLitPos[i].xyz - worldPos;\n vec3 PL = normalize(PLU);\n vec3 PH = normalize(PL + V);\n float PNL = max(dot(N, PL), 0.001);\n float PNH = max(dot(N, PH), 0.0);\n float distSqr = dot(PLU, PLU);\n float litRadius = cc_sphereLitSizeRange[i].x;\n float litRadiusSqr = litRadius * litRadius;\n float illum = 3.14159265359 * (litRadiusSqr / max(litRadiusSqr , distSqr));\n float attRadiusSqrInv = 1.0 / max(cc_sphereLitSizeRange[i].y, 0.01);\n attRadiusSqrInv *= attRadiusSqrInv;\n float att = GetDistAtt(distSqr, attRadiusSqrInv);\n vec3 lspec = specular * CalcSpecular(roughness, PNH, PH, N);\n lighting += PNL * cc_sphereLitColor[i].rgb * cc_sphereLitColor[i].w * illum * att * (diffuseContrib + lspec);\n }\n for (int i = 0; i < 2; i++) {\n vec3 SLU = cc_spotLitPos[i].xyz - worldPos;\n vec3 SL = normalize(SLU);\n vec3 SH = normalize(SL + V);\n float SNL = max(dot(N, SL), 0.001);\n float SNH = max(dot(N, SH), 0.0);\n float distSqr = dot(SLU, SLU);\n float litRadius = cc_spotLitSizeRangeAngle[i].x;\n float litRadiusSqr = litRadius * litRadius;\n float illum = 3.14159265359 * (litRadiusSqr / max(litRadiusSqr , distSqr));\n float attRadiusSqrInv = 1.0 / max(cc_spotLitSizeRangeAngle[i].y, 0.01);\n attRadiusSqrInv *= attRadiusSqrInv;\n float cosInner = max(dot(-cc_spotLitDir[i].xyz, SL), 0.01);\n float cosOuter = cc_spotLitSizeRangeAngle[i].z;\n float litAngleScale = 1.0 / max(0.001, cosInner - cosOuter);\n float litAngleOffset = -cosOuter * litAngleScale;\n float att = GetDistAtt(distSqr, attRadiusSqrInv);\n att *= GetAngleAtt(SL, -cc_spotLitDir[i].xyz, litAngleScale, litAngleOffset);\n vec3 lspec = specular * CalcSpecular(roughness, SNH, SH, N);\n lighting += SNL * cc_spotLitColor[i].rgb * cc_spotLitColor[i].w * illum * att * (diffuseContrib + lspec);\n }\n return lighting;\n}\nstruct StandardSurface {\n vec4 albedo;\n vec3 position;\n vec3 normal;\n vec3 emissive;\n float roughness;\n float metallic;\n float occlusion;\n};\nvec4 CCStandardShading (StandardSurface s) {\n vec3 diffuse = s.albedo.rgb * (1.0 - s.metallic);\n vec3 specular = mix(vec3(0.04), s.albedo.rgb, s.metallic);\n vec3 N = normalize(s.normal);\n vec3 V = normalize(cc_cameraPos.xyz - s.position);\n vec3 L = normalize(-cc_mainLitDir.xyz);\n vec3 H = normalize(L+V);\n float NV = max(abs(dot(N, V)), 0.001);\n float NL = max(dot(N, L), 0.001);\n float NH = max(dot(N, H), 0.0);\n specular = BRDFApprox(specular, s.roughness, NV);\n vec3 diffuseContrib = diffuse / 3.14159265359;\n vec3 specularContrib = specular * CalcSpecular(s.roughness, NH, H, N);\n vec3 finalColor = NL * cc_mainLitColor.rgb * cc_mainLitColor.w * (diffuseContrib + specularContrib);\n finalColor += CalcDynamicLighting(s.position, N, V, diffuse, specular, s.roughness);\n float fAmb = 0.5 - N.y * 0.5;\n vec3 ambDiff = mix(cc_ambientSky.rgb, cc_ambientGround.rgb, fAmb) * cc_ambientSky.w;\n finalColor += (ambDiff.rgb * diffuse);\n #if CC_USE_IBL\n vec3 R = normalize(reflect(-V, N));\n vec4 envmap = textureLod(cc_environment, R, s.roughness * cc_ambientGround.w);\n #if CC_USE_IBL == 2\n vec3 env = unpackRGBE(envmap);\n #else\n vec3 env = SRGBToLinear(envmap.rgb) * cc_ambientSky.w;\n #endif\n finalColor += env * specular;\n #endif\n finalColor = finalColor * s.occlusion;\n #if CC_USE_HDR\n s.emissive *= cc_exposure.w;\n #endif\n finalColor += s.emissive;\n return vec4(finalColor, s.albedo.a);\n}\nvec3 ACESToneMap (vec3 color) {\n const float A = 2.51;\n const float B = 0.03;\n const float C = 2.43;\n const float D = 0.59;\n const float E = 0.14;\n return (color * (A * color + B)) / (color * (C * color + D) + E);\n}\nvec4 CCFragOutput (vec4 color) {\n #if !CC_USE_HDR\n color.rgb = sqrt(ACESToneMap(color.rgb));\n #endif\n return color;\n}\nuniform Constants {\n vec4 tilingOffset;\n vec4 albedo;\n vec4 albedoScaleAndCutoff;\n vec4 pbrParams;\n vec4 emissive;\n vec4 emissiveScale;\n};\nin vec3 v_position;\nin vec2 v_uv;\nin vec2 v_uv1;\nin vec3 v_normal;\n#if USE_VERTEX_COLOR\n in vec3 v_color;\n#endif\n#if USE_ALBEDO_MAP\n uniform sampler2D albedoMap;\n#endif\n#if USE_NORMAL_MAP\n in vec3 v_tangent;\n in vec3 v_bitangent;\n uniform sampler2D normalMap;\n#endif\n#if USE_PBR_MAP\n uniform sampler2D pbrMap;\n#endif\n#if USE_METALLIC_ROUGHNESS_MAP\n uniform sampler2D metallicRoughnessMap;\n#endif\n#if USE_OCCLUSION_MAP\n uniform sampler2D occlusionMap;\n#endif\n#if USE_EMISSIVE_MAP\n uniform sampler2D emissiveMap;\n#endif\n#if USE_ALPHA_TEST\n#endif\nvoid surf (out StandardSurface s) {\n vec4 baseColor = albedo;\n #if USE_VERTEX_COLOR\n baseColor.rgb *= v_color;\n #endif\n #if USE_ALBEDO_MAP\n vec4 texColor = texture(albedoMap, ALBEDO_UV);\n texColor.rgb = SRGBToLinear(texColor.rgb);\n baseColor *= texColor;\n #endif\n s.albedo = baseColor;\n s.albedo.rgb *= albedoScaleAndCutoff.xyz;\n #if USE_ALPHA_TEST\n if (s.albedo.ALPHA_TEST_CHANNEL < albedoScaleAndCutoff.w) discard;\n #endif\n s.normal = v_normal;\n #if USE_NORMAL_MAP\n vec3 nmmp = texture(normalMap, v_uv).xyz - vec3(0.5);\n s.normal =\n (nmmp.x * pbrParams.w) * normalize(v_tangent) +\n (nmmp.y * pbrParams.w) * normalize(v_bitangent) +\n nmmp.z * normalize(s.normal);\n #endif\n s.position = v_position;\n vec4 pbr = pbrParams;\n #if USE_PBR_MAP\n vec4 res = texture(pbrMap, v_uv);\n pbr.x *= res.OCCLUSION_CHANNEL;\n pbr.y *= res.ROUGHNESS_CHANNEL;\n pbr.z *= res.METALLIC_CHANNEL;\n #endif\n #if USE_METALLIC_ROUGHNESS_MAP\n vec4 metallicRoughness = texture(metallicRoughnessMap, v_uv);\n pbr.z *= metallicRoughness.METALLIC_CHANNEL;\n pbr.y *= metallicRoughness.ROUGHNESS_CHANNEL;\n #endif\n #if USE_OCCLUSION_MAP\n pbr.x *= texture(occlusionMap, v_uv).OCCLUSION_CHANNEL;\n #endif\n s.occlusion = clamp(pbr.x, 0.0, 0.96);\n s.roughness = clamp(pbr.y, 0.04, 1.0);\n s.metallic = pbr.z;\n s.emissive = emissive.rgb * emissiveScale.xyz;\n #if USE_EMISSIVE_MAP\n s.emissive *= SRGBToLinear(texture(emissiveMap, EMISSIVE_UV).rgb);\n #endif\n}\nvec4 frag () {\n StandardSurface s; surf(s);\n vec4 color = CCStandardShading(s);\n return CCFragOutput(color);\n}\nout vec4 cc_FragColor;\nvoid main() { cc_FragColor = frag(); }` }, "glsl1": { "vert": `\nprecision highp float;\nuniform highp mat4 cc_matView;\nuniform mat4 cc_matProj;\n#if CC_USE_BATCHING\n attribute float a_dyn_batch_id;\n uniform highp mat4 cc_matWorlds[10];\n#else\nuniform highp mat4 cc_matWorld;\nuniform highp mat4 cc_matWorldIT;\n#endif\nstruct StandardVertInput {\n highp vec4 position;\n vec3 normal;\n vec4 tangent;\n};\nattribute vec3 a_position;\nattribute vec3 a_normal;\nattribute vec4 a_tangent;\n#if CC_USE_SKINNING\nattribute vec4 a_weights;\nattribute vec4 a_joints;\nuniform highp vec4 cc_jointsTextureInfo;\nuniform highp vec4 cc_jointsAnimInfo;\nuniform sampler2D cc_jointsTexture;\n#if CC_USE_SKINNING == 1\n highp float decode32 (highp vec4 rgba) {\n rgba = rgba * 255.0;\n highp float Sign = 1.0 - step(128.0, rgba[3]) * 2.0;\n highp float Exponent = 2.0 * mod(rgba[3], 128.0) + step(128.0, rgba[2]) - 127.0;\n highp float Mantissa = mod(rgba[2], 128.0) * 65536.0 + rgba[1] * 256.0 + rgba[0] + 8388608.0;\n return Sign * exp2(Exponent - 23.0) * Mantissa;\n }\n#endif\n#if CC_USE_SKINNING == 1\n mat4 getJointMatrix (float i) {\n highp float j = 12.0 * (cc_jointsAnimInfo.x * i + cc_jointsAnimInfo.y) + cc_jointsTextureInfo.z;\n highp float invSize = cc_jointsTextureInfo.y;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointsTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = vec4(\n decode32(texture2D(cc_jointsTexture, vec2((x + 0.5) * invSize, y))),\n decode32(texture2D(cc_jointsTexture, vec2((x + 1.5) * invSize, y))),\n decode32(texture2D(cc_jointsTexture, vec2((x + 2.5) * invSize, y))),\n decode32(texture2D(cc_jointsTexture, vec2((x + 3.5) * invSize, y)))\n );\n vec4 v2 = vec4(\n decode32(texture2D(cc_jointsTexture, vec2((x + 4.5) * invSize, y))),\n decode32(texture2D(cc_jointsTexture, vec2((x + 5.5) * invSize, y))),\n decode32(texture2D(cc_jointsTexture, vec2((x + 6.5) * invSize, y))),\n decode32(texture2D(cc_jointsTexture, vec2((x + 7.5) * invSize, y)))\n );\n vec4 v3 = vec4(\n decode32(texture2D(cc_jointsTexture, vec2((x + 8.5) * invSize, y))),\n decode32(texture2D(cc_jointsTexture, vec2((x + 9.5) * invSize, y))),\n decode32(texture2D(cc_jointsTexture, vec2((x + 10.5) * invSize, y))),\n decode32(texture2D(cc_jointsTexture, vec2((x + 11.5) * invSize, y)))\n );\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n#elif CC_USE_SKINNING == 2\n mat4 getJointMatrix (float i) {\n highp float j = 3.0 * (cc_jointsAnimInfo.x * i + cc_jointsAnimInfo.y) + cc_jointsTextureInfo.z;\n highp float invSize = cc_jointsTextureInfo.y;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointsTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = texture2D(cc_jointsTexture, vec2((x + 0.5) * invSize, y));\n vec4 v2 = texture2D(cc_jointsTexture, vec2((x + 1.5) * invSize, y));\n vec4 v3 = texture2D(cc_jointsTexture, vec2((x + 2.5) * invSize, y));\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n#endif\nmat4 skinMatrix () {\n return getJointMatrix(a_joints.x) * a_weights.x\n + getJointMatrix(a_joints.y) * a_weights.y;\n + getJointMatrix(a_joints.z) * a_weights.z;\n + getJointMatrix(a_joints.w) * a_weights.w;\n}\nvoid CCSkin (inout vec4 position) {\n mat4 m = skinMatrix();\n position = m * position;\n}\nvoid CCSkin (inout StandardVertInput attr) {\n mat4 m = skinMatrix();\n attr.position = m * attr.position;\n attr.normal = (m * vec4(attr.normal, 0.0)).xyz;\n attr.tangent.xyz = (m * vec4(attr.tangent.xyz, 0.0)).xyz;\n}\n#endif\nuniform vec4 tilingOffset;\n#if USE_VERTEX_COLOR\n attribute vec3 a_color;\n varying vec3 v_color;\n#endif\nvarying vec3 v_position;\nvarying vec3 v_normal;\n#if USE_NORMAL_MAP\n varying vec3 v_tangent;\n varying vec3 v_bitangent;\n#endif\nattribute vec2 a_texCoord;\nvarying vec2 v_uv;\nattribute vec2 a_texCoord1;\nvarying vec2 v_uv1;\nhighp vec4 vert () {\n StandardVertInput In;\n In.position = vec4(a_position, 1.0);\n In.normal = a_normal;\n In.tangent = a_tangent;\n #if CC_USE_SKINNING\n CCSkin(In);\n #endif\n highp mat4 matWorld, matWorldIT;\n #if CC_USE_BATCHING\n matWorld = cc_matWorlds[int(a_dyn_batch_id + 0.5)];\n matWorldIT = matWorld;\n #else\n matWorld = cc_matWorld;\n matWorldIT = cc_matWorldIT;\n #endif\n highp vec4 pos = matWorld * In.position;\n v_position = pos.xyz;\n v_normal = normalize((matWorldIT * vec4(In.normal, 0.0)).xyz);\n #if USE_NORMAL_MAP\n v_tangent = normalize((matWorldIT * vec4(In.tangent.xyz, 0.0)).xyz);\n v_bitangent = cross(v_normal, v_tangent) * In.tangent.w;\n #endif\n v_uv = a_texCoord * tilingOffset.xy + tilingOffset.zw;\n v_uv1 = a_texCoord1 * tilingOffset.xy + tilingOffset.zw;\n #if USE_VERTEX_COLOR\n v_color = a_color;\n #endif\n return cc_matProj * (cc_matView * matWorld) * In.position;\n}\nvoid main() { gl_Position = vert(); }`, diff --git a/cocos/core/3d/framework/camera-component.ts b/cocos/core/3d/framework/camera-component.ts index 715459dade..fa2667a7bc 100644 --- a/cocos/core/3d/framework/camera-component.ts +++ b/cocos/core/3d/framework/camera-component.ts @@ -34,12 +34,12 @@ import { ray } from '../../geom-utils'; import { GFXClearFlag } from '../../gfx/define'; import { GFXWindow } from '../../gfx/window'; import { Color, Rect, toRadian, Vec3 } from '../../math'; +import { CameraDefaultMask } from '../../pipeline/define'; import { Camera } from '../../renderer'; import { SKYBOX_FLAG } from '../../renderer/scene/camera'; +import { Root } from '../../root'; import { Layers, Scene } from '../../scene-graph'; import { Enum } from '../../value-types'; -import { CameraDefaultMask } from '../../pipeline/define'; -import { director } from '../../director'; /** * The projection type
@@ -118,7 +118,7 @@ export class CameraComponent extends Component { */ @property({ type: ProjectionType, - tooltip:'相机的投影类型', + tooltip: '相机的投影类型', }) get projection () { return this._projection; @@ -134,7 +134,7 @@ export class CameraComponent extends Component { * @zh 相机的优先级顺序,只能在编辑器中设置,动态设置无效。 */ @property({ - tooltip:'相机的优先级顺序,只能在编辑器中设置,动态设置无效', + tooltip: '相机的优先级顺序,只能在编辑器中设置,动态设置无效', }) get priority () { return this._priority; @@ -152,7 +152,7 @@ export class CameraComponent extends Component { * @zh 相机的视角大小。 */ @property({ - tooltip:'相机的视角大小', + tooltip: '相机的视角大小', }) get fov () { return this._fov; @@ -168,7 +168,7 @@ export class CameraComponent extends Component { * @zh 正交模式下的相机视角大小。 */ @property({ - tooltip:'正交模式下的相机视角大小', + tooltip: '正交模式下的相机视角大小', }) get orthoHeight () { return this._orthoHeight; @@ -184,7 +184,7 @@ export class CameraComponent extends Component { * @zh 相机的近平面。 */ @property({ - tooltip:'相机的近平面', + tooltip: '相机的近平面', }) get near () { return this._near; @@ -200,7 +200,7 @@ export class CameraComponent extends Component { * @zh 相机的远平面。 */ @property({ - tooltip:'相机的远平面', + tooltip: '相机的远平面', }) get far () { return this._far; @@ -216,7 +216,7 @@ export class CameraComponent extends Component { * @zh 相机的颜色缓冲默认值。 */ @property({ - tooltip:'相机的颜色缓冲默认值', + tooltip: '相机的颜色缓冲默认值', }) // @constget get color (): Readonly { @@ -238,7 +238,7 @@ export class CameraComponent extends Component { * @zh 相机的深度缓冲默认值。 */ @property({ - tooltip:'相机的深度缓冲默认值', + tooltip: '相机的深度缓冲默认值', }) get depth () { return this._depth; @@ -254,7 +254,7 @@ export class CameraComponent extends Component { * @zh 相机的模板缓冲默认值。 */ @property({ - tooltip:'相机的模板缓冲默认值', + tooltip: '相机的模板缓冲默认值', }) get stencil () { return this._stencil; @@ -271,7 +271,7 @@ export class CameraComponent extends Component { */ @property({ type: CameraClearFlag, - tooltip:'相机的缓冲清除标志位', + tooltip: '相机的缓冲清除标志位', }) get clearFlags () { return this._clearFlags; @@ -287,7 +287,7 @@ export class CameraComponent extends Component { * @zh 相机相对屏幕的 viewport。 */ @property({ - tooltip:'相机相对屏幕的 viewport', + tooltip: '相机相对屏幕的 viewport', }) get rect () { return this._rect; @@ -318,7 +318,7 @@ export class CameraComponent extends Component { */ @property({ type: Layers.BitMask, - tooltip:'设置摄像机可见掩码,与 Component 中的 visibility 同时使用,用于过滤摄像机不需要渲染的物体', + tooltip: '设置摄像机可见掩码,与 Component 中的 visibility 同时使用,用于过滤摄像机不需要渲染的物体', }) get visibility () { return this._visibility; @@ -336,7 +336,7 @@ export class CameraComponent extends Component { */ @property({ type: RenderTexture, - tooltip:'设置摄像机 RenderTexture', + tooltip: '设置摄像机 RenderTexture', }) get targetTexture () { return this._targetTexture; @@ -353,16 +353,16 @@ export class CameraComponent extends Component { this._updateTargetTexture(); if (!value && this._camera){ - this._camera.changeTargetWindow(CC_EDITOR? cc.director.root.tempWindow: null); + this._camera.changeTargetWindow(CC_EDITOR ? cc.director.root.tempWindow : null); this._camera.isWindowSize = true; } } - get inEditorMode() { + get inEditorMode () { return this._inEditorMode; } - set inEditorMode(value) { + set inEditorMode (value) { this._inEditorMode = value; if (this._camera) { this._camera.changeTargetWindow(value ? cc.director.root && cc.director.root.mainWindow : cc.director.root && cc.director.root.tempWindow); @@ -387,7 +387,7 @@ export class CameraComponent extends Component { } } - public onDisable() { + public onDisable () { if (this._camera) { this._detachFromScene(); } @@ -423,7 +423,7 @@ export class CameraComponent extends Component { } protected _createCamera () { - this._camera = director.root!.createCamera(); + this._camera = (cc.director.root as Root).createCamera(); this._camera.initialize({ name: this.node.name, node: this.node, @@ -452,7 +452,7 @@ export class CameraComponent extends Component { this._updateTargetTexture(); } - protected _attachToScene() { + protected _attachToScene () { if (!this.node.scene || !this._camera) { return; } @@ -463,7 +463,7 @@ export class CameraComponent extends Component { scene.addCamera(this._camera); } - protected _detachFromScene() { + protected _detachFromScene () { if (this._camera && this._camera.scene) { this._camera.scene.removeCamera(this._camera); } diff --git a/cocos/core/3d/framework/directional-light-component.ts b/cocos/core/3d/framework/directional-light-component.ts index e208b45ef9..70b2b7404b 100644 --- a/cocos/core/3d/framework/directional-light-component.ts +++ b/cocos/core/3d/framework/directional-light-component.ts @@ -52,7 +52,7 @@ export class DirectionalLightComponent extends LightComponent { */ @property({ unit: 'lx', - tooltip:'光源强度' + tooltip: '光源强度', }) get illuminance () { return this._illuminance; @@ -62,25 +62,14 @@ export class DirectionalLightComponent extends LightComponent { if (this._light) { this._light.illuminance = this._illuminance; } } - constructor() { + constructor () { super(); this._lightType = DirectionalLight; } - protected _createLight (scene?: RenderScene) { - if (!this.node.scene) { return; } - scene = scene || this._getRenderScene(); - if (scene.mainLight.node!.activeInHierarchy) { - console.warn('there can be only one directional(main) light.'); - return; - } - this._light = scene.mainLight; + protected _createLight () { + super._createLight(); + if (!this._light) { return; } this.illuminance = this._illuminance; } - - protected _destroyLight (scene?: RenderScene) { - if (!this.node.scene || !this._light) { return; } - scene = scene || this._getRenderScene(); - this._light.node = scene.defaultMainLightNode; - } } diff --git a/cocos/core/3d/framework/light-component.ts b/cocos/core/3d/framework/light-component.ts index db60637706..c2f10c614b 100644 --- a/cocos/core/3d/framework/light-component.ts +++ b/cocos/core/3d/framework/light-component.ts @@ -32,7 +32,11 @@ import { ccclass, property } from '../../data/class-decorator'; import { Color } from '../../math'; import { Enum } from '../../value-types'; +import { DirectionalLight } from '../../renderer/scene/directional-light'; import { Light, LightType } from '../../renderer/scene/light'; +import { SphereLight } from '../../renderer/scene/sphere-light'; +import { SpotLight } from '../../renderer/scene/spot-light'; +import { Root } from '../../root'; export const PhotometricTerm = Enum({ LUMINOUS_POWER: 0, @@ -52,7 +56,7 @@ export class LightComponent extends Component { protected _colorTemperature = 6550; protected _type = LightType.UNKNOWN; - protected _lightType : typeof Light; + protected _lightType: typeof Light; protected _light: Light | null = null; /** @@ -62,7 +66,7 @@ export class LightComponent extends Component { * 光源颜色。 */ @property({ - tooltip:'光源颜色', + tooltip: '光源颜色', }) // @constget get color (): Readonly { @@ -84,7 +88,7 @@ export class LightComponent extends Component { * 是否启用光源色温。 */ @property({ - tooltip:'是否启用光源色温' + tooltip: '是否启用光源色温', }) get useColorTemperature () { return this._useColorTemperature; @@ -103,7 +107,7 @@ export class LightComponent extends Component { @property({ slide: true, range: [1000, 15000, 1], - tooltip:'光源色温' + tooltip: '光源色温', }) get colorTemperature () { return this._colorTemperature; @@ -124,12 +128,12 @@ export class LightComponent extends Component { return this._type; } - constructor() { + constructor () { super(); this._lightType = Light; } - public onLoad(){ + public onLoad (){ this._createLight(); } @@ -146,15 +150,13 @@ export class LightComponent extends Component { } protected _createLight () { - if (this._light) { - return; + if (!this._light) { + this._light = (cc.director.root as Root).createLight(this._lightType); } - this._light = cc.director.root.createLight(this._lightType); this.color = this._color; this.useColorTemperature = this._useColorTemperature; this.colorTemperature = this._colorTemperature; - this._light!.node = this.node; - this._light!.enabled = this.enabledInHierarchy; + this._light.node = this.node; } protected _destroyLight () { @@ -164,34 +166,34 @@ export class LightComponent extends Component { } } - protected _attachToScene() { + protected _attachToScene () { this._detachFromScene(); if (this._light && !this._light.scene && this.node.scene) { switch (this._type) { case LightType.DIRECTIONAL: - this._light.attachToScene(this._getRenderScene()); + this._getRenderScene().setMainLight(this._light as DirectionalLight); break; case LightType.SPHERE: - this._getRenderScene().addSphereLight(this._light as any); + this._getRenderScene().addSphereLight(this._light as SphereLight); break; case LightType.SPOT: - this._getRenderScene().addSpotLight(this._light as any); + this._getRenderScene().addSpotLight(this._light as SpotLight); break; } } } - protected _detachFromScene() { + protected _detachFromScene () { if (this._light && this._light.scene) { switch (this._type) { case LightType.DIRECTIONAL: - this._light.detachFromScene(); + this._light.scene.unsetMainLight(this._light as DirectionalLight); break; case LightType.SPHERE: - this._light.scene.removeSphereLight(this._light as any); + this._light.scene.removeSphereLight(this._light as SphereLight); break; case LightType.SPOT: - this._light.scene.removeSpotLight(this._light as any); + this._light.scene.removeSpotLight(this._light as SpotLight); break; } } diff --git a/cocos/core/3d/framework/model-component.ts b/cocos/core/3d/framework/model-component.ts index 68862fe352..a997c04884 100644 --- a/cocos/core/3d/framework/model-component.ts +++ b/cocos/core/3d/framework/model-component.ts @@ -30,11 +30,11 @@ import { Material, Mesh } from '../../assets'; import { ccclass, executeInEditMode, executionOrder, menu, property } from '../../data/class-decorator'; import { Model } from '../../renderer/scene/model'; +import { Root } from '../../root'; import { TransformBit } from '../../scene-graph/node-enum'; import { Enum } from '../../value-types'; import { builtinResMgr } from '../builtin'; import { RenderableComponent } from './renderable-component'; -import { Root } from '../../root'; /** * Shadow projection mode
@@ -148,7 +148,7 @@ export class ModelComponent extends RenderableComponent { public static ShadowCastingMode = ModelShadowCastingMode; - protected _modelType : typeof Model; + protected _modelType: typeof Model; protected _model: Model | null = null; @@ -164,7 +164,7 @@ export class ModelComponent extends RenderableComponent { @property private _receiveShadows = false; - constructor() { + constructor () { super(); this._modelType = Model; } @@ -201,9 +201,10 @@ export class ModelComponent extends RenderableComponent { } if (this._model) { - cc.director.root.destroyModel(this._model); + this._model.destroy(); + } else { + this._createModel(); } - this._createModel(); this._updateModelParams(); @@ -236,7 +237,7 @@ export class ModelComponent extends RenderableComponent { this._models.push(this._model); } - protected _attachToScene() { + protected _attachToScene () { if (!this.node.scene && !this._model) { return; } @@ -247,7 +248,7 @@ export class ModelComponent extends RenderableComponent { scene.addModel(this._model!); } - protected _detachFromScene() { + protected _detachFromScene () { if (this._model && this._model.scene) { this._model.scene.removeModel(this._model); } diff --git a/cocos/core/3d/framework/skinning-model-component.ts b/cocos/core/3d/framework/skinning-model-component.ts index 74a110c8ba..bbcfdf572a 100644 --- a/cocos/core/3d/framework/skinning-model-component.ts +++ b/cocos/core/3d/framework/skinning-model-component.ts @@ -36,7 +36,6 @@ import { Node } from '../../scene-graph/node'; import { INode } from '../../utils/interfaces'; import { builtinResMgr } from '../builtin'; import { ModelComponent } from './model-component'; -import { Model } from '../../renderer'; /** * @en The Skinning Model Component @@ -91,7 +90,7 @@ export class SkinningModelComponent extends ModelComponent { return (this._model as SkinningModel); } - constructor() { + constructor () { super(); this._modelType = SkinningModel; } diff --git a/cocos/core/3d/framework/sphere-light-component.ts b/cocos/core/3d/framework/sphere-light-component.ts index e942174445..aad47620b2 100644 --- a/cocos/core/3d/framework/sphere-light-component.ts +++ b/cocos/core/3d/framework/sphere-light-component.ts @@ -28,7 +28,6 @@ import { ccclass, executeInEditMode, menu, property } from '../../data/class-decorator'; import { LightType, nt2lm } from '../../renderer/scene/light'; -import { RenderScene } from '../../renderer/scene/render-scene'; import { SphereLight } from '../../renderer/scene/sphere-light'; import { LightComponent, PhotometricTerm } from './light-component'; @@ -54,7 +53,7 @@ export class SphereLightComponent extends LightComponent { */ @property({ unit: 'lm', - tooltip:'光通量', + tooltip: '光通量', }) get luminousPower () { return this._luminance * nt2lm(this._size); @@ -69,7 +68,7 @@ export class SphereLightComponent extends LightComponent { */ @property({ unit: 'cd/m²', - tooltip:'亮度', + tooltip: '亮度', }) get luminance () { return this._luminance; @@ -84,7 +83,7 @@ export class SphereLightComponent extends LightComponent { */ @property({ type: PhotometricTerm, - tooltip:'指定光通量或亮度', + tooltip: '指定光通量或亮度', }) get term () { return this._term; @@ -100,7 +99,7 @@ export class SphereLightComponent extends LightComponent { * 针对聚光灯和点光源设置光源大小。 */ @property({ - tooltip:'针对聚光灯和点光源设置光源大小' + tooltip: '针对聚光灯和点光源设置光源大小', }) get size () { return this._size; @@ -117,7 +116,7 @@ export class SphereLightComponent extends LightComponent { * 针对聚光灯和点光源设置光源范围。 */ @property({ - tooltip:'针对聚光灯和点光源设置光源范围', + tooltip: '针对聚光灯和点光源设置光源范围', }) get range () { return this._range; @@ -127,18 +126,15 @@ export class SphereLightComponent extends LightComponent { if (this._light) { this._light.range = val; } } - constructor() { + constructor () { super(); this._lightType = SphereLight; } - protected _createLight (scene?: RenderScene) { + protected _createLight () { super._createLight(); - if (!this._light) { - console.warn('we don\'t support this many lights in forward pipeline.'); - return; - } - this._light.luminance = this._luminance; + if (!this._light) { return; } + this.luminance = this._luminance; this.size = this._size; this.range = this._range; } diff --git a/cocos/core/3d/framework/spot-light-component.ts b/cocos/core/3d/framework/spot-light-component.ts index 084f0c4f3b..57aee3b2d0 100644 --- a/cocos/core/3d/framework/spot-light-component.ts +++ b/cocos/core/3d/framework/spot-light-component.ts @@ -30,7 +30,6 @@ import { ccclass, executeInEditMode, menu, property } from '../../data/class-decorator'; import { toRadian } from '../../math'; import { LightType, nt2lm } from '../../renderer/scene/light'; -import { RenderScene } from '../../renderer/scene/render-scene'; import { SpotLight } from '../../renderer/scene/spot-light'; import { LightComponent, PhotometricTerm } from './light-component'; @@ -58,7 +57,7 @@ export class SpotLightComponent extends LightComponent { */ @property({ unit: 'lm', - tooltip:'光通量', + tooltip: '光通量', }) get luminousPower () { return this._luminance * nt2lm(this._size); @@ -73,7 +72,7 @@ export class SpotLightComponent extends LightComponent { */ @property({ unit: 'cd/m²', - tooltip:'亮度', + tooltip: '亮度', }) get luminance () { return this._luminance; @@ -88,7 +87,7 @@ export class SpotLightComponent extends LightComponent { */ @property({ type: PhotometricTerm, - tooltip:'指定光通量或亮度', + tooltip: '指定光通量或亮度', }) get term () { return this._term; @@ -104,7 +103,7 @@ export class SpotLightComponent extends LightComponent { * 针对聚光灯和点光源设置光源大小。 */ @property({ - tooltip:'针对聚光灯和点光源设置光源大小', + tooltip: '针对聚光灯和点光源设置光源大小', }) get size () { return this._size; @@ -121,7 +120,7 @@ export class SpotLightComponent extends LightComponent { * 针对聚光灯和点光源设置光源范围。 */ @property({ - tooltip:'针对聚光灯和点光源设置光源范围', + tooltip: '针对聚光灯和点光源设置光源范围', }) get range () { return this._range; @@ -140,7 +139,7 @@ export class SpotLightComponent extends LightComponent { @property({ slide: true, range: [2, 180, 1], - tooltip:'聚光灯锥角', + tooltip: '聚光灯锥角', }) get spotAngle () { return this._spotAngle; @@ -150,19 +149,16 @@ export class SpotLightComponent extends LightComponent { this._spotAngle = val; if (this._light) { this._light.spotAngle = toRadian(val); } } - - constructor() { + + constructor () { super(); this._lightType = SpotLight; } - protected _createLight (scene?: RenderScene) { + protected _createLight () { super._createLight(); - if (!this._light) { - console.warn('we don\'t support this many lights in forward pipeline.'); - return; - } - this._light.luminance = this._luminance; + if (!this._light) { return; } + this.luminance = this._luminance; this.size = this._size; this.range = this._range; this.spotAngle = this._spotAngle; diff --git a/cocos/core/components/ui-base/canvas-component.ts b/cocos/core/components/ui-base/canvas-component.ts index 4c421a4a86..28d671bc1a 100644 --- a/cocos/core/components/ui-base/canvas-component.ts +++ b/cocos/core/components/ui-base/canvas-component.ts @@ -28,22 +28,22 @@ * @category ui */ -import { Component } from '../component'; -import { ccclass, disallowMultiple, executeInEditMode, executionOrder, menu, property, requireComponent } from '../../data/class-decorator'; -import { Vec3, Color } from '../../math'; -import { GFXClearFlag } from '../../gfx/define'; -import { Camera } from '../../renderer'; -import { UITransformComponent } from './ui-transfrom-component'; -import { Node } from '../../scene-graph/node'; -import { RenderTexture } from '../../assets/render-texture'; -import { GFXWindow } from '../../gfx/window'; -import { director, Director } from '../../director'; -import { view, ResolutionPolicy } from '../../platform/view'; -import visibleRect from '../../platform/visible-rect'; import { CameraComponent } from '../../3d/framework/camera-component'; +import { RenderTexture } from '../../assets/render-texture'; +import { ccclass, disallowMultiple, executeInEditMode, executionOrder, menu, property, requireComponent } from '../../data/class-decorator'; +import { director, Director } from '../../director'; +import { game } from '../../game'; +import { GFXClearFlag } from '../../gfx/define'; +import { GFXWindow } from '../../gfx/window'; +import { Color, Vec3 } from '../../math'; +import { ResolutionPolicy, view } from '../../platform/view'; +import visibleRect from '../../platform/visible-rect'; +import { Camera } from '../../renderer'; +import { Node } from '../../scene-graph/node'; import { INode } from '../../utils/interfaces'; import { Enum } from '../../value-types'; -import { game } from '../../game'; +import { Component } from '../component'; +import { UITransformComponent } from './ui-transfrom-component'; const _worldPos = new Vec3(); @@ -74,7 +74,7 @@ const RenderMode = Enum({ export class CanvasComponent extends Component { @property({ type: CanvasClearFlag, - tooltip:'清理屏幕缓冲标记', + tooltip: '清理屏幕缓冲标记', }) get clearFlag () { return this._clearFlag; @@ -88,7 +88,7 @@ export class CanvasComponent extends Component { } @property({ - tooltip:'清理颜色缓冲区后的颜色', + tooltip: '清理颜色缓冲区后的颜色', }) get color () { return this._color; @@ -106,7 +106,7 @@ export class CanvasComponent extends Component { @property({ type: RenderMode, - tooltip:'Canvas 渲染模式,intersperse 下可以指定 Canvas 与场景中的相机的渲染顺序,overlay 下 Canvas 会在所有场景相机渲染完成后渲染。\n注意:启用 intersperse 模式,如果 3D 场景的相机内容显示上要在 Canvas 前面,相机的 clearFlags 也要为 none', + tooltip: 'Canvas 渲染模式,intersperse 下可以指定 Canvas 与场景中的相机的渲染顺序,overlay 下 Canvas 会在所有场景相机渲染完成后渲染。\n注意:启用 intersperse 模式,如果 3D 场景的相机内容显示上要在 Canvas 前面,相机的 clearFlags 也要为 none', }) get renderMode () { return this._renderMode; @@ -126,7 +126,7 @@ export class CanvasComponent extends Component { * @param value - 渲染优先级。 */ @property({ - tooltip:'相机排序优先级。当 RenderMode 为 intersperse 时,指定与其它相机的渲染顺序,当 RenderMode 为 overlay 时,指定跟其余 Canvas 做排序使用', + tooltip: '相机排序优先级。当 RenderMode 为 intersperse 时,指定与其它相机的渲染顺序,当 RenderMode 为 overlay 时,指定跟其余 Canvas 做排序使用', }) get priority () { return this._priority; @@ -138,7 +138,7 @@ export class CanvasComponent extends Component { this._camera.priority = this._getViewPriority(); } - if(director.root && director.root.ui){ + if (director.root && director.root.ui){ director.root.ui.sortScreens(); } } @@ -148,14 +148,14 @@ export class CanvasComponent extends Component { */ @property({ type: RenderTexture, - tooltip:'目标渲染纹理', + tooltip: '目标渲染纹理', }) get targetTexture (){ return this._targetTexture; } set targetTexture (value) { - if(this._targetTexture === value){ + if (this._targetTexture === value){ return; } @@ -251,19 +251,20 @@ export class CanvasComponent extends Component { director.root!.ui.addScreen(this); } - public onEnable() { + public onEnable () { if (this._camera) { director.root!.ui.renderScene.addCamera(this._camera); } } - public onDisable() { + public onDisable () { if (this._camera) { director.root!.ui.renderScene.removeCamera(this._camera); } } public onDestroy () { + director.root!.ui.removeScreen(this); if (this._camera) { director.root!.destroyCamera(this._camera); } @@ -277,7 +278,6 @@ export class CanvasComponent extends Component { } view.off('design-resolution-changed', this._thisOnResized); - director.root!.ui.removeScreen(this); // if (CanvasComponent.instance === this) { // CanvasComponent.instance = null; // } @@ -368,12 +368,12 @@ export class CanvasComponent extends Component { // } // } - protected _chechTargetTextureEvent(old: RenderTexture | null) { + protected _chechTargetTextureEvent (old: RenderTexture | null) { const resizeFunc = (window: GFXWindow) => { if (this._camera) { this._camera.setFixedSize(window.width, window.height); } - } + }; if (old) { old.off('resize'); @@ -384,7 +384,7 @@ export class CanvasComponent extends Component { } } - protected _updateTargetTexture() { + protected _updateTargetTexture () { if (!this._camera) { return; } diff --git a/cocos/core/components/ui-coodinate-tracker-component.ts b/cocos/core/components/ui-coodinate-tracker-component.ts index 7b5aa08e3b..2409b76bc0 100644 --- a/cocos/core/components/ui-coodinate-tracker-component.ts +++ b/cocos/core/components/ui-coodinate-tracker-component.ts @@ -24,12 +24,13 @@ THE SOFTWARE. */ -import { Component, EventHandler } from '../../core/components'; -import { ccclass, property, menu, executionOrder } from '../data/class-decorator'; +import { Component } from '../../core/components/component'; +import { EventHandler } from '../../core/components/component-event-handler'; +import { CameraComponent } from '../3d/framework/camera-component'; +import { ccclass, executionOrder, menu, property } from '../data/class-decorator'; +import { Vec3 } from '../math'; import { Node } from '../scene-graph'; import { convertUtils } from '../utils'; -import { CameraComponent } from '../3d'; -import { Vec3 } from '../math'; /** * @zh 3D 节点映射 UI 节点组件 @@ -45,13 +46,13 @@ export class UICoordinateTrackerComponent extends Component { */ @property({ type: Node, - tooltip: '目标对象' + tooltip: '目标对象', }) - get target() { + get target () { return this._target; } - set target(value) { + set target (value) { if (this._target === value) { return; } @@ -66,13 +67,13 @@ export class UICoordinateTrackerComponent extends Component { */ @property({ type: CameraComponent, - tooltip: '照射相机' + tooltip: '照射相机', }) - get camera() { + get camera () { return this._camera; } - set camera(value) { + set camera (value) { if (this._camera === value) { return; } @@ -86,13 +87,13 @@ export class UICoordinateTrackerComponent extends Component { * 是否是缩放映射。 */ @property({ - tooltip: '是否是缩放映射' + tooltip: '是否是缩放映射', }) - get useScale() { + get useScale () { return this._useScale; } - set useScale(value) { + set useScale (value) { if (this._useScale === value) { return; } @@ -105,13 +106,13 @@ export class UICoordinateTrackerComponent extends Component { * 距相机多少距离为正常显示计算大小。 */ @property({ - tooltip: '距相机多少距离为正常显示计算大小' + tooltip: '距相机多少距离为正常显示计算大小', }) - get distance() { + get distance () { return this._distance; } - set distance(value) { + set distance (value) { if (this._distance === value) { return; } @@ -125,7 +126,7 @@ export class UICoordinateTrackerComponent extends Component { */ @property({ type: [EventHandler], - tooltip: '映射数据事件。回调的第一个参数是映射后的本地坐标,第二个是距相机距离比' + tooltip: '映射数据事件。回调的第一个参数是映射后的本地坐标,第二个是距相机距离比', }) public syncEvents: EventHandler[] = []; @@ -143,11 +144,11 @@ export class UICoordinateTrackerComponent extends Component { protected _canMove = true; protected _lastWpos = new Vec3(); - public onEnable() { + public onEnable () { this._checkCanMove(); } - public update() { + public update () { const wpos = this.node.worldPosition; // @ts-ignore if (!this._canMove || !this._camera!._camera || this._lastWpos.equals(wpos)) { @@ -171,7 +172,7 @@ export class UICoordinateTrackerComponent extends Component { } } - protected _checkCanMove() { + protected _checkCanMove () { this._canMove = !!(this._camera && this._target); } } diff --git a/cocos/core/pipeline/render-flow.ts b/cocos/core/pipeline/render-flow.ts index 4cbe1cf5d2..6dde6844ff 100644 --- a/cocos/core/pipeline/render-flow.ts +++ b/cocos/core/pipeline/render-flow.ts @@ -129,7 +129,8 @@ export abstract class RenderFlow { * @param view 渲染视图。 */ public render (view: RenderView) { - for (const stage of this._stages) { + for (let i = 0; i < this._stages.length; i++) { + const stage = this._stages[i]; stage.render(view); } } diff --git a/cocos/core/pipeline/render-pipeline.ts b/cocos/core/pipeline/render-pipeline.ts index 5d8aa39ce3..c7e989803b 100644 --- a/cocos/core/pipeline/render-pipeline.ts +++ b/cocos/core/pipeline/render-pipeline.ts @@ -24,9 +24,7 @@ import { IInternalBindingInst } from './define'; import { IRenderFlowInfo, RenderFlow } from './render-flow'; import { RenderView } from './render-view'; -const _vec4Array = new Float32Array(4); -const _v3tmp = new Vec3(); -const _v4Zero = new Vec4(0.0, 0.0, 0.0, 0.0); +const v3_1 = new Vec3(); /** * @zh @@ -375,7 +373,8 @@ export abstract class RenderPipeline { this.updateUBOs(view); - for (const flow of view.flows) { + for (let i = 0; i < view.flows.length; i++) { + const flow = view.flows[i]; flow.render(view); } } @@ -1161,9 +1160,8 @@ export abstract class RenderPipeline { fv[UBOGlobal.EXPOSURE_OFFSET + 2] = this._isHDR ? 1.0 : 0.0; fv[UBOGlobal.EXPOSURE_OFFSET + 3] = this._fpScale / exposure; - Vec3.toArray(fv, mainLight.direction, UBOGlobal.MAIN_LIT_DIR_OFFSET); - - if (mainLight.scene) { + if (mainLight) { + Vec3.toArray(fv, mainLight.direction, UBOGlobal.MAIN_LIT_DIR_OFFSET); Vec3.toArray(fv, mainLight.color, UBOGlobal.MAIN_LIT_COLOR_OFFSET); if (mainLight.useColorTemperature) { const colorTempRGB = mainLight.colorTemperatureRGB; @@ -1178,7 +1176,7 @@ export abstract class RenderPipeline { fv[UBOGlobal.MAIN_LIT_COLOR_OFFSET + 3] = mainLight.illuminance * exposure; } } else { - Vec4.toArray(fv, _v4Zero, UBOGlobal.MAIN_LIT_COLOR_OFFSET); + Vec4.toArray(fv, Vec4.ZERO, UBOGlobal.MAIN_LIT_COLOR_OFFSET); } const skyColor = ambient.skyColor; @@ -1208,13 +1206,12 @@ export abstract class RenderPipeline { this._renderObjects.length = 0; const mainLight = scene.mainLight; - if (mainLight && mainLight.scene) { - mainLight.update(); - } - const planarShadows = scene.planarShadows; - if (planarShadows.enabled && mainLight.node!.hasChangedFlags) { - planarShadows.updateDirLight(mainLight); + if (mainLight) { + mainLight.update(); + if (planarShadows.enabled && mainLight.node!.hasChangedFlags) { + planarShadows.updateDirLight(mainLight); + } } if (scene.skybox.enabled && (camera.clearFlag & SKYBOX_FLAG)) { @@ -1268,9 +1265,8 @@ export abstract class RenderPipeline { protected addVisibleModel (model: Model, camera: Camera) { let depth = 0; if (model.node) { - model.node.getWorldPosition(_v3tmp); - Vec3.subtract(_v3tmp, _v3tmp, camera.position); - depth = Vec3.dot(_v3tmp, camera.forward); + Vec3.subtract(v3_1, model.node.worldPosition, camera.position); + depth = Vec3.dot(v3_1, camera.forward); } this._renderObjects.push({ model, diff --git a/cocos/core/renderer/models/skinning-model.ts b/cocos/core/renderer/models/skinning-model.ts index e9321d6646..8d907bed8b 100644 --- a/cocos/core/renderer/models/skinning-model.ts +++ b/cocos/core/renderer/models/skinning-model.ts @@ -74,7 +74,7 @@ export class SkinningModel extends Model { } } - public attachToScene(scene: RenderScene) { + public attachToScene (scene: RenderScene) { super.attachToScene(scene); const texture = scene.root.dataPoolManager.jointsTexturePool.getDefaultJointsTexture(); this._jointsMedium.texture = texture; diff --git a/cocos/core/renderer/scene/camera.ts b/cocos/core/renderer/scene/camera.ts index aeac31537a..c6d3d47244 100644 --- a/cocos/core/renderer/scene/camera.ts +++ b/cocos/core/renderer/scene/camera.ts @@ -136,7 +136,7 @@ export class Camera { } - public initialize(info: ICameraInfo) { + public initialize (info: ICameraInfo) { this._name = info.name; this._node = info.node; this._proj = info.projection; @@ -150,7 +150,7 @@ export class Camera { }); this.changeTargetWindow(info.window); - console.log('Alloc Camera: ' + this._name + ' ' + this._width + ' x ' + this._height); + console.log('Created Camera: ' + this._name + ' ' + this._width + 'x' + this._height); } public destroy () { @@ -159,12 +159,14 @@ export class Camera { this._name = null; } - public attachToScene(scene: RenderScene) { + public attachToScene (scene: RenderScene) { this._scene = scene; + if (this._view) { this._view.enable(true); } } - public detachFromScene() { + public detachFromScene () { this._scene = null; + if (this._view) { this._view.enable(false); } } public resize (width: number, height: number) { @@ -423,21 +425,23 @@ export class Camera { set visibility (vis) { this._visibility = vis; - if (this._view) + if (this._view) { this._view.visibility = vis; + } } get visibility () { return this._visibility; } - get priority(): number { + get priority (): number { return this._view ? this._view.priority : -1; } set priority (val: number) { this._priority = val; - if (this._view) + if (this._view) { this._view.priority = this._priority; + } } set aperture (val: CameraAperture) { diff --git a/cocos/core/renderer/scene/directional-light.ts b/cocos/core/renderer/scene/directional-light.ts index c3bd1986df..592d0cae5c 100644 --- a/cocos/core/renderer/scene/directional-light.ts +++ b/cocos/core/renderer/scene/directional-light.ts @@ -1,7 +1,6 @@ import { Quat, Vec3 } from '../../math'; -import { INode } from '../../utils/interfaces'; +import { Ambient } from './ambient'; import { Light, LightType } from './light'; -import { RenderScene } from './render-scene'; const _forward = new Vec3(0, 0, -1); const _v3 = new Vec3(); @@ -10,7 +9,7 @@ const _qt = new Quat(); export class DirectionalLight extends Light { protected _dir: Vec3 = new Vec3(1.0, -1.0, -1.0); - protected _illum: number = 65000.0; + protected _illum: number = Ambient.SUN_ILLUM; set direction (dir: Vec3) { this._dir = dir; diff --git a/cocos/core/renderer/scene/light.ts b/cocos/core/renderer/scene/light.ts index 1e7e7c6e03..d5e4c314eb 100644 --- a/cocos/core/renderer/scene/light.ts +++ b/cocos/core/renderer/scene/light.ts @@ -1,7 +1,7 @@ import { Vec3 } from '../../math'; +import { TransformBit } from '../../scene-graph/node-enum'; import { INode } from '../../utils/interfaces'; import { RenderScene } from './render-scene'; -import { TransformBit } from '../../scene-graph/node-enum'; // Color temperature (in Kelvin) to RGB export function ColorTemperatureToRGB (rgb: Vec3, kelvin: number) { @@ -89,7 +89,7 @@ export class Light { return this._name; } - get scene() { + get scene () { return this._scene; } @@ -106,21 +106,21 @@ export class Light { this._type = LightType.UNKNOWN; } - public initialize(name: string, node: INode) { + public initialize (name: string, node: INode) { this._name = name; this._type = LightType.UNKNOWN; this._node = node; } - public attachToScene(scene: RenderScene) { + public attachToScene (scene: RenderScene) { this._scene = scene; } - public detachFromScene() { + public detachFromScene () { this._scene = null; } - public destroy() { + public destroy () { this._name = null; this._type = LightType.UNKNOWN; this._node = null; diff --git a/cocos/core/renderer/scene/model.ts b/cocos/core/renderer/scene/model.ts index d8b2e432a4..d606730210 100644 --- a/cocos/core/renderer/scene/model.ts +++ b/cocos/core/renderer/scene/model.ts @@ -172,7 +172,7 @@ export class Model { this._device = cc.director.root!.device; } - public initialize(node: INode) { + public initialize (node: INode) { this._transform = this._node = node; } @@ -202,12 +202,12 @@ export class Model { this._inited = false; } - public attachToScene(scene: RenderScene) { + public attachToScene (scene: RenderScene) { this._scene = scene; this._id = this._scene.generateModelId(); } - public detachFromScene() { + public detachFromScene () { this._scene = null; this._id = -1; } diff --git a/cocos/core/renderer/scene/planar-shadows.ts b/cocos/core/renderer/scene/planar-shadows.ts index 9a72c54ff0..5552c9ba9a 100644 --- a/cocos/core/renderer/scene/planar-shadows.ts +++ b/cocos/core/renderer/scene/planar-shadows.ts @@ -29,7 +29,7 @@ export class PlanarShadows { set enabled (enable: boolean) { this._enabled = enable; - this.updateDirLight(); + if (this._scene.mainLight) { this.updateDirLight(this._scene.mainLight); } this._cmdBuffs.clear(); } @@ -39,7 +39,7 @@ export class PlanarShadows { set normal (val: Vec3) { Vec3.copy(this._normal, val); - this.updateDirLight(); + if (this._scene.mainLight) { this.updateDirLight(this._scene.mainLight); } } get normal () { return this._normal; @@ -47,7 +47,7 @@ export class PlanarShadows { set distance (val: number) { this._distance = val; - this.updateDirLight(); + if (this._scene.mainLight) { this.updateDirLight(this._scene.mainLight); } } get distance () { return this._distance; @@ -128,7 +128,7 @@ export class PlanarShadows { this._globalBindings.buffer!.update(this.data); } - public updateDirLight (light: DirectionalLight = this._scene.mainLight) { + public updateDirLight (light: DirectionalLight) { light.node!.getWorldRotation(_qt); Vec3.transformQuat(_v3, _forward, _qt); const n = this._normal; const d = this._distance; @@ -158,7 +158,7 @@ export class PlanarShadows { public updateCommandBuffers (frstm: frustum) { this._cmdBuffs.clear(); - if (!this._scene.mainLight.enabled) { return; } + if (!this._scene.mainLight) { return; } for (const model of this._scene.models) { if (!model.enabled || !model.node || !model.castShadow) { continue; } if (model.worldBounds) { diff --git a/cocos/core/renderer/scene/render-scene.ts b/cocos/core/renderer/scene/render-scene.ts index 611bbc8cd9..26b9092225 100644 --- a/cocos/core/renderer/scene/render-scene.ts +++ b/cocos/core/renderer/scene/render-scene.ts @@ -57,11 +57,7 @@ export class RenderScene { return this._planarShadows; } - get defaultMainLightNode (): INode { - return this._defaultMainLightNode; - } - - get mainLight (): DirectionalLight { + get mainLight (): DirectionalLight | null { return this._mainLight; } @@ -119,19 +115,14 @@ export class RenderScene { private _ambient: Ambient; private _skybox: Skybox; private _planarShadows: PlanarShadows; - private _mainLight: DirectionalLight; - private _defaultMainLightNode: INode; + private _models: Model[] = []; private _sphereLights: SphereLight[] = []; private _spotLights: SpotLight[] = []; - private _models: Model[] = []; + private _mainLight: DirectionalLight | null = null; private _modelId: number = 0; constructor (root: Root) { this._root = root; - this._defaultMainLightNode = new Node('Main Light'); - this._mainLight = new DirectionalLight(); - this._mainLight.initialize('Main Light', this._defaultMainLightNode); - this._mainLight.illuminance = Ambient.SUN_ILLUM; this._ambient = new Ambient(this); this._skybox = new Skybox(this); this._planarShadows = new PlanarShadows(this); @@ -173,30 +164,40 @@ export class RenderScene { this._cameras.splice(0); } - public addSphereLight (sl:SphereLight) { - sl.attachToScene(this); - this._sphereLights.push(sl); + public setMainLight (dl: DirectionalLight) { + dl.attachToScene(this); + this._mainLight = dl; } - public removeSphereLight (light: SphereLight) { + public unsetMainLight (dl: DirectionalLight) { + dl.detachFromScene(); + this._mainLight = null; + } + + public addSphereLight (pl: SphereLight) { + pl.attachToScene(this); + this._sphereLights.push(pl); + } + + public removeSphereLight (pl: SphereLight) { for (let i = 0; i < this._sphereLights.length; ++i) { - if (this._sphereLights[i] === light) { - light.detachFromScene(); + if (this._sphereLights[i] === pl) { + pl.detachFromScene(); this._sphereLights.splice(i, 1); return; } } } - public addSpotLight (sl:SpotLight) { + public addSpotLight (sl: SpotLight) { sl.attachToScene(this); this._spotLights.push(sl); } - public removeSpotLight (light: SpotLight) { + public removeSpotLight (sl: SpotLight) { for (let i = 0; i < this._spotLights.length; ++i) { - if (this._spotLights[i] === light) { - light.detachFromScene(); + if (this._spotLights[i] === sl) { + sl.detachFromScene(); this._spotLights.splice(i, 1); return; } @@ -217,7 +218,7 @@ export class RenderScene { this._spotLights = []; } - public addModel (m:Model) { + public addModel (m: Model) { m.attachToScene(this); this._models.push(m); } diff --git a/cocos/core/root.ts b/cocos/core/root.ts index 1f33865293..2d5f1a841f 100644 --- a/cocos/core/root.ts +++ b/cocos/core/root.ts @@ -5,18 +5,18 @@ import { builtinResMgr } from './3d/builtin'; import { GFXDevice } from './gfx/device'; import { GFXWindow, IGFXWindowInfo } from './gfx/window'; +import { Pool } from './memop'; import { ForwardPipeline } from './pipeline/forward/forward-pipeline'; import { RenderPipeline } from './pipeline/render-pipeline'; import { IRenderViewInfo, RenderView } from './pipeline/render-view'; +import { Camera, Light, Model } from './renderer'; import { DataPoolManager } from './renderer/data-pool-manager'; -import { IRenderSceneInfo, RenderScene } from './renderer/scene/render-scene'; -import { UI } from './renderer/ui/ui'; -import { Model, Camera, Light } from './renderer'; -import { Pool } from './memop'; import { DirectionalLight } from './renderer/scene/directional-light'; +import { LightType } from './renderer/scene/light'; +import { IRenderSceneInfo, RenderScene } from './renderer/scene/render-scene'; import { SphereLight } from './renderer/scene/sphere-light'; import { SpotLight } from './renderer/scene/spot-light'; -import { LightType } from './renderer/scene/light'; +import { UI } from './renderer/ui/ui'; export let _createSceneFun; export let _createViewFun; @@ -189,9 +189,9 @@ export class Root { private _dataPoolMgr: DataPoolManager; private _scenes: RenderScene[] = []; private _views: RenderView[] = []; - private _modelPools: Map> = new Map>(); + private _modelPools: Map> = new Map>(); private _cameraPool: Pool | null = null; - private _lightPools: Map> = new Map>(); + private _lightPools: Map> = new Map>(); private _directLightPool: Pool | null = null; private _sphereLightPool: Pool | null = null; private _spotLightPool: Pool | null = null; @@ -214,7 +214,7 @@ export class Root { RenderScene.registerCreateFunc(this); RenderView.registerCreateFunc(this); - this._cameraPool = new Pool(() => new Camera, 4); + this._cameraPool = new Pool(() => new Camera(), 4); } /** @@ -350,11 +350,13 @@ export class Root { this._fpsTime = 0.0; } - this._views.sort((a: RenderView, b: RenderView) => { + const views = this._views; + views.sort((a: RenderView, b: RenderView) => { return a.priority - b.priority; }); - for (const view of this._views) { + for (let i = 0; i < views.length; i++) { + const view = views[i]; if (view.isEnable && (view.window && (view.window.isOffscreen || (!view.window.isOffscreen && (view.window === this._curWindow))))) { @@ -486,7 +488,7 @@ export class Root { this._views = []; } - public createModel(mClass: new () => T): T { + public createModel (mClass: new () => T): T { let p = this._modelPools.get(mClass); if (!p) { this._modelPools.set(mClass, new Pool(() => new mClass(), 10)); @@ -495,7 +497,7 @@ export class Root { return p.alloc(); } - public destroyModel(m: Model) { + public destroyModel (m: Model) { const p = this._modelPools.get(m.constructor); if (p) { p.free(m); @@ -506,11 +508,11 @@ export class Root { } } - public createCamera(): Camera { + public createCamera (): Camera { return this._cameraPool!.alloc(); } - public destroyCamera(c: Camera) { + public destroyCamera (c: Camera) { this._cameraPool!.free(c); c.destroy(); if (c.scene) { @@ -518,7 +520,7 @@ export class Root { } } - public createLight(lClass: new () => T): T { + public createLight (lClass: new () => T): T { let l = this._lightPools.get(lClass); if (!l) { this._lightPools.set(lClass, new Pool(() => new lClass(), 4)); @@ -527,7 +529,7 @@ export class Root { return l.alloc(); } - public destroyLight(l: Light) { + public destroyLight (l: Light) { const p = this._lightPools.get(l.constructor); l.destroy(); if (p) { From f47cea1422d8054605570c94a0f93418892b7edf Mon Sep 17 00:00:00 2001 From: Yun Hsiao Wu Date: Fri, 29 Nov 2019 13:26:34 +0800 Subject: [PATCH 10/21] better playground framework (#5805) * better playground framework * remove redundant memops * minor * linter * restore memops --- cocos/core/3d/builtin/effects.ts | 13 +- cocos/core/3d/framework/model-component.ts | 3 + cocos/core/event/callbacks-invoker.ts | 2 +- cocos/core/geom-utils/index.ts | 1 - cocos/core/geom-utils/octree.ts | 259 --------- cocos/core/gfx/webgl/webgl-command-buffer.ts | 2 +- .../core/gfx/webgl2/webgl2-command-buffer.ts | 2 +- cocos/core/index.ts | 8 +- cocos/core/memop/cached-array.ts | 26 +- cocos/core/memop/fixed-array.ts | 116 ---- cocos/core/memop/index.ts | 9 +- cocos/core/memop/linked-array.ts | 2 +- cocos/core/memop/pool.ts | 3 +- cocos/core/memop/recycle-pool.ts | 12 +- cocos/core/pipeline/render-pipeline.ts | 1 + cocos/core/renderer/scene/model.ts | 2 +- cocos/core/renderer/ui/render-data.ts | 4 +- cocos/core/renderer/ui/ui-material.ts | 2 +- cocos/core/renderer/ui/ui.ts | 2 +- cocos/core/scene-graph/scene-globals.ts | 2 +- cocos/particle/particle-utils.ts | 32 +- .../renderer/particle-system-renderer.ts | 26 +- cocos/particle/renderer/trail.ts | 46 +- cocos/ui/assembler/graphics/webgl/impl.ts | 2 +- exports/base.ts | 2 +- package-lock.json | 12 + package.json | 4 +- playground/audio.html | 163 ------ playground/cocos2d-x.png | Bin 20990 -> 0 bytes playground/{ => common}/camera.js | 0 .../{cubetexture.png => common/texture.png} | Bin playground/files.js | 12 - playground/gizmo.html | 177 ------ playground/index.html | 546 ++++-------------- playground/loadMaterial.html | 92 --- playground/planarShadow.html | 113 ---- playground/savePrimitivesAsWavefrontOBJ.html | 53 -- playground/shell.js | 152 +++++ playground/simple.html | 169 ------ playground/src/collision-detection.js | 209 +++++++ playground/src/custom-effect.js | 32 + playground/src/gizmo.js | 128 ++++ playground/src/planar-shadow.js | 51 ++ playground/src/save-primitive-objs.js | 19 + playground/src/simple.js | 116 ++++ playground/ui-render.html | 112 ---- playground/ui.html | 96 --- 47 files changed, 923 insertions(+), 1912 deletions(-) delete mode 100644 cocos/core/geom-utils/octree.ts delete mode 100644 cocos/core/memop/fixed-array.ts delete mode 100644 playground/audio.html delete mode 100644 playground/cocos2d-x.png rename playground/{ => common}/camera.js (100%) rename playground/{cubetexture.png => common/texture.png} (100%) delete mode 100644 playground/files.js delete mode 100644 playground/gizmo.html delete mode 100644 playground/loadMaterial.html delete mode 100644 playground/planarShadow.html delete mode 100644 playground/savePrimitivesAsWavefrontOBJ.html create mode 100644 playground/shell.js delete mode 100644 playground/simple.html create mode 100644 playground/src/collision-detection.js create mode 100644 playground/src/custom-effect.js create mode 100644 playground/src/gizmo.js create mode 100644 playground/src/planar-shadow.js create mode 100644 playground/src/save-primitive-objs.js create mode 100644 playground/src/simple.js delete mode 100644 playground/ui-render.html delete mode 100644 playground/ui.html diff --git a/cocos/core/3d/builtin/effects.ts b/cocos/core/3d/builtin/effects.ts index bdfe9609b5..1dabfb2837 100644 --- a/cocos/core/3d/builtin/effects.ts +++ b/cocos/core/3d/builtin/effects.ts @@ -60,6 +60,7 @@ export default [ }, "builtins": {"globals":{"blocks":[{"name":"CCGlobal", "defines":[]}], "samplers":[]}, "locals":{"blocks":[{"name":"CCLocal", "defines":[]}], "samplers":[]}}, "defines": [ + {"name":"CC_RENDER_MODE", "type":"number", "range":[0, 4]}, {"name":"CC_DRAW_WIRE_FRAME", "type":"boolean"}, {"name":"CC_USE_WORLD_SPACE", "type":"boolean"}, {"name":"CC_USE_HDR", "type":"boolean"} @@ -88,22 +89,18 @@ export default [ "shaders": [ { "name": "builtin-particle|particle-vs-legacy:lpvs_main|tinted-fs:add", - "hash": 3128424677, + "hash": 520861802, "glsl3": { - "vert": `\nprecision highp float;\nvec4 quaternionFromAxis (vec3 xAxis,vec3 yAxis,vec3 zAxis){\n mat3 m = mat3(xAxis,yAxis,zAxis);\n float trace = m[0][0] + m[1][1] + m[2][2];\n vec4 quat;\n if (trace > 0.) {\n float s = 0.5 / sqrt(trace + 1.0);\n quat.w = 0.25 / s;\n quat.x = (m[2][1] - m[1][2]) * s;\n quat.y = (m[0][2] - m[2][0]) * s;\n quat.z = (m[1][0] - m[0][1]) * s;\n } else if ((m[0][0] > m[1][1]) && (m[0][0] > m[2][2])) {\n float s = 2.0 * sqrt(1.0 + m[0][0] - m[1][1] - m[2][2]);\n quat.w = (m[2][1] - m[1][2]) / s;\n quat.x = 0.25 * s;\n quat.y = (m[0][1] + m[1][0]) / s;\n quat.z = (m[0][2] + m[2][0]) / s;\n } else if (m[1][1] > m[2][2]) {\n float s = 2.0 * sqrt(1.0 + m[1][1] - m[0][0] - m[2][2]);\n quat.w = (m[0][2] - m[2][0]) / s;\n quat.x = (m[0][1] + m[1][0]) / s;\n quat.y = 0.25 * s;\n quat.z = (m[1][2] + m[2][1]) / s;\n } else {\n float s = 2.0 * sqrt(1.0 + m[2][2] - m[0][0] - m[1][1]);\n quat.w = (m[1][0] - m[0][1]) / s;\n quat.x = (m[0][2] + m[2][0]) / s;\n quat.y = (m[1][2] + m[2][1]) / s;\n quat.z = 0.25 * s;\n }\n float len = quat.x * quat.x + quat.y * quat.y + quat.z * quat.z + quat.w * quat.w;\n if (len > 0.) {\n len = 1. / sqrt(len);\n quat.x = quat.x * len;\n quat.y = quat.y * len;\n quat.z = quat.z * len;\n quat.w = quat.w * len;\n }\n return quat;\n}\nvec4 quaternionFromEuler (vec3 angle){\n float x = angle.x / 2.;\n float y = angle.y / 2.;\n float z = angle.z / 2.;\n float sx = sin(x);\n float cx = cos(x);\n float sy = sin(y);\n float cy = cos(y);\n float sz = sin(z);\n float cz = cos(z);\n vec4 quat = vec4(0);\n quat.x = sx * cy * cz + cx * sy * sz;\n quat.y = cx * sy * cz + sx * cy * sz;\n quat.z = cx * cy * sz - sx * sy * cz;\n quat.w = cx * cy * cz - sx * sy * sz;\n return quat;\n}\nmat4 matrixFromRT (vec4 q, vec3 p){\n float x2 = q.x + q.x;\n float y2 = q.y + q.y;\n float z2 = q.z + q.z;\n float xx = q.x * x2;\n float xy = q.x * y2;\n float xz = q.x * z2;\n float yy = q.y * y2;\n float yz = q.y * z2;\n float zz = q.z * z2;\n float wx = q.w * x2;\n float wy = q.w * y2;\n float wz = q.w * z2;\n return mat4(\n 1. - (yy + zz), xy + wz, xz - wy, 0,\n xy - wz, 1. - (xx + zz), yz + wx, 0,\n xz + wy, yz - wx, 1. - (xx + yy), 0,\n p.x, p.y, p.z, 1\n );\n}\nmat4 matFromRTS (vec4 q, vec3 t, vec3 s){\n float x = q.x, y = q.y, z = q.z, w = q.w;\n float x2 = x + x;\n float y2 = y + y;\n float z2 = z + z;\n float xx = x * x2;\n float xy = x * y2;\n float xz = x * z2;\n float yy = y * y2;\n float yz = y * z2;\n float zz = z * z2;\n float wx = w * x2;\n float wy = w * y2;\n float wz = w * z2;\n float sx = s.x;\n float sy = s.y;\n float sz = s.z;\n return mat4((1. - (yy + zz)) * sx, (xy + wz) * sx, (xz - wy) * sx, 0,\n (xy - wz) * sy, (1. - (xx + zz)) * sy, (yz + wx) * sy, 0,\n (xz + wy) * sz, (yz - wx) * sz, (1. - (xx + yy)) * sz, 0,\n t.x, t.y, t.z, 1);\n}\nvec4 quatMultiply (vec4 a, vec4 b){\n vec4 quat;\n quat.x = a.x * b.w + a.w * b.x + a.y * b.z - a.z * b.y;\n quat.y = a.y * b.w + a.w * b.y + a.z * b.x - a.x * b.z;\n quat.z = a.z * b.w + a.w * b.z + a.x * b.y - a.y * b.x;\n quat.w = a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z;\n return quat;\n}\nvoid rotateVecFromQuat (inout vec3 v, vec4 q){\n float ix = q.w * v.x + q.y * v.z - q.z * v.y;\n float iy = q.w * v.y + q.z * v.x - q.x * v.z;\n float iz = q.w * v.z + q.x * v.y - q.y * v.x;\n float iw = -q.x * v.x - q.y * v.y - q.z * v.z;\n v.x = ix * q.w + iw * -q.x + iy * -q.z - iz * -q.y;\n v.y = iy * q.w + iw * -q.y + iz * -q.x - ix * -q.z;\n v.z = iz * q.w + iw * -q.z + ix * -q.y - iy * -q.x;\n}\nvec3 rotateInLocalSpace (vec3 pos, vec3 xAxis, vec3 yAxis, vec3 zAxis, vec4 q){\n vec4 viewQuat = quaternionFromAxis(xAxis, yAxis, zAxis);\n vec4 rotQuat = quatMultiply(viewQuat, q);\n rotateVecFromQuat(pos, rotQuat);\n return pos;\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}\nuniform Constants {\n vec4 mainTiling_Offset;\n vec4 frameTile_velLenScale;\n vec4 scale;\n};\nuniform CCGlobal {\n vec4 cc_time;\n vec4 cc_screenSize;\n vec4 cc_screenScale;\n vec4 cc_nativeSize;\n highp mat4 cc_matView;\n mat4 cc_matViewInv;\n mat4 cc_matProj;\n mat4 cc_matProjInv;\n mat4 cc_matViewProj;\n mat4 cc_matViewProjInv;\n vec4 cc_cameraPos;\n vec4 cc_exposure;\n vec4 cc_mainLitDir;\n vec4 cc_mainLitColor;\n vec4 cc_ambientSky;\n vec4 cc_ambientGround;\n};\nuniform CCLocal {\n highp mat4 cc_matWorld;\n highp mat4 cc_matWorldIT;\n};\nout vec2 uv;\nout vec4 color;\nvoid computeVertPos (inout vec4 pos, vec2 vertOffset, vec4 q, vec3 s\n#if CC_USE_BILLBOARD || CC_USE_VERTICAL_BILLBOARD\n , mat4 viewInv\n#endif\n#if CC_USE_STRETCHED_BILLBOARD\n , vec3 eye\n , vec4 velocity\n , float velocityScale\n , float lengthScale\n , float xIndex\n#endif\n) {\n#if CC_USE_BILLBOARD\n vec3 viewSpaceVert = vec3(vertOffset.x * s.x, vertOffset.y * s.y, 0.);\n vec3 camX = normalize(vec3(viewInv[0][0], viewInv[1][0], viewInv[2][0]));\n vec3 camY = normalize(vec3(viewInv[0][1], viewInv[1][1], viewInv[2][1]));\n vec3 camZ = normalize(vec3(viewInv[0][2], viewInv[1][2], viewInv[2][2]));\n pos.xyz += rotateInLocalSpace(viewSpaceVert, camX, camY, camZ, q);\n#elif CC_USE_STRETCHED_BILLBOARD\n vec3 camRight = normalize(cross(pos.xyz - eye, velocity.xyz)) * s.x;\n vec3 camUp = velocity.xyz * velocityScale + normalize(velocity.xyz) * lengthScale * s.y;\n pos.xyz += (camRight * abs(vertOffset.x) * sign(vertOffset.y)) - camUp * xIndex;\n#elif CC_USE_HORIZONTAL_BILLBOARD\n vec3 viewSpaceVert = vec3(vertOffset.x * s.x, vertOffset.y * s.y, 0.);\n vec3 camX = vec3(1, 0, 0);\n vec3 camY = vec3(0, 0, -1);\n pos.xyz += rotateInLocalSpace(viewSpaceVert, camX, camY, cross(camX, camY), q);\n#elif CC_USE_VERTICAL_BILLBOARD\n vec2 viewSpaceVert = vec2(vertOffset.x * s.x, vertOffset.y * s.y);\n rotateCorner(viewSpaceVert, q.z);\n vec3 camX = normalize(vec3(cc_matView[0][0], cc_matView[1][0], cc_matView[2][0]));\n vec3 camY = vec3(0, 1, 0);\n vec3 offset = camX * viewSpaceVert.x + camY * viewSpaceVert.y;\n pos.xyz += offset;\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#if !CC_USE_MESH\n vertIndex.y = 1. - vertIndex.y;\n#endif\n return (aniUV.xy + vertIndex) / vec2(frameTile.x, frameTile.y);\n}\nin vec3 a_position;\nin vec3 a_texCoord;\nin vec3 a_texCoord1;\nin vec3 a_texCoord2;\nin vec4 a_color;\n#if CC_USE_MESH\n in vec3 a_texCoord3;\n in vec3 a_normal;\n in vec4 a_color1;\n#elif CC_USE_STRETCHED_BILLBOARD\n in vec3 a_color1;\n#endif\nvec4 lpvs_main () {\n vec3 compScale = scale.xyz * a_texCoord1;\n vec4 pos = vec4(a_position, 1);\n #if CC_USE_STRETCHED_BILLBOARD\n vec4 velocity = vec4(a_color1.xyz, 0);\n #endif\n #if !CC_USE_WORLD_SPACE\n pos = cc_matWorld * pos;\n #if CC_USE_STRETCHED_BILLBOARD\n velocity = cc_matWorld * velocity;\n #endif\n #endif\n #if !CC_USE_MESH\n vec2 cornerOffset = vec2((a_texCoord.xy - 0.5));\n #if CC_USE_BILLBOARD\n vec3 rotEuler = a_texCoord2;\n #elif CC_USE_STRETCHED_BILLBOARD\n vec3 rotEuler = vec3(0.);\n #else\n vec3 rotEuler = vec3(0., 0., a_texCoord2.z);\n #endif\n computeVertPos(pos, cornerOffset, quaternionFromEuler(rotEuler), compScale\n #if CC_USE_BILLBOARD || CC_USE_VERTICAL_BILLBOARD\n , cc_matViewInv\n #endif\n #if CC_USE_STRETCHED_BILLBOARD\n , cc_cameraPos.xyz\n , velocity\n , frameTile_velLenScale.z\n , frameTile_velLenScale.w\n , a_texCoord.x\n #endif\n );\n color = a_color;\n #else\n mat4 xformNoScale = matrixFromRT(quaternionFromEuler(a_texCoord2), pos.xyz);\n mat4 xform = matFromRTS(quaternionFromEuler(a_texCoord2), pos.xyz, compScale);\n pos = xform * vec4(a_texCoord3, 1);\n vec4 normal = xformNoScale * vec4(a_normal, 0);\n color = a_color * a_color1;\n #endif\n uv = computeUV(a_texCoord.z, a_texCoord.xy, frameTile_velLenScale.xy) * mainTiling_Offset.xy + mainTiling_Offset.zw;\n pos = cc_matViewProj * pos;\n return pos;\n}\nvoid main() { gl_Position = lpvs_main(); }`, + "vert": `\nprecision highp float;\nvec4 quaternionFromAxis (vec3 xAxis,vec3 yAxis,vec3 zAxis){\n mat3 m = mat3(xAxis,yAxis,zAxis);\n float trace = m[0][0] + m[1][1] + m[2][2];\n vec4 quat;\n if (trace > 0.) {\n float s = 0.5 / sqrt(trace + 1.0);\n quat.w = 0.25 / s;\n quat.x = (m[2][1] - m[1][2]) * s;\n quat.y = (m[0][2] - m[2][0]) * s;\n quat.z = (m[1][0] - m[0][1]) * s;\n } else if ((m[0][0] > m[1][1]) && (m[0][0] > m[2][2])) {\n float s = 2.0 * sqrt(1.0 + m[0][0] - m[1][1] - m[2][2]);\n quat.w = (m[2][1] - m[1][2]) / s;\n quat.x = 0.25 * s;\n quat.y = (m[0][1] + m[1][0]) / s;\n quat.z = (m[0][2] + m[2][0]) / s;\n } else if (m[1][1] > m[2][2]) {\n float s = 2.0 * sqrt(1.0 + m[1][1] - m[0][0] - m[2][2]);\n quat.w = (m[0][2] - m[2][0]) / s;\n quat.x = (m[0][1] + m[1][0]) / s;\n quat.y = 0.25 * s;\n quat.z = (m[1][2] + m[2][1]) / s;\n } else {\n float s = 2.0 * sqrt(1.0 + m[2][2] - m[0][0] - m[1][1]);\n quat.w = (m[1][0] - m[0][1]) / s;\n quat.x = (m[0][2] + m[2][0]) / s;\n quat.y = (m[1][2] + m[2][1]) / s;\n quat.z = 0.25 * s;\n }\n float len = quat.x * quat.x + quat.y * quat.y + quat.z * quat.z + quat.w * quat.w;\n if (len > 0.) {\n len = 1. / sqrt(len);\n quat.x = quat.x * len;\n quat.y = quat.y * len;\n quat.z = quat.z * len;\n quat.w = quat.w * len;\n }\n return quat;\n}\nvec4 quaternionFromEuler (vec3 angle){\n float x = angle.x / 2.;\n float y = angle.y / 2.;\n float z = angle.z / 2.;\n float sx = sin(x);\n float cx = cos(x);\n float sy = sin(y);\n float cy = cos(y);\n float sz = sin(z);\n float cz = cos(z);\n vec4 quat = vec4(0);\n quat.x = sx * cy * cz + cx * sy * sz;\n quat.y = cx * sy * cz + sx * cy * sz;\n quat.z = cx * cy * sz - sx * sy * cz;\n quat.w = cx * cy * cz - sx * sy * sz;\n return quat;\n}\nmat4 matrixFromRT (vec4 q, vec3 p){\n float x2 = q.x + q.x;\n float y2 = q.y + q.y;\n float z2 = q.z + q.z;\n float xx = q.x * x2;\n float xy = q.x * y2;\n float xz = q.x * z2;\n float yy = q.y * y2;\n float yz = q.y * z2;\n float zz = q.z * z2;\n float wx = q.w * x2;\n float wy = q.w * y2;\n float wz = q.w * z2;\n return mat4(\n 1. - (yy + zz), xy + wz, xz - wy, 0,\n xy - wz, 1. - (xx + zz), yz + wx, 0,\n xz + wy, yz - wx, 1. - (xx + yy), 0,\n p.x, p.y, p.z, 1\n );\n}\nmat4 matFromRTS (vec4 q, vec3 t, vec3 s){\n float x = q.x, y = q.y, z = q.z, w = q.w;\n float x2 = x + x;\n float y2 = y + y;\n float z2 = z + z;\n float xx = x * x2;\n float xy = x * y2;\n float xz = x * z2;\n float yy = y * y2;\n float yz = y * z2;\n float zz = z * z2;\n float wx = w * x2;\n float wy = w * y2;\n float wz = w * z2;\n float sx = s.x;\n float sy = s.y;\n float sz = s.z;\n return mat4((1. - (yy + zz)) * sx, (xy + wz) * sx, (xz - wy) * sx, 0,\n (xy - wz) * sy, (1. - (xx + zz)) * sy, (yz + wx) * sy, 0,\n (xz + wy) * sz, (yz - wx) * sz, (1. - (xx + yy)) * sz, 0,\n t.x, t.y, t.z, 1);\n}\nvec4 quatMultiply (vec4 a, vec4 b){\n vec4 quat;\n quat.x = a.x * b.w + a.w * b.x + a.y * b.z - a.z * b.y;\n quat.y = a.y * b.w + a.w * b.y + a.z * b.x - a.x * b.z;\n quat.z = a.z * b.w + a.w * b.z + a.x * b.y - a.y * b.x;\n quat.w = a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z;\n return quat;\n}\nvoid rotateVecFromQuat (inout vec3 v, vec4 q){\n float ix = q.w * v.x + q.y * v.z - q.z * v.y;\n float iy = q.w * v.y + q.z * v.x - q.x * v.z;\n float iz = q.w * v.z + q.x * v.y - q.y * v.x;\n float iw = -q.x * v.x - q.y * v.y - q.z * v.z;\n v.x = ix * q.w + iw * -q.x + iy * -q.z - iz * -q.y;\n v.y = iy * q.w + iw * -q.y + iz * -q.x - ix * -q.z;\n v.z = iz * q.w + iw * -q.z + ix * -q.y - iy * -q.x;\n}\nvec3 rotateInLocalSpace (vec3 pos, vec3 xAxis, vec3 yAxis, vec3 zAxis, vec4 q){\n vec4 viewQuat = quaternionFromAxis(xAxis, yAxis, zAxis);\n vec4 rotQuat = quatMultiply(viewQuat, q);\n rotateVecFromQuat(pos, rotQuat);\n return pos;\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}\nuniform Constants {\n vec4 mainTiling_Offset;\n vec4 frameTile_velLenScale;\n vec4 scale;\n};\nuniform CCGlobal {\n vec4 cc_time;\n vec4 cc_screenSize;\n vec4 cc_screenScale;\n vec4 cc_nativeSize;\n highp mat4 cc_matView;\n mat4 cc_matViewInv;\n mat4 cc_matProj;\n mat4 cc_matProjInv;\n mat4 cc_matViewProj;\n mat4 cc_matViewProjInv;\n vec4 cc_cameraPos;\n vec4 cc_exposure;\n vec4 cc_mainLitDir;\n vec4 cc_mainLitColor;\n vec4 cc_ambientSky;\n vec4 cc_ambientGround;\n};\nuniform CCLocal {\n highp mat4 cc_matWorld;\n highp mat4 cc_matWorldIT;\n};\nout vec2 uv;\nout vec4 color;\nvoid computeVertPos (inout vec4 pos, vec2 vertOffset, vec4 q, vec3 s\n#if CC_RENDER_MODE == 0 || CC_RENDER_MODE == 3\n , mat4 viewInv\n#endif\n#if CC_RENDER_MODE == 1\n , vec3 eye\n , vec4 velocity\n , float velocityScale\n , float lengthScale\n , float xIndex\n#endif\n) {\n#if CC_RENDER_MODE == 0\n vec3 viewSpaceVert = vec3(vertOffset.x * s.x, vertOffset.y * s.y, 0.);\n vec3 camX = normalize(vec3(viewInv[0][0], viewInv[1][0], viewInv[2][0]));\n vec3 camY = normalize(vec3(viewInv[0][1], viewInv[1][1], viewInv[2][1]));\n vec3 camZ = normalize(vec3(viewInv[0][2], viewInv[1][2], viewInv[2][2]));\n pos.xyz += rotateInLocalSpace(viewSpaceVert, camX, camY, camZ, q);\n#elif CC_RENDER_MODE == 1\n vec3 camRight = normalize(cross(pos.xyz - eye, velocity.xyz)) * s.x;\n vec3 camUp = velocity.xyz * velocityScale + normalize(velocity.xyz) * lengthScale * s.y;\n pos.xyz += (camRight * abs(vertOffset.x) * sign(vertOffset.y)) - camUp * xIndex;\n#elif CC_RENDER_MODE == 2\n vec3 viewSpaceVert = vec3(vertOffset.x * s.x, vertOffset.y * s.y, 0.);\n vec3 camX = vec3(1, 0, 0);\n vec3 camY = vec3(0, 0, -1);\n pos.xyz += rotateInLocalSpace(viewSpaceVert, camX, camY, cross(camX, camY), q);\n#elif CC_RENDER_MODE == 3\n vec2 viewSpaceVert = vec2(vertOffset.x * s.x, vertOffset.y * s.y);\n rotateCorner(viewSpaceVert, q.z);\n vec3 camX = normalize(vec3(cc_matView[0][0], cc_matView[1][0], cc_matView[2][0]));\n vec3 camY = vec3(0, 1, 0);\n vec3 offset = camX * viewSpaceVert.x + camY * viewSpaceVert.y;\n pos.xyz += offset;\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#if CC_RENDER_MODE != 4\n vertIndex.y = 1. - vertIndex.y;\n#endif\n return (aniUV.xy + vertIndex) / vec2(frameTile.x, frameTile.y);\n}\nin vec3 a_position;\nin vec3 a_texCoord;\nin vec3 a_texCoord1;\nin vec3 a_texCoord2;\nin vec4 a_color;\n#if CC_RENDER_MODE == 1\n in vec3 a_color1;\n#endif\n#if CC_RENDER_MODE == 4\n in vec3 a_texCoord3;\n in vec3 a_normal;\n in vec4 a_color1;\n#endif\nvec4 lpvs_main () {\n vec3 compScale = scale.xyz * a_texCoord1;\n vec4 pos = vec4(a_position, 1);\n #if CC_RENDER_MODE == 1\n vec4 velocity = vec4(a_color1.xyz, 0);\n #endif\n #if !CC_USE_WORLD_SPACE\n pos = cc_matWorld * pos;\n #if CC_RENDER_MODE == 1\n velocity = cc_matWorld * velocity;\n #endif\n #endif\n #if CC_RENDER_MODE != 4\n vec2 cornerOffset = vec2((a_texCoord.xy - 0.5));\n #if CC_RENDER_MODE == 0\n vec3 rotEuler = a_texCoord2;\n #elif CC_RENDER_MODE == 1\n vec3 rotEuler = vec3(0.);\n #else\n vec3 rotEuler = vec3(0., 0., a_texCoord2.z);\n #endif\n computeVertPos(pos, cornerOffset, quaternionFromEuler(rotEuler), compScale\n #if CC_RENDER_MODE == 0 || CC_RENDER_MODE == 3\n , cc_matViewInv\n #endif\n #if CC_RENDER_MODE == 1\n , cc_cameraPos.xyz\n , velocity\n , frameTile_velLenScale.z\n , frameTile_velLenScale.w\n , a_texCoord.x\n #endif\n );\n color = a_color;\n #else\n mat4 xformNoScale = matrixFromRT(quaternionFromEuler(a_texCoord2), pos.xyz);\n mat4 xform = matFromRTS(quaternionFromEuler(a_texCoord2), pos.xyz, compScale);\n pos = xform * vec4(a_texCoord3, 1);\n vec4 normal = xformNoScale * vec4(a_normal, 0);\n color = a_color * a_color1;\n #endif\n uv = computeUV(a_texCoord.z, a_texCoord.xy, frameTile_velLenScale.xy) * mainTiling_Offset.xy + mainTiling_Offset.zw;\n pos = cc_matViewProj * pos;\n return pos;\n}\nvoid main() { gl_Position = lpvs_main(); }`, "frag": `\nprecision highp float;\nuniform CCGlobal {\n vec4 cc_time;\n vec4 cc_screenSize;\n vec4 cc_screenScale;\n vec4 cc_nativeSize;\n highp mat4 cc_matView;\n mat4 cc_matViewInv;\n mat4 cc_matProj;\n mat4 cc_matProjInv;\n mat4 cc_matViewProj;\n mat4 cc_matViewProjInv;\n vec4 cc_cameraPos;\n vec4 cc_exposure;\n vec4 cc_mainLitDir;\n vec4 cc_mainLitColor;\n vec4 cc_ambientSky;\n vec4 cc_ambientGround;\n};\nvec3 SRGBToLinear (vec3 gamma) {\n return gamma * gamma;\n}\nvec4 CCFragOutput (vec4 color) {\n #if CC_USE_HDR\n color.rgb = mix(color.rgb, SRGBToLinear(color.rgb) * cc_exposure.w, vec3(cc_exposure.z));\n #endif\n return color;\n}\nin vec2 uv;\nin vec4 color;\nuniform sampler2D mainTexture;\nuniform FragConstants {\n vec4 tintColor;\n};\nvec4 add () {\n vec4 col = 2.0 * color * tintColor * texture(mainTexture, uv);\n return CCFragOutput(col);\n}\nout vec4 cc_FragColor;\nvoid main() { cc_FragColor = add(); }` }, "glsl1": { - "vert": `\nprecision highp float;\nvec4 quaternionFromAxis (vec3 xAxis,vec3 yAxis,vec3 zAxis){\n mat3 m = mat3(xAxis,yAxis,zAxis);\n float trace = m[0][0] + m[1][1] + m[2][2];\n vec4 quat;\n if (trace > 0.) {\n float s = 0.5 / sqrt(trace + 1.0);\n quat.w = 0.25 / s;\n quat.x = (m[2][1] - m[1][2]) * s;\n quat.y = (m[0][2] - m[2][0]) * s;\n quat.z = (m[1][0] - m[0][1]) * s;\n } else if ((m[0][0] > m[1][1]) && (m[0][0] > m[2][2])) {\n float s = 2.0 * sqrt(1.0 + m[0][0] - m[1][1] - m[2][2]);\n quat.w = (m[2][1] - m[1][2]) / s;\n quat.x = 0.25 * s;\n quat.y = (m[0][1] + m[1][0]) / s;\n quat.z = (m[0][2] + m[2][0]) / s;\n } else if (m[1][1] > m[2][2]) {\n float s = 2.0 * sqrt(1.0 + m[1][1] - m[0][0] - m[2][2]);\n quat.w = (m[0][2] - m[2][0]) / s;\n quat.x = (m[0][1] + m[1][0]) / s;\n quat.y = 0.25 * s;\n quat.z = (m[1][2] + m[2][1]) / s;\n } else {\n float s = 2.0 * sqrt(1.0 + m[2][2] - m[0][0] - m[1][1]);\n quat.w = (m[1][0] - m[0][1]) / s;\n quat.x = (m[0][2] + m[2][0]) / s;\n quat.y = (m[1][2] + m[2][1]) / s;\n quat.z = 0.25 * s;\n }\n float len = quat.x * quat.x + quat.y * quat.y + quat.z * quat.z + quat.w * quat.w;\n if (len > 0.) {\n len = 1. / sqrt(len);\n quat.x = quat.x * len;\n quat.y = quat.y * len;\n quat.z = quat.z * len;\n quat.w = quat.w * len;\n }\n return quat;\n}\nvec4 quaternionFromEuler (vec3 angle){\n float x = angle.x / 2.;\n float y = angle.y / 2.;\n float z = angle.z / 2.;\n float sx = sin(x);\n float cx = cos(x);\n float sy = sin(y);\n float cy = cos(y);\n float sz = sin(z);\n float cz = cos(z);\n vec4 quat = vec4(0);\n quat.x = sx * cy * cz + cx * sy * sz;\n quat.y = cx * sy * cz + sx * cy * sz;\n quat.z = cx * cy * sz - sx * sy * cz;\n quat.w = cx * cy * cz - sx * sy * sz;\n return quat;\n}\nmat4 matrixFromRT (vec4 q, vec3 p){\n float x2 = q.x + q.x;\n float y2 = q.y + q.y;\n float z2 = q.z + q.z;\n float xx = q.x * x2;\n float xy = q.x * y2;\n float xz = q.x * z2;\n float yy = q.y * y2;\n float yz = q.y * z2;\n float zz = q.z * z2;\n float wx = q.w * x2;\n float wy = q.w * y2;\n float wz = q.w * z2;\n return mat4(\n 1. - (yy + zz), xy + wz, xz - wy, 0,\n xy - wz, 1. - (xx + zz), yz + wx, 0,\n xz + wy, yz - wx, 1. - (xx + yy), 0,\n p.x, p.y, p.z, 1\n );\n}\nmat4 matFromRTS (vec4 q, vec3 t, vec3 s){\n float x = q.x, y = q.y, z = q.z, w = q.w;\n float x2 = x + x;\n float y2 = y + y;\n float z2 = z + z;\n float xx = x * x2;\n float xy = x * y2;\n float xz = x * z2;\n float yy = y * y2;\n float yz = y * z2;\n float zz = z * z2;\n float wx = w * x2;\n float wy = w * y2;\n float wz = w * z2;\n float sx = s.x;\n float sy = s.y;\n float sz = s.z;\n return mat4((1. - (yy + zz)) * sx, (xy + wz) * sx, (xz - wy) * sx, 0,\n (xy - wz) * sy, (1. - (xx + zz)) * sy, (yz + wx) * sy, 0,\n (xz + wy) * sz, (yz - wx) * sz, (1. - (xx + yy)) * sz, 0,\n t.x, t.y, t.z, 1);\n}\nvec4 quatMultiply (vec4 a, vec4 b){\n vec4 quat;\n quat.x = a.x * b.w + a.w * b.x + a.y * b.z - a.z * b.y;\n quat.y = a.y * b.w + a.w * b.y + a.z * b.x - a.x * b.z;\n quat.z = a.z * b.w + a.w * b.z + a.x * b.y - a.y * b.x;\n quat.w = a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z;\n return quat;\n}\nvoid rotateVecFromQuat (inout vec3 v, vec4 q){\n float ix = q.w * v.x + q.y * v.z - q.z * v.y;\n float iy = q.w * v.y + q.z * v.x - q.x * v.z;\n float iz = q.w * v.z + q.x * v.y - q.y * v.x;\n float iw = -q.x * v.x - q.y * v.y - q.z * v.z;\n v.x = ix * q.w + iw * -q.x + iy * -q.z - iz * -q.y;\n v.y = iy * q.w + iw * -q.y + iz * -q.x - ix * -q.z;\n v.z = iz * q.w + iw * -q.z + ix * -q.y - iy * -q.x;\n}\nvec3 rotateInLocalSpace (vec3 pos, vec3 xAxis, vec3 yAxis, vec3 zAxis, vec4 q){\n vec4 viewQuat = quaternionFromAxis(xAxis, yAxis, zAxis);\n vec4 rotQuat = quatMultiply(viewQuat, q);\n rotateVecFromQuat(pos, rotQuat);\n return pos;\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}\nuniform vec4 mainTiling_Offset;\nuniform vec4 frameTile_velLenScale;\nuniform vec4 scale;\nuniform highp mat4 cc_matView;\nuniform mat4 cc_matViewInv;\nuniform mat4 cc_matViewProj;\nuniform vec4 cc_cameraPos;\nuniform highp mat4 cc_matWorld;\nvarying vec2 uv;\nvarying vec4 color;\nvoid computeVertPos (inout vec4 pos, vec2 vertOffset, vec4 q, vec3 s\n#if CC_USE_BILLBOARD || CC_USE_VERTICAL_BILLBOARD\n , mat4 viewInv\n#endif\n#if CC_USE_STRETCHED_BILLBOARD\n , vec3 eye\n , vec4 velocity\n , float velocityScale\n , float lengthScale\n , float xIndex\n#endif\n) {\n#if CC_USE_BILLBOARD\n vec3 viewSpaceVert = vec3(vertOffset.x * s.x, vertOffset.y * s.y, 0.);\n vec3 camX = normalize(vec3(viewInv[0][0], viewInv[1][0], viewInv[2][0]));\n vec3 camY = normalize(vec3(viewInv[0][1], viewInv[1][1], viewInv[2][1]));\n vec3 camZ = normalize(vec3(viewInv[0][2], viewInv[1][2], viewInv[2][2]));\n pos.xyz += rotateInLocalSpace(viewSpaceVert, camX, camY, camZ, q);\n#elif CC_USE_STRETCHED_BILLBOARD\n vec3 camRight = normalize(cross(pos.xyz - eye, velocity.xyz)) * s.x;\n vec3 camUp = velocity.xyz * velocityScale + normalize(velocity.xyz) * lengthScale * s.y;\n pos.xyz += (camRight * abs(vertOffset.x) * sign(vertOffset.y)) - camUp * xIndex;\n#elif CC_USE_HORIZONTAL_BILLBOARD\n vec3 viewSpaceVert = vec3(vertOffset.x * s.x, vertOffset.y * s.y, 0.);\n vec3 camX = vec3(1, 0, 0);\n vec3 camY = vec3(0, 0, -1);\n pos.xyz += rotateInLocalSpace(viewSpaceVert, camX, camY, cross(camX, camY), q);\n#elif CC_USE_VERTICAL_BILLBOARD\n vec2 viewSpaceVert = vec2(vertOffset.x * s.x, vertOffset.y * s.y);\n rotateCorner(viewSpaceVert, q.z);\n vec3 camX = normalize(vec3(cc_matView[0][0], cc_matView[1][0], cc_matView[2][0]));\n vec3 camY = vec3(0, 1, 0);\n vec3 offset = camX * viewSpaceVert.x + camY * viewSpaceVert.y;\n pos.xyz += offset;\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#if !CC_USE_MESH\n vertIndex.y = 1. - vertIndex.y;\n#endif\n return (aniUV.xy + vertIndex) / vec2(frameTile.x, frameTile.y);\n}\nattribute vec3 a_position;\nattribute vec3 a_texCoord;\nattribute vec3 a_texCoord1;\nattribute vec3 a_texCoord2;\nattribute vec4 a_color;\n#if CC_USE_MESH\n attribute vec3 a_texCoord3;\n attribute vec3 a_normal;\n attribute vec4 a_color1;\n#elif CC_USE_STRETCHED_BILLBOARD\n attribute vec3 a_color1;\n#endif\nvec4 lpvs_main () {\n vec3 compScale = scale.xyz * a_texCoord1;\n vec4 pos = vec4(a_position, 1);\n #if CC_USE_STRETCHED_BILLBOARD\n vec4 velocity = vec4(a_color1.xyz, 0);\n #endif\n #if !CC_USE_WORLD_SPACE\n pos = cc_matWorld * pos;\n #if CC_USE_STRETCHED_BILLBOARD\n velocity = cc_matWorld * velocity;\n #endif\n #endif\n #if !CC_USE_MESH\n vec2 cornerOffset = vec2((a_texCoord.xy - 0.5));\n #if CC_USE_BILLBOARD\n vec3 rotEuler = a_texCoord2;\n #elif CC_USE_STRETCHED_BILLBOARD\n vec3 rotEuler = vec3(0.);\n #else\n vec3 rotEuler = vec3(0., 0., a_texCoord2.z);\n #endif\n computeVertPos(pos, cornerOffset, quaternionFromEuler(rotEuler), compScale\n #if CC_USE_BILLBOARD || CC_USE_VERTICAL_BILLBOARD\n , cc_matViewInv\n #endif\n #if CC_USE_STRETCHED_BILLBOARD\n , cc_cameraPos.xyz\n , velocity\n , frameTile_velLenScale.z\n , frameTile_velLenScale.w\n , a_texCoord.x\n #endif\n );\n color = a_color;\n #else\n mat4 xformNoScale = matrixFromRT(quaternionFromEuler(a_texCoord2), pos.xyz);\n mat4 xform = matFromRTS(quaternionFromEuler(a_texCoord2), pos.xyz, compScale);\n pos = xform * vec4(a_texCoord3, 1);\n vec4 normal = xformNoScale * vec4(a_normal, 0);\n color = a_color * a_color1;\n #endif\n uv = computeUV(a_texCoord.z, a_texCoord.xy, frameTile_velLenScale.xy) * mainTiling_Offset.xy + mainTiling_Offset.zw;\n pos = cc_matViewProj * pos;\n return pos;\n}\nvoid main() { gl_Position = lpvs_main(); }`, + "vert": `\nprecision highp float;\nvec4 quaternionFromAxis (vec3 xAxis,vec3 yAxis,vec3 zAxis){\n mat3 m = mat3(xAxis,yAxis,zAxis);\n float trace = m[0][0] + m[1][1] + m[2][2];\n vec4 quat;\n if (trace > 0.) {\n float s = 0.5 / sqrt(trace + 1.0);\n quat.w = 0.25 / s;\n quat.x = (m[2][1] - m[1][2]) * s;\n quat.y = (m[0][2] - m[2][0]) * s;\n quat.z = (m[1][0] - m[0][1]) * s;\n } else if ((m[0][0] > m[1][1]) && (m[0][0] > m[2][2])) {\n float s = 2.0 * sqrt(1.0 + m[0][0] - m[1][1] - m[2][2]);\n quat.w = (m[2][1] - m[1][2]) / s;\n quat.x = 0.25 * s;\n quat.y = (m[0][1] + m[1][0]) / s;\n quat.z = (m[0][2] + m[2][0]) / s;\n } else if (m[1][1] > m[2][2]) {\n float s = 2.0 * sqrt(1.0 + m[1][1] - m[0][0] - m[2][2]);\n quat.w = (m[0][2] - m[2][0]) / s;\n quat.x = (m[0][1] + m[1][0]) / s;\n quat.y = 0.25 * s;\n quat.z = (m[1][2] + m[2][1]) / s;\n } else {\n float s = 2.0 * sqrt(1.0 + m[2][2] - m[0][0] - m[1][1]);\n quat.w = (m[1][0] - m[0][1]) / s;\n quat.x = (m[0][2] + m[2][0]) / s;\n quat.y = (m[1][2] + m[2][1]) / s;\n quat.z = 0.25 * s;\n }\n float len = quat.x * quat.x + quat.y * quat.y + quat.z * quat.z + quat.w * quat.w;\n if (len > 0.) {\n len = 1. / sqrt(len);\n quat.x = quat.x * len;\n quat.y = quat.y * len;\n quat.z = quat.z * len;\n quat.w = quat.w * len;\n }\n return quat;\n}\nvec4 quaternionFromEuler (vec3 angle){\n float x = angle.x / 2.;\n float y = angle.y / 2.;\n float z = angle.z / 2.;\n float sx = sin(x);\n float cx = cos(x);\n float sy = sin(y);\n float cy = cos(y);\n float sz = sin(z);\n float cz = cos(z);\n vec4 quat = vec4(0);\n quat.x = sx * cy * cz + cx * sy * sz;\n quat.y = cx * sy * cz + sx * cy * sz;\n quat.z = cx * cy * sz - sx * sy * cz;\n quat.w = cx * cy * cz - sx * sy * sz;\n return quat;\n}\nmat4 matrixFromRT (vec4 q, vec3 p){\n float x2 = q.x + q.x;\n float y2 = q.y + q.y;\n float z2 = q.z + q.z;\n float xx = q.x * x2;\n float xy = q.x * y2;\n float xz = q.x * z2;\n float yy = q.y * y2;\n float yz = q.y * z2;\n float zz = q.z * z2;\n float wx = q.w * x2;\n float wy = q.w * y2;\n float wz = q.w * z2;\n return mat4(\n 1. - (yy + zz), xy + wz, xz - wy, 0,\n xy - wz, 1. - (xx + zz), yz + wx, 0,\n xz + wy, yz - wx, 1. - (xx + yy), 0,\n p.x, p.y, p.z, 1\n );\n}\nmat4 matFromRTS (vec4 q, vec3 t, vec3 s){\n float x = q.x, y = q.y, z = q.z, w = q.w;\n float x2 = x + x;\n float y2 = y + y;\n float z2 = z + z;\n float xx = x * x2;\n float xy = x * y2;\n float xz = x * z2;\n float yy = y * y2;\n float yz = y * z2;\n float zz = z * z2;\n float wx = w * x2;\n float wy = w * y2;\n float wz = w * z2;\n float sx = s.x;\n float sy = s.y;\n float sz = s.z;\n return mat4((1. - (yy + zz)) * sx, (xy + wz) * sx, (xz - wy) * sx, 0,\n (xy - wz) * sy, (1. - (xx + zz)) * sy, (yz + wx) * sy, 0,\n (xz + wy) * sz, (yz - wx) * sz, (1. - (xx + yy)) * sz, 0,\n t.x, t.y, t.z, 1);\n}\nvec4 quatMultiply (vec4 a, vec4 b){\n vec4 quat;\n quat.x = a.x * b.w + a.w * b.x + a.y * b.z - a.z * b.y;\n quat.y = a.y * b.w + a.w * b.y + a.z * b.x - a.x * b.z;\n quat.z = a.z * b.w + a.w * b.z + a.x * b.y - a.y * b.x;\n quat.w = a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z;\n return quat;\n}\nvoid rotateVecFromQuat (inout vec3 v, vec4 q){\n float ix = q.w * v.x + q.y * v.z - q.z * v.y;\n float iy = q.w * v.y + q.z * v.x - q.x * v.z;\n float iz = q.w * v.z + q.x * v.y - q.y * v.x;\n float iw = -q.x * v.x - q.y * v.y - q.z * v.z;\n v.x = ix * q.w + iw * -q.x + iy * -q.z - iz * -q.y;\n v.y = iy * q.w + iw * -q.y + iz * -q.x - ix * -q.z;\n v.z = iz * q.w + iw * -q.z + ix * -q.y - iy * -q.x;\n}\nvec3 rotateInLocalSpace (vec3 pos, vec3 xAxis, vec3 yAxis, vec3 zAxis, vec4 q){\n vec4 viewQuat = quaternionFromAxis(xAxis, yAxis, zAxis);\n vec4 rotQuat = quatMultiply(viewQuat, q);\n rotateVecFromQuat(pos, rotQuat);\n return pos;\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}\nuniform vec4 mainTiling_Offset;\nuniform vec4 frameTile_velLenScale;\nuniform vec4 scale;\nuniform highp mat4 cc_matView;\nuniform mat4 cc_matViewInv;\nuniform mat4 cc_matViewProj;\nuniform vec4 cc_cameraPos;\nuniform highp mat4 cc_matWorld;\nvarying vec2 uv;\nvarying vec4 color;\nvoid computeVertPos (inout vec4 pos, vec2 vertOffset, vec4 q, vec3 s\n#if CC_RENDER_MODE == 0 || CC_RENDER_MODE == 3\n , mat4 viewInv\n#endif\n#if CC_RENDER_MODE == 1\n , vec3 eye\n , vec4 velocity\n , float velocityScale\n , float lengthScale\n , float xIndex\n#endif\n) {\n#if CC_RENDER_MODE == 0\n vec3 viewSpaceVert = vec3(vertOffset.x * s.x, vertOffset.y * s.y, 0.);\n vec3 camX = normalize(vec3(viewInv[0][0], viewInv[1][0], viewInv[2][0]));\n vec3 camY = normalize(vec3(viewInv[0][1], viewInv[1][1], viewInv[2][1]));\n vec3 camZ = normalize(vec3(viewInv[0][2], viewInv[1][2], viewInv[2][2]));\n pos.xyz += rotateInLocalSpace(viewSpaceVert, camX, camY, camZ, q);\n#elif CC_RENDER_MODE == 1\n vec3 camRight = normalize(cross(pos.xyz - eye, velocity.xyz)) * s.x;\n vec3 camUp = velocity.xyz * velocityScale + normalize(velocity.xyz) * lengthScale * s.y;\n pos.xyz += (camRight * abs(vertOffset.x) * sign(vertOffset.y)) - camUp * xIndex;\n#elif CC_RENDER_MODE == 2\n vec3 viewSpaceVert = vec3(vertOffset.x * s.x, vertOffset.y * s.y, 0.);\n vec3 camX = vec3(1, 0, 0);\n vec3 camY = vec3(0, 0, -1);\n pos.xyz += rotateInLocalSpace(viewSpaceVert, camX, camY, cross(camX, camY), q);\n#elif CC_RENDER_MODE == 3\n vec2 viewSpaceVert = vec2(vertOffset.x * s.x, vertOffset.y * s.y);\n rotateCorner(viewSpaceVert, q.z);\n vec3 camX = normalize(vec3(cc_matView[0][0], cc_matView[1][0], cc_matView[2][0]));\n vec3 camY = vec3(0, 1, 0);\n vec3 offset = camX * viewSpaceVert.x + camY * viewSpaceVert.y;\n pos.xyz += offset;\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#if CC_RENDER_MODE != 4\n vertIndex.y = 1. - vertIndex.y;\n#endif\n return (aniUV.xy + vertIndex) / vec2(frameTile.x, frameTile.y);\n}\nattribute vec3 a_position;\nattribute vec3 a_texCoord;\nattribute vec3 a_texCoord1;\nattribute vec3 a_texCoord2;\nattribute vec4 a_color;\n#if CC_RENDER_MODE == 1\n attribute vec3 a_color1;\n#endif\n#if CC_RENDER_MODE == 4\n attribute vec3 a_texCoord3;\n attribute vec3 a_normal;\n attribute vec4 a_color1;\n#endif\nvec4 lpvs_main () {\n vec3 compScale = scale.xyz * a_texCoord1;\n vec4 pos = vec4(a_position, 1);\n #if CC_RENDER_MODE == 1\n vec4 velocity = vec4(a_color1.xyz, 0);\n #endif\n #if !CC_USE_WORLD_SPACE\n pos = cc_matWorld * pos;\n #if CC_RENDER_MODE == 1\n velocity = cc_matWorld * velocity;\n #endif\n #endif\n #if CC_RENDER_MODE != 4\n vec2 cornerOffset = vec2((a_texCoord.xy - 0.5));\n #if CC_RENDER_MODE == 0\n vec3 rotEuler = a_texCoord2;\n #elif CC_RENDER_MODE == 1\n vec3 rotEuler = vec3(0.);\n #else\n vec3 rotEuler = vec3(0., 0., a_texCoord2.z);\n #endif\n computeVertPos(pos, cornerOffset, quaternionFromEuler(rotEuler), compScale\n #if CC_RENDER_MODE == 0 || CC_RENDER_MODE == 3\n , cc_matViewInv\n #endif\n #if CC_RENDER_MODE == 1\n , cc_cameraPos.xyz\n , velocity\n , frameTile_velLenScale.z\n , frameTile_velLenScale.w\n , a_texCoord.x\n #endif\n );\n color = a_color;\n #else\n mat4 xformNoScale = matrixFromRT(quaternionFromEuler(a_texCoord2), pos.xyz);\n mat4 xform = matFromRTS(quaternionFromEuler(a_texCoord2), pos.xyz, compScale);\n pos = xform * vec4(a_texCoord3, 1);\n vec4 normal = xformNoScale * vec4(a_normal, 0);\n color = a_color * a_color1;\n #endif\n uv = computeUV(a_texCoord.z, a_texCoord.xy, frameTile_velLenScale.xy) * mainTiling_Offset.xy + mainTiling_Offset.zw;\n pos = cc_matViewProj * pos;\n return pos;\n}\nvoid main() { gl_Position = lpvs_main(); }`, "frag": `\nprecision highp float;\nuniform vec4 cc_exposure;\nvec3 SRGBToLinear (vec3 gamma) {\n return gamma * gamma;\n}\nvec4 CCFragOutput (vec4 color) {\n #if CC_USE_HDR\n color.rgb = mix(color.rgb, SRGBToLinear(color.rgb) * cc_exposure.w, vec3(cc_exposure.z));\n #endif\n return color;\n}\nvarying vec2 uv;\nvarying vec4 color;\nuniform sampler2D mainTexture;\nuniform vec4 tintColor;\nvec4 add () {\n vec4 col = 2.0 * color * tintColor * texture2D(mainTexture, uv);\n return CCFragOutput(col);\n}\nvoid main() { gl_FragColor = add(); }` }, "builtins": {"globals":{"blocks":[{"name":"CCGlobal", "defines":[]}], "samplers":[]}, "locals":{"blocks":[{"name":"CCLocal", "defines":[]}], "samplers":[]}}, "defines": [ - {"name":"CC_USE_BILLBOARD", "type":"boolean"}, - {"name":"CC_USE_STRETCHED_BILLBOARD", "type":"boolean"}, - {"name":"CC_USE_HORIZONTAL_BILLBOARD", "type":"boolean"}, - {"name":"CC_USE_VERTICAL_BILLBOARD", "type":"boolean"}, - {"name":"CC_USE_MESH", "type":"boolean"}, + {"name":"CC_RENDER_MODE", "type":"number", "range":[0, 4]}, {"name":"CC_USE_WORLD_SPACE", "type":"boolean"}, {"name":"CC_USE_HDR", "type":"boolean"} ], diff --git a/cocos/core/3d/framework/model-component.ts b/cocos/core/3d/framework/model-component.ts index a997c04884..ffe7a9413f 100644 --- a/cocos/core/3d/framework/model-component.ts +++ b/cocos/core/3d/framework/model-component.ts @@ -78,6 +78,9 @@ export class ModelComponent extends RenderableComponent { this._mesh = val; this._onMeshChanged(old); this._updateModels(); + if (this.node.activeInHierarchy) { + this._attachToScene(); + } } /** diff --git a/cocos/core/event/callbacks-invoker.ts b/cocos/core/event/callbacks-invoker.ts index b85d24e7ce..70a966d393 100644 --- a/cocos/core/event/callbacks-invoker.ts +++ b/cocos/core/event/callbacks-invoker.ts @@ -28,7 +28,7 @@ * @hidden */ -import Pool from '../memop/pool'; +import { Pool } from '../memop'; import { array, createMap } from '../utils/js'; const fastRemoveAt = array.fastRemoveAt; diff --git a/cocos/core/geom-utils/index.ts b/cocos/core/geom-utils/index.ts index 88cebe1279..85ede55866 100644 --- a/cocos/core/geom-utils/index.ts +++ b/cocos/core/geom-utils/index.ts @@ -14,7 +14,6 @@ export { default as sphere } from './sphere'; export { default as aabb } from './aabb'; export { default as obb } from './obb'; export { frustum } from './frustum'; -export { default as Octree } from './octree'; export { Keyframe, AnimationCurve } from './curve'; import './deprecated'; diff --git a/cocos/core/geom-utils/octree.ts b/cocos/core/geom-utils/octree.ts deleted file mode 100644 index 577ce829e4..0000000000 --- a/cocos/core/geom-utils/octree.ts +++ /dev/null @@ -1,259 +0,0 @@ -/** - * @category geometry - */ - -import { Vec3 } from '../math'; -import { FixedArray } from '../memop'; -import aabb from './aabb'; -import intersect from './intersect'; - -const mul = (out, v, x, y, z) => { - return Vec3.set(out, v.x * x, v.y * y, v.z * z); -}; - -class OctreeBlock { - public minPos: Vec3; - public maxPos: Vec3; - public boundingBox: aabb; - public capacity: number; - public depth: number; - public maxDepth: number; - public blocks: null | OctreeBlock[]; - public entries: FixedArray; - - private _getBoundingShape: Function; - - constructor (minPos, maxPos, capacity, depth, maxDepth, getBoundingShape) { - this.minPos = minPos; - this.maxPos = maxPos; - this.boundingBox = aabb.fromPoints(aabb.create(), minPos, maxPos); - this.capacity = capacity; - this.depth = depth; - this.maxDepth = maxDepth; - this._getBoundingShape = getBoundingShape; - this.blocks = null; - this.entries = new FixedArray(this.capacity); - } - - public addEntry (entry) { - if (this.blocks) { - for (const block of this.blocks) { - block.addEntry(entry); - } - } else { - const shape = this._getBoundingShape(entry); - if (!intersect.resolve(this.boundingBox, shape)) { return; } - this.entries.push(entry); - if (this.entries.length >= this.capacity && this.depth < this.maxDepth) { - this.blocks = Octree.createBlocks(this.minPos, this.maxPos, this.entries, - this.capacity, this.depth, this.maxDepth, this._getBoundingShape); - this.entries.reset(); - } - } - } - - public removeEntry (entry) { - if (this.blocks) { - for (const block of this.blocks) { - block.removeEntry(entry); - } - } else { - this.entries.fastRemove(this.entries.indexOf(entry)); - } - } - - public select (out, shape) { - if (!intersect.resolve(this.boundingBox, shape)) { return; } - if (this.blocks) { - for (const block of this.blocks) { - block.select(out, shape); - } - } else { - for (let i = 0; i < this.entries.length; i++) { - out.add(this.entries.data[i]); - } - } - } - - public frustumSelect (out, frustum) { - if (!intersect.aabb_frustum(this.boundingBox, frustum)) { return; } - if (this.blocks) { - for (const block of this.blocks) { - block.frustumSelect(out, frustum); - } - } else { - for (let i = 0; i < this.entries.length; i++) { - out.add(this.entries.data[i]); - } - } - } -} - -/** - * An octree acceleration data structure - * @example - * ``` - * let octree = new Octree(); - * octree.build(models, model => { - * return model._boundingShape; - * }); - * octree.select(enums.SHAPE_FRUSTUM, view._frustum); - * ``` - */ -export default class Octree { - - /** - * @en Create sub blocks and populate them with given entries - * @zh 创建子块,并用给定的条目填充它们 - * @param {Vec3} worldMin - min position of the parent bounding box - * @param {Vec3} worldMax - max position of the parent bounding box - * @param {Array} entries - the entries to be inserted - * @param {number} blockCapacity - maximum capacity for each block node - * before it's been subdivided, might be exceeded if `maxDepth` is reached - * @param {number} curDepth - depth before subdivided - * @param {number} maxDepth - maximum depth of this tree - * @param {function(entry: Object): Object} getBoundingShape - a function takes an entry and returns its primitive info - * @return {OctreeBlock[]} the sub blocks - */ - public static createBlocks (worldMin, worldMax, entries, blockCapacity, curDepth, maxDepth, getBoundingShape) { - const blocks: OctreeBlock[] = []; - const blockSize = new Vec3(); - Vec3.multiplyScalar(blockSize, Vec3.subtract(blockSize, worldMax, worldMin), 0.5); - for (let x = 0; x < 2; x++) { - for (let y = 0; y < 2; y++) { - for (let z = 0; z < 2; z++) { - const localMin = new Vec3(); - const localMax = new Vec3(); - Vec3.add(localMin, worldMin, mul(localMin, blockSize, x, y, z)); - Vec3.add(localMax, worldMin, mul(localMax, blockSize, x + 1, y + 1, z + 1)); - const block = new OctreeBlock(localMin, localMax, - blockCapacity, curDepth + 1, maxDepth, getBoundingShape); - for (let i = 0; i < entries.length; i++) { - const entry = (entries.data || entries)[i]; - block.addEntry(entry); - } - blocks.push(block); - } - } - } - return blocks; - } - - public blockCapacity: number; - public maxDepth: number; - public blocks: OctreeBlock[]; - public dynamics: any[]; - - private _selection: Set; - private _getBoundingShape: Function; - - /** - * Create a octree structure - * @param {number} blockCapacity - maximum capacity for each block node - * before it's been subdivided, might be exceeded if `maxDepth` is reached - * @param {number} maxDepth - maximum depth of this tree - */ - constructor (blockCapacity = 32, maxDepth = 5) { - this.blockCapacity = blockCapacity; - this.maxDepth = maxDepth; - this.blocks = []; - this.dynamics = []; - this._selection = new Set(); - this._getBoundingShape = () => this._getBoundingShape; - } - - /** - * @en Build this octree from given entries.
- * Root Boundary is the bounding box of all the entries. - * @zh 从给定的项中构建这个八叉树。根边界是所有这些条目的边界框。 - * @param {Array} entries - a collection of entries to be queried later - * @param {function(entry: Object): Object} getBoundingShape - * - a function takes an entry and returns its primitive info - */ - public build (entries, getBoundingShape) { - // calc world min & max - const worldMin = new Vec3(Infinity, Infinity, Infinity); - const worldMax = new Vec3(-Infinity, -Infinity, -Infinity); - const minPos = new Vec3(); - const maxPos = new Vec3(); - const staticEntries: any[] = []; this.dynamics = []; - for (let i = 0; i < entries.length; i++) { - const entry = (entries.data || entries)[i]; - const shape = getBoundingShape(entry); - if (!shape) { - this.dynamics.push(entry); - } else { - shape.getBoundary(minPos, maxPos); - Vec3.min(worldMin, worldMin, minPos); - Vec3.max(worldMax, worldMax, maxPos); - staticEntries.push(entry); - } - } - this.blocks = Octree.createBlocks(worldMin, worldMax, staticEntries, - this.blockCapacity, 0, this.maxDepth, getBoundingShape); - this._getBoundingShape = getBoundingShape; - } - - /** - * @en Add an entry to this tree. Should be called after `build`. - * @zh 在这个树中添加一个条目。应该在构建之后调用。 - * @param {Object} entry - the new entry - */ - public addEntry (entry) { - if (!this._getBoundingShape(entry).shape) { - this.dynamics.push(entry); - return; - } - for (const block of this.blocks) { - block.addEntry(entry); - } - } - - /** - * @en Remove an entry from this tree. Should be called after `build`. - * @zh 从这个树中删除一个条目。应该在构建之后调用。 - * @param {Object} entry - the entry to be removed - */ - public removeEntry (entry) { - if (!this._getBoundingShape(entry).shape) { - this.dynamics.splice(this.dynamics.indexOf(entry), 1); - return; - } - for (const block of this.blocks) { - block.removeEntry(entry); - } - } - - /** - * @en Select all the entries overlapping the given primitive - * @zh 选择与给定原始项重叠的所有项 - * @param {Object} shape - the selecting primitive - * @return {Set} the resulting set of entries - */ - public select (shape) { - this._selection.clear(); - for (const block of this.blocks) { - block.select(this._selection, shape); - } - for (const dynamic of this.dynamics) { - this._selection.add(dynamic); - } - return this._selection; - } - - /** - * Specialized selection for frustums - * @param {Object} frustum - the selecting frustum - * @return {Set} the resulting set of entries - */ - public frustumSelect (frustum) { - this._selection.clear(); - for (const block of this.blocks) { - block.frustumSelect(this._selection, frustum); - } - for (const dynamic of this.dynamics) { - this._selection.add(dynamic); - } - return this._selection; - } -} diff --git a/cocos/core/gfx/webgl/webgl-command-buffer.ts b/cocos/core/gfx/webgl/webgl-command-buffer.ts index 7868aa3a99..d3367606b3 100644 --- a/cocos/core/gfx/webgl/webgl-command-buffer.ts +++ b/cocos/core/gfx/webgl/webgl-command-buffer.ts @@ -465,7 +465,7 @@ export class WebGLGFXCommandBuffer extends GFXCommandBuffer { this.cmdPackage.copyBufferToTextureCmds.push(cmd); } - this.cmdPackage.cmds.concat(webGLCmdBuff.cmdPackage.cmds); + this.cmdPackage.cmds.concat(webGLCmdBuff.cmdPackage.cmds.array); this._numDrawCalls += webGLCmdBuff._numDrawCalls; this._numTris += webGLCmdBuff._numTris; diff --git a/cocos/core/gfx/webgl2/webgl2-command-buffer.ts b/cocos/core/gfx/webgl2/webgl2-command-buffer.ts index 1d349dd850..17e64dfe94 100644 --- a/cocos/core/gfx/webgl2/webgl2-command-buffer.ts +++ b/cocos/core/gfx/webgl2/webgl2-command-buffer.ts @@ -459,7 +459,7 @@ export class WebGL2GFXCommandBuffer extends GFXCommandBuffer { this.cmdPackage.copyBufferToTextureCmds.push(cmd); } - this.cmdPackage.cmds.concat(webGLCmdBuff.cmdPackage.cmds); + this.cmdPackage.cmds.concat(webGLCmdBuff.cmdPackage.cmds.array); this._numDrawCalls += webGLCmdBuff._numDrawCalls; this._numTris += webGLCmdBuff._numTris; diff --git a/cocos/core/index.ts b/cocos/core/index.ts index 9d50508878..99bc904eb0 100644 --- a/cocos/core/index.ts +++ b/cocos/core/index.ts @@ -27,12 +27,14 @@ * @category core */ -import * as math from './math'; import * as geometry from './geom-utils'; +import * as math from './math'; +import * as memop from './memop'; cc.math = math; cc.geometry = geometry; +cc.memop = memop; -export { math, geometry }; +export { math, memop, geometry }; export * from './math'; export * from './memop'; @@ -58,5 +60,5 @@ import './primitive'; export * from './utils/profiler/profiler'; -import './splash-image'; import './deprecated'; +import './splash-image'; diff --git a/cocos/core/memop/cached-array.ts b/cocos/core/memop/cached-array.ts index 816113099c..69ccffdab2 100644 --- a/cocos/core/memop/cached-array.ts +++ b/cocos/core/memop/cached-array.ts @@ -59,7 +59,7 @@ export class CachedArray { * @param item 数组元素 */ public pop (): T | undefined { - return this.array[this.length--]; + return this.array[--this.length]; } /** @@ -92,19 +92,29 @@ export class CachedArray { * @zh * 连接一个指定数组中的所有元素到当前数组末尾 */ - public concat (array: CachedArray) { + public concat (array: T[]) { for (let i = 0; i < array.length; ++i) { - this.array[this.length++] = array.array[i]; + this.array[this.length++] = array[i]; } } /** - * @zh - * 向数组中追加一组数据 + * @zh 删除指定位置的元素并将最后一个元素移动至该位置。 + * @param idx 数组索引。 */ - public append (array: T[]) { - for (const item of array) { - this.array[this.length++] = item; + public fastRemove (idx: number) { + if (idx >= this.length || idx < 0) { + return; } + const last = --this.length; + this.array[idx] = this.array[last]; + } + + /** + * @zh 返回某个数组元素对应的下标。 + * @param val 数组元素。 + */ + public indexOf (val: T) { + return this.array.indexOf(val); } } diff --git a/cocos/core/memop/fixed-array.ts b/cocos/core/memop/fixed-array.ts deleted file mode 100644 index 7494551905..0000000000 --- a/cocos/core/memop/fixed-array.ts +++ /dev/null @@ -1,116 +0,0 @@ - -/** - * @category memop - */ - -import sort from './timsort'; - -/** - * @zh 定长数组。 - */ -export default class FixedArray { - private _count: number; - private _data: Array; - - /** - * 构造函数。 - * @param size 数组长度。 - */ - constructor (size: number) { - this._count = 0; - this._data = new Array(size); - } - - public _resize (size: number) { - if (size > this._data.length) { - for (let i = this._data.length; i < size; ++i) { - this._data[i] = undefined; - } - } - } - - /** - * @zh 当前有效数据长度。 - */ - get length () { - return this._count; - } - - /** - * @zh 获取数组元素。 - */ - get data () { - return this._data; - } - - /** - * @zh 将数组清空。 - */ - public reset () { - for (let i = 0; i < this._count; ++i) { - this._data[i] = undefined; - } - - this._count = 0; - } - - /** - * @zh 把一个对象插入到数组末尾。 - * @param val 一个数组元素 - */ - public push (val) { - if (this._count >= this._data.length) { - this._resize(this._data.length * 2); - } - - this._data[this._count] = val; - ++this._count; - } - - /** - * @zh 删除数组最后一个元素并返回。 - */ - public pop () { - --this._count; - - if (this._count < 0) { - this._count = 0; - } - - const ret = this._data[this._count]; - this._data[this._count] = undefined; - - return ret; - } - - /** - * @zh 删除指定位置的元素并将最后一个元素移动至该位置。 - * @param idx 数组索引。 - */ - public fastRemove (idx) { - if (idx >= this._count || idx < 0) { - return; - } - - const last = this._count - 1; - this._data[idx] = this._data[last]; - this._data[last] = undefined; - this._count -= 1; - } - - /** - * @zh 返回某个数组元素对应的下标。 - * @param val 数组元素。 - */ - public indexOf (val) { - return this._data.indexOf(val); - } - - /** - * @zh 对数组进行排序。 - * @param cmp 比较函数。 - */ - public sort (cmp) { - return sort(this._data, 0, this._count, cmp); - } -} diff --git a/cocos/core/memop/index.ts b/cocos/core/memop/index.ts index 4fb1e3a29a..291254ab96 100644 --- a/cocos/core/memop/index.ts +++ b/cocos/core/memop/index.ts @@ -2,9 +2,6 @@ * @hidden */ -export { default as CircularPool } from './circular-pool'; -export { default as FixedArray } from './fixed-array'; -export { default as LinkedArray } from './linked-array'; -export { default as Pool } from './pool'; -export { default as RecyclePool } from './recycle-pool'; -export { default as TypedArrayPool } from './typed-array-pool'; +export * from './pool'; +export * from './recycle-pool'; +export * from './cached-array'; diff --git a/cocos/core/memop/linked-array.ts b/cocos/core/memop/linked-array.ts index afbf1efdb8..178c9430df 100644 --- a/cocos/core/memop/linked-array.ts +++ b/cocos/core/memop/linked-array.ts @@ -3,7 +3,7 @@ * @category memop */ -import Pool from './pool'; +import { Pool } from './pool'; // NOTE: you must have `_prev` and `_next` field in the object returns by `fn` diff --git a/cocos/core/memop/pool.ts b/cocos/core/memop/pool.ts index b635180350..2070777464 100644 --- a/cocos/core/memop/pool.ts +++ b/cocos/core/memop/pool.ts @@ -4,11 +4,10 @@ * @category memop */ - /** * @zh 对象池。 */ -export default class Pool { +export class Pool { private _fn: () => T; private _idx: number; diff --git a/cocos/core/memop/recycle-pool.ts b/cocos/core/memop/recycle-pool.ts index ce74d46d1d..b4d7b83031 100644 --- a/cocos/core/memop/recycle-pool.ts +++ b/cocos/core/memop/recycle-pool.ts @@ -3,12 +3,10 @@ * @category memop */ -import sort from './timsort'; - /** * @zh 循环对象池。 */ -export default class RecyclePool { +export class RecyclePool { private _fn: () => T; private _count = 0; private _data: T[]; @@ -86,12 +84,4 @@ export default class RecyclePool { this._data[last] = tmp; this._count -= 1; } - - /** - * @zh 对对象池中的元素进行排序。 - * @param compare 比较函数。 - */ - public sort (compare: (a: T, b: T) => number) { - return sort(this._data, 0, this._count, compare); - } } diff --git a/cocos/core/pipeline/render-pipeline.ts b/cocos/core/pipeline/render-pipeline.ts index c7e989803b..cb29f9acb9 100644 --- a/cocos/core/pipeline/render-pipeline.ts +++ b/cocos/core/pipeline/render-pipeline.ts @@ -1176,6 +1176,7 @@ export abstract class RenderPipeline { fv[UBOGlobal.MAIN_LIT_COLOR_OFFSET + 3] = mainLight.illuminance * exposure; } } else { + Vec3.toArray(fv, Vec3.UNIT_Z, UBOGlobal.MAIN_LIT_DIR_OFFSET); Vec4.toArray(fv, Vec4.ZERO, UBOGlobal.MAIN_LIT_COLOR_OFFSET); } diff --git a/cocos/core/renderer/scene/model.ts b/cocos/core/renderer/scene/model.ts index d606730210..c4f14f031f 100644 --- a/cocos/core/renderer/scene/model.ts +++ b/cocos/core/renderer/scene/model.ts @@ -9,7 +9,7 @@ import { GFXDevice } from '../../gfx/device'; import { GFXPipelineState } from '../../gfx/pipeline-state'; import { GFXUniformBlock } from '../../gfx/shader'; import { Mat4, Vec3 } from '../../math'; -import Pool from '../../memop/pool'; +import { Pool } from '../../memop'; import { IInternalBindingInst, UBOForwardLight, UBOLocal } from '../../pipeline/define'; import { Layers } from '../../scene-graph/layers'; import { INode } from '../../utils/interfaces'; diff --git a/cocos/core/renderer/ui/render-data.ts b/cocos/core/renderer/ui/render-data.ts index 1545f0738f..dabdfe84ff 100644 --- a/cocos/core/renderer/ui/render-data.ts +++ b/cocos/core/renderer/ui/render-data.ts @@ -27,9 +27,9 @@ * @hidden */ -import { Pool, RecyclePool } from '../../memop'; import { Material } from '../../assets'; import { Color } from '../../math'; +import { Pool, RecyclePool } from '../../memop'; export interface IRenderData { x: number; @@ -47,7 +47,6 @@ export class BaseRenderData { } export class RenderData extends BaseRenderData { - public vData: Float32Array | null = null; get dataLength () { return this._datas.length; @@ -88,6 +87,7 @@ export class RenderData extends BaseRenderData { _pool.data[idx].clear(); _pool.removeAt(idx); } + public vData: Float32Array | null = null; public uvDirty: boolean = true; public vertDirty: boolean = true; diff --git a/cocos/core/renderer/ui/ui-material.ts b/cocos/core/renderer/ui/ui-material.ts index 032e767a53..e7755efae8 100644 --- a/cocos/core/renderer/ui/ui-material.ts +++ b/cocos/core/renderer/ui/ui-material.ts @@ -27,8 +27,8 @@ */ import { Material } from '../../assets/material'; -import Pool from '../../memop/pool'; import { GFXPipelineState } from '../../gfx/pipeline-state'; +import { Pool } from '../../memop'; import { Pass } from '../../renderer/core/pass'; export interface IUIMaterialInfo { diff --git a/cocos/core/renderer/ui/ui.ts b/cocos/core/renderer/ui/ui.ts index a45cfc3c09..34354ab3b8 100644 --- a/cocos/core/renderer/ui/ui.ts +++ b/cocos/core/renderer/ui/ui.ts @@ -397,7 +397,7 @@ export class UI { } public commitStaticBatch (comp: UIStaticBatchComponent) { - this._batches.append(comp.drawBatchList); + this._batches.concat(comp.drawBatchList); this.finishMergeBatches(); } diff --git a/cocos/core/scene-graph/scene-globals.ts b/cocos/core/scene-graph/scene-globals.ts index 243c6dd7f8..51d4146299 100644 --- a/cocos/core/scene-graph/scene-globals.ts +++ b/cocos/core/scene-graph/scene-globals.ts @@ -28,7 +28,7 @@ */ import { TextureCube } from '../assets/texture-cube'; -import { ccclass, property, float } from '../data/class-decorator'; +import { ccclass, float, property } from '../data/class-decorator'; import { CCBoolean, CCFloat } from '../data/utils/attribute'; import { Color, Quat, Vec3 } from '../math'; import { Ambient } from '../renderer/scene/ambient'; diff --git a/cocos/particle/particle-utils.ts b/cocos/particle/particle-utils.ts index 9d2b711172..b08a74a874 100644 --- a/cocos/particle/particle-utils.ts +++ b/cocos/particle/particle-utils.ts @@ -2,16 +2,14 @@ * @hidden */ -import { ParticleSystemComponent } from './particle-system-component'; -import { CCObject } from '../core/data/object'; -import { Node } from '../core/scene-graph'; -import { Pool } from '../core/memop'; -import { Director, director } from '../core/director'; import { instantiate } from '../core/data'; +import { CCObject } from '../core/data/object'; +import { Director, director } from '../core/director'; +import { Pool } from '../core/memop'; +import { Node } from '../core/scene-graph'; +import { ParticleSystemComponent } from './particle-system-component'; export class ParticleUtils { - private static particleSystemPool: Map> = new Map>(); - private static registeredSceneEvent: boolean = false; /** * instantiate @@ -36,15 +34,6 @@ export class ParticleUtils { } } - private static onSceneUnload () { - this.particleSystemPool.forEach((value) => { - value.clear((prefab) => { - prefab.destroy(); - }); - }); - this.particleSystemPool.clear(); - } - public static play (rootNode: Node) { for (const ps of rootNode.getComponentsInChildren(ParticleSystemComponent)) { (ps as ParticleSystemComponent).play(); @@ -56,4 +45,15 @@ export class ParticleUtils { (ps as ParticleSystemComponent).stop(); } } + private static particleSystemPool: Map> = new Map>(); + private static registeredSceneEvent: boolean = false; + + private static onSceneUnload () { + this.particleSystemPool.forEach((value) => { + value.clear((prefab) => { + prefab.destroy(); + }); + }); + this.particleSystemPool.clear(); + } } diff --git a/cocos/particle/renderer/particle-system-renderer.ts b/cocos/particle/renderer/particle-system-renderer.ts index a304228f00..294271ff31 100644 --- a/cocos/particle/renderer/particle-system-renderer.ts +++ b/cocos/particle/renderer/particle-system-renderer.ts @@ -1,14 +1,14 @@ +import { builtinResMgr } from '../../core/3d/builtin'; +import { Material, Mesh } from '../../core/assets'; import { Component } from '../../core/components'; import { ccclass, property } from '../../core/data/class-decorator'; -import { Mat4, Vec2, Vec3, Vec4 } from '../../core/math'; import { GFXAttributeName, GFXFormat } from '../../core/gfx/define'; import { IGFXAttribute } from '../../core/gfx/input-assembler'; +import { Mat4, Vec2, Vec3, Vec4 } from '../../core/math'; +import { RecyclePool } from '../../core/memop'; import { IDefineMap } from '../../core/renderer/core/pass'; -import ParticleBatchModel from '../models/particle-batch-model'; -import { Mesh, Material } from '../../core/assets'; -import { builtinResMgr } from '../../core/3d/builtin'; -import RecyclePool from '../../core/memop/recycle-pool'; import { RenderMode, Space } from '../enum'; +import ParticleBatchModel from '../models/particle-batch-model'; import Particle from '../particle'; const _tempAttribUV = new Vec3(); @@ -66,7 +66,7 @@ export default class ParticleSystemRenderer { @property({ type: RenderMode, displayOrder: 0, - tooltip:'设定粒子生成模式', + tooltip: '设定粒子生成模式', }) public get renderMode () { return this._renderMode; @@ -87,7 +87,7 @@ export default class ParticleSystemRenderer { */ @property({ displayOrder: 1, - tooltip:'在粒子生成方式为 StrecthedBillboard 时,对粒子在运动方向上按速度大小进行拉伸', + tooltip: '在粒子生成方式为 StrecthedBillboard 时,对粒子在运动方向上按速度大小进行拉伸', }) public get velocityScale () { return this._velocityScale; @@ -104,7 +104,7 @@ export default class ParticleSystemRenderer { */ @property({ displayOrder: 2, - tooltip:'在粒子生成方式为 StrecthedBillboard 时,对粒子在运动方向上按粒子大小进行拉伸', + tooltip: '在粒子生成方式为 StrecthedBillboard 时,对粒子在运动方向上按粒子大小进行拉伸', }) public get lengthScale () { return this._lengthScale; @@ -146,7 +146,7 @@ export default class ParticleSystemRenderer { @property({ type: Mesh, displayOrder: 7, - tooltip:'粒子发射的模型', + tooltip: '粒子发射的模型', }) public get mesh () { return this._mesh; @@ -165,7 +165,7 @@ export default class ParticleSystemRenderer { @property({ type: Material, displayOrder: 8, - tooltip:'粒子使用的材质', + tooltip: '粒子使用的材质', }) public get particleMaterial () { if (!this._particleSystem) { @@ -184,7 +184,7 @@ export default class ParticleSystemRenderer { @property({ type: Material, displayOrder: 9, - tooltip:'拖尾使用的材质', + tooltip: '拖尾使用的材质', }) public get trailMaterial () { if (!this._particleSystem) { @@ -258,7 +258,7 @@ export default class ParticleSystemRenderer { } } - public _attachToScene() { + public _attachToScene () { if (this._model) { if (this._model.scene) { this._detachFromScene(); @@ -267,7 +267,7 @@ export default class ParticleSystemRenderer { } } - public _detachFromScene() { + public _detachFromScene () { if (this._model && this._model.scene) { this._model.scene.removeModel(this._model); } diff --git a/cocos/particle/renderer/trail.ts b/cocos/particle/renderer/trail.ts index 02fdac02e0..cfe2a65707 100644 --- a/cocos/particle/renderer/trail.ts +++ b/cocos/particle/renderer/trail.ts @@ -3,17 +3,17 @@ * @category particle */ -import { Color, Vec3, Mat4, Quat, toRadian } from '../../core/math'; +import { Material } from '../../core/assets/material'; +import { IRenderingSubmesh } from '../../core/assets/mesh'; import { ccclass, property } from '../../core/data/class-decorator'; +import { director } from '../../core/director'; import { GFX_DRAW_INFO_SIZE, GFXBuffer, IGFXIndirectBuffer } from '../../core/gfx/buffer'; import { GFXAttributeName, GFXBufferUsageBit, GFXFormat, GFXFormatInfos, GFXMemoryUsageBit, GFXPrimitiveMode } from '../../core/gfx/define'; import { GFXDevice } from '../../core/gfx/device'; import { IGFXAttribute } from '../../core/gfx/input-assembler'; -import { Model } from '../../core/renderer'; -import { Material } from '../../core/assets/material'; -import { IRenderingSubmesh } from '../../core/assets/mesh'; +import { Color, Mat4, Quat, toRadian, Vec3 } from '../../core/math'; import { Pool } from '../../core/memop'; -import { director } from '../../core/director'; +import { Model } from '../../core/renderer'; import CurveRange from '../animator/curve-range'; import GradientRange from '../animator/gradient-range'; import { Space, TextureMode, TrailMode } from '../enum'; @@ -31,15 +31,15 @@ const _temp_vec3 = new Vec3(); const _temp_vec3_1 = new Vec3(); const _temp_color = new Color(); -const barycentric = [1,0,0, 0,1,0, 0,0,1]; // -let _bcIdx = 0; +const barycentric = [1, 0, 0, 0, 1, 0, 0, 0, 1]; // +const _bcIdx = 0; interface ITrailElement { position: Vec3; lifetime: number; width: number; velocity: Vec3; - direction: number; //if one element's direction differs from the previous one,it means the trail's direction reverse. + direction: number; // if one element's direction differs from the previous one,it means the trail's direction reverse. color: Color; } @@ -178,7 +178,7 @@ export default class TrailModule { @property({ type: TrailMode, displayOrder: 1, - tooltip:'Particle在每个粒子的运动轨迹上形成拖尾效果', + tooltip: 'Particle在每个粒子的运动轨迹上形成拖尾效果', }) public mode = TrailMode.Particles; @@ -188,7 +188,7 @@ export default class TrailModule { @property({ type: CurveRange, displayOrder: 3, - tooltip:'拖尾的生命周期', + tooltip: '拖尾的生命周期', }) public lifeTime = new CurveRange(); @@ -200,7 +200,7 @@ export default class TrailModule { */ @property({ displayOrder: 5, - tooltip:'粒子每生成一个拖尾节点所运行的最短距离', + tooltip: '粒子每生成一个拖尾节点所运行的最短距离', }) public get minParticleDistance () { return this._minParticleDistance; @@ -214,7 +214,7 @@ export default class TrailModule { @property({ type: Space, displayOrder: 6, - tooltip:'拖尾所在的坐标系,World在世界坐标系中运行,Local在本地坐标系中运行', + tooltip: '拖尾所在的坐标系,World在世界坐标系中运行,Local在本地坐标系中运行', }) public get space () { return this._space; @@ -232,7 +232,7 @@ export default class TrailModule { */ @property({ displayOrder: 7, - tooltip:'拖尾是否跟随粒子一起消失', + tooltip: '拖尾是否跟随粒子一起消失', }) public existWithParticles = true; @@ -242,13 +242,13 @@ export default class TrailModule { @property({ type: TextureMode, displayOrder: 8, - tooltip:'贴图在拖尾上的展开形式,Stretch贴图覆盖在整条拖尾上,Repeat贴图覆盖在一段拖尾上', + tooltip: '贴图在拖尾上的展开形式,Stretch贴图覆盖在整条拖尾上,Repeat贴图覆盖在一段拖尾上', }) public textureMode = TextureMode.Stretch; @property({ displayOrder: 9, - tooltip:'拖尾宽度继承自粒子大小' + tooltip: '拖尾宽度继承自粒子大小', }) public widthFromParticle = true; @@ -258,27 +258,27 @@ export default class TrailModule { @property({ type: CurveRange, displayOrder: 10, - tooltip:'拖尾宽度,如果继承自粒子则是粒子大小的比例', + tooltip: '拖尾宽度,如果继承自粒子则是粒子大小的比例', }) public widthRatio = new CurveRange(); @property({ displayOrder: 11, - tooltip:'拖尾颜色是否继承自粒子' + tooltip: '拖尾颜色是否继承自粒子', }) public colorFromParticle = false; @property({ type: GradientRange, displayOrder: 12, - tooltip:'拖尾颜色随拖尾自身长度的颜色渐变' + tooltip: '拖尾颜色随拖尾自身长度的颜色渐变', }) public colorOverTrail = new GradientRange(); @property({ type: GradientRange, displayOrder: 13, - tooltip:'拖尾颜色随时间的颜色渐变' + tooltip: '拖尾颜色随时间的颜色渐变', }) public colorOvertime = new GradientRange(); @@ -363,7 +363,7 @@ export default class TrailModule { this._detachFromScene(); } - public _attachToScene() { + public _attachToScene () { if (this._trailModel) { if (this._trailModel.scene) { this._detachFromScene(); @@ -372,7 +372,7 @@ export default class TrailModule { } } - public _detachFromScene() { + public _detachFromScene () { if (this._trailModel && this._trailModel.scene) { this._trailModel.scene.removeModel(this._trailModel); } @@ -529,8 +529,8 @@ export default class TrailModule { const lastThirdTrail = trailSeg.getElement(trailSeg.end - 2)!; Vec3.subtract(_temp_vec3, lastThirdTrail.position, lastSecondTrail.position); Vec3.subtract(_temp_vec3_1, _temp_trailEle.position, lastSecondTrail.position); - Vec3.normalize(_temp_vec3,_temp_vec3); - Vec3.normalize(_temp_vec3_1,_temp_vec3_1); + Vec3.normalize(_temp_vec3, _temp_vec3); + Vec3.normalize(_temp_vec3_1, _temp_vec3_1); Vec3.subtract(lastSecondTrail.velocity, _temp_vec3_1, _temp_vec3); Vec3.normalize(lastSecondTrail.velocity, lastSecondTrail.velocity); this._checkDirectionReverse(lastSecondTrail, lastThirdTrail); diff --git a/cocos/ui/assembler/graphics/webgl/impl.ts b/cocos/ui/assembler/graphics/webgl/impl.ts index 12610f8740..05ccd33269 100644 --- a/cocos/ui/assembler/graphics/webgl/impl.ts +++ b/cocos/ui/assembler/graphics/webgl/impl.ts @@ -1,7 +1,7 @@ import { Color, Vec2 } from '../../../../core/math'; +import { RecyclePool } from '../../../../core/memop'; import { MeshRenderData } from '../../../../core/renderer/ui/render-data'; -import RecyclePool from '../../../../core/memop/recycle-pool'; import { arc, ellipse, roundRect, tesselateBezier } from '../helper'; import { LineCap, LineJoin, PointFlags} from '../types'; diff --git a/exports/base.ts b/exports/base.ts index 261577632e..b6940bffe4 100644 --- a/exports/base.ts +++ b/exports/base.ts @@ -21,4 +21,4 @@ export { primitives, }; cc.primitives = primitives; -export * from '../cocos/core/primitive/primitive'; \ No newline at end of file +export * from '../cocos/core/primitive/primitive'; diff --git a/package-lock.json b/package-lock.json index 42577bbaca..56f97d9e9c 100644 --- a/package-lock.json +++ b/package-lock.json @@ -11868,6 +11868,12 @@ "integrity": "sha1-NpS1gEVnpFjTyARYQqY1hjL2JlQ=", "dev": true }, + "spectorjs": { + "version": "0.9.10", + "resolved": "https://registry.npmjs.org/spectorjs/-/spectorjs-0.9.10.tgz", + "integrity": "sha512-BUAWoz5DkroWlvnQz3a0sn/s9LDW8sVFU5gc6f41vod740otCnWHk1DQT/xHJMDbV0f14tgf2ZXWRqvucFG06g==", + "dev": true + }, "split": { "version": "0.3.3", "resolved": "https://registry.npm.taobao.org/split/download/split-0.3.3.tgz", @@ -11936,6 +11942,12 @@ } } }, + "stats.js": { + "version": "0.17.0", + "resolved": "https://registry.npmjs.org/stats.js/-/stats.js-0.17.0.tgz", + "integrity": "sha1-scPcRtlEmLV4t/05hbgaznExzH0=", + "dev": true + }, "stealthy-require": { "version": "1.1.1", "resolved": "https://registry.npm.taobao.org/stealthy-require/download/stealthy-require-1.1.1.tgz", diff --git a/package.json b/package.json index 1fd0331566..8fd3cc6183 100644 --- a/package.json +++ b/package.json @@ -9,7 +9,7 @@ ], "module": "index.js", "scripts": { - "server": "http-server . -p 8002 -o http://127.0.0.1:8002/playground", + "server": "http-server . -p 8002 -o http://127.0.0.1:8002/playground/index.html", "build": "npm run build:min && npm run build-declaration", "build:dev": "node ./rollup/out/build-engine-cli.js --sourcemap --platform=universal --physics=cannon --destination=./bin/cocos-3d.dev.js", "build:min": "node ./rollup/out/build-engine-cli.js --compress --sourcemap --platform=universal --physics=cannon --destination=./bin/cocos3d-js.min.js", @@ -83,6 +83,8 @@ "rollup-plugin-terser": "^5.1.1", "rollup-plugin-uglify": "^6.0.2", "rollup-watch": "^4.3.1", + "spectorjs": "^0.9.10", + "stats.js": "^0.17.0", "tfig": "^1.1.0", "ts-jest": "^24.0.2", "tween.js": "github:cocos-creator/tween.js#cocos-master", diff --git a/playground/audio.html b/playground/audio.html deleted file mode 100644 index 7a75ce494c..0000000000 --- a/playground/audio.html +++ /dev/null @@ -1,163 +0,0 @@ - - - - - audio - - - - - - - - - - - - - - - diff --git a/playground/cocos2d-x.png b/playground/cocos2d-x.png deleted file mode 100644 index 6a78452419e26f0a5f61d70758c29395665abe47..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 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 diff --git a/playground/camera.js b/playground/common/camera.js similarity index 100% rename from playground/camera.js rename to playground/common/camera.js diff --git a/playground/cubetexture.png b/playground/common/texture.png similarity index 100% rename from playground/cubetexture.png rename to playground/common/texture.png diff --git a/playground/files.js b/playground/files.js deleted file mode 100644 index ebe3332c72..0000000000 --- a/playground/files.js +++ /dev/null @@ -1,12 +0,0 @@ -window.files = { - "demos": [ - "simple", - "gizmo", - "loadMaterial", - "planarShadow", - "savePrimitivesAsWavefrontOBJ", - "audio", - "ui", - "ui-render", - ], -}; diff --git a/playground/gizmo.html b/playground/gizmo.html deleted file mode 100644 index 678de0ff55..0000000000 --- a/playground/gizmo.html +++ /dev/null @@ -1,177 +0,0 @@ - - - - - gizmo - - - - - - - - - - - - - - - - diff --git a/playground/index.html b/playground/index.html index 8f9ba5d5bb..f49f118043 100644 --- a/playground/index.html +++ b/playground/index.html @@ -1,446 +1,100 @@ - - - - engine-3d / examples - - - - - - -
    -

    engine-3d / examples

    - - - - - -
    - - x -
    -
    -
    - - - - - - - - + + + + + + + + + + + + + + + + + +
    +
    +
    +
    + FPS +
    +
    + Spector +
    +
    + VConsole +
    +
    + + +
    + + + diff --git a/playground/loadMaterial.html b/playground/loadMaterial.html deleted file mode 100644 index 03e569854d..0000000000 --- a/playground/loadMaterial.html +++ /dev/null @@ -1,92 +0,0 @@ - - - - - load material - - - - - - - - - - - - - - - diff --git a/playground/planarShadow.html b/playground/planarShadow.html deleted file mode 100644 index 4e67cbc79a..0000000000 --- a/playground/planarShadow.html +++ /dev/null @@ -1,113 +0,0 @@ - - - - - planar shadow - - - - - - - - - - - - - - diff --git a/playground/savePrimitivesAsWavefrontOBJ.html b/playground/savePrimitivesAsWavefrontOBJ.html deleted file mode 100644 index 897b60e6a7..0000000000 --- a/playground/savePrimitivesAsWavefrontOBJ.html +++ /dev/null @@ -1,53 +0,0 @@ - - - - - spec-scroll-view - - - - - - - - - - - - - diff --git a/playground/shell.js b/playground/shell.js new file mode 100644 index 0000000000..0279a9b750 --- /dev/null +++ b/playground/shell.js @@ -0,0 +1,152 @@ +'use strict'; + +(() => { + function loadPromise(url) { + return new Promise((resolve, reject) => { + const xhr = new window.XMLHttpRequest(); + xhr.open('GET', url + '?_=' + new Date().getTime(), true); // force no cache + xhr.onreadystatechange = onreadystatechange; + xhr.send(null); + + function onreadystatechange(e) { + if (xhr.readyState !== 4) { + return; + } + + // Testing harness file:/// results in 0. + if ([0, 200, 304].indexOf(xhr.status) === -1) { + reject(`While loading from url ${url} server responded with a status of ${xhr.status}`); + } else { + resolve(e.target.response); + } + } + }); + } + + function _load(url) { + loadPromise(url).then(result => { + + if (window.dgui) { + window.dgui.destroy(); + window.dgui = null; + } + + cc.director.off(cc.Director.EVENT_BEFORE_UPDATE); + // cc.director.off(cc.Director.EVENT_AFTER_UPDATE); // should uncomment these after UI manager move to global + // cc.director.off(cc.Director.EVENT_BEFORE_DRAW); + // cc.director.off(cc.Director.EVENT_AFTER_DRAW); + cc.systemEvent.off(cc.SystemEvent.EventType.MOUSE_WHEEL); + cc.systemEvent.off(cc.SystemEvent.EventType.KEY_DOWN); + cc.systemEvent.off(cc.SystemEvent.EventType.KEY_UP); + cc.systemEvent.off(cc.SystemEvent.EventType.TOUCH_START); + cc.systemEvent.off(cc.SystemEvent.EventType.TOUCH_MOVE); + cc.systemEvent.off(cc.SystemEvent.EventType.TOUCH_END); + + // init dgui + if (window.dat) { + const dgui = new dat.GUI({ width: 270 }); + dgui.domElement.classList.add('dgui'); + window.dgui = dgui; + } + + const getCurAbsPath = () => { + const scripts = document.getElementsByTagName('script'); + const lastScriptPath = scripts[scripts.length -1].src; + const segs = lastScriptPath.split('/'); + if (segs.length >= 1) { + segs.pop(); + } + const path = segs.join('/') + '/'; + return path; + }; + + eval(`(() => {\n${result}\n})();\n\n//# sourceURL=${getCurAbsPath() + url}`); + window.cc.director.on(cc.Director.EVENT_BEFORE_UPDATE, () => { + window.stats.update(); + }); + + }).catch(err => { + console.error(err); + }); + } + + document.addEventListener('readystatechange', () => { + if (document.readyState !== 'complete') return; + + const view = document.getElementById('view'); + const showFPS = document.getElementById('showFPS'); + const enableSpector = document.getElementById('spector'); + const enableVConsole = document.getElementById('vconsole'); + const exampleList = document.getElementById('exampleList'); + + // update profile + showFPS.checked = localStorage.getItem('engine.showFPS') === 'true'; + enableSpector.checked = localStorage.getItem('engine.enableSpector') === 'true'; + enableVConsole.checked = localStorage.getItem('engine.enableVConsole') === 'true'; + let exampleIndex = parseInt(localStorage.getItem('engine.exampleIndex')); + if (isNaN(exampleIndex) || exampleIndex >= exampleList.childElementCount) exampleIndex = 0; + exampleList.selectedIndex = exampleIndex; + + // init stats + if (window.Stats) { + const stats = new window.Stats(); + stats.dom.style.cssText = 'position:fixed;top:0;right:0;cursor:pointer;opacity:0.9;z-index:10000'; + stats.dom.style.display = showFPS.checked ? 'block' : 'none'; + document.body.appendChild(stats.dom); + window.stats = stats; + showFPS.addEventListener('click', event => { + localStorage.setItem('engine.showFPS', event.target.checked); + stats.dom.style.display = event.target.checked ? 'block' : 'none'; + }); + } + + // init spector + const url = '../node_modules/spectorjs/dist/spector.bundle.js'; + loadPromise(url).then(result => { + eval(`${result}\n//# sourceURL=${url}`); + if (enableSpector.checked) { + window.spector = new window.SPECTOR.Spector(); + window.spector.displayUI(); + } + enableSpector.addEventListener('click', event => { + // localStorage.setItem('engine.enableSpector', event.target.checked); + if (enableSpector.checked) { + window.spector = new window.SPECTOR.Spector(); + window.spector.displayUI(); + } + }); + }); + + // init vconsole + if (window.VConsole) { + if (enableVConsole.checked) window.vconsole = new window.VConsole(); + enableVConsole.addEventListener('click', event => { + // localStorage.setItem('engine.enableVConsole', event.target.checked); + if (enableVConsole.checked) window.vconsole = new window.VConsole(); + }); + } + + // create canvas + const bcr = view.getBoundingClientRect(); + const canvas = document.createElement('canvas'); + canvas.classList.add('fit'); + canvas.tabIndex = -1; + canvas.id = 'canvas'; + canvas.width = bcr.width; + canvas.height = bcr.height; + view.appendChild(canvas); + + // init engine + window.cc.game.run({ id: canvas.id }, () => { + _load(exampleList.value); + window.addEventListener('resize', () => { + const bcr = view.getBoundingClientRect(); + cc.director.root.resize(bcr.width, bcr.height); + }); + exampleList.addEventListener('change', event => { + localStorage.setItem('engine.exampleIndex', event.target.selectedIndex); + _load(exampleList.value); + }); + }); + }); +})(); diff --git a/playground/simple.html b/playground/simple.html deleted file mode 100644 index 0a52e3d6bd..0000000000 --- a/playground/simple.html +++ /dev/null @@ -1,169 +0,0 @@ - - - - - simple - - - - - - - - - - - - - - - - - diff --git a/playground/src/collision-detection.js b/playground/src/collision-detection.js new file mode 100644 index 0000000000..f8e242ba2f --- /dev/null +++ b/playground/src/collision-detection.js @@ -0,0 +1,209 @@ + +const { cc, dgui } = window; +const { CameraComponent, Component, DirectionalLightComponent, GFXBlendFactor, Scene, + SphereColliderComponent, Material, ModelComponent, Node } = cc; +const { Color, randomRange, toRadian, Vec3, Vec4 } = cc.math; +const { sphere, capsule } = cc.primitives; +const { createMesh } = cc.utils; + +const dobj = { + playing: true, + play: () => { + dobj.playing = true; + }, + pause: () => { + dobj.playing = false; + }, + stop: () => { + dobj.playing = false; + emitters.forEach(e => { + e.reapAll(); + }); + }, + step: () => { + dobj.playing = true; + emitters.forEach(e => { + e.update(); + }); + dobj.playing = false; + } +}; + +const scene = new Scene(); +const poolSize = 50; +const hintMesh = createMesh(capsule(1)); +const sphereMesh = createMesh(sphere(1)); +const outOfBounds = (v, border = 20) => Math.abs(v.x) > border || Math.abs(v.y) > border || Math.abs(v.z) > border; + +const v3_1 = new Vec3(); + +class Element { + constructor () { + this.velocity = new Vec3(); + this.color = new Color(); + this.collided = false; + this.framesRemaining = 0; + this.pass = null; + this.hColor = 0; + this.node = null; + } +} + +// encapsulate an interesting emitter, emitted particles will +// annihilate after collision, if satisfying filter condition +class Emitter { + constructor (group, mask, pos, minAngle, maxAngle, color) { + this.node = new Node('emitter_' + group); + this.node.parent = scene; + this.node.setPosition(pos); + this.group = group; + this.mask = mask; + this.minAngle = minAngle; + this.maxAngle = maxAngle; + this.color = color; + this._deadpool = []; + this._livepool = []; + this._elements = []; + // emitter hint + const hint = new Node('hint'); + const hintModel = hint.addComponent(ModelComponent); + const hintMat = new Material(); + hintMat.initialize({ effectName: 'builtin-standard' }); + hintMat.setProperty('albedo', this.color); + hintMat.setProperty('metallic', 0.1); + hintModel.material = hintMat; + hintModel.mesh = hintMesh; + hint.parent = this.node; + // elements + for (let i = 0; i < poolSize; i++) { + const node = new Node(i); + node.parent = this.node; + // element info + const ele = new Element(); + ele.node = node; + ele.color.set(this.color); + // model + const model = node.addComponent(ModelComponent); + const mat = new Material(); + mat.initialize({ + effectName: 'builtin-standard', + states: { + blendState: { targets: [{ + blend: true, + blendSrc: GFXBlendFactor.SRC_ALPHA, + blendDst: GFXBlendFactor.ONE_MINUS_SRC_ALPHA, + blendDstAlpha: GFXBlendFactor.ONE_MINUS_SRC_ALPHA, + }] }, + depthStencilState: { depthTest: false }, + } + }); + mat.setProperty('metallic', 0.1); + ele.pass = mat.passes[0]; + ele.hColor = ele.pass.getHandle('albedo'); + ele.pass.setUniform(ele.hColor, ele.color); + model.material = mat; + model.mesh = sphereMesh; + // collider + const col = node.addComponent(SphereColliderComponent); + col.radius = 1; + col.isTrigger = true; + col.setGroup(this.group); col.setMask(this.mask); + col.on('onTriggerEnter', (e) => { + const col = e.selfCollider; + const ele = this._elements[col.node.name]; + if (ele.collided) return; + ele.color.a = 255; + ele.pass.setUniform(ele.hColor, ele.color); + ele.collided = true; + ele.framesRemaining = 5; + Vec3.set(ele.velocity, 0, 0, 0); + col.setGroup(0); col.setMask(0); + }); + // store + node.active = false; + this._deadpool.push(ele); + this._elements.push(ele); + } + } + + update () { + if (!dobj.playing) return; + for (let i = 0; i < this._livepool.length; i++) { + const ele = this._livepool[i]; + if (ele.collided) { + if (ele.framesRemaining-- <= 0) this.reap(ele); + } else { + Vec3.add(v3_1, ele.node.position, ele.velocity); + ele.node.setPosition(v3_1); + if (outOfBounds(v3_1)) this.reap(ele); + } + } + if (this._deadpool.length > 0) this.resurrect(); + // for (let i = 0; i < this._deadpool.length; i++) this.resurrect(); + } + + reap (ele) { + ele.node.active = false; + this._livepool.splice(this._livepool.indexOf(ele), 1); + this._deadpool.push(ele); + } + + reapAll () { + for (let i = 0; i < this._livepool.length; i++) { + const ele = this._livepool[i]; + ele.node.active = false; + this._deadpool.push(ele); + } + this._livepool.length = 0; + } + + resurrect () { + const ele = this._deadpool.pop(); + const theta = toRadian(randomRange(this.minAngle, this.maxAngle)); + const phi = randomRange(1, 2); + const speed = randomRange(0.1, 0.3); + Vec3.set(ele.velocity, Math.cos(theta) * Math.sin(phi) * speed, + Math.cos(phi) * speed, Math.sin(theta) * Math.sin(phi) * speed); + ele.color.a = this.color.a; ele.collided = false; + ele.pass.setUniform(ele.hColor, ele.color); + const col = ele.node.getComponent(SphereColliderComponent); + col.setGroup(this.group); col.setMask(this.mask); + ele.node.setPosition(0, 0, 0); + this._livepool.push(ele); + ele.node.active = true; + } +} + +// camera +const cameraNode = new Node('camera'); +cameraNode.parent = scene; +cameraNode.setPosition(-20, 50, 12); +cameraNode.lookAt(Vec3.ZERO); +cameraNode.addComponent(CameraComponent); +cameraNode.addComponent(FirstPersonCamera); + +// light +const light = new Node('light'); +light.parent = scene; +light.setRotationFromEuler(-80, 20, -40); +light.addComponent(DirectionalLightComponent); + +cc.director.on(cc.Director.EVENT_BEFORE_UPDATE, () => { + for (let i = 0; i < emitters.length; i++) { + emitters[i].update(); + } +}); + +dgui.add(dobj, 'play'); +dgui.add(dobj, 'pause'); +dgui.add(dobj, 'stop'); +dgui.add(dobj, 'step'); + +cc.director.runSceneImmediate(scene); // have to run the scene before set collider groups & masks + +// set the stage +const emitters = []; // a particle does not collide with those come from the same group +emitters.push(new Emitter(1, ~1, new Vec3(-10, 0, 10), 0, -90, new Color(204, 178, 128, 51))); +emitters.push(new Emitter(2, ~2, new Vec3( 10, 0, -10), 90, 180, new Color( 51, 76, 128, 51))); +emitters.push(new Emitter(4, ~4, new Vec3(-10, 0, -10), 0, 90, new Color(204, 76, 128, 51))); +emitters.push(new Emitter(8, ~8, new Vec3( 10, 0, 10), -90, -180, new Color( 51, 178, 128, 51))); diff --git a/playground/src/custom-effect.js b/playground/src/custom-effect.js new file mode 100644 index 0000000000..7c56aae3db --- /dev/null +++ b/playground/src/custom-effect.js @@ -0,0 +1,32 @@ + +cc.AssetLibrary.init({ + libraryPath: 'library', + rawAssetsBase: 'library', + rawAssets: { + assets: { + // https://github.com/cocos-creator/example-3d/blob/master/demo02/assets/effects/test.effect + "97051ce4-0cc9-4ae0-a584-d73943d7c11a": ["test", "cc.EffectAsset"] + } + } +}); + +const scene = new cc.Scene(); + +const cameraNode = new cc.Node('Camera'); +cameraNode.parent = scene; +cameraNode.setPosition(6, 0, 2); +cameraNode.setRotationFromEuler(0, 70, 0); +cameraNode.addComponent(cc.CameraComponent); +cameraNode.addComponent(FirstPersonCamera); + +const modelNode = new cc.Node('test'); +modelNode.parent = scene; +const modelComp = modelNode.addComponent('cc.ModelComponent'); +modelComp.mesh = cc.utils.createMesh(cc.primitives.sphere()); +cc.director.runSceneImmediate(scene); + +cc.loader.loadRes('test', cc.EffectAsset, (err, effect) => { + const material = new cc.Material(); + material.initialize({ effectAsset: effect }); + modelComp.material = material; +}); diff --git a/playground/src/gizmo.js b/playground/src/gizmo.js new file mode 100644 index 0000000000..f6b9d25978 --- /dev/null +++ b/playground/src/gizmo.js @@ -0,0 +1,128 @@ + +const scene = new cc.Scene('scene'); + +const cameraNode = new cc.Node('camera'); +cameraNode.parent = scene; +cameraNode.setPosition(20, 20, 20); +cameraNode.lookAt(cc.v3()); +cameraNode.addComponent(FirstPersonCamera); +cameraNode.addComponent(cc.CameraComponent); + +const material = new cc.Material(); +material.initialize({ + effectName: 'builtin-unlit', + defines: { USE_COLOR: true }, +}); +const material2 = new cc.Material(); +material2.initialize({ + effectName: 'builtin-unlit', + defines: { USE_COLOR: true }, + states: { + depthStencilState: { depthTest: false, depthWrite: false }, + rasterizerState: { cullMode: cc.GFXCullMode.NONE }, + blendState: { targets: [ + { blend: true, blendDst: cc.GFXBlendFactor.ONE_MINUS_SRC_ALPHA, blendDstAlpha: cc.GFXBlendFactor.ONE_MINUS_SRC_ALPHA } + ] } + } +}); + +const createArrow = (color, rotation) => { + const arrow = new cc.Node('arrow'); + arrow.setRotation(rotation); + const arrowHead = new cc.Node('arrowHead'); + arrowHead.parent = arrow; + arrowHead.setPosition(0, 10, 0); + const headModel = arrowHead.addComponent(cc.ModelComponent); + headModel.mesh = cc.utils.createMesh(cc.primitives.cone()); + headModel.material = material; + headModel.material.setProperty('color', color); + const arrowBody = new cc.Node('arrowBody'); + arrowBody.parent = arrow; + const bodyModel = arrowBody.addComponent(cc.ModelComponent); + bodyModel.mesh = cc.utils.createMesh({ + positions: [0, 0, 0, 0, 10, 0], + indices: [0, 1], + primitiveMode: cc.GFXPrimitiveMode.LINE_LIST, + }); + + bodyModel.material = material; + bodyModel.material.overridePipelineStates({ primitive: cc.GFXPrimitiveMode.LINE_LIST }); + bodyModel.material.setProperty('color', color); + return arrow; +}; +const createBorderPlane = (color, position, rotation) => { + const borderPlane = new cc.Node('borderPlane'); + borderPlane.setPosition(position); + borderPlane.setRotation(rotation); + const plane = new cc.Node('plane'); + plane.parent = borderPlane; + const planeModel = plane.addComponent(cc.ModelComponent); + const mesh = planeModel.mesh = cc.utils.createMesh(cc.primitives.quad()); + const submesh = mesh.renderingMesh.getSubmesh(0); + + const vbInfo = mesh.struct.vertexBundles[0].view; + submesh.vbuffer = mesh.data.buffer.slice(vbInfo.offset, vbInfo.offset + vbInfo.length); + const ibInfo = mesh.struct.primitives[0].indexView; + submesh.ibuffer = mesh.data.buffer.slice(ibInfo.offset, ibInfo.offset + ibInfo.length); + + planeModel.material = material2; + planeModel.material.setProperty('color', cc.color(0, 0, 0, 0).lerp(color, 0.5)); + const border = new cc.Node('border'); + border.parent = borderPlane; + const borderModel = border.addComponent(cc.ModelComponent); + borderModel.mesh = cc.utils.createMesh({ + positions: [0.5, 0.5, 0, 0, 0.5, 0, 0.5, 0, 0], + indices: [0, 1, 0, 2], + primitiveMode: cc.GFXPrimitiveMode.LINE_LIST, + }); + borderModel.material = material; + borderModel.material.overridePipelineStates({ primitive: cc.GFXPrimitiveMode.LINE_LIST }); + borderModel.material.setProperty('color', color); + return borderPlane; +}; + +const moveTool = new cc.Node('moveTool'); +moveTool.parent = scene; +createArrow(cc.Color.RED, cc.Quat.fromEuler(new cc.Quat(), 90, 0, 0)).parent = moveTool; +createArrow(cc.Color.GREEN, cc.Quat.fromEuler(new cc.Quat(), 0, 0, 0)).parent = moveTool; +createArrow(cc.Color.BLUE, cc.Quat.fromEuler(new cc.Quat(), 0, 0, -90)).parent = moveTool; +createBorderPlane(cc.Color.RED, cc.v3(0.5, 0.5, 0), cc.Quat.fromEuler(new cc.Quat(), 0, 0, 0)).parent = moveTool; +createBorderPlane(cc.Color.GREEN, cc.v3(0.5, 0, 0.5), cc.Quat.fromEuler(new cc.Quat(), -90, -90, 0)).parent = moveTool; +createBorderPlane(cc.Color.BLUE, cc.v3(0, 0.5, 0.5), cc.Quat.fromEuler(new cc.Quat(), 90, 0, 90)).parent = moveTool; + +const vel = cc.v3(), speed = 0.1, keys = 'IKJLOUR'; +const KEYCODE = new Array(keys.length).fill(0).reduce((acc, _, i) => (acc[keys[i]] = keys.charCodeAt(i), acc), {}); +cc.systemEvent.on(cc.SystemEvent.EventType.KEY_DOWN, (e) => { + if (e.keyCode === KEYCODE.I) vel.z = speed; + else if (e.keyCode === KEYCODE.K) vel.z = -speed; + else if (e.keyCode === KEYCODE.J) vel.x = speed; + else if (e.keyCode === KEYCODE.L) vel.x = -speed; + else if (e.keyCode === KEYCODE.O) vel.y = speed; + else if (e.keyCode === KEYCODE.U) vel.y = -speed; +}); +cc.systemEvent.on(cc.SystemEvent.EventType.KEY_UP, (e) => { + if (e.keyCode === KEYCODE.I) vel.z = 0; + else if (e.keyCode === KEYCODE.K) vel.z = 0; + else if (e.keyCode === KEYCODE.J) vel.x = 0; + else if (e.keyCode === KEYCODE.L) vel.x = 0; + else if (e.keyCode === KEYCODE.O) vel.y = 0; + else if (e.keyCode === KEYCODE.U) vel.y = 0; + else if (e.keyCode === KEYCODE.R) moveTool.active = !moveTool.active; +}); +cc.director.on(cc.Director.EVENT_BEFORE_UPDATE, () => { + moveTool.setPosition(cc.Vec3.add(moveTool._lpos, moveTool._lpos, vel)); +}); + +// cc.director.once(cc.Director.EVENT_BEFORE_UPDATE, () => { +// const comp = cc.director.getScene().getChildByName('moveTool').getChildByName('borderPlane').getChildByName('plane').getComponent(cc.ModelComponent); +// const model = comp.model.getSubModel(0); +// const ia = model.inputAssembler; +// if (ia && model.subMeshData) { +// const mesh = model.subMeshData; +// const points = [0, 1, 2]; +// ia.updateIndexBuffer(mesh.ibuffer, points); +// model.updateCommandBuffer(); +// } +// }); + +cc.director.runSceneImmediate(scene); diff --git a/playground/src/planar-shadow.js b/playground/src/planar-shadow.js new file mode 100644 index 0000000000..4871875e02 --- /dev/null +++ b/playground/src/planar-shadow.js @@ -0,0 +1,51 @@ + +const scene = new cc.Scene(); +const root = new cc.Node(); +root.parent = scene; +const altitude = 0; +root.setPosition(0, altitude, 0); + +const cameraNode = new cc.Node('Camera'); +cameraNode.parent = root; +cameraNode.setPosition(-16, 2, 16); +cameraNode.setRotationFromEuler(-12, -63, 0); +cameraNode.addComponent(cc.CameraComponent); +cameraNode.addComponent(FirstPersonCamera); + +const lightNode = new cc.Node('Light'); +lightNode.parent = root; +lightNode.setPosition(-10, 10, -10); +lightNode.setRotationFromEuler(-50, 0, 0); +const lightComp = lightNode.addComponent(cc.DirectionalLightComponent); + +const material = new cc.Material(); +material.initialize({ effectName: 'builtin-standard' }); + +const manifest = [ + { name: 'box', pos: cc.v3(0, 1, 10) }, + { name: 'sphere', pos: cc.v3(5, 1, 15) }, + { name: 'cylinder', pos: cc.v3(-5, 1, 5) }, + { name: 'torus', pos: cc.v3(5, 1, 5) }, + { name: 'cone', pos: cc.v3(-5, 1, 15) }, + { name: 'plane', pos: cc.v3(0, 0, 0), param: { width: 100, length: 100 } }, +]; +const models = {}; +for (const info of manifest) { + const modelNode = new cc.Node(`${info.name}`); + modelNode.parent = root; + const modelComp = modelNode.addComponent('cc.ModelComponent'); + modelComp.material = info.mat || material; + modelComp.mesh = cc.utils.createMesh(cc.primitives[info.name](info.param)); + if (info.name !== 'plane') modelComp.shadowCastingMode = cc.ModelComponent.ShadowCastingMode.ON; + modelNode.setPosition(info.pos); + models[info.name] = modelComp; +} + +const qt = cc.Quat.fromEuler(cc.quat(), 10, 20, 0); +models.plane.node.setRotation(qt); + +scene.globals.planarShadows.enabled = true; +scene.globals.planarShadows.setPlaneFromNode(models.plane.node); +scene.globals.planarShadows.shadowColor = cc.color('#2a4e90'); + +cc.director.runSceneImmediate(scene); diff --git a/playground/src/save-primitive-objs.js b/playground/src/save-primitive-objs.js new file mode 100644 index 0000000000..49b0a45501 --- /dev/null +++ b/playground/src/save-primitive-objs.js @@ -0,0 +1,19 @@ + +function write (name) { + const text = cc.primitives.toWavefrontOBJ(cc.primitives[name](), 100); + const blob = new Blob([text], { type: 'text/plain' }); + const anchor = document.createElement('a'); + anchor.download = `${name}.obj`; + anchor.href = (window.webkitURL || window.URL).createObjectURL(blob); + anchor.dataset.downloadurl = ['text/plain', anchor.download, anchor.href].join(':'); + anchor.click(); +} + +// write('box'); +// write('sphere'); +// write('cylinder'); +write('cone'); +// write('capsule'); +// write('torus'); +// write('plane'); +// write('quad'); diff --git a/playground/src/simple.js b/playground/src/simple.js new file mode 100644 index 0000000000..a439293048 --- /dev/null +++ b/playground/src/simple.js @@ -0,0 +1,116 @@ + +const geomList = ['box', 'sphere', 'cylinder', 'cone', 'torus', 'capsule']; + +const scene = new cc.Scene(); +const cameraNode = new cc.Node('Camera'); +cameraNode.parent = scene; +cameraNode.setPosition(-2.2, 3.6, -5.3); +cameraNode.setRotationFromEuler(-13.6, -165.5, 0); +cameraNode.addComponent(FirstPersonCamera); +const camComp = cameraNode.addComponent(cc.CameraComponent); + +const skybox = scene.globals.skybox; +skybox.enabled = true; +camComp.clearFlags = cc.CameraComponent.CameraClearFlag.SKYBOX; + +const lightNode = new cc.Node('Light'); +lightNode.parent = scene; +lightNode.setRotationFromEuler(-40, 0, 0); +lightNode.addComponent(cc.DirectionalLightComponent); + +// parsed effect file is embedded in cocos/3d/builtin/effects.js +const material = new cc.Material(); +material.initialize({ + /* * + effectName: 'builtin-standard', + /* */ + effectName: 'builtin-unlit', + defines: { USE_COLOR: true }, + /* */ +}); + +const len = 50; +const models = [], passes = []; +const color = cc.color(); +for (let i = 0; i < len; i++) { + const modelNode = new cc.Node(`${i}`); + modelNode.parent = scene; + const modelCom = modelNode.addComponent('cc.ModelComponent'); + modelCom.material = material; + 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('mainColor'); + +const canvasNode = new cc.Node('Canvas'); +canvasNode.parent = scene; +canvasNode.addComponent(cc.CanvasComponent); + +const spriteNode = new cc.Node('test-sprite'); +spriteNode.parent = canvasNode; +const spriteComp = spriteNode.addComponent('cc.SpriteComponent'); +spriteComp.sizeMode = cc.SpriteComponent.SizeMode.CUSTOM; +spriteNode.getComponent('cc.UITransformComponent').contentSize = cc.size(64, 64); +const widgetComp = spriteNode.addComponent(cc.WidgetComponent); +widgetComp.isAlignBottom = widgetComp.isAlignLeft = true; +widgetComp.bottom = widgetComp.left = 10; + +const img = document.createElement('img'); +img.src = './common/texture.png'; +img.onload = () => { + const textureCube = new cc.TextureCube(); + textureCube.image = { + right: new cc.ImageAsset(img), + left: new cc.ImageAsset(img), + top: new cc.ImageAsset(img), + bottom: new cc.ImageAsset(img), + front: new cc.ImageAsset(img), + back: new cc.ImageAsset(img), + }; + skybox.envmap = textureCube; + const texture = new cc.Texture2D(); + texture.image = new cc.ImageAsset(img); + const originalSize = cc.size(img.width, img.height); + const rect = cc.rect(0, 0, img.width, img.height); + const spriteFrame = new cc.SpriteFrame(); + spriteFrame.reset({ texture, originalSize, rect }); + spriteComp.spriteFrame = spriteFrame; +}; + +const material2 = new cc.Material(); +material2.initialize({ effectName: 'builtin-standard' }); +const modelNode2 = new cc.Node('test2'); +modelNode2.parent = scene; +const modelCom2 = modelNode2.addComponent('cc.ModelComponent'); +modelCom2.material = material2; +const shape2 = cc.primitives.sphere(); +modelCom2.mesh = cc.utils.createMesh(shape2); + +let buttonDown = false, pos = cc.v2(); +cc.systemEvent.on(cc.SystemEvent.EventType.TOUCH_START, (e) => buttonDown = true); +cc.systemEvent.on(cc.SystemEvent.EventType.TOUCH_END, (e) => buttonDown = false); +cc.systemEvent.on(cc.SystemEvent.EventType.TOUCH_MOVE, (e) => e.getLocation(pos)); + +cc.director.on(cc.Director.EVENT_BEFORE_UPDATE, () => { + if (buttonDown) { + const ray = camComp.screenPointToRay(pos.x, pos.y); + const scene = cc.director.getScene().renderScene; + const res = scene.raycastAllModels(ray); + if (res) scene.rayResultModels.forEach((r) => console.log(r.node.name, r.distance)); + } + models.forEach((m, i) => { + const dt = cc.director._deltaTime; + const t = cc.director._totalFrames / (60); + const rad = i * Math.PI * 8 / len; + const x = Math.cos(rad + t), y = Math.sin(rad + t); + let z = m.position.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); + }); +}); + +cc.director.runSceneImmediate(scene); diff --git a/playground/ui-render.html b/playground/ui-render.html deleted file mode 100644 index 4d1ffc7386..0000000000 --- a/playground/ui-render.html +++ /dev/null @@ -1,112 +0,0 @@ - - - - - ui - - - - - - - - - - - - - - - diff --git a/playground/ui.html b/playground/ui.html deleted file mode 100644 index 4dc35f1151..0000000000 --- a/playground/ui.html +++ /dev/null @@ -1,96 +0,0 @@ - - - - - ui - - - - - - - - - - - - - - - From dda6f56b797bace748a6ad429f2b2863531a3457 Mon Sep 17 00:00:00 2001 From: zxg0622 <247274249@qq.com> Date: Fri, 29 Nov 2019 13:43:03 +0800 Subject: [PATCH 11/21] change particle rendermode defines & adapt line billboard to new renderscene interface (#5806) --- cocos/core/renderer/scene/camera.ts | 8 +++- cocos/particle/billboard-component.ts | 28 ++++++++++--- cocos/particle/line-component.ts | 42 ++++++++++++++----- cocos/particle/models/line-model.ts | 4 +- .../renderer/particle-system-renderer.ts | 42 ++++++------------- cocos/ui/components/ui-model-component.ts | 2 +- 6 files changed, 74 insertions(+), 52 deletions(-) diff --git a/cocos/core/renderer/scene/camera.ts b/cocos/core/renderer/scene/camera.ts index c6d3d47244..ae8416dd3d 100644 --- a/cocos/core/renderer/scene/camera.ts +++ b/cocos/core/renderer/scene/camera.ts @@ -161,12 +161,16 @@ export class Camera { public attachToScene (scene: RenderScene) { this._scene = scene; - if (this._view) { this._view.enable(true); } + if (this._view) { + this._view.enable(true); + } } public detachFromScene () { this._scene = null; - if (this._view) { this._view.enable(false); } + if (this._view) { + this._view.enable(false); + } } public resize (width: number, height: number) { diff --git a/cocos/particle/billboard-component.ts b/cocos/particle/billboard-component.ts index 2a9c57b0d4..fd30f766d2 100644 --- a/cocos/particle/billboard-component.ts +++ b/cocos/particle/billboard-component.ts @@ -117,10 +117,12 @@ export class BillboardComponent extends Component { super(); } + public onLoad () { + this.createModel(); + } + public onEnable () { - if (!this._model) { - this.createModel(); - } + this.attachToScene(); this._model!.enabled = true; this.width = this._width; this.height = this._height; @@ -129,8 +131,21 @@ export class BillboardComponent extends Component { } public onDisable () { - if (this._model) { - this._model.enabled = false; + this.detachFromScene(); + } + + private attachToScene () { + if (this._model && this.node && this.node.scene) { + if (this._model.scene) { + this.detachFromScene(); + } + this._getRenderScene().addModel(this._model); + } + } + + private detachFromScene () { + if (this._model && this._model.scene) { + this._model.scene.removeModel(this._model); } } @@ -157,7 +172,8 @@ export class BillboardComponent extends Component { ], indices: [0, 1, 2, 1, 2, 3], }, undefined, { calculateBounds: false }); - this._model = this._getRenderScene().createModel(Model, this.node); + this._model = cc.director.root.createModel(Model, this.node); + this._model.initialize(this.node); if (this._material == null) { this._material = new Material(); this._material.copy(builtinResMgr.get('default-billboard-material')); diff --git a/cocos/particle/line-component.ts b/cocos/particle/line-component.ts index b136fc08d5..2842977a9c 100644 --- a/cocos/particle/line-component.ts +++ b/cocos/particle/line-component.ts @@ -199,19 +199,24 @@ export class LineComponent extends Component { super(); } + public onLoad () { + this._model = cc.director.root.createModel(LineModel); + this._model.initialize(this.node); + this._model.setCapacity(100); + if (this._material == null) { + this._material = new Material(); + this._material.copy(builtinResMgr.get('default-trail-material')); + define[CC_USE_WORLD_SPACE] = this.worldSpace; + this._material.recompileShaders(define); + } + this._model.setSubModelMaterial(0, this._material!); + } + public onEnable () { if (!this._model) { - this._model = this._getRenderScene().createModel(LineModel, this.node); - this._model.setCapacity(100); - if (this._material == null) { - this._material = new Material(); - this._material.copy(builtinResMgr.get('default-trail-material')); - define[CC_USE_WORLD_SPACE] = this.worldSpace; - this._material.recompileShaders(define); - } - this._model.setSubModelMaterial(0, this._material!); + return; } - this._model!.enabled = true; + this.attachToScene(); this.texture = this.texture; this.tile = this._tile; this.offset = this._offset; @@ -220,7 +225,22 @@ export class LineComponent extends Component { public onDisable () { if (this._model) { - this._model.enabled = false; + this.detachFromScene(); + } + } + + private attachToScene () { + if (this._model && this.node && this.node.scene) { + if (this._model.scene) { + this.detachFromScene(); + } + this._getRenderScene().addModel(this._model); + } + } + + private detachFromScene () { + if (this._model && this._model.scene) { + this._model.scene.removeModel(this._model); } } } diff --git a/cocos/particle/models/line-model.ts b/cocos/particle/models/line-model.ts index 7eb5929e6d..000993fa02 100644 --- a/cocos/particle/models/line-model.ts +++ b/cocos/particle/models/line-model.ts @@ -36,8 +36,8 @@ export class LineModel extends Model { private _vertCount: number = 0; private _indexCount: number = 0; - constructor (scene: RenderScene, node: INode) { - super(scene, node); + constructor () { + super(); this._capacity = 100; this._iaInfo = { drawInfos: [{ diff --git a/cocos/particle/renderer/particle-system-renderer.ts b/cocos/particle/renderer/particle-system-renderer.ts index 294271ff31..c1c248d04a 100644 --- a/cocos/particle/renderer/particle-system-renderer.ts +++ b/cocos/particle/renderer/particle-system-renderer.ts @@ -23,11 +23,13 @@ const _uvs = [ ]; const CC_USE_WORLD_SPACE = 'CC_USE_WORLD_SPACE'; -const CC_USE_BILLBOARD = 'CC_USE_BILLBOARD'; -const CC_USE_STRETCHED_BILLBOARD = 'CC_USE_STRETCHED_BILLBOARD'; -const CC_USE_HORIZONTAL_BILLBOARD = 'CC_USE_HORIZONTAL_BILLBOARD'; -const CC_USE_VERTICAL_BILLBOARD = 'CC_USE_VERTICAL_BILLBOARD'; -const CC_USE_MESH = 'CC_USE_MESH'; + +const CC_RENDER_MODE = 'CC_RENDER_MODE'; +const RENDER_MODE_BILLBOARD = 0; +const RENDER_MODE_STRETCHED_BILLBOARD = 1; +const RENDER_MODE_HORIZONTAL_BILLBOARD = 2; +const RENDER_MODE_VERTICAL_BILLBOARD = 3; +const RENDER_MODE_MESH = 4; const _vertex_attrs = [ { name: GFXAttributeName.ATTR_POSITION, format: GFXFormat.RGB32F }, // position @@ -466,37 +468,17 @@ export default class ParticleSystemRenderer { } if (this._renderMode === RenderMode.Billboard) { - this._defines[CC_USE_BILLBOARD] = true; - this._defines[CC_USE_STRETCHED_BILLBOARD] = false; - this._defines[CC_USE_HORIZONTAL_BILLBOARD] = false; - this._defines[CC_USE_VERTICAL_BILLBOARD] = false; - this._defines[CC_USE_MESH] = false; + this._defines[CC_RENDER_MODE] = RENDER_MODE_BILLBOARD; } else if (this._renderMode === RenderMode.StrecthedBillboard) { - this._defines[CC_USE_BILLBOARD] = false; - this._defines[CC_USE_STRETCHED_BILLBOARD] = true; - this._defines[CC_USE_HORIZONTAL_BILLBOARD] = false; - this._defines[CC_USE_VERTICAL_BILLBOARD] = false; - this._defines[CC_USE_MESH] = false; + this._defines[CC_RENDER_MODE] = RENDER_MODE_STRETCHED_BILLBOARD; this.frameTile_velLenScale.z = this._velocityScale; this.frameTile_velLenScale.w = this._lengthScale; } else if (this._renderMode === RenderMode.HorizontalBillboard) { - this._defines[CC_USE_BILLBOARD] = false; - this._defines[CC_USE_STRETCHED_BILLBOARD] = false; - this._defines[CC_USE_HORIZONTAL_BILLBOARD] = true; - this._defines[CC_USE_VERTICAL_BILLBOARD] = false; - this._defines[CC_USE_MESH] = false; + this._defines[CC_RENDER_MODE] = RENDER_MODE_HORIZONTAL_BILLBOARD; } else if (this._renderMode === RenderMode.VerticalBillboard) { - this._defines[CC_USE_BILLBOARD] = false; - this._defines[CC_USE_STRETCHED_BILLBOARD] = false; - this._defines[CC_USE_HORIZONTAL_BILLBOARD] = false; - this._defines[CC_USE_VERTICAL_BILLBOARD] = true; - this._defines[CC_USE_MESH] = false; + this._defines[CC_RENDER_MODE] = RENDER_MODE_VERTICAL_BILLBOARD; } else if (this._renderMode === RenderMode.Mesh) { - this._defines[CC_USE_BILLBOARD] = false; - this._defines[CC_USE_STRETCHED_BILLBOARD] = false; - this._defines[CC_USE_HORIZONTAL_BILLBOARD] = false; - this._defines[CC_USE_VERTICAL_BILLBOARD] = false; - this._defines[CC_USE_MESH] = true; + this._defines[CC_RENDER_MODE] = RENDER_MODE_MESH; } else { console.warn(`particle system renderMode ${this._renderMode} not support.`); } diff --git a/cocos/ui/components/ui-model-component.ts b/cocos/ui/components/ui-model-component.ts index ffceb60ce9..6f374232c5 100644 --- a/cocos/ui/components/ui-model-component.ts +++ b/cocos/ui/components/ui-model-component.ts @@ -92,7 +92,7 @@ export class UIModelComponent extends UIComponent { } this._modelComponent._sceneGetter = null; - if (cc.isValid(this.node, true)) { + if (cc.isValid(this._modelComponent, true)) { this._modelComponent._attachToScene(); } this._models = null; From 64e131795db89c2da99032bfd2352580fc7358f8 Mon Sep 17 00:00:00 2001 From: JoneLau <32630749+JoneLau@users.noreply.github.com> Date: Fri, 29 Nov 2019 13:45:05 +0800 Subject: [PATCH 12/21] align pos when horizontal or vertical (#5788) --- cocos/ui/components/layout-component.ts | 99 ++++++++++++++++--------- 1 file changed, 62 insertions(+), 37 deletions(-) diff --git a/cocos/ui/components/layout-component.ts b/cocos/ui/components/layout-component.ts index d7a0ddd9f4..2d074193c0 100644 --- a/cocos/ui/components/layout-component.ts +++ b/cocos/ui/components/layout-component.ts @@ -187,6 +187,8 @@ export class LayoutComponent extends Component { // return; // } } + + this._isAlign = true; this._doLayoutDirty(); } /** @@ -219,7 +221,9 @@ export class LayoutComponent extends Component { * @zh * 每个格子的大小,只有布局类型为 GRID 的时候才有效。 */ - @property + @property({ + tooltip: '每个格子的大小,只有布局类型为 GRID 的时候才有效', + }) // @constget get cellSize (): Readonly { return this._cellSize; @@ -240,6 +244,7 @@ export class LayoutComponent extends Component { */ @property({ type: AxisDirection, + tooltip: '起始轴方向类型,可进行水平和垂直布局排列,只有布局类型为 GRID 的时候才有效', }) get startAxis () { return this._startAxis; @@ -264,7 +269,9 @@ export class LayoutComponent extends Component { * @zh * 容器内左边距,只会在一个布局方向上生效。 */ - @property + @property({ + tooltip: '容器内左边距,只会在一个布局方向上生效', + }) get paddingLeft () { return this._paddingLeft; } @@ -281,7 +288,9 @@ export class LayoutComponent extends Component { * @zh * 容器内右边距,只会在一个布局方向上生效。 */ - @property + @property({ + tooltip: '容器内右边距,只会在一个布局方向上生效', + }) get paddingRight () { return this._paddingRight; } @@ -298,7 +307,9 @@ export class LayoutComponent extends Component { * @zh * 容器内上边距,只会在一个布局方向上生效。 */ - @property + @property({ + tooltip: '容器内上边距,只会在一个布局方向上生效', + }) get paddingTop () { return this._paddingTop; } @@ -315,7 +326,9 @@ export class LayoutComponent extends Component { * @zh * 容器内下边距,只会在一个布局方向上生效。 */ - @property + @property({ + tooltip: '容器内下边距,只会在一个布局方向上生效', + }) get paddingBottom () { return this._paddingBottom; } @@ -332,7 +345,9 @@ export class LayoutComponent extends Component { * @zh * 子节点之间的水平间距。 */ - @property + @property({ + tooltip: '子节点之间的水平间距', + }) get spacingX () { return this._spacingX; } @@ -350,7 +365,9 @@ export class LayoutComponent extends Component { * @zh * 子节点之间的垂直间距。 */ - @property + @property({ + tooltip: '子节点之间的垂直间距', + }) get spacingY () { return this._spacingY; } @@ -370,6 +387,7 @@ export class LayoutComponent extends Component { */ @property({ type: VerticalDirection, + tooltip: '垂直排列子节点的方向', }) get verticalDirection () { return this._verticalDirection; @@ -390,6 +408,7 @@ export class LayoutComponent extends Component { */ @property({ type: HorizontalDirection, + tooltip: '水平排列子节点的方向', }) get horizontalDirection () { return this._horizontalDirection; @@ -408,7 +427,9 @@ export class LayoutComponent extends Component { * @zh * 容器内边距,该属性会在四个布局方向上生效。 */ - @property + @property({ + tooltip: '容器内边距,该属性会在四个布局方向上生效', + }) get padding () { return this._paddingLeft; } @@ -424,7 +445,9 @@ export class LayoutComponent extends Component { * @zh * 子节点缩放比例是否影响布局。 */ - @property + @property({ + tooltip: '子节点缩放比例是否影响布局', + }) get affectedByScale () { return this._affectedByScale; } @@ -440,37 +463,39 @@ export class LayoutComponent extends Component { public static ResizeMode = ResizeMode; public static AxisDirection = AxisDirection; - private _layoutDirty = true; @property - private _resizeMode = ResizeMode.NONE; + protected _resizeMode = ResizeMode.NONE; // TODO: refactoring this name after data upgrade machanism is out. @property - private _N$layoutType = Type.NONE; + protected _N$layoutType = Type.NONE; @property - private _N$padding = 0; + protected _N$padding = 0; @property - private _cellSize = new Size(40, 40); + protected _cellSize = new Size(40, 40); @property - private _startAxis = AxisDirection.HORIZONTAL; + protected _startAxis = AxisDirection.HORIZONTAL; @property - private _paddingLeft = 0; + protected _paddingLeft = 0; @property - private _paddingRight = 0; + protected _paddingRight = 0; @property - private _paddingTop = 0; + protected _paddingTop = 0; @property - private _paddingBottom = 0; + protected _paddingBottom = 0; @property - private _spacingX = 0; + protected _spacingX = 0; @property - private _spacingY = 0; + protected _spacingY = 0; + @property + protected _verticalDirection = VerticalDirection.TOP_TO_BOTTOM; + @property + protected _horizontalDirection = HorizontalDirection.LEFT_TO_RIGHT; + @property + protected _affectedByScale = false; + private _layoutSize = new Size(300, 200); - @property - private _verticalDirection = VerticalDirection.TOP_TO_BOTTOM; - @property - private _horizontalDirection = HorizontalDirection.LEFT_TO_RIGHT; - @property - private _affectedByScale = false; + private _layoutDirty = true; + private _isAlign = false; /** * @zh @@ -585,7 +610,7 @@ export class LayoutComponent extends Component { this._doLayoutDirty(); } - private _doLayoutHorizontally (baseWidth, rowBreak, fnPositionY, applyChildren) { + private _doLayoutHorizontally (baseWidth: number, rowBreak: boolean, fnPositionY: Function, applyChildren: boolean) { const layoutAnchor = this.node.getAnchorPoint(); const children = this.node.children; @@ -722,7 +747,7 @@ export class LayoutComponent extends Component { private _doLayoutVertically ( baseHeight: number, columnBreak: boolean, - fnPositionX: (node: INode, columnMaxWidth: number, col: number) => number, + fnPositionX: Function, applyChildren: boolean, ) { const layoutAnchor = this.node.getAnchorPoint(); @@ -1054,24 +1079,24 @@ export class LayoutComponent extends Component { if (this._N$layoutType === Type.HORIZONTAL) { const newWidth = this._getHorizontalBaseWidth(this.node.children); - const fnPositionY = (child) => { - child.getPosition(_tempPos); - return _tempPos.y; + const fnPositionY = (child: INode) => { + const pos = this._isAlign ? this.node.position : child.position; + return pos.y; }; this._doLayoutHorizontally(newWidth, false, fnPositionY, true); - + this._isAlign = false; this.node.width = newWidth; } else if (this._N$layoutType === Type.VERTICAL) { const newHeight = this._getVerticalBaseHeight(this.node.children); - const fnPositionX = (child) => { - child.getPosition(_tempPos); - return _tempPos.x; + const fnPositionX = (child: INode) => { + const pos = this._isAlign ? this.node.position : child.position; + return pos.x; }; this._doLayoutVertically(newHeight, false, fnPositionX, true); - + this._isAlign = false; this.node.height = newHeight; } else if (this._N$layoutType === Type.NONE) { if (this._resizeMode === ResizeMode.CONTAINER) { From b92d852e73975f4b157aec92c0cee1e5bdba6001 Mon Sep 17 00:00:00 2001 From: JoneLau <32630749+JoneLau@users.noreply.github.com> Date: Fri, 29 Nov 2019 13:46:47 +0800 Subject: [PATCH 13/21] fix buffer overflow in ui static component (#5775) --- EngineErrorMap.md | 10 +++++++++- cocos/ui/components/ui-static-batch-component.ts | 7 ++++--- 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/EngineErrorMap.md b/EngineErrorMap.md index b41c587dd6..015a4662d4 100644 --- a/EngineErrorMap.md +++ b/EngineErrorMap.md @@ -574,7 +574,7 @@ Please do not specifiy "default" attribute in decorator of "%s" property in "%s" Default value must be initialized at their declaration: ``` // Before: -@property({ default: 0 }) // <-- +@property({ default: 0 }) // <-- @integer value; // After: @@ -1964,3 +1964,11 @@ texture size exceeds current device limits %d/%d ### 9200 Priority can't be set in Canvas node + +### 9300 + +The current buffer beyond the limit in ui static component, please reduce the amount + +### 9301 + +The UI has not been initialized diff --git a/cocos/ui/components/ui-static-batch-component.ts b/cocos/ui/components/ui-static-batch-component.ts index 336199aa28..5a1dd72920 100644 --- a/cocos/ui/components/ui-static-batch-component.ts +++ b/cocos/ui/components/ui-static-batch-component.ts @@ -32,7 +32,7 @@ import { UI } from '../../core/renderer/ui/ui'; import { MeshBuffer } from '../../core/renderer/ui/mesh-buffer'; import { ccclass, menu, executionOrder, property } from '../../core/data/class-decorator'; import { UIDrawBatch } from '../../core/renderer/ui/ui-draw-batch'; -import { director, Color, GFXBlendFactor, Material } from '../../core'; +import { director, Color, GFXBlendFactor, Material, warnID } from '../../core'; import { vfmt } from '../../core/renderer/ui/ui-vertex-format'; @@ -147,6 +147,7 @@ export class UIStaticBatchComponent extends UIRenderComponent { this._meshBuffer = buffer; } + this._meshBuffer!.reset(); for (let i = 0; i < this._uiDrawBathcList.length; i++) { const element = this._uiDrawBathcList[i]; element.destroy(ui); @@ -222,11 +223,11 @@ export class UIStaticBatchComponent extends UIRenderComponent { return director.root.ui; } - cc.warn('The UI has not been initialized'); + warnID(9301); return null; } protected _arrivalMaxBuffer (){ - cc.warn('The current buffer beyond the limit, please reduce the amount'); + warnID(9300); } } From 8ea37e5b40e8f2d6e948e51fcb16023518d29289 Mon Sep 17 00:00:00 2001 From: Yun Hsiao Wu Date: Mon, 2 Dec 2019 10:35:25 +0800 Subject: [PATCH 14/21] support more than 32 macros (#5807) * support more than 32 macros * update dynamic batching switch for transparent model --- cocos/core/3d/builtin/effects.ts | 16 +++++++---- cocos/core/renderer/core/program-lib.ts | 37 +++++++++++++++++++------ cocos/core/renderer/scene/model.ts | 1 + 3 files changed, 39 insertions(+), 15 deletions(-) diff --git a/cocos/core/3d/builtin/effects.ts b/cocos/core/3d/builtin/effects.ts index 1dabfb2837..62c6f3fba9 100644 --- a/cocos/core/3d/builtin/effects.ts +++ b/cocos/core/3d/builtin/effects.ts @@ -153,19 +153,19 @@ export default [ { "name": "builtin-standard", "techniques": [ - {"name":"opaque", "passes":[{"program":"builtin-standard|standard-vs:vert|standard-fs:frag", "properties":{"tilingOffset":{"value":[1, 1, 0, 0], "type":16}, "mainColor":{"value":[1, 1, 1, 1], "type":16, "handleInfo":["albedo", 0, 16]}, "albedoScale":{"value":[1, 1, 1], "type":15, "handleInfo":["albedoScaleAndCutoff", 0, 15]}, "alphaThreshold":{"value":[0.5], "type":13, "handleInfo":["albedoScaleAndCutoff", 3, 13]}, "occlusion":{"value":[1], "type":13, "handleInfo":["pbrParams", 0, 13]}, "roughness":{"value":[0.8], "type":13, "handleInfo":["pbrParams", 1, 13]}, "metallic":{"value":[0.6], "type":13, "handleInfo":["pbrParams", 2, 13]}, "normalStrenth":{"value":[1], "type":13, "handleInfo":["pbrParams", 3, 13]}, "emissive":{"value":[0, 0, 0, 1], "type":16}, "emissiveScale":{"value":[1, 1, 1, 1], "type":16}, "mainTexture":{"value":"grey", "type":28, "handleInfo":["albedoMap", 0, 28]}, "normalMap":{"value":"normal", "type":28}, "pbrMap":{"value":"grey", "type":28}, "metallicRoughnessMap":{"value":"grey", "type":28}, "occlusionMap":{"value":"white", "type":28}, "emissiveMap":{"value":"grey", "type":28}, "albedo":{"type":16, "value":[1, 1, 1, 1]}, "albedoScaleAndCutoff":{"type":16, "value":[1, 1, 1, 0.5]}, "pbrParams":{"type":16, "value":[1, 0.8, 0.6, 1]}, "albedoMap":{"type":28, "value":"grey"}}}]} + {"name":"opaque", "passes":[{"program":"builtin-standard|standard-vs:vert|standard-fs:frag", "properties":{"tilingOffset":{"value":[1, 1, 0, 0], "type":16}, "mainColor":{"value":[1, 1, 1, 1], "type":16, "handleInfo":["albedo", 0, 16]}, "albedoScale":{"value":[1, 1, 1], "type":15, "handleInfo":["albedoScaleAndCutoff", 0, 15]}, "alphaThreshold":{"value":[0.5], "type":13, "handleInfo":["albedoScaleAndCutoff", 3, 13]}, "occlusion":{"value":[1], "type":13, "handleInfo":["pbrParams", 0, 13]}, "roughness":{"value":[0.8], "type":13, "handleInfo":["pbrParams", 1, 13]}, "metallic":{"value":[0.6], "type":13, "handleInfo":["pbrParams", 2, 13]}, "normalStrenth":{"value":[1], "type":13, "handleInfo":["pbrParams", 3, 13]}, "emissive":{"value":[0, 0, 0, 1], "type":16}, "emissiveScale":{"value":[1, 1, 1], "type":15, "handleInfo":["emissiveScaleParam", 0, 15]}, "mainTexture":{"value":"grey", "type":28, "handleInfo":["albedoMap", 0, 28]}, "normalMap":{"value":"normal", "type":28}, "pbrMap":{"value":"grey", "type":28}, "metallicRoughnessMap":{"value":"grey", "type":28}, "occlusionMap":{"value":"white", "type":28}, "emissiveMap":{"value":"grey", "type":28}, "albedo":{"type":16, "value":[1, 1, 1, 1]}, "albedoScaleAndCutoff":{"type":16, "value":[1, 1, 1, 0.5]}, "pbrParams":{"type":16, "value":[1, 0.8, 0.6, 1]}, "emissiveScaleParam":{"type":16, "value":[1, 1, 1, 0]}, "albedoMap":{"type":28, "value":"grey"}}}]} ], "shaders": [ { "name": "builtin-standard|standard-vs:vert|standard-fs:frag", - "hash": 2119024206, + "hash": 1345843824, "glsl3": { - "vert": `\nprecision highp float;\nuniform CCGlobal {\n vec4 cc_time;\n vec4 cc_screenSize;\n vec4 cc_screenScale;\n vec4 cc_nativeSize;\n highp mat4 cc_matView;\n mat4 cc_matViewInv;\n mat4 cc_matProj;\n mat4 cc_matProjInv;\n mat4 cc_matViewProj;\n mat4 cc_matViewProjInv;\n vec4 cc_cameraPos;\n vec4 cc_exposure;\n vec4 cc_mainLitDir;\n vec4 cc_mainLitColor;\n vec4 cc_ambientSky;\n vec4 cc_ambientGround;\n};\n#if CC_USE_BATCHING\n in float a_dyn_batch_id;\n uniform CCLocalBatched {\n highp mat4 cc_matWorlds[10];\n };\n#else\nuniform CCLocal {\n highp mat4 cc_matWorld;\n highp mat4 cc_matWorldIT;\n};\n#endif\nstruct StandardVertInput {\n highp vec4 position;\n vec3 normal;\n vec4 tangent;\n};\nin vec3 a_position;\nin vec3 a_normal;\nin vec4 a_tangent;\n#if CC_USE_SKINNING\nin vec4 a_weights;\nin vec4 a_joints;\nuniform CCSkinningTexture {\n highp vec4 cc_jointsTextureInfo;\n};\nuniform CCSkinningAnimation {\n highp vec4 cc_jointsAnimInfo;\n};\nuniform sampler2D cc_jointsTexture;\n#if CC_USE_SKINNING == 1\n highp float decode32 (highp vec4 rgba) {\n rgba = rgba * 255.0;\n highp float Sign = 1.0 - step(128.0, rgba[3]) * 2.0;\n highp float Exponent = 2.0 * mod(rgba[3], 128.0) + step(128.0, rgba[2]) - 127.0;\n highp float Mantissa = mod(rgba[2], 128.0) * 65536.0 + rgba[1] * 256.0 + rgba[0] + 8388608.0;\n return Sign * exp2(Exponent - 23.0) * Mantissa;\n }\n#endif\n#if CC_USE_SKINNING == 1\n mat4 getJointMatrix (float i) {\n highp float j = 12.0 * (cc_jointsAnimInfo.x * i + cc_jointsAnimInfo.y) + cc_jointsTextureInfo.z;\n highp float invSize = cc_jointsTextureInfo.y;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointsTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = vec4(\n decode32(texture(cc_jointsTexture, vec2((x + 0.5) * invSize, y))),\n decode32(texture(cc_jointsTexture, vec2((x + 1.5) * invSize, y))),\n decode32(texture(cc_jointsTexture, vec2((x + 2.5) * invSize, y))),\n decode32(texture(cc_jointsTexture, vec2((x + 3.5) * invSize, y)))\n );\n vec4 v2 = vec4(\n decode32(texture(cc_jointsTexture, vec2((x + 4.5) * invSize, y))),\n decode32(texture(cc_jointsTexture, vec2((x + 5.5) * invSize, y))),\n decode32(texture(cc_jointsTexture, vec2((x + 6.5) * invSize, y))),\n decode32(texture(cc_jointsTexture, vec2((x + 7.5) * invSize, y)))\n );\n vec4 v3 = vec4(\n decode32(texture(cc_jointsTexture, vec2((x + 8.5) * invSize, y))),\n decode32(texture(cc_jointsTexture, vec2((x + 9.5) * invSize, y))),\n decode32(texture(cc_jointsTexture, vec2((x + 10.5) * invSize, y))),\n decode32(texture(cc_jointsTexture, vec2((x + 11.5) * invSize, y)))\n );\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n#elif CC_USE_SKINNING == 2\n mat4 getJointMatrix (float i) {\n highp float j = 3.0 * (cc_jointsAnimInfo.x * i + cc_jointsAnimInfo.y) + cc_jointsTextureInfo.z;\n highp float invSize = cc_jointsTextureInfo.y;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointsTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = texture(cc_jointsTexture, vec2((x + 0.5) * invSize, y));\n vec4 v2 = texture(cc_jointsTexture, vec2((x + 1.5) * invSize, y));\n vec4 v3 = texture(cc_jointsTexture, vec2((x + 2.5) * invSize, y));\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n#endif\nmat4 skinMatrix () {\n return getJointMatrix(a_joints.x) * a_weights.x\n + getJointMatrix(a_joints.y) * a_weights.y;\n + getJointMatrix(a_joints.z) * a_weights.z;\n + getJointMatrix(a_joints.w) * a_weights.w;\n}\nvoid CCSkin (inout vec4 position) {\n mat4 m = skinMatrix();\n position = m * position;\n}\nvoid CCSkin (inout StandardVertInput attr) {\n mat4 m = skinMatrix();\n attr.position = m * attr.position;\n attr.normal = (m * vec4(attr.normal, 0.0)).xyz;\n attr.tangent.xyz = (m * vec4(attr.tangent.xyz, 0.0)).xyz;\n}\n#endif\nuniform Constants {\n vec4 tilingOffset;\n vec4 albedo;\n vec4 albedoScaleAndCutoff;\n vec4 pbrParams;\n vec4 emissive;\n vec4 emissiveScale;\n};\n#if USE_VERTEX_COLOR\n in vec3 a_color;\n out vec3 v_color;\n#endif\nout vec3 v_position;\nout vec3 v_normal;\n#if USE_NORMAL_MAP\n out vec3 v_tangent;\n out vec3 v_bitangent;\n#endif\nin vec2 a_texCoord;\nout vec2 v_uv;\nin vec2 a_texCoord1;\nout vec2 v_uv1;\nhighp vec4 vert () {\n StandardVertInput In;\n In.position = vec4(a_position, 1.0);\n In.normal = a_normal;\n In.tangent = a_tangent;\n #if CC_USE_SKINNING\n CCSkin(In);\n #endif\n highp mat4 matWorld, matWorldIT;\n #if CC_USE_BATCHING\n matWorld = cc_matWorlds[int(a_dyn_batch_id + 0.5)];\n matWorldIT = matWorld;\n #else\n matWorld = cc_matWorld;\n matWorldIT = cc_matWorldIT;\n #endif\n highp vec4 pos = matWorld * In.position;\n v_position = pos.xyz;\n v_normal = normalize((matWorldIT * vec4(In.normal, 0.0)).xyz);\n #if USE_NORMAL_MAP\n v_tangent = normalize((matWorldIT * vec4(In.tangent.xyz, 0.0)).xyz);\n v_bitangent = cross(v_normal, v_tangent) * In.tangent.w;\n #endif\n v_uv = a_texCoord * tilingOffset.xy + tilingOffset.zw;\n v_uv1 = a_texCoord1 * tilingOffset.xy + tilingOffset.zw;\n #if USE_VERTEX_COLOR\n v_color = a_color;\n #endif\n return cc_matProj * (cc_matView * matWorld) * In.position;\n}\nvoid main() { gl_Position = vert(); }`, - "frag": `\nprecision highp float;\nuniform CCGlobal {\n vec4 cc_time;\n vec4 cc_screenSize;\n vec4 cc_screenScale;\n vec4 cc_nativeSize;\n highp mat4 cc_matView;\n mat4 cc_matViewInv;\n mat4 cc_matProj;\n mat4 cc_matProjInv;\n mat4 cc_matViewProj;\n mat4 cc_matViewProjInv;\n vec4 cc_cameraPos;\n vec4 cc_exposure;\n vec4 cc_mainLitDir;\n vec4 cc_mainLitColor;\n vec4 cc_ambientSky;\n vec4 cc_ambientGround;\n};\n#if CC_USE_IBL\nuniform samplerCube cc_environment;\nvec3 unpackRGBE (vec4 rgbe) {\n return rgbe.rgb * pow(2.0, rgbe.a * 255.0 - 128.0);\n}\n#endif\nvec3 SRGBToLinear (vec3 gamma) {\n return gamma * gamma;\n}\nuniform CCForwardLight {\n highp vec4 cc_sphereLitPos[2];\n vec4 cc_sphereLitSizeRange[2];\n vec4 cc_sphereLitColor[2];\n highp vec4 cc_spotLitPos[2];\n vec4 cc_spotLitSizeRangeAngle[2];\n vec4 cc_spotLitDir[2];\n vec4 cc_spotLitColor[2];\n};\nfloat SmoothDistAtt (float distSqr, float invSqrAttRadius) {\n float factor = distSqr * invSqrAttRadius;\n float smoothFactor = clamp(1.0 - factor * factor, 0.0, 1.0);\n return smoothFactor * smoothFactor;\n}\nfloat GetDistAtt (float distSqr, float invSqrAttRadius) {\n float attenuation = 1.0 / max(distSqr, 0.01*0.01);\n attenuation *= SmoothDistAtt(distSqr , invSqrAttRadius);\n return attenuation;\n}\nfloat GetAngleAtt (vec3 L, vec3 litDir, float litAngleScale, float litAngleOffset) {\n float cd = dot(litDir, L);\n float attenuation = clamp(cd * litAngleScale + litAngleOffset, 0.0, 1.0);\n return (attenuation * attenuation);\n}\nfloat GGXMobile (float roughness, float NoH, vec3 H, vec3 N) {\n vec3 NxH = cross(N, H);\n float OneMinusNoHSqr = dot(NxH, NxH);\n float a = roughness * roughness;\n float n = NoH * a;\n float p = a / (OneMinusNoHSqr + n * n);\n return p * p;\n}\nfloat CalcSpecular (float roughness, float NoH, vec3 H, vec3 N) {\n return (roughness*0.25 + 0.25) * GGXMobile(roughness, NoH, H, N);\n}\nvec3 BRDFApprox (vec3 specular, float roughness, float NoV) {\n const vec4 c0 = vec4(-1.0, -0.0275, -0.572, 0.022);\n const vec4 c1 = vec4(1.0, 0.0425, 1.04, -0.04);\n vec4 r = roughness * c0 + c1;\n float a004 = min( r.x * r.x, exp2( -9.28 * NoV ) ) * r.x + r.y;\n vec2 AB = vec2( -1.04, 1.04 ) * a004 + r.zw;\n AB.y *= clamp(50.0 * specular.g, 0.0, 1.0);\n return specular * AB.x + AB.y;\n}\nvec3 CalcDynamicLighting (vec3 worldPos, vec3 N, vec3 V, vec3 diffuse, vec3 specular, float roughness) {\n vec3 lighting = vec3(0.0);\n vec3 diffuseContrib = diffuse / 3.14159265359;\n for (int i = 0; i < 2; i++) {\n vec3 PLU = cc_sphereLitPos[i].xyz - worldPos;\n vec3 PL = normalize(PLU);\n vec3 PH = normalize(PL + V);\n float PNL = max(dot(N, PL), 0.001);\n float PNH = max(dot(N, PH), 0.0);\n float distSqr = dot(PLU, PLU);\n float litRadius = cc_sphereLitSizeRange[i].x;\n float litRadiusSqr = litRadius * litRadius;\n float illum = 3.14159265359 * (litRadiusSqr / max(litRadiusSqr , distSqr));\n float attRadiusSqrInv = 1.0 / max(cc_sphereLitSizeRange[i].y, 0.01);\n attRadiusSqrInv *= attRadiusSqrInv;\n float att = GetDistAtt(distSqr, attRadiusSqrInv);\n vec3 lspec = specular * CalcSpecular(roughness, PNH, PH, N);\n lighting += PNL * cc_sphereLitColor[i].rgb * cc_sphereLitColor[i].w * illum * att * (diffuseContrib + lspec);\n }\n for (int i = 0; i < 2; i++) {\n vec3 SLU = cc_spotLitPos[i].xyz - worldPos;\n vec3 SL = normalize(SLU);\n vec3 SH = normalize(SL + V);\n float SNL = max(dot(N, SL), 0.001);\n float SNH = max(dot(N, SH), 0.0);\n float distSqr = dot(SLU, SLU);\n float litRadius = cc_spotLitSizeRangeAngle[i].x;\n float litRadiusSqr = litRadius * litRadius;\n float illum = 3.14159265359 * (litRadiusSqr / max(litRadiusSqr , distSqr));\n float attRadiusSqrInv = 1.0 / max(cc_spotLitSizeRangeAngle[i].y, 0.01);\n attRadiusSqrInv *= attRadiusSqrInv;\n float cosInner = max(dot(-cc_spotLitDir[i].xyz, SL), 0.01);\n float cosOuter = cc_spotLitSizeRangeAngle[i].z;\n float litAngleScale = 1.0 / max(0.001, cosInner - cosOuter);\n float litAngleOffset = -cosOuter * litAngleScale;\n float att = GetDistAtt(distSqr, attRadiusSqrInv);\n att *= GetAngleAtt(SL, -cc_spotLitDir[i].xyz, litAngleScale, litAngleOffset);\n vec3 lspec = specular * CalcSpecular(roughness, SNH, SH, N);\n lighting += SNL * cc_spotLitColor[i].rgb * cc_spotLitColor[i].w * illum * att * (diffuseContrib + lspec);\n }\n return lighting;\n}\nstruct StandardSurface {\n vec4 albedo;\n vec3 position;\n vec3 normal;\n vec3 emissive;\n float roughness;\n float metallic;\n float occlusion;\n};\nvec4 CCStandardShading (StandardSurface s) {\n vec3 diffuse = s.albedo.rgb * (1.0 - s.metallic);\n vec3 specular = mix(vec3(0.04), s.albedo.rgb, s.metallic);\n vec3 N = normalize(s.normal);\n vec3 V = normalize(cc_cameraPos.xyz - s.position);\n vec3 L = normalize(-cc_mainLitDir.xyz);\n vec3 H = normalize(L+V);\n float NV = max(abs(dot(N, V)), 0.001);\n float NL = max(dot(N, L), 0.001);\n float NH = max(dot(N, H), 0.0);\n specular = BRDFApprox(specular, s.roughness, NV);\n vec3 diffuseContrib = diffuse / 3.14159265359;\n vec3 specularContrib = specular * CalcSpecular(s.roughness, NH, H, N);\n vec3 finalColor = NL * cc_mainLitColor.rgb * cc_mainLitColor.w * (diffuseContrib + specularContrib);\n finalColor += CalcDynamicLighting(s.position, N, V, diffuse, specular, s.roughness);\n float fAmb = 0.5 - N.y * 0.5;\n vec3 ambDiff = mix(cc_ambientSky.rgb, cc_ambientGround.rgb, fAmb) * cc_ambientSky.w;\n finalColor += (ambDiff.rgb * diffuse);\n #if CC_USE_IBL\n vec3 R = normalize(reflect(-V, N));\n vec4 envmap = textureLod(cc_environment, R, s.roughness * cc_ambientGround.w);\n #if CC_USE_IBL == 2\n vec3 env = unpackRGBE(envmap);\n #else\n vec3 env = SRGBToLinear(envmap.rgb) * cc_ambientSky.w;\n #endif\n finalColor += env * specular;\n #endif\n finalColor = finalColor * s.occlusion;\n #if CC_USE_HDR\n s.emissive *= cc_exposure.w;\n #endif\n finalColor += s.emissive;\n return vec4(finalColor, s.albedo.a);\n}\nvec3 ACESToneMap (vec3 color) {\n const float A = 2.51;\n const float B = 0.03;\n const float C = 2.43;\n const float D = 0.59;\n const float E = 0.14;\n return (color * (A * color + B)) / (color * (C * color + D) + E);\n}\nvec4 CCFragOutput (vec4 color) {\n #if !CC_USE_HDR\n color.rgb = sqrt(ACESToneMap(color.rgb));\n #endif\n return color;\n}\nuniform Constants {\n vec4 tilingOffset;\n vec4 albedo;\n vec4 albedoScaleAndCutoff;\n vec4 pbrParams;\n vec4 emissive;\n vec4 emissiveScale;\n};\nin vec3 v_position;\nin vec2 v_uv;\nin vec2 v_uv1;\nin vec3 v_normal;\n#if USE_VERTEX_COLOR\n in vec3 v_color;\n#endif\n#if USE_ALBEDO_MAP\n uniform sampler2D albedoMap;\n#endif\n#if USE_NORMAL_MAP\n in vec3 v_tangent;\n in vec3 v_bitangent;\n uniform sampler2D normalMap;\n#endif\n#if USE_PBR_MAP\n uniform sampler2D pbrMap;\n#endif\n#if USE_METALLIC_ROUGHNESS_MAP\n uniform sampler2D metallicRoughnessMap;\n#endif\n#if USE_OCCLUSION_MAP\n uniform sampler2D occlusionMap;\n#endif\n#if USE_EMISSIVE_MAP\n uniform sampler2D emissiveMap;\n#endif\n#if USE_ALPHA_TEST\n#endif\nvoid surf (out StandardSurface s) {\n vec4 baseColor = albedo;\n #if USE_VERTEX_COLOR\n baseColor.rgb *= v_color;\n #endif\n #if USE_ALBEDO_MAP\n vec4 texColor = texture(albedoMap, ALBEDO_UV);\n texColor.rgb = SRGBToLinear(texColor.rgb);\n baseColor *= texColor;\n #endif\n s.albedo = baseColor;\n s.albedo.rgb *= albedoScaleAndCutoff.xyz;\n #if USE_ALPHA_TEST\n if (s.albedo.ALPHA_TEST_CHANNEL < albedoScaleAndCutoff.w) discard;\n #endif\n s.normal = v_normal;\n #if USE_NORMAL_MAP\n vec3 nmmp = texture(normalMap, v_uv).xyz - vec3(0.5);\n s.normal =\n (nmmp.x * pbrParams.w) * normalize(v_tangent) +\n (nmmp.y * pbrParams.w) * normalize(v_bitangent) +\n nmmp.z * normalize(s.normal);\n #endif\n s.position = v_position;\n vec4 pbr = pbrParams;\n #if USE_PBR_MAP\n vec4 res = texture(pbrMap, v_uv);\n pbr.x *= res.OCCLUSION_CHANNEL;\n pbr.y *= res.ROUGHNESS_CHANNEL;\n pbr.z *= res.METALLIC_CHANNEL;\n #endif\n #if USE_METALLIC_ROUGHNESS_MAP\n vec4 metallicRoughness = texture(metallicRoughnessMap, v_uv);\n pbr.z *= metallicRoughness.METALLIC_CHANNEL;\n pbr.y *= metallicRoughness.ROUGHNESS_CHANNEL;\n #endif\n #if USE_OCCLUSION_MAP\n pbr.x *= texture(occlusionMap, v_uv).OCCLUSION_CHANNEL;\n #endif\n s.occlusion = clamp(pbr.x, 0.0, 0.96);\n s.roughness = clamp(pbr.y, 0.04, 1.0);\n s.metallic = pbr.z;\n s.emissive = emissive.rgb * emissiveScale.xyz;\n #if USE_EMISSIVE_MAP\n s.emissive *= SRGBToLinear(texture(emissiveMap, EMISSIVE_UV).rgb);\n #endif\n}\nvec4 frag () {\n StandardSurface s; surf(s);\n vec4 color = CCStandardShading(s);\n return CCFragOutput(color);\n}\nout vec4 cc_FragColor;\nvoid main() { cc_FragColor = frag(); }` + "vert": `\nprecision highp float;\nuniform CCGlobal {\n vec4 cc_time;\n vec4 cc_screenSize;\n vec4 cc_screenScale;\n vec4 cc_nativeSize;\n highp mat4 cc_matView;\n mat4 cc_matViewInv;\n mat4 cc_matProj;\n mat4 cc_matProjInv;\n mat4 cc_matViewProj;\n mat4 cc_matViewProjInv;\n vec4 cc_cameraPos;\n vec4 cc_exposure;\n vec4 cc_mainLitDir;\n vec4 cc_mainLitColor;\n vec4 cc_ambientSky;\n vec4 cc_ambientGround;\n};\n#if CC_USE_BATCHING\n in float a_dyn_batch_id;\n uniform CCLocalBatched {\n highp mat4 cc_matWorlds[10];\n };\n#else\nuniform CCLocal {\n highp mat4 cc_matWorld;\n highp mat4 cc_matWorldIT;\n};\n#endif\nstruct StandardVertInput {\n highp vec4 position;\n vec3 normal;\n vec4 tangent;\n};\nin vec3 a_position;\nin vec3 a_normal;\nin vec4 a_tangent;\n#if CC_USE_SKINNING\nin vec4 a_weights;\nin vec4 a_joints;\nuniform CCSkinningTexture {\n highp vec4 cc_jointsTextureInfo;\n};\nuniform CCSkinningAnimation {\n highp vec4 cc_jointsAnimInfo;\n};\nuniform sampler2D cc_jointsTexture;\n#if CC_USE_SKINNING == 1\n highp float decode32 (highp vec4 rgba) {\n rgba = rgba * 255.0;\n highp float Sign = 1.0 - step(128.0, rgba[3]) * 2.0;\n highp float Exponent = 2.0 * mod(rgba[3], 128.0) + step(128.0, rgba[2]) - 127.0;\n highp float Mantissa = mod(rgba[2], 128.0) * 65536.0 + rgba[1] * 256.0 + rgba[0] + 8388608.0;\n return Sign * exp2(Exponent - 23.0) * Mantissa;\n }\n#endif\n#if CC_USE_SKINNING == 1\n mat4 getJointMatrix (float i) {\n highp float j = 12.0 * (cc_jointsAnimInfo.x * i + cc_jointsAnimInfo.y) + cc_jointsTextureInfo.z;\n highp float invSize = cc_jointsTextureInfo.y;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointsTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = vec4(\n decode32(texture(cc_jointsTexture, vec2((x + 0.5) * invSize, y))),\n decode32(texture(cc_jointsTexture, vec2((x + 1.5) * invSize, y))),\n decode32(texture(cc_jointsTexture, vec2((x + 2.5) * invSize, y))),\n decode32(texture(cc_jointsTexture, vec2((x + 3.5) * invSize, y)))\n );\n vec4 v2 = vec4(\n decode32(texture(cc_jointsTexture, vec2((x + 4.5) * invSize, y))),\n decode32(texture(cc_jointsTexture, vec2((x + 5.5) * invSize, y))),\n decode32(texture(cc_jointsTexture, vec2((x + 6.5) * invSize, y))),\n decode32(texture(cc_jointsTexture, vec2((x + 7.5) * invSize, y)))\n );\n vec4 v3 = vec4(\n decode32(texture(cc_jointsTexture, vec2((x + 8.5) * invSize, y))),\n decode32(texture(cc_jointsTexture, vec2((x + 9.5) * invSize, y))),\n decode32(texture(cc_jointsTexture, vec2((x + 10.5) * invSize, y))),\n decode32(texture(cc_jointsTexture, vec2((x + 11.5) * invSize, y)))\n );\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n#elif CC_USE_SKINNING == 2\n mat4 getJointMatrix (float i) {\n highp float j = 3.0 * (cc_jointsAnimInfo.x * i + cc_jointsAnimInfo.y) + cc_jointsTextureInfo.z;\n highp float invSize = cc_jointsTextureInfo.y;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointsTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = texture(cc_jointsTexture, vec2((x + 0.5) * invSize, y));\n vec4 v2 = texture(cc_jointsTexture, vec2((x + 1.5) * invSize, y));\n vec4 v3 = texture(cc_jointsTexture, vec2((x + 2.5) * invSize, y));\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n#endif\nmat4 skinMatrix () {\n return getJointMatrix(a_joints.x) * a_weights.x\n + getJointMatrix(a_joints.y) * a_weights.y;\n + getJointMatrix(a_joints.z) * a_weights.z;\n + getJointMatrix(a_joints.w) * a_weights.w;\n}\nvoid CCSkin (inout vec4 position) {\n mat4 m = skinMatrix();\n position = m * position;\n}\nvoid CCSkin (inout StandardVertInput attr) {\n mat4 m = skinMatrix();\n attr.position = m * attr.position;\n attr.normal = (m * vec4(attr.normal, 0.0)).xyz;\n attr.tangent.xyz = (m * vec4(attr.tangent.xyz, 0.0)).xyz;\n}\n#endif\nuniform Constants {\n vec4 tilingOffset;\n vec4 albedo;\n vec4 albedoScaleAndCutoff;\n vec4 pbrParams;\n vec4 emissive;\n vec4 emissiveScaleParam;\n};\n#if USE_VERTEX_COLOR\n in vec3 a_color;\n out vec3 v_color;\n#endif\nout vec3 v_position;\nout vec3 v_normal;\n#if USE_NORMAL_MAP\n out vec3 v_tangent;\n out vec3 v_bitangent;\n#endif\nin vec2 a_texCoord;\nout vec2 v_uv;\nin vec2 a_texCoord1;\nout vec2 v_uv1;\nhighp vec4 vert () {\n StandardVertInput In;\n In.position = vec4(a_position, 1.0);\n In.normal = a_normal;\n In.tangent = a_tangent;\n #if CC_USE_SKINNING\n CCSkin(In);\n #endif\n highp mat4 matWorld, matWorldIT;\n #if CC_USE_BATCHING\n matWorld = cc_matWorlds[int(a_dyn_batch_id + 0.5)];\n matWorldIT = matWorld;\n #else\n matWorld = cc_matWorld;\n matWorldIT = cc_matWorldIT;\n #endif\n highp vec4 pos = matWorld * In.position;\n v_position = pos.xyz;\n v_normal = normalize((matWorldIT * vec4(In.normal, 0.0)).xyz);\n #if USE_NORMAL_MAP\n v_tangent = normalize((matWorldIT * vec4(In.tangent.xyz, 0.0)).xyz);\n v_bitangent = cross(v_normal, v_tangent) * In.tangent.w;\n #endif\n v_uv = a_texCoord * tilingOffset.xy + tilingOffset.zw;\n v_uv1 = a_texCoord1 * tilingOffset.xy + tilingOffset.zw;\n #if USE_VERTEX_COLOR\n v_color = a_color;\n #endif\n return cc_matProj * (cc_matView * matWorld) * In.position;\n}\nvoid main() { gl_Position = vert(); }`, + "frag": `\nprecision highp float;\nuniform CCGlobal {\n vec4 cc_time;\n vec4 cc_screenSize;\n vec4 cc_screenScale;\n vec4 cc_nativeSize;\n highp mat4 cc_matView;\n mat4 cc_matViewInv;\n mat4 cc_matProj;\n mat4 cc_matProjInv;\n mat4 cc_matViewProj;\n mat4 cc_matViewProjInv;\n vec4 cc_cameraPos;\n vec4 cc_exposure;\n vec4 cc_mainLitDir;\n vec4 cc_mainLitColor;\n vec4 cc_ambientSky;\n vec4 cc_ambientGround;\n};\n#if CC_USE_IBL\nuniform samplerCube cc_environment;\nvec3 unpackRGBE (vec4 rgbe) {\n return rgbe.rgb * pow(2.0, rgbe.a * 255.0 - 128.0);\n}\n#endif\nvec3 SRGBToLinear (vec3 gamma) {\n return gamma * gamma;\n}\nuniform CCForwardLight {\n highp vec4 cc_sphereLitPos[2];\n vec4 cc_sphereLitSizeRange[2];\n vec4 cc_sphereLitColor[2];\n highp vec4 cc_spotLitPos[2];\n vec4 cc_spotLitSizeRangeAngle[2];\n vec4 cc_spotLitDir[2];\n vec4 cc_spotLitColor[2];\n};\nfloat SmoothDistAtt (float distSqr, float invSqrAttRadius) {\n float factor = distSqr * invSqrAttRadius;\n float smoothFactor = clamp(1.0 - factor * factor, 0.0, 1.0);\n return smoothFactor * smoothFactor;\n}\nfloat GetDistAtt (float distSqr, float invSqrAttRadius) {\n float attenuation = 1.0 / max(distSqr, 0.01*0.01);\n attenuation *= SmoothDistAtt(distSqr , invSqrAttRadius);\n return attenuation;\n}\nfloat GetAngleAtt (vec3 L, vec3 litDir, float litAngleScale, float litAngleOffset) {\n float cd = dot(litDir, L);\n float attenuation = clamp(cd * litAngleScale + litAngleOffset, 0.0, 1.0);\n return (attenuation * attenuation);\n}\nfloat GGXMobile (float roughness, float NoH, vec3 H, vec3 N) {\n vec3 NxH = cross(N, H);\n float OneMinusNoHSqr = dot(NxH, NxH);\n float a = roughness * roughness;\n float n = NoH * a;\n float p = a / (OneMinusNoHSqr + n * n);\n return p * p;\n}\nfloat CalcSpecular (float roughness, float NoH, vec3 H, vec3 N) {\n return (roughness*0.25 + 0.25) * GGXMobile(roughness, NoH, H, N);\n}\nvec3 BRDFApprox (vec3 specular, float roughness, float NoV) {\n const vec4 c0 = vec4(-1.0, -0.0275, -0.572, 0.022);\n const vec4 c1 = vec4(1.0, 0.0425, 1.04, -0.04);\n vec4 r = roughness * c0 + c1;\n float a004 = min( r.x * r.x, exp2( -9.28 * NoV ) ) * r.x + r.y;\n vec2 AB = vec2( -1.04, 1.04 ) * a004 + r.zw;\n AB.y *= clamp(50.0 * specular.g, 0.0, 1.0);\n return specular * AB.x + AB.y;\n}\nvec3 CalcDynamicLighting (vec3 worldPos, vec3 N, vec3 V, vec3 diffuse, vec3 specular, float roughness) {\n vec3 lighting = vec3(0.0);\n vec3 diffuseContrib = diffuse / 3.14159265359;\n for (int i = 0; i < 2; i++) {\n vec3 PLU = cc_sphereLitPos[i].xyz - worldPos;\n vec3 PL = normalize(PLU);\n vec3 PH = normalize(PL + V);\n float PNL = max(dot(N, PL), 0.001);\n float PNH = max(dot(N, PH), 0.0);\n float distSqr = dot(PLU, PLU);\n float litRadius = cc_sphereLitSizeRange[i].x;\n float litRadiusSqr = litRadius * litRadius;\n float illum = 3.14159265359 * (litRadiusSqr / max(litRadiusSqr , distSqr));\n float attRadiusSqrInv = 1.0 / max(cc_sphereLitSizeRange[i].y, 0.01);\n attRadiusSqrInv *= attRadiusSqrInv;\n float att = GetDistAtt(distSqr, attRadiusSqrInv);\n vec3 lspec = specular * CalcSpecular(roughness, PNH, PH, N);\n lighting += PNL * cc_sphereLitColor[i].rgb * cc_sphereLitColor[i].w * illum * att * (diffuseContrib + lspec);\n }\n for (int i = 0; i < 2; i++) {\n vec3 SLU = cc_spotLitPos[i].xyz - worldPos;\n vec3 SL = normalize(SLU);\n vec3 SH = normalize(SL + V);\n float SNL = max(dot(N, SL), 0.001);\n float SNH = max(dot(N, SH), 0.0);\n float distSqr = dot(SLU, SLU);\n float litRadius = cc_spotLitSizeRangeAngle[i].x;\n float litRadiusSqr = litRadius * litRadius;\n float illum = 3.14159265359 * (litRadiusSqr / max(litRadiusSqr , distSqr));\n float attRadiusSqrInv = 1.0 / max(cc_spotLitSizeRangeAngle[i].y, 0.01);\n attRadiusSqrInv *= attRadiusSqrInv;\n float cosInner = max(dot(-cc_spotLitDir[i].xyz, SL), 0.01);\n float cosOuter = cc_spotLitSizeRangeAngle[i].z;\n float litAngleScale = 1.0 / max(0.001, cosInner - cosOuter);\n float litAngleOffset = -cosOuter * litAngleScale;\n float att = GetDistAtt(distSqr, attRadiusSqrInv);\n att *= GetAngleAtt(SL, -cc_spotLitDir[i].xyz, litAngleScale, litAngleOffset);\n vec3 lspec = specular * CalcSpecular(roughness, SNH, SH, N);\n lighting += SNL * cc_spotLitColor[i].rgb * cc_spotLitColor[i].w * illum * att * (diffuseContrib + lspec);\n }\n return lighting;\n}\nstruct StandardSurface {\n vec4 albedo;\n vec3 position;\n vec3 normal;\n vec3 emissive;\n float roughness;\n float metallic;\n float occlusion;\n};\nvec4 CCStandardShading (StandardSurface s) {\n vec3 diffuse = s.albedo.rgb * (1.0 - s.metallic);\n vec3 specular = mix(vec3(0.04), s.albedo.rgb, s.metallic);\n vec3 N = normalize(s.normal);\n vec3 V = normalize(cc_cameraPos.xyz - s.position);\n vec3 L = normalize(-cc_mainLitDir.xyz);\n vec3 H = normalize(L+V);\n float NV = max(abs(dot(N, V)), 0.001);\n float NL = max(dot(N, L), 0.001);\n float NH = max(dot(N, H), 0.0);\n specular = BRDFApprox(specular, s.roughness, NV);\n vec3 diffuseContrib = diffuse / 3.14159265359;\n vec3 specularContrib = specular * CalcSpecular(s.roughness, NH, H, N);\n vec3 finalColor = NL * cc_mainLitColor.rgb * cc_mainLitColor.w * (diffuseContrib + specularContrib);\n finalColor += CalcDynamicLighting(s.position, N, V, diffuse, specular, s.roughness);\n float fAmb = 0.5 - N.y * 0.5;\n vec3 ambDiff = mix(cc_ambientSky.rgb, cc_ambientGround.rgb, fAmb) * cc_ambientSky.w;\n finalColor += (ambDiff.rgb * diffuse);\n #if CC_USE_IBL\n vec3 R = normalize(reflect(-V, N));\n vec4 envmap = textureLod(cc_environment, R, s.roughness * cc_ambientGround.w);\n #if CC_USE_IBL == 2\n vec3 env = unpackRGBE(envmap);\n #else\n vec3 env = SRGBToLinear(envmap.rgb) * cc_ambientSky.w;\n #endif\n finalColor += env * specular;\n #endif\n finalColor = finalColor * s.occlusion;\n #if CC_USE_HDR\n s.emissive *= cc_exposure.w;\n #endif\n finalColor += s.emissive;\n return vec4(finalColor, s.albedo.a);\n}\nvec3 ACESToneMap (vec3 color) {\n const float A = 2.51;\n const float B = 0.03;\n const float C = 2.43;\n const float D = 0.59;\n const float E = 0.14;\n return (color * (A * color + B)) / (color * (C * color + D) + E);\n}\nvec4 CCFragOutput (vec4 color) {\n #if !CC_USE_HDR\n color.rgb = sqrt(ACESToneMap(color.rgb));\n #endif\n return color;\n}\nuniform Constants {\n vec4 tilingOffset;\n vec4 albedo;\n vec4 albedoScaleAndCutoff;\n vec4 pbrParams;\n vec4 emissive;\n vec4 emissiveScaleParam;\n};\nin vec3 v_position;\nin vec2 v_uv;\nin vec2 v_uv1;\nin vec3 v_normal;\n#if USE_VERTEX_COLOR\n in vec3 v_color;\n#endif\n#if USE_ALBEDO_MAP\n uniform sampler2D albedoMap;\n#endif\n#if USE_NORMAL_MAP\n in vec3 v_tangent;\n in vec3 v_bitangent;\n uniform sampler2D normalMap;\n#endif\n#if USE_PBR_MAP\n uniform sampler2D pbrMap;\n#endif\n#if USE_METALLIC_ROUGHNESS_MAP\n uniform sampler2D metallicRoughnessMap;\n#endif\n#if USE_OCCLUSION_MAP\n uniform sampler2D occlusionMap;\n#endif\n#if USE_EMISSIVE_MAP\n uniform sampler2D emissiveMap;\n#endif\n#if USE_ALPHA_TEST\n#endif\nvoid surf (out StandardSurface s) {\n vec4 baseColor = albedo;\n #if USE_VERTEX_COLOR\n baseColor.rgb *= v_color;\n #endif\n #if USE_ALBEDO_MAP\n vec4 texColor = texture(albedoMap, ALBEDO_UV);\n texColor.rgb = SRGBToLinear(texColor.rgb);\n baseColor *= texColor;\n #endif\n s.albedo = baseColor;\n s.albedo.rgb *= albedoScaleAndCutoff.xyz;\n #if USE_ALPHA_TEST\n if (s.albedo.ALPHA_TEST_CHANNEL < albedoScaleAndCutoff.w) discard;\n #endif\n s.normal = v_normal;\n #if USE_NORMAL_MAP\n vec3 nmmp = texture(normalMap, NORMAL_UV).xyz - vec3(0.5);\n s.normal =\n (nmmp.x * pbrParams.w) * normalize(v_tangent) +\n (nmmp.y * pbrParams.w) * normalize(v_bitangent) +\n nmmp.z * normalize(s.normal);\n #endif\n s.position = v_position;\n vec4 pbr = pbrParams;\n #if USE_PBR_MAP\n vec4 res = texture(pbrMap, PBR_UV);\n pbr.x *= res.OCCLUSION_CHANNEL;\n pbr.y *= res.ROUGHNESS_CHANNEL;\n pbr.z *= res.METALLIC_CHANNEL;\n #endif\n #if USE_METALLIC_ROUGHNESS_MAP\n vec4 metallicRoughness = texture(metallicRoughnessMap, METALLIC_ROUGHNESS_UV);\n pbr.z *= metallicRoughness.METALLIC_CHANNEL;\n pbr.y *= metallicRoughness.ROUGHNESS_CHANNEL;\n #endif\n #if USE_OCCLUSION_MAP\n pbr.x *= texture(occlusionMap, OCCLUSION_UV).OCCLUSION_CHANNEL;\n #endif\n s.occlusion = clamp(pbr.x, 0.0, 0.96);\n s.roughness = clamp(pbr.y, 0.04, 1.0);\n s.metallic = pbr.z;\n s.emissive = emissive.rgb * emissiveScaleParam.xyz;\n #if USE_EMISSIVE_MAP\n s.emissive *= SRGBToLinear(texture(emissiveMap, EMISSIVE_UV).rgb);\n #endif\n}\nvec4 frag () {\n StandardSurface s; surf(s);\n vec4 color = CCStandardShading(s);\n return CCFragOutput(color);\n}\nout vec4 cc_FragColor;\nvoid main() { cc_FragColor = frag(); }` }, "glsl1": { "vert": `\nprecision highp float;\nuniform highp mat4 cc_matView;\nuniform mat4 cc_matProj;\n#if CC_USE_BATCHING\n attribute float a_dyn_batch_id;\n uniform highp mat4 cc_matWorlds[10];\n#else\nuniform highp mat4 cc_matWorld;\nuniform highp mat4 cc_matWorldIT;\n#endif\nstruct StandardVertInput {\n highp vec4 position;\n vec3 normal;\n vec4 tangent;\n};\nattribute vec3 a_position;\nattribute vec3 a_normal;\nattribute vec4 a_tangent;\n#if CC_USE_SKINNING\nattribute vec4 a_weights;\nattribute vec4 a_joints;\nuniform highp vec4 cc_jointsTextureInfo;\nuniform highp vec4 cc_jointsAnimInfo;\nuniform sampler2D cc_jointsTexture;\n#if CC_USE_SKINNING == 1\n highp float decode32 (highp vec4 rgba) {\n rgba = rgba * 255.0;\n highp float Sign = 1.0 - step(128.0, rgba[3]) * 2.0;\n highp float Exponent = 2.0 * mod(rgba[3], 128.0) + step(128.0, rgba[2]) - 127.0;\n highp float Mantissa = mod(rgba[2], 128.0) * 65536.0 + rgba[1] * 256.0 + rgba[0] + 8388608.0;\n return Sign * exp2(Exponent - 23.0) * Mantissa;\n }\n#endif\n#if CC_USE_SKINNING == 1\n mat4 getJointMatrix (float i) {\n highp float j = 12.0 * (cc_jointsAnimInfo.x * i + cc_jointsAnimInfo.y) + cc_jointsTextureInfo.z;\n highp float invSize = cc_jointsTextureInfo.y;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointsTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = vec4(\n decode32(texture2D(cc_jointsTexture, vec2((x + 0.5) * invSize, y))),\n decode32(texture2D(cc_jointsTexture, vec2((x + 1.5) * invSize, y))),\n decode32(texture2D(cc_jointsTexture, vec2((x + 2.5) * invSize, y))),\n decode32(texture2D(cc_jointsTexture, vec2((x + 3.5) * invSize, y)))\n );\n vec4 v2 = vec4(\n decode32(texture2D(cc_jointsTexture, vec2((x + 4.5) * invSize, y))),\n decode32(texture2D(cc_jointsTexture, vec2((x + 5.5) * invSize, y))),\n decode32(texture2D(cc_jointsTexture, vec2((x + 6.5) * invSize, y))),\n decode32(texture2D(cc_jointsTexture, vec2((x + 7.5) * invSize, y)))\n );\n vec4 v3 = vec4(\n decode32(texture2D(cc_jointsTexture, vec2((x + 8.5) * invSize, y))),\n decode32(texture2D(cc_jointsTexture, vec2((x + 9.5) * invSize, y))),\n decode32(texture2D(cc_jointsTexture, vec2((x + 10.5) * invSize, y))),\n decode32(texture2D(cc_jointsTexture, vec2((x + 11.5) * invSize, y)))\n );\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n#elif CC_USE_SKINNING == 2\n mat4 getJointMatrix (float i) {\n highp float j = 3.0 * (cc_jointsAnimInfo.x * i + cc_jointsAnimInfo.y) + cc_jointsTextureInfo.z;\n highp float invSize = cc_jointsTextureInfo.y;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointsTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = texture2D(cc_jointsTexture, vec2((x + 0.5) * invSize, y));\n vec4 v2 = texture2D(cc_jointsTexture, vec2((x + 1.5) * invSize, y));\n vec4 v3 = texture2D(cc_jointsTexture, vec2((x + 2.5) * invSize, y));\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n#endif\nmat4 skinMatrix () {\n return getJointMatrix(a_joints.x) * a_weights.x\n + getJointMatrix(a_joints.y) * a_weights.y;\n + getJointMatrix(a_joints.z) * a_weights.z;\n + getJointMatrix(a_joints.w) * a_weights.w;\n}\nvoid CCSkin (inout vec4 position) {\n mat4 m = skinMatrix();\n position = m * position;\n}\nvoid CCSkin (inout StandardVertInput attr) {\n mat4 m = skinMatrix();\n attr.position = m * attr.position;\n attr.normal = (m * vec4(attr.normal, 0.0)).xyz;\n attr.tangent.xyz = (m * vec4(attr.tangent.xyz, 0.0)).xyz;\n}\n#endif\nuniform vec4 tilingOffset;\n#if USE_VERTEX_COLOR\n attribute vec3 a_color;\n varying vec3 v_color;\n#endif\nvarying vec3 v_position;\nvarying vec3 v_normal;\n#if USE_NORMAL_MAP\n varying vec3 v_tangent;\n varying vec3 v_bitangent;\n#endif\nattribute vec2 a_texCoord;\nvarying vec2 v_uv;\nattribute vec2 a_texCoord1;\nvarying vec2 v_uv1;\nhighp vec4 vert () {\n StandardVertInput In;\n In.position = vec4(a_position, 1.0);\n In.normal = a_normal;\n In.tangent = a_tangent;\n #if CC_USE_SKINNING\n CCSkin(In);\n #endif\n highp mat4 matWorld, matWorldIT;\n #if CC_USE_BATCHING\n matWorld = cc_matWorlds[int(a_dyn_batch_id + 0.5)];\n matWorldIT = matWorld;\n #else\n matWorld = cc_matWorld;\n matWorldIT = cc_matWorldIT;\n #endif\n highp vec4 pos = matWorld * In.position;\n v_position = pos.xyz;\n v_normal = normalize((matWorldIT * vec4(In.normal, 0.0)).xyz);\n #if USE_NORMAL_MAP\n v_tangent = normalize((matWorldIT * vec4(In.tangent.xyz, 0.0)).xyz);\n v_bitangent = cross(v_normal, v_tangent) * In.tangent.w;\n #endif\n v_uv = a_texCoord * tilingOffset.xy + tilingOffset.zw;\n v_uv1 = a_texCoord1 * tilingOffset.xy + tilingOffset.zw;\n #if USE_VERTEX_COLOR\n v_color = a_color;\n #endif\n return cc_matProj * (cc_matView * matWorld) * In.position;\n}\nvoid main() { gl_Position = vert(); }`, - "frag": `\n#if CC_USE_IBL\n #ifdef GL_EXT_shader_texture_lod\n #extension GL_EXT_shader_texture_lod : enable\n #endif\n#endif\nprecision highp float;\nuniform vec4 cc_cameraPos;\nuniform vec4 cc_exposure;\nuniform vec4 cc_mainLitDir;\nuniform vec4 cc_mainLitColor;\nuniform vec4 cc_ambientSky;\nuniform vec4 cc_ambientGround;\n#if CC_USE_IBL\nuniform samplerCube cc_environment;\nvec3 unpackRGBE (vec4 rgbe) {\n return rgbe.rgb * pow(2.0, rgbe.a * 255.0 - 128.0);\n}\n#endif\nvec3 SRGBToLinear (vec3 gamma) {\n return gamma * gamma;\n}\nuniform highp vec4 cc_sphereLitPos[2];\nuniform vec4 cc_sphereLitSizeRange[2];\nuniform vec4 cc_sphereLitColor[2];\nuniform highp vec4 cc_spotLitPos[2];\nuniform vec4 cc_spotLitSizeRangeAngle[2];\nuniform vec4 cc_spotLitDir[2];\nuniform vec4 cc_spotLitColor[2];\nfloat SmoothDistAtt (float distSqr, float invSqrAttRadius) {\n float factor = distSqr * invSqrAttRadius;\n float smoothFactor = clamp(1.0 - factor * factor, 0.0, 1.0);\n return smoothFactor * smoothFactor;\n}\nfloat GetDistAtt (float distSqr, float invSqrAttRadius) {\n float attenuation = 1.0 / max(distSqr, 0.01*0.01);\n attenuation *= SmoothDistAtt(distSqr , invSqrAttRadius);\n return attenuation;\n}\nfloat GetAngleAtt (vec3 L, vec3 litDir, float litAngleScale, float litAngleOffset) {\n float cd = dot(litDir, L);\n float attenuation = clamp(cd * litAngleScale + litAngleOffset, 0.0, 1.0);\n return (attenuation * attenuation);\n}\nfloat GGXMobile (float roughness, float NoH, vec3 H, vec3 N) {\n vec3 NxH = cross(N, H);\n float OneMinusNoHSqr = dot(NxH, NxH);\n float a = roughness * roughness;\n float n = NoH * a;\n float p = a / (OneMinusNoHSqr + n * n);\n return p * p;\n}\nfloat CalcSpecular (float roughness, float NoH, vec3 H, vec3 N) {\n return (roughness*0.25 + 0.25) * GGXMobile(roughness, NoH, H, N);\n}\nvec3 BRDFApprox (vec3 specular, float roughness, float NoV) {\n const vec4 c0 = vec4(-1.0, -0.0275, -0.572, 0.022);\n const vec4 c1 = vec4(1.0, 0.0425, 1.04, -0.04);\n vec4 r = roughness * c0 + c1;\n float a004 = min( r.x * r.x, exp2( -9.28 * NoV ) ) * r.x + r.y;\n vec2 AB = vec2( -1.04, 1.04 ) * a004 + r.zw;\n AB.y *= clamp(50.0 * specular.g, 0.0, 1.0);\n return specular * AB.x + AB.y;\n}\nvec3 CalcDynamicLighting (vec3 worldPos, vec3 N, vec3 V, vec3 diffuse, vec3 specular, float roughness) {\n vec3 lighting = vec3(0.0);\n vec3 diffuseContrib = diffuse / 3.14159265359;\n for (int i = 0; i < 2; i++) {\n vec3 PLU = cc_sphereLitPos[i].xyz - worldPos;\n vec3 PL = normalize(PLU);\n vec3 PH = normalize(PL + V);\n float PNL = max(dot(N, PL), 0.001);\n float PNH = max(dot(N, PH), 0.0);\n float distSqr = dot(PLU, PLU);\n float litRadius = cc_sphereLitSizeRange[i].x;\n float litRadiusSqr = litRadius * litRadius;\n float illum = 3.14159265359 * (litRadiusSqr / max(litRadiusSqr , distSqr));\n float attRadiusSqrInv = 1.0 / max(cc_sphereLitSizeRange[i].y, 0.01);\n attRadiusSqrInv *= attRadiusSqrInv;\n float att = GetDistAtt(distSqr, attRadiusSqrInv);\n vec3 lspec = specular * CalcSpecular(roughness, PNH, PH, N);\n lighting += PNL * cc_sphereLitColor[i].rgb * cc_sphereLitColor[i].w * illum * att * (diffuseContrib + lspec);\n }\n for (int i = 0; i < 2; i++) {\n vec3 SLU = cc_spotLitPos[i].xyz - worldPos;\n vec3 SL = normalize(SLU);\n vec3 SH = normalize(SL + V);\n float SNL = max(dot(N, SL), 0.001);\n float SNH = max(dot(N, SH), 0.0);\n float distSqr = dot(SLU, SLU);\n float litRadius = cc_spotLitSizeRangeAngle[i].x;\n float litRadiusSqr = litRadius * litRadius;\n float illum = 3.14159265359 * (litRadiusSqr / max(litRadiusSqr , distSqr));\n float attRadiusSqrInv = 1.0 / max(cc_spotLitSizeRangeAngle[i].y, 0.01);\n attRadiusSqrInv *= attRadiusSqrInv;\n float cosInner = max(dot(-cc_spotLitDir[i].xyz, SL), 0.01);\n float cosOuter = cc_spotLitSizeRangeAngle[i].z;\n float litAngleScale = 1.0 / max(0.001, cosInner - cosOuter);\n float litAngleOffset = -cosOuter * litAngleScale;\n float att = GetDistAtt(distSqr, attRadiusSqrInv);\n att *= GetAngleAtt(SL, -cc_spotLitDir[i].xyz, litAngleScale, litAngleOffset);\n vec3 lspec = specular * CalcSpecular(roughness, SNH, SH, N);\n lighting += SNL * cc_spotLitColor[i].rgb * cc_spotLitColor[i].w * illum * att * (diffuseContrib + lspec);\n }\n return lighting;\n}\nstruct StandardSurface {\n vec4 albedo;\n vec3 position;\n vec3 normal;\n vec3 emissive;\n float roughness;\n float metallic;\n float occlusion;\n};\nvec4 CCStandardShading (StandardSurface s) {\n vec3 diffuse = s.albedo.rgb * (1.0 - s.metallic);\n vec3 specular = mix(vec3(0.04), s.albedo.rgb, s.metallic);\n vec3 N = normalize(s.normal);\n vec3 V = normalize(cc_cameraPos.xyz - s.position);\n vec3 L = normalize(-cc_mainLitDir.xyz);\n vec3 H = normalize(L+V);\n float NV = max(abs(dot(N, V)), 0.001);\n float NL = max(dot(N, L), 0.001);\n float NH = max(dot(N, H), 0.0);\n specular = BRDFApprox(specular, s.roughness, NV);\n vec3 diffuseContrib = diffuse / 3.14159265359;\n vec3 specularContrib = specular * CalcSpecular(s.roughness, NH, H, N);\n vec3 finalColor = NL * cc_mainLitColor.rgb * cc_mainLitColor.w * (diffuseContrib + specularContrib);\n finalColor += CalcDynamicLighting(s.position, N, V, diffuse, specular, s.roughness);\n float fAmb = 0.5 - N.y * 0.5;\n vec3 ambDiff = mix(cc_ambientSky.rgb, cc_ambientGround.rgb, fAmb) * cc_ambientSky.w;\n finalColor += (ambDiff.rgb * diffuse);\n #if CC_USE_IBL\n vec3 R = normalize(reflect(-V, N));\n #ifdef GL_EXT_shader_texture_lod\n vec4 envmap = textureCubeLodEXT(cc_environment, R, s.roughness * cc_ambientGround.w);\n #else\n vec4 envmap = textureCube(cc_environment, R);\n #endif\n #if CC_USE_IBL == 2\n vec3 env = unpackRGBE(envmap);\n #else\n vec3 env = SRGBToLinear(envmap.rgb) * cc_ambientSky.w;\n #endif\n finalColor += env * specular;\n #endif\n finalColor = finalColor * s.occlusion;\n #if CC_USE_HDR\n s.emissive *= cc_exposure.w;\n #endif\n finalColor += s.emissive;\n return vec4(finalColor, s.albedo.a);\n}\nvec3 ACESToneMap (vec3 color) {\n const float A = 2.51;\n const float B = 0.03;\n const float C = 2.43;\n const float D = 0.59;\n const float E = 0.14;\n return (color * (A * color + B)) / (color * (C * color + D) + E);\n}\nvec4 CCFragOutput (vec4 color) {\n #if !CC_USE_HDR\n color.rgb = sqrt(ACESToneMap(color.rgb));\n #endif\n return color;\n}\nuniform vec4 albedo;\nuniform vec4 albedoScaleAndCutoff;\nuniform vec4 pbrParams;\nuniform vec4 emissive;\nuniform vec4 emissiveScale;\nvarying vec3 v_position;\nvarying vec2 v_uv;\nvarying vec2 v_uv1;\nvarying vec3 v_normal;\n#if USE_VERTEX_COLOR\n varying vec3 v_color;\n#endif\n#if USE_ALBEDO_MAP\n uniform sampler2D albedoMap;\n#endif\n#if USE_NORMAL_MAP\n varying vec3 v_tangent;\n varying vec3 v_bitangent;\n uniform sampler2D normalMap;\n#endif\n#if USE_PBR_MAP\n uniform sampler2D pbrMap;\n#endif\n#if USE_METALLIC_ROUGHNESS_MAP\n uniform sampler2D metallicRoughnessMap;\n#endif\n#if USE_OCCLUSION_MAP\n uniform sampler2D occlusionMap;\n#endif\n#if USE_EMISSIVE_MAP\n uniform sampler2D emissiveMap;\n#endif\n#if USE_ALPHA_TEST\n#endif\nvoid surf (out StandardSurface s) {\n vec4 baseColor = albedo;\n #if USE_VERTEX_COLOR\n baseColor.rgb *= v_color;\n #endif\n #if USE_ALBEDO_MAP\n vec4 texColor = texture2D(albedoMap, ALBEDO_UV);\n texColor.rgb = SRGBToLinear(texColor.rgb);\n baseColor *= texColor;\n #endif\n s.albedo = baseColor;\n s.albedo.rgb *= albedoScaleAndCutoff.xyz;\n #if USE_ALPHA_TEST\n if (s.albedo.ALPHA_TEST_CHANNEL < albedoScaleAndCutoff.w) discard;\n #endif\n s.normal = v_normal;\n #if USE_NORMAL_MAP\n vec3 nmmp = texture2D(normalMap, v_uv).xyz - vec3(0.5);\n s.normal =\n (nmmp.x * pbrParams.w) * normalize(v_tangent) +\n (nmmp.y * pbrParams.w) * normalize(v_bitangent) +\n nmmp.z * normalize(s.normal);\n #endif\n s.position = v_position;\n vec4 pbr = pbrParams;\n #if USE_PBR_MAP\n vec4 res = texture2D(pbrMap, v_uv);\n pbr.x *= res.OCCLUSION_CHANNEL;\n pbr.y *= res.ROUGHNESS_CHANNEL;\n pbr.z *= res.METALLIC_CHANNEL;\n #endif\n #if USE_METALLIC_ROUGHNESS_MAP\n vec4 metallicRoughness = texture2D(metallicRoughnessMap, v_uv);\n pbr.z *= metallicRoughness.METALLIC_CHANNEL;\n pbr.y *= metallicRoughness.ROUGHNESS_CHANNEL;\n #endif\n #if USE_OCCLUSION_MAP\n pbr.x *= texture2D(occlusionMap, v_uv).OCCLUSION_CHANNEL;\n #endif\n s.occlusion = clamp(pbr.x, 0.0, 0.96);\n s.roughness = clamp(pbr.y, 0.04, 1.0);\n s.metallic = pbr.z;\n s.emissive = emissive.rgb * emissiveScale.xyz;\n #if USE_EMISSIVE_MAP\n s.emissive *= SRGBToLinear(texture2D(emissiveMap, EMISSIVE_UV).rgb);\n #endif\n}\nvec4 frag () {\n StandardSurface s; surf(s);\n vec4 color = CCStandardShading(s);\n return CCFragOutput(color);\n}\nvoid main() { gl_FragColor = frag(); }` + "frag": `\n#if CC_USE_IBL\n #ifdef GL_EXT_shader_texture_lod\n #extension GL_EXT_shader_texture_lod : enable\n #endif\n#endif\nprecision highp float;\nuniform vec4 cc_cameraPos;\nuniform vec4 cc_exposure;\nuniform vec4 cc_mainLitDir;\nuniform vec4 cc_mainLitColor;\nuniform vec4 cc_ambientSky;\nuniform vec4 cc_ambientGround;\n#if CC_USE_IBL\nuniform samplerCube cc_environment;\nvec3 unpackRGBE (vec4 rgbe) {\n return rgbe.rgb * pow(2.0, rgbe.a * 255.0 - 128.0);\n}\n#endif\nvec3 SRGBToLinear (vec3 gamma) {\n return gamma * gamma;\n}\nuniform highp vec4 cc_sphereLitPos[2];\nuniform vec4 cc_sphereLitSizeRange[2];\nuniform vec4 cc_sphereLitColor[2];\nuniform highp vec4 cc_spotLitPos[2];\nuniform vec4 cc_spotLitSizeRangeAngle[2];\nuniform vec4 cc_spotLitDir[2];\nuniform vec4 cc_spotLitColor[2];\nfloat SmoothDistAtt (float distSqr, float invSqrAttRadius) {\n float factor = distSqr * invSqrAttRadius;\n float smoothFactor = clamp(1.0 - factor * factor, 0.0, 1.0);\n return smoothFactor * smoothFactor;\n}\nfloat GetDistAtt (float distSqr, float invSqrAttRadius) {\n float attenuation = 1.0 / max(distSqr, 0.01*0.01);\n attenuation *= SmoothDistAtt(distSqr , invSqrAttRadius);\n return attenuation;\n}\nfloat GetAngleAtt (vec3 L, vec3 litDir, float litAngleScale, float litAngleOffset) {\n float cd = dot(litDir, L);\n float attenuation = clamp(cd * litAngleScale + litAngleOffset, 0.0, 1.0);\n return (attenuation * attenuation);\n}\nfloat GGXMobile (float roughness, float NoH, vec3 H, vec3 N) {\n vec3 NxH = cross(N, H);\n float OneMinusNoHSqr = dot(NxH, NxH);\n float a = roughness * roughness;\n float n = NoH * a;\n float p = a / (OneMinusNoHSqr + n * n);\n return p * p;\n}\nfloat CalcSpecular (float roughness, float NoH, vec3 H, vec3 N) {\n return (roughness*0.25 + 0.25) * GGXMobile(roughness, NoH, H, N);\n}\nvec3 BRDFApprox (vec3 specular, float roughness, float NoV) {\n const vec4 c0 = vec4(-1.0, -0.0275, -0.572, 0.022);\n const vec4 c1 = vec4(1.0, 0.0425, 1.04, -0.04);\n vec4 r = roughness * c0 + c1;\n float a004 = min( r.x * r.x, exp2( -9.28 * NoV ) ) * r.x + r.y;\n vec2 AB = vec2( -1.04, 1.04 ) * a004 + r.zw;\n AB.y *= clamp(50.0 * specular.g, 0.0, 1.0);\n return specular * AB.x + AB.y;\n}\nvec3 CalcDynamicLighting (vec3 worldPos, vec3 N, vec3 V, vec3 diffuse, vec3 specular, float roughness) {\n vec3 lighting = vec3(0.0);\n vec3 diffuseContrib = diffuse / 3.14159265359;\n for (int i = 0; i < 2; i++) {\n vec3 PLU = cc_sphereLitPos[i].xyz - worldPos;\n vec3 PL = normalize(PLU);\n vec3 PH = normalize(PL + V);\n float PNL = max(dot(N, PL), 0.001);\n float PNH = max(dot(N, PH), 0.0);\n float distSqr = dot(PLU, PLU);\n float litRadius = cc_sphereLitSizeRange[i].x;\n float litRadiusSqr = litRadius * litRadius;\n float illum = 3.14159265359 * (litRadiusSqr / max(litRadiusSqr , distSqr));\n float attRadiusSqrInv = 1.0 / max(cc_sphereLitSizeRange[i].y, 0.01);\n attRadiusSqrInv *= attRadiusSqrInv;\n float att = GetDistAtt(distSqr, attRadiusSqrInv);\n vec3 lspec = specular * CalcSpecular(roughness, PNH, PH, N);\n lighting += PNL * cc_sphereLitColor[i].rgb * cc_sphereLitColor[i].w * illum * att * (diffuseContrib + lspec);\n }\n for (int i = 0; i < 2; i++) {\n vec3 SLU = cc_spotLitPos[i].xyz - worldPos;\n vec3 SL = normalize(SLU);\n vec3 SH = normalize(SL + V);\n float SNL = max(dot(N, SL), 0.001);\n float SNH = max(dot(N, SH), 0.0);\n float distSqr = dot(SLU, SLU);\n float litRadius = cc_spotLitSizeRangeAngle[i].x;\n float litRadiusSqr = litRadius * litRadius;\n float illum = 3.14159265359 * (litRadiusSqr / max(litRadiusSqr , distSqr));\n float attRadiusSqrInv = 1.0 / max(cc_spotLitSizeRangeAngle[i].y, 0.01);\n attRadiusSqrInv *= attRadiusSqrInv;\n float cosInner = max(dot(-cc_spotLitDir[i].xyz, SL), 0.01);\n float cosOuter = cc_spotLitSizeRangeAngle[i].z;\n float litAngleScale = 1.0 / max(0.001, cosInner - cosOuter);\n float litAngleOffset = -cosOuter * litAngleScale;\n float att = GetDistAtt(distSqr, attRadiusSqrInv);\n att *= GetAngleAtt(SL, -cc_spotLitDir[i].xyz, litAngleScale, litAngleOffset);\n vec3 lspec = specular * CalcSpecular(roughness, SNH, SH, N);\n lighting += SNL * cc_spotLitColor[i].rgb * cc_spotLitColor[i].w * illum * att * (diffuseContrib + lspec);\n }\n return lighting;\n}\nstruct StandardSurface {\n vec4 albedo;\n vec3 position;\n vec3 normal;\n vec3 emissive;\n float roughness;\n float metallic;\n float occlusion;\n};\nvec4 CCStandardShading (StandardSurface s) {\n vec3 diffuse = s.albedo.rgb * (1.0 - s.metallic);\n vec3 specular = mix(vec3(0.04), s.albedo.rgb, s.metallic);\n vec3 N = normalize(s.normal);\n vec3 V = normalize(cc_cameraPos.xyz - s.position);\n vec3 L = normalize(-cc_mainLitDir.xyz);\n vec3 H = normalize(L+V);\n float NV = max(abs(dot(N, V)), 0.001);\n float NL = max(dot(N, L), 0.001);\n float NH = max(dot(N, H), 0.0);\n specular = BRDFApprox(specular, s.roughness, NV);\n vec3 diffuseContrib = diffuse / 3.14159265359;\n vec3 specularContrib = specular * CalcSpecular(s.roughness, NH, H, N);\n vec3 finalColor = NL * cc_mainLitColor.rgb * cc_mainLitColor.w * (diffuseContrib + specularContrib);\n finalColor += CalcDynamicLighting(s.position, N, V, diffuse, specular, s.roughness);\n float fAmb = 0.5 - N.y * 0.5;\n vec3 ambDiff = mix(cc_ambientSky.rgb, cc_ambientGround.rgb, fAmb) * cc_ambientSky.w;\n finalColor += (ambDiff.rgb * diffuse);\n #if CC_USE_IBL\n vec3 R = normalize(reflect(-V, N));\n #ifdef GL_EXT_shader_texture_lod\n vec4 envmap = textureCubeLodEXT(cc_environment, R, s.roughness * cc_ambientGround.w);\n #else\n vec4 envmap = textureCube(cc_environment, R);\n #endif\n #if CC_USE_IBL == 2\n vec3 env = unpackRGBE(envmap);\n #else\n vec3 env = SRGBToLinear(envmap.rgb) * cc_ambientSky.w;\n #endif\n finalColor += env * specular;\n #endif\n finalColor = finalColor * s.occlusion;\n #if CC_USE_HDR\n s.emissive *= cc_exposure.w;\n #endif\n finalColor += s.emissive;\n return vec4(finalColor, s.albedo.a);\n}\nvec3 ACESToneMap (vec3 color) {\n const float A = 2.51;\n const float B = 0.03;\n const float C = 2.43;\n const float D = 0.59;\n const float E = 0.14;\n return (color * (A * color + B)) / (color * (C * color + D) + E);\n}\nvec4 CCFragOutput (vec4 color) {\n #if !CC_USE_HDR\n color.rgb = sqrt(ACESToneMap(color.rgb));\n #endif\n return color;\n}\nuniform vec4 albedo;\nuniform vec4 albedoScaleAndCutoff;\nuniform vec4 pbrParams;\nuniform vec4 emissive;\nuniform vec4 emissiveScaleParam;\nvarying vec3 v_position;\nvarying vec2 v_uv;\nvarying vec2 v_uv1;\nvarying vec3 v_normal;\n#if USE_VERTEX_COLOR\n varying vec3 v_color;\n#endif\n#if USE_ALBEDO_MAP\n uniform sampler2D albedoMap;\n#endif\n#if USE_NORMAL_MAP\n varying vec3 v_tangent;\n varying vec3 v_bitangent;\n uniform sampler2D normalMap;\n#endif\n#if USE_PBR_MAP\n uniform sampler2D pbrMap;\n#endif\n#if USE_METALLIC_ROUGHNESS_MAP\n uniform sampler2D metallicRoughnessMap;\n#endif\n#if USE_OCCLUSION_MAP\n uniform sampler2D occlusionMap;\n#endif\n#if USE_EMISSIVE_MAP\n uniform sampler2D emissiveMap;\n#endif\n#if USE_ALPHA_TEST\n#endif\nvoid surf (out StandardSurface s) {\n vec4 baseColor = albedo;\n #if USE_VERTEX_COLOR\n baseColor.rgb *= v_color;\n #endif\n #if USE_ALBEDO_MAP\n vec4 texColor = texture2D(albedoMap, ALBEDO_UV);\n texColor.rgb = SRGBToLinear(texColor.rgb);\n baseColor *= texColor;\n #endif\n s.albedo = baseColor;\n s.albedo.rgb *= albedoScaleAndCutoff.xyz;\n #if USE_ALPHA_TEST\n if (s.albedo.ALPHA_TEST_CHANNEL < albedoScaleAndCutoff.w) discard;\n #endif\n s.normal = v_normal;\n #if USE_NORMAL_MAP\n vec3 nmmp = texture2D(normalMap, NORMAL_UV).xyz - vec3(0.5);\n s.normal =\n (nmmp.x * pbrParams.w) * normalize(v_tangent) +\n (nmmp.y * pbrParams.w) * normalize(v_bitangent) +\n nmmp.z * normalize(s.normal);\n #endif\n s.position = v_position;\n vec4 pbr = pbrParams;\n #if USE_PBR_MAP\n vec4 res = texture2D(pbrMap, PBR_UV);\n pbr.x *= res.OCCLUSION_CHANNEL;\n pbr.y *= res.ROUGHNESS_CHANNEL;\n pbr.z *= res.METALLIC_CHANNEL;\n #endif\n #if USE_METALLIC_ROUGHNESS_MAP\n vec4 metallicRoughness = texture2D(metallicRoughnessMap, METALLIC_ROUGHNESS_UV);\n pbr.z *= metallicRoughness.METALLIC_CHANNEL;\n pbr.y *= metallicRoughness.ROUGHNESS_CHANNEL;\n #endif\n #if USE_OCCLUSION_MAP\n pbr.x *= texture2D(occlusionMap, OCCLUSION_UV).OCCLUSION_CHANNEL;\n #endif\n s.occlusion = clamp(pbr.x, 0.0, 0.96);\n s.roughness = clamp(pbr.y, 0.04, 1.0);\n s.metallic = pbr.z;\n s.emissive = emissive.rgb * emissiveScaleParam.xyz;\n #if USE_EMISSIVE_MAP\n s.emissive *= SRGBToLinear(texture2D(emissiveMap, EMISSIVE_UV).rgb);\n #endif\n}\nvec4 frag () {\n StandardSurface s; surf(s);\n vec4 color = CCStandardShading(s);\n return CCFragOutput(color);\n}\nvoid main() { gl_FragColor = frag(); }` }, "builtins": {"globals":{"blocks":[{"name":"CCGlobal", "defines":[]}], "samplers":[{"name":"cc_environment", "defines":["CC_USE_IBL"]}]}, "locals":{"blocks":[{"name":"CCLocalBatched", "defines":["CC_USE_BATCHING"]}, {"name":"CCLocal", "defines":[]}, {"name":"CCSkinningTexture", "defines":["CC_USE_SKINNING"]}, {"name":"CCSkinningAnimation", "defines":["CC_USE_SKINNING"]}, {"name":"CCForwardLight", "defines":[]}], "samplers":[{"name":"cc_jointsTexture", "defines":["CC_USE_SKINNING"]}]}}, "defines": [ @@ -177,9 +177,13 @@ export default [ {"name":"CC_USE_HDR", "type":"boolean"}, {"name":"USE_ALBEDO_MAP", "type":"boolean"}, {"name":"ALBEDO_UV", "type":"string", "options":["v_uv", "v_uv1"]}, + {"name":"NORMAL_UV", "type":"string", "options":["v_uv", "v_uv1"]}, {"name":"USE_PBR_MAP", "type":"boolean"}, + {"name":"PBR_UV", "type":"string", "options":["v_uv", "v_uv1"]}, {"name":"USE_METALLIC_ROUGHNESS_MAP", "type":"boolean"}, + {"name":"METALLIC_ROUGHNESS_UV", "type":"string", "options":["v_uv", "v_uv1"]}, {"name":"USE_OCCLUSION_MAP", "type":"boolean"}, + {"name":"OCCLUSION_UV", "type":"string", "options":["v_uv", "v_uv1"]}, {"name":"USE_EMISSIVE_MAP", "type":"boolean"}, {"name":"EMISSIVE_UV", "type":"string", "options":["v_uv", "v_uv1"]}, {"name":"OCCLUSION_CHANNEL", "type":"string", "options":["r", "g", "b"]}, @@ -195,7 +199,7 @@ export default [ {"name":"albedoScaleAndCutoff", "type":16, "count":1}, {"name":"pbrParams", "type":16, "count":1}, {"name":"emissive", "type":16, "count":1}, - {"name":"emissiveScale", "type":16, "count":1} + {"name":"emissiveScaleParam", "type":16, "count":1} ]} ], "samplers": [ diff --git a/cocos/core/renderer/core/program-lib.ts b/cocos/core/renderer/core/program-lib.ts index 57bb279aae..08db68ebe2 100644 --- a/cocos/core/renderer/core/program-lib.ts +++ b/cocos/core/renderer/core/program-lib.ts @@ -54,6 +54,7 @@ export interface IProgramInfo extends IShaderInfo { offsets: number[][]; globalsInited: boolean; localsInited: boolean; + uber: boolean; // macro number exceeds default limits } export interface IMacroInfo { name: string; @@ -207,6 +208,7 @@ class ProgramLib { def._offset = offset; offset += cnt; } + if (offset > 31) { tmpl.uber = true; } tmpl.blocks.forEach((b) => (b.size = getSize(b), b.bindingType = GFXBindingType.UNIFORM_BUFFER)); tmpl.samplers.forEach((s) => (s.bindingType = GFXBindingType.SAMPLER)); tmpl.handleMap = genHandles(tmpl); @@ -238,17 +240,34 @@ class ProgramLib { */ public getKey (name: string, defines: IDefineMap) { 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; + const tmplDefs = tmpl.defines; + if (tmpl.uber) { + let key = ''; + for (let i = 0; i < tmplDefs.length; i++) { + const tmplDef = tmplDefs[i]; + const value = defines[tmplDef.name]; + if (value === undefined || !tmplDef._map) { + continue; + } + const mapped = tmplDef._map(value); + const offset = tmplDef._offset; + key += offset + (mapped + '|'); } - const mapped = tmplDef._map(value); - const offset = tmplDef._offset; - key |= mapped << offset; + return key + tmpl.hash; + } else { + let key = 0; + for (let i = 0; i < tmplDefs.length; i++) { + const tmplDef = tmplDefs[i]; + const value = defines[tmplDef.name]; + if (value === undefined || !tmplDef._map) { + continue; + } + const mapped = tmplDef._map(value); + const offset = tmplDef._offset; + key |= mapped << offset; + } + return `${key.toString(16)}|${tmpl.hash}`; } - return `${key.toString(16)}|${tmpl.hash}`; } /** diff --git a/cocos/core/renderer/scene/model.ts b/cocos/core/renderer/scene/model.ts index c4f14f031f..dd871fb184 100644 --- a/cocos/core/renderer/scene/model.ts +++ b/cocos/core/renderer/scene/model.ts @@ -358,6 +358,7 @@ export class Model { protected _doCreatePSO (pass: Pass, defineOverrides?: IDefineMap, stateOverrides?: IPassStates) { defineOverrides = defineOverrides || {}; + if (pass.blendState.targets[0].blend) { this._isDynamicBatching = false; } defineOverrides.CC_USE_BATCHING = this._isDynamicBatching; const pso = pass.createPipelineState(defineOverrides, stateOverrides)!; pso.pipelineLayout.layouts[0].bindBuffer(UBOLocal.BLOCK.binding, this._localBindings.get(UBOLocal.BLOCK.name)!.buffer!); From fce470c9c9153ae1ec9273b749d92cf7191a29cf Mon Sep 17 00:00:00 2001 From: ChiaNing Date: Mon, 2 Dec 2019 15:34:39 +0800 Subject: [PATCH 15/21] alipay adapter & oppo adapter (#5813) * adapter * adapters useless remove * bug fix * clip getplayer * alipay adapter update * redefin remove * log remove * deprecated redefine fix * predefine update * AliPay console adapter * prefab update --- cocos/audio/assets/clip.ts | 27 +-- cocos/audio/assets/player-wx.ts | 156 ------------------ cocos/audio/assets/player.ts | 2 + cocos/audio/audio-downloader.ts | 23 +-- cocos/core/assets/image-asset.ts | 2 +- cocos/core/assets/prefab.ts | 6 +- .../ui-coodinate-tracker-component.ts | 10 +- cocos/core/game.ts | 29 +--- cocos/core/gfx/webgl/webgl-commands.ts | 2 +- cocos/core/load-pipeline/downloader.ts | 7 + cocos/core/load-pipeline/loader.ts | 4 +- cocos/core/platform/sys.ts | 111 +------------ cocos/core/platform/view.ts | 12 ++ cocos/core/splash-image.ts | 2 + cocos/core/utils/deprecated.ts | 1 + predefine.ts | 16 +- 16 files changed, 73 insertions(+), 337 deletions(-) delete mode 100644 cocos/audio/assets/player-wx.ts diff --git a/cocos/audio/assets/clip.ts b/cocos/audio/assets/clip.ts index b9d8a257c5..e0a8218510 100644 --- a/cocos/audio/assets/clip.ts +++ b/cocos/audio/assets/clip.ts @@ -33,12 +33,11 @@ import { Enum } from '../../core/value-types'; import { AudioPlayer, PlayingState } from './player'; import { AudioPlayerDOM } from './player-dom'; import { AudioPlayerWeb } from './player-web'; -import { AudioPlayerWX } from './player-wx'; export const AudioType = Enum({ WEB_AUDIO: 0, DOM_AUDIO: 1, - WX_GAME_AUDIO: 2, + MINI_GAME_AUDIO: 2, UNKNOWN_AUDIO: 3, }); @@ -74,20 +73,22 @@ export class AudioClip extends Asset { return super.destroy(); } + private _getPlayer (clip: any) { + let ctor: any; + if (typeof AudioBuffer !== 'undefined' && clip instanceof AudioBuffer) { + ctor = AudioPlayerWeb; + this._loadMode = AudioType.WEB_AUDIO; + } else { + ctor = AudioPlayerDOM; + this._loadMode = AudioType.DOM_AUDIO; + } + return ctor; + } + set _nativeAsset (clip: any) { this._audio = clip; if (clip) { - let ctor: any; - if (CC_WECHATGAME) { - ctor = AudioPlayerWX; - this._loadMode = AudioType.WX_GAME_AUDIO; - } else if (typeof AudioBuffer !== 'undefined' && clip instanceof AudioBuffer) { - ctor = AudioPlayerWeb; - this._loadMode = AudioType.WEB_AUDIO; - } else { - ctor = AudioPlayerDOM; - this._loadMode = AudioType.DOM_AUDIO; - } + const ctor = this._getPlayer(clip); this._player = new ctor({ clip, duration: this._duration, eventTarget: this }); this.loaded = true; this.emit('load'); diff --git a/cocos/audio/assets/player-wx.ts b/cocos/audio/assets/player-wx.ts deleted file mode 100644 index dde598e960..0000000000 --- a/cocos/audio/assets/player-wx.ts +++ /dev/null @@ -1,156 +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. - */ - -/** - * @category component/audio - */ - -import { clamp } from '../../core/math/utils'; -import { AudioPlayer, IAudioInfo, PlayingState } from './player'; - -/** - * The main lesson learnt during the porting is, - * be very careful with the getter methods on InnerAudioContext, - * serious performance issue have been encountered when accessed frequently. - * For now this includes duration, current time and volume, - * so those are all maintained manually here. - */ -export class AudioPlayerWX extends AudioPlayer { - protected _startTime = 0; - protected _offset = 0; - protected _volume = 1; - protected _loop = false; - protected _oneShoting = false; - protected _audio: InnerAudioContext; - - constructor (info: IAudioInfo) { - super(info); - this._audio = info.clip; - // [HACK] volume property doesn't work on some devices during the first playthrough - this._audio.play(); - this._audio.stop(); - - this._audio.onPlay(() => { - if (this._state === PlayingState.PLAYING) { return; } - this._state = PlayingState.PLAYING; - this._startTime = performance.now(); - this._eventTarget.emit('started'); - }); - this._audio.onPause(() => { - if (this._state === PlayingState.STOPPED) { return; } - this._state = PlayingState.STOPPED; - this._offset += performance.now() - this._startTime; - }); - this._audio.onStop(() => { - if (this._state === PlayingState.STOPPED) { return; } - this._state = PlayingState.STOPPED; - this._offset = 0; - if (this._oneShoting) { - this._audio.volume = this._volume; - this._audio.loop = this._loop; - this._oneShoting = false; - } - }); - this._audio.onEnded(() => { - if (this._state === PlayingState.STOPPED) { return; } - this._state = PlayingState.STOPPED; - this._offset = 0; - this._eventTarget.emit('ended'); - if (this._oneShoting) { - this._audio.volume = this._volume; - this._audio.loop = this._loop; - this._oneShoting = false; - } - }); - this._audio.onError((res: any) => console.error(res.errMsg)); - } - - public play () { - if (!this._audio || this._state === PlayingState.PLAYING) { return; } - if (this._blocking) { this._interrupted = true; return; } - this._audio.play(); - } - - public pause () { - if (!this._audio || this._state !== PlayingState.PLAYING) { return; } - this._audio.pause(); - } - - public stop () { - if (!this._audio) { return; } - this._audio.stop(); - } - - public playOneShot (volume = 1) { - /* InnerAudioContext doesn't support multiple playback at the - same time so here we fall back to re-start style approach */ - if (!this._audio) { return; } - this._offset = 0; - this._oneShoting = true; - this._audio.stop(); - this._audio.loop = false; - this._audio.volume = volume; - this._audio.play(); - } - - public getCurrentTime () { - if (this._state !== PlayingState.PLAYING) { return this._offset / 1000; } - let current = (performance.now() - this._startTime + this._offset) / 1000; - if (current > this._duration) { current -= this._duration; this._startTime += this._duration * 1000; } - return current; - } - - public setCurrentTime (val: number) { - if (!this._audio) { return; } - this._offset = clamp(val, 0, this._duration) * 1000; - this._startTime = performance.now(); - this._audio.seek(val); - } - - public getVolume () { - return this._volume; - } - - public setVolume (val: number, immediate: boolean) { - this._volume = val; - if (this._audio) { this._audio.volume = val; } - } - - public getLoop () { - return this._loop; - } - - public setLoop (val: boolean) { - this._loop = val; - if (this._audio) { this._audio.loop = val; } - } - - public destroy () { - if (this._audio) { this._audio.destroy(); } - wx.offAudioInterruptionBegin(this._onHide); - wx.offAudioInterruptionEnd(this._onShow); - super.destroy(); - } -} diff --git a/cocos/audio/assets/player.ts b/cocos/audio/assets/player.ts index e7522deb2c..da910930ae 100644 --- a/cocos/audio/assets/player.ts +++ b/cocos/audio/assets/player.ts @@ -84,3 +84,5 @@ export abstract class AudioPlayer { cc.game.off(cc.Game.EVENT_SHOW, this._onShow); } } + +cc.AudioPlayer = AudioPlayer; diff --git a/cocos/audio/audio-downloader.ts b/cocos/audio/audio-downloader.ts index fdd864dc86..beac8a1980 100644 --- a/cocos/audio/audio-downloader.ts +++ b/cocos/audio/audio-downloader.ts @@ -27,7 +27,6 @@ * @category loader */ -import { loader } from '../core/load-pipeline'; import { getError, log } from '../core/platform/debug'; import sys from '../core/platform/sys'; import { AudioClip, AudioType } from './assets/clip'; @@ -35,12 +34,6 @@ import { AudioClip, AudioType } from './assets/clip'; const __audioSupport = sys.__audioSupport; const formatSupport = __audioSupport.format; -function loadWXAudio (item, callback) { - const clip = wx.createInnerAudioContext(); - clip.src = item.url; - clip.onCanplay(() => callback(null, clip)); -} - function loadDomAudio (item, callback) { const dom = document.createElement('audio'); dom.src = item.url; @@ -83,7 +76,7 @@ function loadWebAudio (item, callback) { callback(new Error(getError(4926))); } - const request = loader.getXMLHttpRequest(); + const request = cc.loader.getXMLHttpRequest(); request.open('GET', item.url, true); request.responseType = 'arraybuffer'; @@ -105,15 +98,13 @@ function loadWebAudio (item, callback) { request.send(); } -function downloadAudio (item, callback) { +export function downloadAudio (item, callback) { if (formatSupport.length === 0) { return new Error(getError(4927)); } let audioLoader; - if (CC_WECHATGAME) { - audioLoader = loadWXAudio; - } else if (!__audioSupport.WEB_AUDIO) { + if (!__audioSupport.WEB_AUDIO) { audioLoader = loadDomAudio; // If WebAudio is not supported, load using DOM mode } else { const loadByDeserializedAudio = item._owner instanceof AudioClip; @@ -125,11 +116,3 @@ function downloadAudio (item, callback) { } audioLoader(item, callback); } - -loader.downloader.addHandlers({ - // Audio - mp3 : downloadAudio, - ogg : downloadAudio, - wav : downloadAudio, - m4a : downloadAudio, -}); diff --git a/cocos/core/assets/image-asset.ts b/cocos/core/assets/image-asset.ts index ae753647e7..c9e6594c9e 100644 --- a/cocos/core/assets/image-asset.ts +++ b/cocos/core/assets/image-asset.ts @@ -181,7 +181,7 @@ export class ImageAsset extends Asset { this._onDataComplete(); } else { this._nativeData = data; - if (CC_WECHATGAME || CC_QQPLAY || (data as any).complete || data instanceof HTMLCanvasElement) { + if (CC_WECHATGAME || CC_QQPLAY || (data as any).complete || data instanceof HTMLCanvasElement) { // todo need adatper this._onDataComplete(); } else { this.loaded = false; diff --git a/cocos/core/assets/prefab.ts b/cocos/core/assets/prefab.ts index 1b2c32a68e..5d48bc2298 100644 --- a/cocos/core/assets/prefab.ts +++ b/cocos/core/assets/prefab.ts @@ -188,4 +188,8 @@ export default class Prefab extends Asset { } cc.Prefab = Prefab; -obsolete(cc, 'cc._Prefab', 'Prefab'); +if (CC_WECHATGAME || CC_RUNTIME) { + cc._Prefab = Prefab; +} else { + obsolete(cc, 'cc._Prefab', 'Prefab'); +} diff --git a/cocos/core/components/ui-coodinate-tracker-component.ts b/cocos/core/components/ui-coodinate-tracker-component.ts index 2409b76bc0..0aeeaa1870 100644 --- a/cocos/core/components/ui-coodinate-tracker-component.ts +++ b/cocos/core/components/ui-coodinate-tracker-component.ts @@ -24,13 +24,13 @@ THE SOFTWARE. */ -import { Component } from '../../core/components/component'; -import { EventHandler } from '../../core/components/component-event-handler'; -import { CameraComponent } from '../3d/framework/camera-component'; -import { ccclass, executionOrder, menu, property } from '../data/class-decorator'; -import { Vec3 } from '../math'; +import { ccclass, property, menu, executionOrder } from '../data/class-decorator'; import { Node } from '../scene-graph'; import { convertUtils } from '../utils'; +import { CameraComponent } from '../3d'; +import { Vec3 } from '../math'; +import { Component } from '../components/component'; +import { EventHandler } from './component-event-handler'; /** * @zh 3D 节点映射 UI 节点组件 diff --git a/cocos/core/game.ts b/cocos/core/game.ts index 036f811c91..7276be439b 100644 --- a/cocos/core/game.ts +++ b/cocos/core/game.ts @@ -493,10 +493,6 @@ export class Game extends EventTarget { this.onStart = onStart; - if (!CC_EDITOR && CC_WECHATGAME/* && !CC_PREVIEW*/) { - SplashScreen.instance.main(this._gfxDevice as any); - } - this.prepare(cc.game.onStart && cc.game.onStart.bind(cc.game)); } @@ -614,12 +610,7 @@ export class Game extends EventTarget { if (cb) { cb(); } }; - if (!CC_EDITOR && CC_WECHATGAME) { - SplashScreen.instance.setOnFinish(start); - SplashScreen.instance.loadFinish = true; - } else { - start(); - } + start(); } // @Methods @@ -783,10 +774,8 @@ export class Game extends EventTarget { let height: any; let localCanvas: HTMLCanvasElement; let localContainer: HTMLElement; - const isWeChatGame = cc.sys.platform === cc.sys.WECHAT_GAME; - const isQQPlay = cc.sys.platform === cc.sys.QQ_PLAY; - if (isWeChatGame || CC_JSB) { + if (CC_JSB) { this.container = localContainer = document.createElement<'div'>('div'); this.frame = localContainer.parentNode === document.body ? document.documentElement : localContainer.parentNode; if (cc.sys.browserType === cc.sys.BROWSER_TYPE_WECHAT_GAME_SUB) { @@ -800,11 +789,6 @@ export class Game extends EventTarget { } this.canvas = localCanvas; } - else if (isQQPlay) { - this.container = cc.container = document.createElement<'div'>('div'); - this.frame = document.documentElement; - this.canvas = localCanvas = window.canvas; - } else { const element = !el ? null : ((el instanceof HTMLElement) ? el : (document.querySelector(el) || document.querySelector('#' + el))); if (!element) { @@ -954,15 +938,6 @@ export class Game extends EventTarget { win.onfocus = onShown; } - if (CC_WECHATGAME && cc.sys.browserType !== cc.sys.BROWSER_TYPE_WECHAT_GAME_SUB) { - if (wx.onShow) { - wx.onShow(onShown); - } - if (wx.onHide) { - wx.onHide(onHidden); - } - } - if ('onpageshow' in window && 'onpagehide' in window) { win.addEventListener('pagehide', onHidden); win.addEventListener('pageshow', onShown); diff --git a/cocos/core/gfx/webgl/webgl-commands.ts b/cocos/core/gfx/webgl/webgl-commands.ts index 8b8a23d37e..f7f22199dd 100644 --- a/cocos/core/gfx/webgl/webgl-commands.ts +++ b/cocos/core/gfx/webgl/webgl-commands.ts @@ -1343,7 +1343,7 @@ export function WebGLCmdFuncCreateShader (device: WebGLGFXDevice, gpuShader: Web const uniformInfo = gl.getActiveUniform(gpuShader.glProgram, i); if (uniformInfo) { const glLoc = gl.getUniformLocation(gpuShader.glProgram, uniformInfo.name); - if (glLoc) { + if (glLoc !== null) { let varName: string; const nameOffset = uniformInfo.name.indexOf('['); if (nameOffset !== -1) { diff --git a/cocos/core/load-pipeline/downloader.ts b/cocos/core/load-pipeline/downloader.ts index 321d93e564..b46b83483c 100644 --- a/cocos/core/load-pipeline/downloader.ts +++ b/cocos/core/load-pipeline/downloader.ts @@ -34,6 +34,7 @@ import * as PackDownloader from './pack-downloader'; import downloadBinary from './binary-downloader'; import downloadText from './text-downloader'; import {urlAppendTimestamp} from './utils'; +import { downloadAudio } from '../../audio/audio-downloader'; function skip () { return null; @@ -143,6 +144,12 @@ let defaultMap = { 'pvr': downloadBinary, 'pkm': downloadBinary, + // Audio + 'mp3' : downloadAudio, + 'ogg' : downloadAudio, + 'wav' : downloadAudio, + 'm4a' : downloadAudio, + // Txt 'txt' : downloadText, 'xml' : downloadText, diff --git a/cocos/core/load-pipeline/loader.ts b/cocos/core/load-pipeline/loader.ts index d643f8344f..fc1aafc30b 100644 --- a/cocos/core/load-pipeline/loader.ts +++ b/cocos/core/load-pipeline/loader.ts @@ -61,7 +61,7 @@ function loadImage (item) { } let image = item.content; - if (!CC_WECHATGAME && !CC_QQPLAY && !(image instanceof Image)) { + if (cc.sys.platform !== cc.sys.FB_PLAYABLE_ADS && !(image instanceof Image)) { return new Error('Image Loader: Input item doesn\'t contain Image content'); } @@ -290,7 +290,7 @@ let ID = 'Loader'; */ export default class Loader implements IPipe { static ID = ID; - + public id = ID; public async = true; public pipeline: Pipeline | null = null; diff --git a/cocos/core/platform/sys.ts b/cocos/core/platform/sys.ts index 4578243431..0396d9ad80 100644 --- a/cocos/core/platform/sys.ts +++ b/cocos/core/platform/sys.ts @@ -34,6 +34,8 @@ */ const sys: { [x: string]: any; } = {}; +const _global = typeof window === 'undefined' ? global : window; + /** * English language code * @property {String} LANGUAGE_ENGLISH @@ -539,7 +541,11 @@ sys.isLittleEndian = (() => { return new Int16Array(buffer)[0] === 256; })(); -if (CC_EDITOR && Editor.isMainProcess) { +if (_global.__globalAdapter && _global.__globalAdapter.adaptSys) { + // init sys info in adapter + _global.__globalAdapter.adaptSys(sys); +} +else if (CC_EDITOR && Editor.isMainProcess) { sys.isMobile = false; sys.platform = sys.EDITOR_CORE; sys.language = sys.LANGUAGE_UNKNOWN; @@ -611,109 +617,6 @@ else if (CC_JSB) { format: ['.mp3'], }; } -else if (CC_WECHATGAME) { - const env = wx.getSystemInfoSync(); - sys.isMobile = true; - sys.platform = sys.WECHAT_GAME; - sys.language = env.language.substr(0, 2); - let system = env.system.toLowerCase(); - if (env.platform === 'android') { - sys.os = sys.OS_ANDROID; - } - else if (env.platform === 'ios') { - sys.os = sys.OS_IOS; - } - else if (env.platform === 'devtools') { - sys.isMobile = false; - if (system.indexOf('android') > -1) { - sys.os = sys.OS_ANDROID; - } - else if (system.indexOf('ios') > -1) { - sys.os = sys.OS_IOS; - } - } - // Adaptation to Android P - if (system === 'android p') { - system = 'android p 9.0'; - } - - const version = /[\d\.]+/.exec(system); - sys.osVersion = version ? version[0] : system; - sys.osMainVersion = parseInt(sys.osVersion); - // wechagame subdomain - if (!wx.getFileSystemManager) { - sys.browserType = sys.BROWSER_TYPE_WECHAT_GAME_SUB; - } - else { - sys.browserType = sys.BROWSER_TYPE_WECHAT_GAME; - } - sys.browserVersion = env.version; - - const w = env.windowWidth; - const h = env.windowHeight; - const ratio = env.pixelRatio || 1; - sys.windowPixelResolution = { - width: ratio * w, - height: ratio * h, - }; - - sys.localStorage = window.localStorage; - - sys.capabilities = { - canvas: true, - opengl: (sys.browserType !== sys.BROWSER_TYPE_WECHAT_GAME_SUB), - webp: false, - }; - sys.__audioSupport = { - ONLY_ONE: false, - WEB_AUDIO: false, - DELAY_CREATE_CTX: false, - format: ['.mp3'], - }; -} -else if (CC_QQPLAY) { - // @ts-ignore - const env = window.BK.Director.queryDeviceInfo(); - sys.isMobile = true; - sys.platform = sys.QQ_PLAY; - sys.language = sys.LANGUAGE_UNKNOWN; - if (env.platform === 'android') { - sys.os = sys.OS_ANDROID; - } - else if (env.platform === 'ios') { - sys.os = sys.OS_IOS; - } - else { - sys.os = sys.OS_UNKNOWN; - } - sys.osVersion = env.version; - sys.osMainVersion = parseInt(sys.osVersion.split('.')[0]); - sys.browserType = sys.BROWSER_TYPE_QQ_PLAY; - sys.browserVersion = 0; - - const w = env.screenWidth; - const h = env.screenHeight; - const ratio = env.pixelRatio || 1; - - sys.windowPixelResolution = { - width: ratio * w, - height: ratio * h, - }; - - sys.localStorage = window.localStorage; - - sys.capabilities = { - canvas: false, - opengl: true, - webp: false, - }; - sys.__audioSupport = { - ONLY_ONE: false, - WEB_AUDIO: false, - DELAY_CREATE_CTX: false, - format: ['.mp3'], - }; -} else { // browser or runtime const win = window, nav = win.navigator, doc = document, docEle = doc.documentElement; diff --git a/cocos/core/platform/view.ts b/cocos/core/platform/view.ts index 3f4551df52..f0cd0c46e5 100644 --- a/cocos/core/platform/view.ts +++ b/cocos/core/platform/view.ts @@ -1328,6 +1328,18 @@ class ContentStrategy { } } + // need to adapt prototype before instantiating + let _global = typeof window === 'undefined' ? global : window; + let globalAdapter = _global.__globalAdapter; + if (globalAdapter) { + if (globalAdapter.adaptContainerStrategy) { + globalAdapter.adaptContainerStrategy(ContainerStrategy.prototype); + } + if (globalAdapter.adaptView) { + globalAdapter.adaptView(View.prototype); + } + } + // Alias: Strategy that makes the container's size equals to the frame's size ContainerStrategy.EQUAL_TO_FRAME = new EqualToFrame(); // Alias: Strategy that scale proportionally the container's size to frame's size diff --git a/cocos/core/splash-image.ts b/cocos/core/splash-image.ts index a2313cdfeb..5546651924 100644 --- a/cocos/core/splash-image.ts +++ b/cocos/core/splash-image.ts @@ -589,3 +589,5 @@ export class SplashScreen { private constructor () { }; } + +cc.SplashScreen = SplashScreen; diff --git a/cocos/core/utils/deprecated.ts b/cocos/core/utils/deprecated.ts index 7c97b4efcd..265a1e4397 100644 --- a/cocos/core/utils/deprecated.ts +++ b/cocos/core/utils/deprecated.ts @@ -4,6 +4,7 @@ import { error, warn } from '../platform/debug'; +// TODO: will redefined in ALIPAY and runtime let defaultLogTimes = 10; diff --git a/predefine.ts b/predefine.ts index 4444585685..1929565409 100644 --- a/predefine.ts +++ b/predefine.ts @@ -221,10 +221,12 @@ export default cc; /** * deprecated */ - -Object.defineProperty(_global, 'CC_PHYSICS_BUILT_IN', { - 'get': () => { - console.warn('CC_PHYSICS_BUILT_IN is deprecated, please using CC_PHYSICS_BUILTIN instead.'); - return _global.CC_PHYSICS_BUILTIN; - } -}) +// TODO: ALIPAY and runtime will redefine +if (!CC_RUNTIME) { + Object.defineProperty(_global, 'CC_PHYSICS_BUILT_IN', { + 'get': () => { + console.warn('CC_PHYSICS_BUILT_IN is deprecated, please using CC_PHYSICS_BUILTIN instead.'); + return _global.CC_PHYSICS_BUILTIN; + }, + }); +} From 6f54d39a291ef431050cda08da62d24df62a6270 Mon Sep 17 00:00:00 2001 From: JoneLau <32630749+JoneLau@users.noreply.github.com> Date: Mon, 2 Dec 2019 19:01:48 +0800 Subject: [PATCH 16/21] fix mask in new model structure (#5801) --- .../components/ui-base/ui-render-component.ts | 15 +++--- .../ui-coodinate-tracker-component.ts | 4 +- cocos/core/renderer/scene/model.ts | 1 + .../graphics/webgl/graphics-assembler.ts | 9 ++-- cocos/ui/components/graphics-component.ts | 46 +++++++++---------- cocos/ui/components/mask-component.ts | 32 +++++++++---- 6 files changed, 57 insertions(+), 50 deletions(-) diff --git a/cocos/core/components/ui-base/ui-render-component.ts b/cocos/core/components/ui-base/ui-render-component.ts index 355af06d40..fcac3cb51b 100644 --- a/cocos/core/components/ui-base/ui-render-component.ts +++ b/cocos/core/components/ui-base/ui-render-component.ts @@ -29,8 +29,6 @@ import { ccclass, - executeInEditMode, - executionOrder, property, } from '../../../core/data/class-decorator'; import { SystemEventType } from '../../../core/platform/event-manager/event-enum'; @@ -43,8 +41,8 @@ import { Material } from '../../assets'; import { RenderableComponent } from '../../../core/3d/framework/renderable-component'; import { IAssembler, IAssemblerManager } from '../../renderer/ui/base'; import { UIComponent } from './ui-component'; -import { UITransformComponent } from './ui-transfrom-component'; import { TransformBit } from '../../scene-graph/node-enum'; +import { INode } from '../../utils/interfaces'; // hack ccenum(GFXBlendFactor); @@ -203,8 +201,8 @@ export class UIRenderComponent extends UIComponent { } // Render data can be submitted even if it is not on the node tree - set simulate (value) { - this._simulate = value; + set delegateSrc (value: INode) { + this._delegateSrc = value; } public static BlendState = GFXBlendFactor; @@ -225,8 +223,8 @@ export class UIRenderComponent extends UIComponent { protected _renderData: RenderData | null = null; protected _renderDataFlag = true; protected _renderFlag = true; - // 特殊渲染标记,在可渲染情况下,因为自身某个原因不给予渲染 - // protected _renderPermit = true; + // 特殊渲染节点,给一些不在节点树上的组件做依赖渲染(例如 mask 组件内置两个 graphics 来渲染) + protected _delegateSrc: INode | null = null; protected _material: Material | null = null; protected _instanceMaterialType = InstanceMaterialType.ADDCOLORANDTEXTURE; protected _blendTemplate = { @@ -241,7 +239,6 @@ export class UIRenderComponent extends UIComponent { depthStencilState: {}, rasterizerState: {}, }; - protected _simulate = false; public __preload (){ super.__preload(); @@ -351,7 +348,7 @@ export class UIRenderComponent extends UIComponent { } protected _canRender () { - return this.material !== null && this.enabled && (this._simulate? true: this.enabledInHierarchy); + return this.material !== null && this.enabled && (this._delegateSrc ? this._delegateSrc.activeInHierarchy : this.enabledInHierarchy); } protected _postCanRender(){} diff --git a/cocos/core/components/ui-coodinate-tracker-component.ts b/cocos/core/components/ui-coodinate-tracker-component.ts index 0aeeaa1870..327cbfbb31 100644 --- a/cocos/core/components/ui-coodinate-tracker-component.ts +++ b/cocos/core/components/ui-coodinate-tracker-component.ts @@ -24,13 +24,13 @@ THE SOFTWARE. */ +import { Component } from './component'; +import { EventHandler } from './component-event-handler'; import { ccclass, property, menu, executionOrder } from '../data/class-decorator'; import { Node } from '../scene-graph'; import { convertUtils } from '../utils'; import { CameraComponent } from '../3d'; import { Vec3 } from '../math'; -import { Component } from '../components/component'; -import { EventHandler } from './component-event-handler'; /** * @zh 3D 节点映射 UI 节点组件 diff --git a/cocos/core/renderer/scene/model.ts b/cocos/core/renderer/scene/model.ts index dd871fb184..f55df7e905 100644 --- a/cocos/core/renderer/scene/model.ts +++ b/cocos/core/renderer/scene/model.ts @@ -200,6 +200,7 @@ export class Model { this._matPSORecord.clear(); this._matRefCount.clear(); this._inited = false; + this._transformUpdated = true; } public attachToScene (scene: RenderScene) { diff --git a/cocos/ui/assembler/graphics/webgl/graphics-assembler.ts b/cocos/ui/assembler/graphics/webgl/graphics-assembler.ts index 0301fc58c4..50e8b8f9c4 100644 --- a/cocos/ui/assembler/graphics/webgl/graphics-assembler.ts +++ b/cocos/ui/assembler/graphics/webgl/graphics-assembler.ts @@ -30,7 +30,6 @@ import { Color, Vec3 } from '../../../../core/math'; import { GFXPrimitiveMode } from '../../../../core/gfx'; import { Model } from '../../../../core/renderer'; -import { RenderScene } from '../../../../core/renderer/scene/render-scene'; import { MeshRenderData } from '../../../../core/renderer/ui/render-data'; import { UI } from '../../../../core/renderer/ui/ui'; import { createMesh } from '../../../../core/3d/misc/utils'; @@ -40,7 +39,8 @@ import { IAssembler } from '../../../../core/renderer/ui/base'; import { LineCap, LineJoin, PointFlags } from '../types'; import { earcut as Earcut } from './earcut'; import { Impl, Point } from './impl'; -import { director } from '../../../../core/director'; +import { director } from '../../../../core'; +import { RenderScene } from '../../../../core/renderer/scene/render-scene'; const MAX_VERTEX = 65535; const MAX_INDICE = MAX_VERTEX * 2; @@ -175,13 +175,10 @@ export const graphicsAssembler: IAssembler = { this.end(graphics); }, - end (graphics: GraphicsComponent){ + end(graphics: GraphicsComponent) { if (graphics.model) { graphics.model.destroy(); - } else { - graphics.model = new Model(); } - const impl = graphics.impl; const primitiveMode = GFXPrimitiveMode.TRIANGLE_LIST; const renderDatas = impl && impl.getRenderDatas(); diff --git a/cocos/ui/components/graphics-component.ts b/cocos/ui/components/graphics-component.ts index 0a599dba65..e0c53fa27c 100644 --- a/cocos/ui/components/graphics-component.ts +++ b/cocos/ui/components/graphics-component.ts @@ -212,14 +212,14 @@ export class GraphicsComponent extends UIRenderComponent { this.impl = this._assembler && (this._assembler as IAssembler).createImpl!(this); } - public onLoad (){ - this._sceneGetter = director.root!.ui.getRenderSceneGetter(); + public onLoad() { + this._sceneGetter = director.root!.ui.getRenderSceneGetter(); if (!this.model) { - this.model = new Model(); + this.model = director.root!.createModel(Model); } } - public onEnable () { + public onEnable() { super.onEnable(); this._attachToScene(); @@ -237,6 +237,7 @@ export class GraphicsComponent extends UIRenderComponent { this._sceneGetter = null; if (this.model) { this.model.destroy(); + director.root!.destroyModel(this.model); this.model = null; } @@ -248,23 +249,6 @@ export class GraphicsComponent extends UIRenderComponent { this.impl = null; } - protected _attachToScene(){ - const scene = director.root!.ui.renderScene; - if (!this.model) { - return; - } - if (this.model!.scene != null) { - this._detachFromScene(); - } - scene.addModel(this.model!); - } - - protected _detachFromScene() { - if (this.model && this.model.scene) { - this.model.scene.removeModel(this.model); - } - } - public _activateMaterial () { if (!this._material) { return; @@ -451,7 +435,6 @@ export class GraphicsComponent extends UIRenderComponent { this.impl.clear(clean); if (this.model) { - this._detachFromScene(); this.model.destroy(); } @@ -528,7 +511,24 @@ export class GraphicsComponent extends UIRenderComponent { return false; } - return this.model ? true : false; + return !!this.model && this.model.inited; + } + + protected _attachToScene() { + const scene = director.root!.ui.renderScene; + if (!this.model) { + return; + } + if (this.model!.scene != null) { + this._detachFromScene(); + } + scene.addModel(this.model!); + } + + protected _detachFromScene() { + if (this.model && this.model.scene) { + this.model.scene.removeModel(this.model); + } } } diff --git a/cocos/ui/components/mask-component.ts b/cocos/ui/components/mask-component.ts index 0cfeab99ad..f6aa3de3f9 100644 --- a/cocos/ui/components/mask-component.ts +++ b/cocos/ui/components/mask-component.ts @@ -39,8 +39,6 @@ import { UI } from '../../core/renderer/ui/ui'; import { Node } from '../../core/scene-graph'; import { ccenum } from '../../core/value-types/enum'; import { GraphicsComponent } from './graphics-component'; -import { UITransformComponent, CanvasComponent } from '../../core'; -import { INode } from '../../core/utils/interfaces'; import { TransformBit } from '../../core/scene-graph/node-enum'; const _worldMatrix = new Mat4(); @@ -283,6 +281,13 @@ export class MaskComponent extends UIRenderComponent { public onLoad () { this._createGraphics(); + if (this._clearGraphics) { + this._clearGraphics.onLoad(); + } + + if (this._graphics) { + this._graphics.onLoad(); + } } /** @@ -311,13 +316,10 @@ export class MaskComponent extends UIRenderComponent { // } // } // else { - if (this._clearGraphics) { - this._clearGraphics.onEnable(); - } - this._updateGraphics(); + this._enableGraphics(); // } - this._activateMaterial(); + // this._activateMaterial(); this.node.on(SystemEventType.TRANSFORM_CHANGED, this._nodeStateChange, this); view.on('design-resolution-changed', this._updateClearGraphics, this); @@ -469,14 +471,12 @@ export class MaskComponent extends UIRenderComponent { if (!this._clearGraphics) { const node = new Node('clear-graphics'); const clearGraphics = this._clearGraphics = node.addComponent(GraphicsComponent)!; + clearGraphics.delegateSrc = this.node; clearGraphics.helpInstanceMaterial(); - clearGraphics._activateMaterial(); clearGraphics.lineWidth = 0; const color = Color.WHITE.clone(); color.a = 0; clearGraphics.fillColor = color; - clearGraphics.simulate = true; - this._updateClearGraphics(); } if (!this._graphics) { @@ -539,6 +539,18 @@ export class MaskComponent extends UIRenderComponent { graphics.fill(); } + private _enableGraphics() { + if (this._clearGraphics) { + this._clearGraphics.onEnable(); + this._updateClearGraphics(); + } + + if (this._graphics) { + this._graphics.onEnable(); + this._updateGraphics(); + } + } + private _disableGraphics () { if (this._graphics) { this._graphics.onDisable(); From 6516bd873fdcc477c298b90db7d0ab4560b2d753 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lelie=20Leight=20=28=E6=9D=8E=E7=9A=84=E5=BA=8F=29?= Date: Mon, 2 Dec 2019 19:03:56 +0800 Subject: [PATCH 17/21] Add cSpell config (#5820) --- .vscode/cSpell.json | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 .vscode/cSpell.json diff --git a/.vscode/cSpell.json b/.vscode/cSpell.json new file mode 100644 index 0000000000..3433a44bfc --- /dev/null +++ b/.vscode/cSpell.json @@ -0,0 +1,35 @@ +{ + "version": "0.1", + "words": [ + "Chukong", + "Yaji", + + "ccclass", + "ccenum", + + "forin", + "struct", + "realloc", + "polyfill", + + "lerp", + "lerpable", + "slerp", + + "renderable", + "grayscale", + "raycast", + "skybox", + "earcut", + + "Arial", + + "OPENGL", + "IGFX", + "UNORM", + "SNORM", + + "WECHAT", + "WECHATGAME" + ] +} \ No newline at end of file From 21cda44a7baaf4b5021a5fdead31481c48080c3c Mon Sep 17 00:00:00 2001 From: "jiaxin.lai" Date: Tue, 3 Dec 2019 14:34:55 +0800 Subject: [PATCH 18/21] fix splash screen when base64Src is null (#5826) --- cocos/core/splash-image.ts | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/cocos/core/splash-image.ts b/cocos/core/splash-image.ts index 5546651924..5fa6fa6749 100644 --- a/cocos/core/splash-image.ts +++ b/cocos/core/splash-image.ts @@ -62,6 +62,7 @@ export class SplashScreen { private _splashFinish: boolean = false; private _loadFinish: boolean = false; + private _directCall: boolean = false; /** text */ private textImg!: TexImageSource; @@ -106,7 +107,7 @@ export class SplashScreen { if (this.callBack) { this.callBack(); } this.callBack = null; (this.setting as any) = null; - delete SplashScreen._ins; + this._directCall = true; return; } else { cc.game.once(cc.Game.EVENT_GAME_INITED, () => { @@ -181,6 +182,12 @@ export class SplashScreen { } public setOnFinish (cb: Function) { + if (this._directCall) { + if (cb) { + delete SplashScreen._ins; + return cb(); + } + } this.callBack = cb; } From f3c198171e3cdb3dafc845986528c447dfd82733 Mon Sep 17 00:00:00 2001 From: ChiaNing Date: Tue, 3 Dec 2019 15:47:23 +0800 Subject: [PATCH 19/21] alipay adapter update (#5824) * alipay adapter update * platform change * update * useless remove --- @types/globals.d.ts | 10 ++-- cocos/core/assets/image-asset.ts | 2 +- cocos/core/assets/prefab.ts | 2 +- cocos/core/platform/sys.ts | 25 ++++------ cocos/core/platform/view.ts | 19 ++------ cocos/core/utils/deprecated.ts | 3 ++ gulp/util/utils.js | 2 +- predefine.ts | 27 ++++++----- rollup/src/build-engine-cli.ts | 13 ++++- rollup/src/build-engine.ts | 83 +++++++++++++++++++++++++------- 10 files changed, 117 insertions(+), 69 deletions(-) diff --git a/@types/globals.d.ts b/@types/globals.d.ts index c8f1cc0546..931267fcbe 100644 --- a/@types/globals.d.ts +++ b/@types/globals.d.ts @@ -31,10 +31,10 @@ 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_WECHAT: boolean; +declare const CC_ALIPAY: boolean; +declare const CC_MINIGAME: boolean; +declare const CC_RUNTIME_BASED: boolean; declare const CC_SUPPORT_JIT: boolean; declare const jsb: any; @@ -45,7 +45,7 @@ declare const CC_PHYSICS_BUILTIN: boolean; interface Window { [x: string]: any; - + WebGL2RenderingContext: any; sharedCanvas: any; diff --git a/cocos/core/assets/image-asset.ts b/cocos/core/assets/image-asset.ts index c9e6594c9e..1bae62bff2 100644 --- a/cocos/core/assets/image-asset.ts +++ b/cocos/core/assets/image-asset.ts @@ -181,7 +181,7 @@ export class ImageAsset extends Asset { this._onDataComplete(); } else { this._nativeData = data; - if (CC_WECHATGAME || CC_QQPLAY || (data as any).complete || data instanceof HTMLCanvasElement) { // todo need adatper + if (CC_MINIGAME || (data as any).complete || data instanceof HTMLCanvasElement) { // todo need adatper this._onDataComplete(); } else { this.loaded = false; diff --git a/cocos/core/assets/prefab.ts b/cocos/core/assets/prefab.ts index 5d48bc2298..2992bba927 100644 --- a/cocos/core/assets/prefab.ts +++ b/cocos/core/assets/prefab.ts @@ -188,7 +188,7 @@ export default class Prefab extends Asset { } cc.Prefab = Prefab; -if (CC_WECHATGAME || CC_RUNTIME) { +if (CC_ALIPAY || CC_RUNTIME_BASED) { cc._Prefab = Prefab; } else { obsolete(cc, 'cc._Prefab', 'Prefab'); diff --git a/cocos/core/platform/sys.ts b/cocos/core/platform/sys.ts index 0396d9ad80..40cf982190 100644 --- a/cocos/core/platform/sys.ts +++ b/cocos/core/platform/sys.ts @@ -364,19 +364,12 @@ sys.BROWSER_TYPE_WECHAT = 'wechat'; */ sys.BROWSER_TYPE_WECHAT_GAME = 'wechatgame'; /** - * BROWSER_TYPE_WECHAT_GAME_SUB - * @property {String} BROWSER_TYPE_WECHAT_GAME_SUB + * BROWSER_TYPE_ALIPAY_GAME + * @property {String} BROWSER_TYPE_ALIPAY_GAME * @readOnly - * @default "wechatgamesub" + * @default "alipaygame" */ -sys.BROWSER_TYPE_WECHAT_GAME_SUB = 'wechatgamesub'; -/** - * BROWSER_TYPE_QQ_PLAY - * @property {String} BROWSER_TYPE_QQ_PLAY - * @readOnly - * @default "qqplay" - */ -sys.BROWSER_TYPE_QQ_PLAY = 'qqplay'; +sys.BROWSER_TYPE_ALIPAY_GAME = 'alipaygame'; /** * * @property {String} BROWSER_TYPE_ANDROID @@ -528,7 +521,7 @@ sys.isNative = CC_JSB; * Is web browser ? * @property {Boolean} isBrowser */ -sys.isBrowser = typeof window === 'object' && typeof document === 'object' && !CC_WECHATGAME && !CC_QQPLAY && !CC_JSB; +sys.isBrowser = typeof window === 'object' && typeof document === 'object' && !CC_MINIGAME && !CC_JSB; /** * Endianess of current platform @@ -716,12 +709,12 @@ else { if (!browserTypes) { browserTypes = typeReg3.exec(ua); } let browserType = browserTypes ? browserTypes[0].toLowerCase() : sys.BROWSER_TYPE_UNKNOWN; - if (CC_WECHATGAME) { + if (CC_WECHAT) { browserType = sys.BROWSER_TYPE_WECHAT_GAME; } - else if (CC_QQPLAY) { - browserType = sys.BROWSER_TYPE_QQ_PLAY; - } + else if(CC_ALIPAY) { + browserType = sys.BROWSER_TYPE_ALIPAY_GAME; + } else if (browserType === 'micromessenger') { browserType = sys.BROWSER_TYPE_WECHAT; } diff --git a/cocos/core/platform/view.ts b/cocos/core/platform/view.ts index f0cd0c46e5..a623a629b1 100644 --- a/cocos/core/platform/view.ts +++ b/cocos/core/platform/view.ts @@ -41,7 +41,7 @@ class BrowserGetter { public adaptationType: any = cc.sys.browserType; public init () { - if (!CC_WECHATGAME) { + if (!CC_MINIGAME) { this.html = document.getElementsByTagName('html')[0]; } } @@ -71,17 +71,8 @@ if (cc.sys.os === cc.sys.OS_IOS) { // All browsers are WebView __BrowserGetter.adaptationType = cc.sys.BROWSER_TYPE_SAFARI; } -if (CC_WECHATGAME) { - if (cc.sys.browserType === cc.sys.BROWSER_TYPE_WECHAT_GAME_SUB) { - __BrowserGetter.adaptationType = cc.sys.BROWSER_TYPE_WECHAT_GAME_SUB; - } - else { - __BrowserGetter.adaptationType = cc.sys.BROWSER_TYPE_WECHAT_GAME; - } -} - -if (CC_QQPLAY) { - __BrowserGetter.adaptationType = cc.sys.BROWSER_TYPE_QQ_PLAY; +if (CC_WECHAT) { + __BrowserGetter.adaptationType = cc.sys.BROWSER_TYPE_WECHAT_GAME; } switch (__BrowserGetter.adaptationType) { @@ -729,7 +720,7 @@ export class View extends EventTarget { * @param {ResolutionPolicy|Number} resolutionPolicy The resolution policy desired */ public setRealPixelResolution (width, height, resolutionPolicy) { - if (!CC_JSB && !CC_WECHATGAME && !CC_QQPLAY) { + if (!CC_JSB && !CC_MINIGAME) { // Set viewport's width this._setViewportMeta({width}, true); @@ -1044,7 +1035,7 @@ export class View extends EventTarget { } private _adjustViewportMeta () { - if (this._isAdjustViewport && !CC_JSB && !CC_WECHATGAME && !CC_QQPLAY) { + if (this._isAdjustViewport && !CC_JSB && !CC_MINIGAME) { this._setViewportMeta(__BrowserGetter.meta, false); this._isAdjustViewport = false; } diff --git a/cocos/core/utils/deprecated.ts b/cocos/core/utils/deprecated.ts index 265a1e4397..74185c389b 100644 --- a/cocos/core/utils/deprecated.ts +++ b/cocos/core/utils/deprecated.ts @@ -79,6 +79,7 @@ replacePropertyLog = function (n: string, dp: string, n2: string, newp: string, }; replaceProperty = (owner: object, ownerName: string, properties: IReplacement[]) => { + if (CC_ALIPAY) { return; } if (owner == null) return; properties.forEach(function (item: IReplacement) { @@ -165,6 +166,7 @@ removePropertyLog = function (n: string, dp: string, f: Function, id: number) { }; removeProperty = (owner: object, ownerName: string, properties: IRemoveItem[]) => { + if (CC_ALIPAY) { return; } if (owner == null) return; properties.forEach(function (item: IRemoveItem) { @@ -192,6 +194,7 @@ markAsWarningLog = function (n: string, dp: string, f: Function, id: number) { }; markAsWarning = (owner: object, ownerName: string, properties: IMarkItem[]) => { + if (CC_ALIPAY) { return; } if (owner == null) return; let _defaultGetSet = function (o: {}, p: string, d: PropertyDescriptor, n: string, dp: string, f: Function, id: number) { diff --git a/gulp/util/utils.js b/gulp/util/utils.js index 14319a4ca9..a23e8dd84b 100644 --- a/gulp/util/utils.js +++ b/gulp/util/utils.js @@ -36,7 +36,7 @@ exports.getMacros = function (platform, flags) { // debug macros res['CC_DEV'] = res['CC_EDITOR'] || res['CC_PREVIEW'] || res['CC_TEST']; res['CC_DEBUG'] = res['CC_DEBUG'] || res['CC_DEV']; - res['CC_SUPPORT_JIT'] = !(res['CC_WECHATGAME'] || res['CC_QQPLAY'] || res['CC_RUNTIME']); + res['CC_SUPPORT_JIT'] = !(res['CC_WECHAT'] || res['CC_RUNTIME_BASED']); return res; }; diff --git a/predefine.ts b/predefine.ts index 1929565409..6dcc9e50cf 100644 --- a/predefine.ts +++ b/predefine.ts @@ -110,13 +110,16 @@ * @property {Boolean} CC_TEST - Running in the engine's unit test. */ /** - * @property {Boolean} CC_WECHATGAME - Running in the Wechat's mini game. + * @property {Boolean} CC_WECHAT - Running in the Wechat's mini game. */ /** - * @property {Boolean} CC_QQPLAY - Running in the bricks. + * @property {Boolean} CC_ALIPAY - Running in the alipay's mini game. */ /** - * @property {Boolean} CC_RUNTIME - Running in runtime environments. + * @property {Boolean} CC_MINIGAME - Running in mini game. + */ +/** + * @property {Boolean} CC_RUNTIME_BASED - Running in runtime environments. */ // PREDEFINE @@ -165,9 +168,10 @@ if (CC_BUILD) { _global.CC_DEV = CC_DEV; _global.CC_DEBUG = CC_DEBUG; _global.CC_JSB = CC_JSB; - _global.CC_WECHATGAME = CC_WECHATGAME; - _global.CC_QQPLAY = CC_QQPLAY; - _global.CC_RUNTIME = CC_RUNTIME; + _global.CC_WECHAT = CC_WECHAT; + _global.CC_ALIPAY = CC_ALIPAY; + _global.CC_MINIGAME = CC_MINIGAME; + _global.CC_RUNTIME_BASED = CC_RUNTIME_BASED; _global.CC_SUPPORT_JIT = CC_SUPPORT_JIT; _global.CC_PHYSICS_BUILTIN = CC_PHYSICS_BUILTIN; _global.CC_PHYSICS_CANNON = CC_PHYSICS_CANNON; @@ -182,12 +186,13 @@ else { defineMacro('CC_DEV', true); // (CC_EDITOR && !CC_BUILD) || CC_PREVIEW || CC_TEST defineMacro('CC_DEBUG', true); // CC_DEV || Debug Build defineMacro('CC_JSB', defined('jsb')); - defineMacro('CC_WECHATGAME_SUB', !!(defined('wx') && wx.getSharedCanvas)); - defineMacro('CC_WECHATGAME', !!(defined('wx') && (wx.getSystemInfoSync || wx.getSharedCanvas))); - defineMacro('CC_QQPLAY', defined('bk')); + defineMacro('CC_WECHAT', !!(defined('wx') && (wx.getSystemInfoSync || wx.getSharedCanvas))); + defineMacro('CC_MINIGAME', false); + defineMacro('CC_RUNTIME_BASED', false); + defineMacro('CC_ALIPAY', false); // @ts-ignore defineMacro('CC_RUNTIME', 'function' === typeof loadRuntime); - defineMacro('CC_SUPPORT_JIT', !(CC_WECHATGAME || CC_QQPLAY || CC_RUNTIME)); + defineMacro('CC_SUPPORT_JIT', !(CC_MINIGAME || CC_RUNTIME_BASED)); defineMacro('CC_PHYSICS_BUILTIN', true); defineMacro('CC_PHYSICS_CANNON', false); defineMacro('CC_PHYSICS_AMMO', false); @@ -222,7 +227,7 @@ export default cc; * deprecated */ // TODO: ALIPAY and runtime will redefine -if (!CC_RUNTIME) { +if (!(CC_RUNTIME_BASED || CC_ALIPAY)) { Object.defineProperty(_global, 'CC_PHYSICS_BUILT_IN', { 'get': () => { console.warn('CC_PHYSICS_BUILT_IN is deprecated, please using CC_PHYSICS_BUILTIN instead.'); diff --git a/rollup/src/build-engine-cli.ts b/rollup/src/build-engine-cli.ts index 8ea498a7d0..3d9ebf2b10 100644 --- a/rollup/src/build-engine-cli.ts +++ b/rollup/src/build-engine-cli.ts @@ -1,10 +1,16 @@ import * as fs from 'fs-extra'; import * as ps from 'path'; import yargs from 'yargs'; -import { build, enumeratePhysicsReps, enumeratePlatformReps, IBuildOptions, IFlags, parsePhysics, parsePlatform, enumerateModuleOptionReps, parseModuleOption } from './build-engine'; +import { build, enumeratePhysicsReps, enumerateBuildModeReps, enumeratePlatformReps, IBuildOptions, IFlags, parsePhysics, parseBuildMode, enumerateModuleOptionReps, parseModuleOption, parsePlatform } from './build-engine'; yargs.help(); -// @ts-ignore +yargs.option('buildmode', { + type: 'string', + alias: 'b', + description: 'Target buildmode.', + demandOption: true, + choices: enumerateBuildModeReps(), +}); yargs.option('platform', { type: 'string', alias: 'p', @@ -65,6 +71,9 @@ const options: IBuildOptions = { if (yargs.argv['module']) { options.moduleFormat = parseModuleOption(yargs.argv['module'] as unknown as string); } +if (yargs.argv.buildmode) { + options.mode = parseBuildMode(yargs.argv.buildmode as unknown as string); +} if (yargs.argv.platform) { options.platform = parsePlatform(yargs.argv.platform as unknown as string); } diff --git a/rollup/src/build-engine.ts b/rollup/src/build-engine.ts index 310d076e25..8c4ce93ea9 100644 --- a/rollup/src/build-engine.ts +++ b/rollup/src/build-engine.ts @@ -65,6 +65,11 @@ interface IAdvancedOptions extends IBaseOptions { } export interface IBuildOptions extends IBaseOptions { + /** + * 构建模式。 + */ + mode?: Mode; + /** * 目标平台。 */ @@ -271,6 +276,26 @@ async function _internalBuild (options: IAdvancedOptions) { } export enum Platform { + HTML5, + WECHAT, + ALIPAY, + BAIDU, + XIAOMI, + OPPO, + VIVO, + HUAWEI, + NATIVE, +} + +export function enumeratePlatformReps () { + return Object.values(Platform).filter((value) => typeof value === 'string') as Array; +} + +export function parsePlatform (rep: string) { + return Reflect.get(Platform, rep); +} + +export enum Mode { universal, editor, preview, @@ -278,12 +303,12 @@ export enum Platform { test, } -export function enumeratePlatformReps () { - return Object.values(Platform).filter((value) => typeof value === 'string'); +export function enumerateBuildModeReps () { + return Object.values(Mode).filter((value) => typeof value === 'string') as Array; } -export function parsePlatform (rep: string) { - return Reflect.get(Platform, rep); +export function parseBuildMode (rep: string) { + return Reflect.get(Mode, rep); } export enum Physics { @@ -324,20 +349,30 @@ export interface IFlags { } interface IGlobaldefines { - // Platform macros + // BuildMode macros CC_EDITOR?: boolean; CC_PREVIEW?: boolean; CC_BUILD?: boolean; CC_TEST?: boolean; - // Flag macros + // Platform macros + CC_HTML5?: boolean; + CC_WECHAT?: boolean; + CC_ALIPAY?: boolean; + CC_BAIDU?: boolean; + CC_XIAOMI?: boolean; + CC_OPPO?: boolean; + CC_VIVO?: boolean; + CC_HUAWEI?: boolean; + CC_NATIVE?: boolean; + + // engine use platform macros + CC_RUNTIME_BASED?: boolean; + CC_MINIGAMES?: boolean; CC_JSB?: boolean; - CC_RUNTIME?: boolean; - CC_WECHATGAME?: boolean; - CC_WECHATGAMESUB?: boolean; - CC_QQPLAY?: boolean; + + // Flag macros CC_DEBUG?: boolean; - CC_NATIVERENDERER?: boolean; // Debug macros CC_DEV?: boolean; @@ -350,18 +385,27 @@ interface IGlobaldefines { } function getGlobalDefs (options: IBuildOptions): object { + const buildmode = options.mode || Mode.universal; + const platform = options.platform; const flags = options.flags; - const platform = options.platform || Platform.universal; - const PLATFORM_MACROS = ['CC_EDITOR', 'CC_PREVIEW', 'CC_BUILD', 'CC_TEST']; + const BUILDMODE_MACROS = ['CC_EDITOR', 'CC_PREVIEW', 'CC_BUILD', 'CC_TEST']; + const PLATFORM_MACROS = ['CC_HTML5', 'CC_WECHAT', 'CC_ALIPAY', 'CC_BAIDU', 'CC_XIAOMI', 'CC_OPPO', 'CC_VIVO', 'CC_HUAWEI', 'CC_NATIVE']; + const FLAGS = ['debug']; - const FLAGS = ['jsb', 'runtime', 'wechatgame', 'wechatgameSub', 'qqplay', 'debug', 'nativeRenderer']; - - const platformMacro = ('CC_' + Platform[platform]).toUpperCase(); - if (PLATFORM_MACROS.indexOf(platformMacro) === -1 && platform !== Platform.universal) { + const buildmodeMacro = ('CC_' + Mode[buildmode]).toUpperCase(); + if (BUILDMODE_MACROS.indexOf(buildmodeMacro) === -1 && buildmode !== Mode.universal) { + throw new Error(`Unknown buildmode ${buildmode}.`); + } + const platformMacro = ('CC_' + Platform[platform!]).toUpperCase(); + if ( PLATFORM_MACROS.indexOf(platformMacro) === -1) { throw new Error(`Unknown platform ${platform}.`); } const result: IGlobaldefines = {}; + for (const macro of BUILDMODE_MACROS) { + result[macro as keyof IGlobaldefines] = (macro === buildmodeMacro); + } + for (const macro of PLATFORM_MACROS) { result[macro as keyof IGlobaldefines] = (macro === platformMacro); } @@ -382,7 +426,10 @@ function getGlobalDefs (options: IBuildOptions): object { result.CC_DEV = result.CC_EDITOR || result.CC_PREVIEW || result.CC_TEST; result.CC_DEBUG = result.CC_DEBUG || result.CC_DEV; - result.CC_SUPPORT_JIT = !(result.CC_WECHATGAME || result.CC_QQPLAY || result.CC_RUNTIME); + result.CC_RUNTIME_BASED = result.CC_OPPO || result.CC_VIVO || result.CC_HUAWEI; + result.CC_MINIGAMES = result.CC_WECHAT || result.CC_ALIPAY || result.CC_XIAOMI || result.CC_BAIDU; + result.CC_JSB = result.CC_NATIVE || result.CC_RUNTIME_BASED; + result.CC_SUPPORT_JIT = !(result.CC_MINIGAMES || result.CC_RUNTIME_BASED); result.CC_PHYSICS_BUILTIN = false; result.CC_PHYSICS_CANNON = false; result.CC_PHYSICS_AMMO = false; From e277107565c6dce61b6b0275dbccf669ca582bdc Mon Sep 17 00:00:00 2001 From: ChiaNing Date: Tue, 3 Dec 2019 17:31:38 +0800 Subject: [PATCH 20/21] spell fix & macro init & bug fix (#5831) * spell fix (cherry picked from commit ca2dbfb5140b52627675d5e97b3d772c39b4d77f) * macro init * glloc fixed & destroyByParent fixed --- cocos/core/gfx/webgl2/webgl2-commands.ts | 2 +- cocos/core/scene-graph/base-node.ts | 2 +- rollup/src/build-engine.ts | 8 +++++--- 3 files changed, 7 insertions(+), 5 deletions(-) diff --git a/cocos/core/gfx/webgl2/webgl2-commands.ts b/cocos/core/gfx/webgl2/webgl2-commands.ts index f8558d1ba8..eb422cf2d6 100644 --- a/cocos/core/gfx/webgl2/webgl2-commands.ts +++ b/cocos/core/gfx/webgl2/webgl2-commands.ts @@ -1609,7 +1609,7 @@ export function WebGL2CmdFuncCreateShader (device: WebGL2GFXDevice, gpuShader: W const uniformInfo = gl.getActiveUniform(gpuShader.glProgram, i); if (uniformInfo) { const glLoc = gl.getUniformLocation(gpuShader.glProgram, uniformInfo.name); - if (glLoc) { + if (glLoc !== null) { let varName: string; const nameOffset = uniformInfo.name.indexOf('['); if (nameOffset !== -1) { diff --git a/cocos/core/scene-graph/base-node.ts b/cocos/core/scene-graph/base-node.ts index 2457952a5a..bc04c50678 100644 --- a/cocos/core/scene-graph/base-node.ts +++ b/cocos/core/scene-graph/base-node.ts @@ -1333,7 +1333,7 @@ export class BaseNode extends CCObject implements IBaseNode, ISchedulable { // detach self and children from editor const parent = this._parent; - const destroyByParent: boolean = (parent !== null) && ((parent._objFlags & Destroying) !== 0); + const destroyByParent: boolean = (!!parent) && ((parent._objFlags & Destroying) !== 0); if (!destroyByParent && (CC_EDITOR || CC_TEST)) { this._registerIfAttached!(false); } diff --git a/rollup/src/build-engine.ts b/rollup/src/build-engine.ts index 8c4ce93ea9..6d94926055 100644 --- a/rollup/src/build-engine.ts +++ b/rollup/src/build-engine.ts @@ -368,7 +368,7 @@ interface IGlobaldefines { // engine use platform macros CC_RUNTIME_BASED?: boolean; - CC_MINIGAMES?: boolean; + CC_MINIGAME?: boolean; CC_JSB?: boolean; // Flag macros @@ -424,12 +424,14 @@ function getGlobalDefs (options: IBuildOptions): object { result[macro as keyof IGlobaldefines] = !!(flags && flags[flag as keyof IFlags]); } + result.CC_RUNTIME_BASED = false; + result.CC_MINIGAME = false; result.CC_DEV = result.CC_EDITOR || result.CC_PREVIEW || result.CC_TEST; result.CC_DEBUG = result.CC_DEBUG || result.CC_DEV; result.CC_RUNTIME_BASED = result.CC_OPPO || result.CC_VIVO || result.CC_HUAWEI; - result.CC_MINIGAMES = result.CC_WECHAT || result.CC_ALIPAY || result.CC_XIAOMI || result.CC_BAIDU; + result.CC_MINIGAME = result.CC_WECHAT || result.CC_ALIPAY || result.CC_XIAOMI || result.CC_BAIDU; result.CC_JSB = result.CC_NATIVE || result.CC_RUNTIME_BASED; - result.CC_SUPPORT_JIT = !(result.CC_MINIGAMES || result.CC_RUNTIME_BASED); + result.CC_SUPPORT_JIT = !(result.CC_MINIGAME || result.CC_RUNTIME_BASED); result.CC_PHYSICS_BUILTIN = false; result.CC_PHYSICS_CANNON = false; result.CC_PHYSICS_AMMO = false; From ff3bb5b332bfb7428281e3158d2d6f5f3540b508 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Tue, 3 Dec 2019 19:33:17 +0800 Subject: [PATCH 21/21] Fix ci --- cocos/core/components/ui-base/canvas-component.ts | 2 +- cocos/core/components/ui-base/ui-component.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/cocos/core/components/ui-base/canvas-component.ts b/cocos/core/components/ui-base/canvas-component.ts index 28d671bc1a..b241754a14 100644 --- a/cocos/core/components/ui-base/canvas-component.ts +++ b/cocos/core/components/ui-base/canvas-component.ts @@ -43,7 +43,7 @@ import { Node } from '../../scene-graph/node'; import { INode } from '../../utils/interfaces'; import { Enum } from '../../value-types'; import { Component } from '../component'; -import { UITransformComponent } from './ui-transfrom-component'; +import { UITransformComponent } from './ui-transform-component'; const _worldPos = new Vec3(); diff --git a/cocos/core/components/ui-base/ui-component.ts b/cocos/core/components/ui-base/ui-component.ts index e94b9cc5a5..a225d1a0fc 100644 --- a/cocos/core/components/ui-base/ui-component.ts +++ b/cocos/core/components/ui-base/ui-component.ts @@ -31,7 +31,7 @@ import { ccclass, disallowMultiple, executeInEditMode, executionOrder, property, import { INode } from '../../../core/utils/interfaces'; import { UI } from '../../renderer/ui/ui'; import { Component } from '../component'; -import { UITransformComponent } from './ui-transfrom-component'; +import { UITransformComponent } from './ui-transform-component'; /** * @zh