From 8bb80df7320480d5d9665e71674b9cd91ad30450 Mon Sep 17 00:00:00 2001 From: Weiliang Wang Date: Thu, 14 Mar 2019 12:03:04 +0800 Subject: [PATCH 1/5] 3d (#4036) * compiler error (#4033) * compiler error * add gen decl module * fix global event and other bug (#4032) * components such as event-target to ts * divide CCEvent and CCTouch into game coordinates and ui coordinate mod * repair editor environment where mask does not take effect bug * fix render component blendState modification does not take effect bug * fix bug * fix ts tip --- .vscode/launch.json | 2 +- cocos/3d/geom-utils/frustum.ts | 2 +- cocos/3d/ui/assembler/label/bmfont.ts | 4 +- cocos/3d/ui/assembler/mask/mask-assembler.ts | 31 +- cocos/3d/ui/components/button-component.ts | 6 +- .../components/editbox/edit-box-component.ts | 9 +- .../3d/ui/components/editbox/edit-box-impl.ts | 69 ++-- cocos/3d/ui/components/layout-component.ts | 233 +++++++------ cocos/3d/ui/components/mask-component.ts | 8 +- .../3d/ui/components/scroll-view-component.ts | 8 +- cocos/3d/ui/components/slider-component.ts | 6 +- cocos/3d/ui/components/sprite-component.ts | 13 +- cocos/3d/ui/components/ui-render-component.ts | 4 +- .../ui/components/ui-transfrom-component.ts | 4 +- cocos/assets/CCSpriteFrame.ts | 58 +--- cocos/components/component.d.ts | 1 - cocos/core/director.js | 27 +- ...lbacks-invoker.js => callbacks-invoker.ts} | 123 +++---- cocos/core/event/event-target-factory.ts | 3 +- .../{event-target.js => event-target.ts} | 64 ++-- cocos/core/event/event.ts | 2 +- cocos/core/event/index.js | 2 +- cocos/core/game.js | 320 +++++++++--------- cocos/core/platform/CCView.js | 104 +++--- cocos/core/platform/event-manager/CCEvent.ts | 66 +++- cocos/core/platform/event-manager/CCTouch.ts | 49 +++ .../core/platform/event-manager/event-enum.ts | 212 ++++++++++++ .../{CCEventListener.ts => event-listener.ts} | 0 .../{CCEventManager.ts => event-manager.ts} | 2 +- cocos/core/platform/event-manager/index.ts | 4 +- .../{CCInputManager.ts => input-manager.ts} | 50 +-- .../platform/event-manager/system-event.js | 173 ---------- .../platform/event-manager/system-event.ts | 228 +++++++++++++ cocos/renderer/ui/ui.ts | 15 +- cocos/scene-graph/base-node.ts | 2 +- cocos/scene-graph/node-event-enum.ts | 46 --- cocos/scene-graph/node-event-processor.ts | 68 ++-- cocos/scene-graph/node.ts | 2 +- scripts/generate-declaration-cli.js | 8 + scripts/generate-declaration.js | 63 +++- 40 files changed, 1261 insertions(+), 830 deletions(-) rename cocos/core/event/{callbacks-invoker.js => callbacks-invoker.ts} (73%) rename cocos/core/event/{event-target.js => event-target.ts} (84%) create mode 100644 cocos/core/platform/event-manager/event-enum.ts rename cocos/core/platform/event-manager/{CCEventListener.ts => event-listener.ts} (100%) rename cocos/core/platform/event-manager/{CCEventManager.ts => event-manager.ts} (99%) rename cocos/core/platform/event-manager/{CCInputManager.ts => input-manager.ts} (96%) delete mode 100644 cocos/core/platform/event-manager/system-event.js create mode 100644 cocos/core/platform/event-manager/system-event.ts delete mode 100644 cocos/scene-graph/node-event-enum.ts create mode 100644 scripts/generate-declaration-cli.js diff --git a/.vscode/launch.json b/.vscode/launch.json index 547b005afc..1ee10e49ed 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -5,7 +5,7 @@ "type": "node", "request": "launch", "name": "Generate declaration", - "program": "${workspaceFolder}\\scripts\\generate-declaration.js" + "program": "${workspaceFolder}\\scripts\\generate-declaration-cli.js" } ] } \ No newline at end of file diff --git a/cocos/3d/geom-utils/frustum.ts b/cocos/3d/geom-utils/frustum.ts index 26330d9e37..e686508970 100644 --- a/cocos/3d/geom-utils/frustum.ts +++ b/cocos/3d/geom-utils/frustum.ts @@ -60,7 +60,7 @@ export class frustum { this._type = enums.SHAPE_FRUSTUM; this.planes = new Array(6); for (let i = 0; i < 6; ++i) { - this.planes[i] = plane.create(); + this.planes[i] = plane.create(0, 0, 0, 0); } this.vertices = new Array(8); for (let i = 0; i < 8; ++i) { diff --git a/cocos/3d/ui/assembler/label/bmfont.ts b/cocos/3d/ui/assembler/label/bmfont.ts index 5429dc6f4c..b64e412b3f 100644 --- a/cocos/3d/ui/assembler/label/bmfont.ts +++ b/cocos/3d/ui/assembler/label/bmfont.ts @@ -40,10 +40,8 @@ export const bmfont: IAssembler = { }, fillBuffers (comp: LabelComponent, renderer: UI) { - const buffer = renderer.currBufferBatch!; - const node = comp.node; - fillMeshVertices3D(node, buffer, comp.renderData!, comp.color); + fillMeshVertices3D(node, renderer, comp.renderData!, comp.color); }, appendQuad (renderData: RenderData, texture: SpriteFrame, rect: Rect, rotated: boolean, x: number, y: number, scale: number) { diff --git a/cocos/3d/ui/assembler/mask/mask-assembler.ts b/cocos/3d/ui/assembler/mask/mask-assembler.ts index ee34175343..78196b4fc2 100644 --- a/cocos/3d/ui/assembler/mask/mask-assembler.ts +++ b/cocos/3d/ui/assembler/mask/mask-assembler.ts @@ -37,6 +37,19 @@ const _stencilManager = StencilManager.sharedManager!; const _worldMatrix = new Mat4(); const WHITE = Color.WHITE; +function getScreen (comp: MaskComponent){ + let parent: Node | null = comp.node; + while (parent){ + if (parent.getComponent(cc.CanvasComponent)){ + return parent; + } + + parent = parent.parent; + } + + return parent; +} + export const maskAssembler: IAssembler = { createData (mask: MaskComponent) { const renderData = mask.requestRenderData(); @@ -95,7 +108,13 @@ export const maskAssembler: IAssembler = { const data3 = new Vec3(); const vec3_temps: Vec3[] = [new Vec3(), new Vec3(), new Vec3(), new Vec3()]; const v = new vec3(); - const screen = renderer.getScreen(mask.visibility); + let screen: Node | null = null; + if (CC_EDITOR){ + screen = getScreen(mask); + }else{ + const comp = renderer.getScreen(mask.visibility); + screen = comp ? comp.node : null; + } if (!screen) { return; } @@ -105,10 +124,10 @@ export const maskAssembler: IAssembler = { // const clearGeometry = mask.getClearGeometry(); const clearMaterial = mask.getClearMaterial()!; - cw = screen.node.width; - ch = screen.node.height; - appx = screen.node.anchorX * cw; - appy = screen.node.anchorY * ch; + cw = screen.width; + ch = screen.height; + appx = screen.anchorX * cw; + appy = screen.anchorY * ch; data0.x = -appx; data0.y = -appy; data3.x = cw - appx; @@ -119,7 +138,7 @@ export const maskAssembler: IAssembler = { vec3.set(vec3_temps[3], data3.x, data3.y, 0); // const meshBuffer = createMeshBuffer(ui, clearGeometry); // const nVert = Math.floor(clearGeometry.positions.length / 3); - screen.node.getWorldMatrix(_worldMatrix); + screen.getWorldMatrix(_worldMatrix); let buffer = renderer.currBufferBatch!; let vertexOffset = buffer.byteOffset >> 2; diff --git a/cocos/3d/ui/components/button-component.ts b/cocos/3d/ui/components/button-component.ts index 6c29f5598e..c9d186f1b1 100644 --- a/cocos/3d/ui/components/button-component.ts +++ b/cocos/3d/ui/components/button-component.ts @@ -26,16 +26,16 @@ // @ts-check // import { SpriteFrame } from '../../../assets/CCSpriteFrame'; -import { EventHandler as ComponentEventHandler } from '../../../components/component-event-handler'; import { Component} from '../../../components/component'; +import { EventHandler as ComponentEventHandler } from '../../../components/component-event-handler'; import { ccclass, executeInEditMode, executionOrder, menu, property } from '../../../core/data/class-decorator'; import { EventMouse, EventTouch } from '../../../core/platform/event-manager'; +import { EventType } from '../../../core/platform/event-manager/event-enum'; import { lerp } from '../../../core/utils/misc'; import { ccenum } from '../../../core/value-types/enum'; import { Color, Vec3 } from '../../../core/value-types/index'; import * as math from '../../../core/vmath/index'; import { Node } from '../../../scene-graph'; -import { EventType } from '../../../scene-graph/node-event-enum'; import { SpriteComponent } from './sprite-component'; import { UIRenderComponent } from './ui-render-component'; @@ -669,7 +669,7 @@ export class ButtonComponent extends Component { return false; } - const hit = this.node.uiTransfromComp!.isHit(touch.getLocation()); + const hit = this.node.uiTransfromComp!.isHit(touch.getUILocation()); if (this._transition === Transition.SCALE && this._target) { if (hit) { diff --git a/cocos/3d/ui/components/editbox/edit-box-component.ts b/cocos/3d/ui/components/editbox/edit-box-component.ts index cc3c55aec6..af992ba7a6 100644 --- a/cocos/3d/ui/components/editbox/edit-box-component.ts +++ b/cocos/3d/ui/components/editbox/edit-box-component.ts @@ -29,14 +29,15 @@ import { Component } from '../../../../components/component'; import { EventHandler as ComponentEventHandler } from '../../../../components/component-event-handler'; import { ccclass, executeInEditMode, executionOrder, menu, property } from '../../../../core/data/class-decorator'; import macro from '../../../../core/platform/CCMacro'; +import { EventType } from '../../../../core/platform/event-manager/event-enum'; import Color from '../../../../core/value-types/color'; +import { Node } from '../../../../scene-graph'; import { LabelComponent } from '../label-component'; import { SpriteComponent } from '../sprite-component'; import { UIRenderComponent } from '../ui-render-component'; import { UITransformComponent } from '../ui-transfrom-component'; import { EditBoxImpl} from './edit-box-impl'; import { InputFlag, InputMode, KeyboardReturnType } from './types'; -import { Node } from '../../../../scene-graph'; const LEFT_PADDING = 2; @@ -476,7 +477,7 @@ export class EditBoxComponent extends Component { public _init () { this._createBackgroundSprite(); this._createLabels(); - this.node.on(cc.Node.EventType.SIZE_CHANGED, this._resizeChildNodes, this); + this.node.on(EventType.SIZE_CHANGED, this._resizeChildNodes, this); const impl = this._impl = new EditBoxImpl(); @@ -504,8 +505,8 @@ export class EditBoxComponent extends Component { } public _registerEvent () { - this.node.on(cc.Node.EventType.TOUCH_START, this._onTouchBegan, this); - this.node.on(cc.Node.EventType.TOUCH_END, this._onTouchEnded, this); + this.node.on(EventType.TOUCH_START, this._onTouchBegan, this); + this.node.on(EventType.TOUCH_END, this._onTouchEnded, this); } public _updateStayOnTop () { diff --git a/cocos/3d/ui/components/editbox/edit-box-impl.ts b/cocos/3d/ui/components/editbox/edit-box-impl.ts index a7dfbdbfb3..1d94e276e4 100644 --- a/cocos/3d/ui/components/editbox/edit-box-impl.ts +++ b/cocos/3d/ui/components/editbox/edit-box-impl.ts @@ -29,16 +29,13 @@ import { ccclass } from '../../../../core/data/class-decorator'; import macro from '../../../../core/platform/CCMacro'; import { contains } from '../../../../core/utils/misc'; -import { Color, Size, Mat4, Vec3 } from '../../../../core/value-types'; +import { Color, Mat4, Size, Vec3 } from '../../../../core/value-types'; import * as math from '../../../../core/vmath'; import { Node } from '../../../../scene-graph/node'; import { UIRenderComponent } from '../ui-render-component'; import { EditBoxComponent} from './edit-box-component'; // import { InputMode, InputFlag, KeyboardReturnType } from './types'; -import * as Types from './types'; -const InputMode = Types.InputMode; -const InputFlag = Types.InputFlag; -const KeyboardReturnType = Types.KeyboardReturnType; +import { InputFlag, InputMode, KeyboardReturnType } from './types'; // https://segmentfault.com/q/1010000002914610 const SCROLLY = 40; @@ -83,25 +80,25 @@ function getKeyboardReturnType (type) { @ccclass export class EditBoxImpl { - private _delegate: EditBoxComponent | null = null; - private _inputMode = -1; - private _inputFlag = -1; - private _returnType = KeyboardReturnType.DEFAULT; - private _maxLength = 50; - private _text = ''; - private _placeholderText = ''; - private _alwaysOnTop = false; - private _size: Size = cc.size(); - private _node: Node | null = null; - private _editing = false; - private __eventListeners: any = {}; - private __fullscreen = false; - private __autoResize = false; - private __rotateScreen = false; - private __orientationChanged: any; - private _edTxt: HTMLElement | null = null; - private _textColor: Color = Color.WHITE; - private _edFontSize = 14; + public _delegate: EditBoxComponent | null = null; + public _inputMode = -1; + public _inputFlag = -1; + public _returnType = KeyboardReturnType.DEFAULT; + public _maxLength = 50; + public _text = ''; + public _placeholderText = ''; + public _alwaysOnTop = false; + public _size: Size = cc.size(); + public _node: Node | null = null; + public _editing = false; + public __eventListeners: any = {}; + public __fullscreen = false; + public __autoResize = false; + public __rotateScreen = false; + public __orientationChanged: any; + public _edTxt: HTMLInputElement | HTMLTextAreaElement | null = null; + public _textColor: Color = Color.WHITE; + public _edFontSize = 14; get text () { return this._text; @@ -119,7 +116,7 @@ export class EditBoxImpl { return this._edFontSize; } - set returnType (value: Types.KeyboardReturnType) { + set returnType (value: KeyboardReturnType) { this._returnType = value; } @@ -212,7 +209,7 @@ export class EditBoxImpl { return this._text; } - public setPlaceholderText (text) { + public setPlaceholderText (text: string) { this._placeholderText = text; } @@ -220,11 +217,11 @@ export class EditBoxImpl { return this._placeholderText; } - public setDelegate (delegate) { + public setDelegate (delegate: EditBoxComponent | null) { this._delegate = delegate; } - public setInputMode (inputMode) { + public setInputMode (inputMode: InputMode) { if (this._inputMode === inputMode) { return; } this._inputMode = inputMode; @@ -234,7 +231,7 @@ export class EditBoxImpl { this._updateSize(this._size.width, this._size.height); } - public setInputFlag (inputFlag) { + public setInputFlag (inputFlag: InputFlag) { if (this._inputFlag === inputFlag) { return; } this._inputFlag = inputFlag; @@ -254,32 +251,32 @@ export class EditBoxImpl { } } - public setReturnType (returnType) { + public setReturnType (returnType: KeyboardReturnType) { this._returnType = returnType; this._updateDomInputType(); } - public setFontSize (fontSize) { + public setFontSize (fontSize: number) { this._edFontSize = fontSize || this._edFontSize; if (this._edTxt) { this._edTxt.style.fontSize = this._edFontSize + 'px'; } } - public setFontColor (color) { + public setFontColor (color: Color) { this._textColor = color; if (this._edTxt) { this._edTxt.style.color = color.toCSS('rgba'); } } - public setSize (width, height) { + public setSize (width: number, height: number) { this._size.width = width; this._size.height = height; this._updateSize(width, height); } - public setNode (node) { + public setNode (node: Node) { this._node = node; } @@ -634,7 +631,7 @@ export class EditBoxImpl { } } -function _inputValueHandle (input, editBoxImpl) { +function _inputValueHandle (input: any, editBoxImpl: EditBoxImpl) { if (input.value.length > editBoxImpl._maxLength) { input.value = input.value.slice(0, editBoxImpl._maxLength); } @@ -646,7 +643,7 @@ function _inputValueHandle (input, editBoxImpl) { } } -function registerInputEventListener (tmpEdTxt: HTMLElement, editBoxImpl: EditBoxImpl, isTextarea = false) { +function registerInputEventListener (tmpEdTxt: HTMLInputElement | HTMLTextAreaElement, editBoxImpl: EditBoxImpl, isTextarea = false) { let inputLock = false; const cbs = editBoxImpl.eventListeners; cbs.compositionstart = () => { diff --git a/cocos/3d/ui/components/layout-component.ts b/cocos/3d/ui/components/layout-component.ts index 52e8f6d1b8..617d8c7785 100644 --- a/cocos/3d/ui/components/layout-component.ts +++ b/cocos/3d/ui/components/layout-component.ts @@ -26,11 +26,11 @@ import { Component } from '../../../components/component'; import { ccclass, executeInEditMode, executionOrder, menu, property } from '../../../core/data/class-decorator'; -import { Size, Vec3, Rect, Vec2 } from '../../../core/value-types'; +import { Rect, Size, Vec2, Vec3 } from '../../../core/value-types'; import { ccenum } from '../../../core/value-types/enum'; +import { vec3 } from '../../../core/vmath'; import { Node } from '../../../scene-graph/node'; import { UITransformComponent } from './ui-transfrom-component'; -import { vec3 } from '../../../core/vmath'; const NodeEvent = Node.EventType; /** * !#en Enum for Layout type @@ -161,8 +161,8 @@ enum HorizontalDirection { ccenum(HorizontalDirection); -let _tempPos = new Vec3(); -let _tempScale = new Vec3(); +const _tempPos = new Vec3(); +const _tempScale = new Vec3(); /** * !#en @@ -192,13 +192,13 @@ export class LayoutComponent extends Component { * @default Layout.Type.NONE */ @property({ - type: Type + type: Type, }) - get type() { + get type () { return this._N$layoutType; } - set type(value: Type) { + set type (value: Type) { this._N$layoutType = value; if (CC_EDITOR && this._N$layoutType !== Type.NONE && this._resizeMode === ResizeMode.CONTAINER /*&& !cc.engine.isPlaying*/) { @@ -220,10 +220,10 @@ export class LayoutComponent extends Component { @property({ type: ResizeMode, }) - get resizeMode() { + get resizeMode () { return this._resizeMode; } - set resizeMode(value) { + set resizeMode (value) { if (this._N$layoutType === Type.NONE && value === ResizeMode.CHILDREN) { return; } @@ -245,11 +245,11 @@ export class LayoutComponent extends Component { * @default cc.size(40, 40) */ @property - get cellSize() { + get cellSize () { return this._cellSize; } - set cellSize(value: Size) { + set cellSize (value: Size) { if (this._cellSize === value) { return; } @@ -266,13 +266,13 @@ export class LayoutComponent extends Component { * @property {Layout.AxisDirection} startAxis */ @property({ - type: AxisDirection + type: AxisDirection, }) - get startAxis() { + get startAxis () { return this._startAxis; } - set startAxis(value) { + set startAxis (value) { if (this._startAxis === value) { return; } @@ -293,10 +293,10 @@ export class LayoutComponent extends Component { * @property {Number} paddingLeft */ @property - get paddingLeft() { + get paddingLeft () { return this._paddingLeft; } - set paddingLeft(value) { + set paddingLeft (value) { if (this._paddingLeft === value) { return; } @@ -311,10 +311,10 @@ export class LayoutComponent extends Component { * @property {Number} paddingRight */ @property - get paddingRight() { + get paddingRight () { return this._paddingRight; } - set paddingRight(value) { + set paddingRight (value) { if (this._paddingRight === value) { return; } @@ -329,10 +329,10 @@ export class LayoutComponent extends Component { * @property {Number} paddingTop */ @property - get paddingTop() { + get paddingTop () { return this._paddingTop; } - set paddingTop(value) { + set paddingTop (value) { if (this._paddingTop === value) { return; } @@ -347,10 +347,10 @@ export class LayoutComponent extends Component { * @property {Number} paddingBottom */ @property - get paddingBottom() { + get paddingBottom () { return this._paddingBottom; } - set paddingBottom(value) { + set paddingBottom (value) { if (this._paddingBottom === value) { return; } @@ -365,11 +365,11 @@ export class LayoutComponent extends Component { * @property {Number} spacingX */ @property - get spacingX() { + get spacingX () { return this._spacingX; } - set spacingX(value) { + set spacingX (value) { if (this._spacingX === value) { return; } @@ -384,11 +384,11 @@ export class LayoutComponent extends Component { * @property {Number} spacingY */ @property - get spacingY() { + get spacingY () { return this._spacingY; } - set spacingY(value) { + set spacingY (value) { if (this._spacingY === value) { return; } @@ -407,11 +407,11 @@ export class LayoutComponent extends Component { @property({ type: VerticalDirection, }) - get verticalDirection() { + get verticalDirection () { return this._verticalDirection; } - set verticalDirection(value: VerticalDirection) { + set verticalDirection (value: VerticalDirection) { if (this._verticalDirection === value) { return; } @@ -430,11 +430,11 @@ export class LayoutComponent extends Component { @property({ type: HorizontalDirection, }) - get horizontalDirection() { + get horizontalDirection () { return this._horizontalDirection; } - set horizontalDirection(value: HorizontalDirection) { + set horizontalDirection (value: HorizontalDirection) { if (this._horizontalDirection === value) { return; } @@ -449,11 +449,11 @@ export class LayoutComponent extends Component { * @property {Number} padding */ @property - get padding() { + get padding () { return this._paddingLeft; } - set padding(value) { + set padding (value) { this._N$padding = value; this._migratePaddingData(); @@ -468,11 +468,11 @@ export class LayoutComponent extends Component { * @default false */ @property - get affectedByScale() { + get affectedByScale () { return this._affectedByScale; } - set affectedByScale(value) { + set affectedByScale (value) { this._affectedByScale = value; this._doLayoutDirty(); } @@ -515,15 +515,27 @@ export class LayoutComponent extends Component { @property private _affectedByScale = false; - private _migratePaddingData() { - this._paddingLeft = this._N$padding; - this._paddingRight = this._N$padding; - this._paddingTop = this._N$padding; - this._paddingBottom = this._N$padding; - this._N$padding = 0; + /** + * !#en Perform the layout update + * !#zh 立即执行更新布局 + * + * @method updateLayout + * + * @example + * layout.type = cc.Layout.HORIZONTAL; + * layout.node.addChild(childNode); + * cc.log(childNode.x); // not yet changed + * layout.updateLayout(); + * cc.log(childNode.x); // changed + */ + public updateLayout () { + if (this._layoutDirty && this.node.children.length > 0) { + this._doLayout(); + this._layoutDirty = false; + } } - protected onEnable() { + protected onEnable () { this._addEventListeners(); if (this.node.getContentSize().equals(cc.size(0, 0))) { @@ -537,11 +549,19 @@ export class LayoutComponent extends Component { this._doLayoutDirty(); } - protected onDisable() { + protected onDisable () { this._removeEventListeners(); } - private _addEventListeners() { + private _migratePaddingData () { + this._paddingLeft = this._N$padding; + this._paddingRight = this._N$padding; + this._paddingTop = this._N$padding; + this._paddingBottom = this._N$padding; + this._N$padding = 0; + } + + private _addEventListeners () { cc.director.on(cc.Director.EVENT_AFTER_UPDATE, this.updateLayout, this); this.node.on(NodeEvent.SIZE_CHANGED, this._resized, this); this.node.on(NodeEvent.ANCHOR_CHANGED, this._doLayoutDirty, this); @@ -551,7 +571,7 @@ export class LayoutComponent extends Component { this._addChildrenEventListeners(); } - private _removeEventListeners() { + private _removeEventListeners () { cc.director.off(cc.Director.EVENT_AFTER_UPDATE, this.updateLayout, this); this.node.off(NodeEvent.SIZE_CHANGED, this._resized, this); this.node.off(NodeEvent.ANCHOR_CHANGED, this._doLayoutDirty, this); @@ -561,7 +581,7 @@ export class LayoutComponent extends Component { this._removeChildrenEventListeners(); } - private _addChildrenEventListeners() { + private _addChildrenEventListeners () { const children = this.node.children; for (const child of children) { child.on(NodeEvent.SCALE_PART, this._doScaleDirty, this); @@ -572,7 +592,7 @@ export class LayoutComponent extends Component { } } - private _removeChildrenEventListeners() { + private _removeChildrenEventListeners () { const children = this.node.children; for (const child of children) { child.off(NodeEvent.SCALE_PART, this._doScaleDirty, this); @@ -583,7 +603,7 @@ export class LayoutComponent extends Component { } } - private _childAdded(child) { + private _childAdded (child) { child.on(NodeEvent.SCALE_PART, this._doScaleDirty, this); child.on(NodeEvent.SIZE_CHANGED, this._doLayoutDirty, this); child.on(NodeEvent.POSITION_PART, this._doLayoutDirty, this); @@ -593,7 +613,7 @@ export class LayoutComponent extends Component { this._doLayoutDirty(); } - private _childRemoved(child) { + private _childRemoved (child) { child.off(NodeEvent.SCALE_PART, this._doScaleDirty, this); child.off(NodeEvent.SIZE_CHANGED, this._doLayoutDirty, this); child.off(NodeEvent.POSITION_PART, this._doLayoutDirty, this); @@ -603,12 +623,12 @@ export class LayoutComponent extends Component { this._doLayoutDirty(); } - private _resized() { + private _resized () { this._layoutSize = this.node.getContentSize(); this._doLayoutDirty(); } - private _doLayoutHorizontally(baseWidth, rowBreak, fnPositionY, applyChildren) { + private _doLayoutHorizontally (baseWidth, rowBreak, fnPositionY, applyChildren) { const layoutAnchor = this.node.getAnchorPoint(); const children = this.node.children; @@ -639,7 +659,7 @@ export class LayoutComponent extends Component { } let newChildWidth = this._cellSize.width; - if (this._N$layoutType!== Type.GRID && this._resizeMode === ResizeMode.CHILDREN) { + if (this._N$layoutType !== Type.GRID && this._resizeMode === ResizeMode.CHILDREN) { newChildWidth = (baseWidth - (this._paddingLeft + this._paddingRight) - (activeChildCount - 1) * this._spacingX) / activeChildCount; } @@ -681,8 +701,15 @@ export class LayoutComponent extends Component { if (rowBreak) { const rowBreakBoundary = nextX + rightBoundaryOfChild + sign * (sign > 0 ? this._paddingRight : this._paddingLeft); - const leftToRightRowBreak = this._horizontalDirection === HorizontalDirection.LEFT_TO_RIGHT && rowBreakBoundary > (1 - layoutAnchor.x) * baseWidth; - const rightToLeftRowBreak = this._horizontalDirection === HorizontalDirection.RIGHT_TO_LEFT && rowBreakBoundary < -layoutAnchor.x * baseWidth; + let leftToRightRowBreak = false; + if (this._horizontalDirection === HorizontalDirection.LEFT_TO_RIGHT && rowBreakBoundary > (1 - layoutAnchor.x) * baseWidth){ + leftToRightRowBreak = true; + } + + let rightToLeftRowBreak = false; + if (this._horizontalDirection === HorizontalDirection.RIGHT_TO_LEFT && rowBreakBoundary < -layoutAnchor.x * baseWidth){ + rightToLeftRowBreak = true; + } if (leftToRightRowBreak || rightToLeftRowBreak) { @@ -735,7 +762,12 @@ export class LayoutComponent extends Component { return containerResizeBoundary; } - private _doLayoutVertically(baseHeight, columnBreak, fnPositionX, applyChildren) { + private _doLayoutVertically ( + baseHeight: number, + columnBreak: boolean, + fnPositionX: (node: Node, columnMaxWidth: number, col: number) => number, + applyChildren: boolean, + ) { const layoutAnchor = this.node.getAnchorPoint(); const children = this.node.children; @@ -764,7 +796,7 @@ export class LayoutComponent extends Component { } let newChildHeight = this._cellSize.height; - if (this._N$layoutType!== Type.GRID && this._resizeMode === ResizeMode.CHILDREN) { + if (this._N$layoutType !== Type.GRID && this._resizeMode === ResizeMode.CHILDREN) { newChildHeight = (baseHeight - (this._paddingTop + this._paddingBottom) - (activeChildCount - 1) * this._spacingY) / activeChildCount; } @@ -783,7 +815,7 @@ export class LayoutComponent extends Component { // for resizing children if (this._resizeMode === ResizeMode.CHILDREN) { child.height = newChildHeight / childScaleY; - if (this._N$layoutType=== Type.GRID) { + if (this._N$layoutType === Type.GRID) { child.width = this._cellSize.width / childScaleX; } } @@ -810,8 +842,15 @@ export class LayoutComponent extends Component { if (columnBreak) { const columnBreakBoundary = nextY + topBoundaryOfChild + sign * (sign > 0 ? this._paddingTop : this._paddingBottom); - const bottomToTopColumnBreak = this._verticalDirection === VerticalDirection.BOTTOM_TO_TOP && columnBreakBoundary > (1 - layoutAnchor.y) * baseHeight; - const topToBottomColumnBreak = this._verticalDirection === VerticalDirection.TOP_TO_BOTTOM && columnBreakBoundary < -layoutAnchor.y * baseHeight; + let bottomToTopColumnBreak = false; + if (this._verticalDirection === VerticalDirection.BOTTOM_TO_TOP && columnBreakBoundary > (1 - layoutAnchor.y) * baseHeight){ + bottomToTopColumnBreak = true; + } + + let topToBottomColumnBreak = false; + if (this._verticalDirection === VerticalDirection.TOP_TO_BOTTOM && columnBreakBoundary < -layoutAnchor.y * baseHeight){ + topToBottomColumnBreak = true; + } if (bottomToTopColumnBreak || topToBottomColumnBreak) { if (childBoundingBoxWidth >= tempMaxWidth) { @@ -865,14 +904,14 @@ export class LayoutComponent extends Component { return containerResizeBoundary; } - private _doLayoutBasic() { + private _doLayoutBasic () { const children = this.node.children; let allChildrenBoundingBox: Rect|null = null; for (const child of children) { const childTransform = child.getComponent(UITransformComponent); - if(!childTransform){ + if (!childTransform){ continue; } @@ -887,19 +926,21 @@ export class LayoutComponent extends Component { if (allChildrenBoundingBox) { const parentTransform = this.node.parent!.getComponent(UITransformComponent); - if(!parentTransform){ + if (!parentTransform){ return; } vec3.set(_tempPos, allChildrenBoundingBox.x, allChildrenBoundingBox.y, 0); - let leftBottomInParentSpace = new Vec3(); + const leftBottomInParentSpace = new Vec3(); parentTransform.convertToNodeSpaceAR(leftBottomInParentSpace, _tempPos); - vec3.set(leftBottomInParentSpace, leftBottomInParentSpace.x - this._paddingLeft, leftBottomInParentSpace.y - this._paddingBottom, leftBottomInParentSpace.z); + vec3.set(leftBottomInParentSpace, + leftBottomInParentSpace.x - this._paddingLeft, leftBottomInParentSpace.y - this._paddingBottom, + leftBottomInParentSpace.z); vec3.set(_tempPos, allChildrenBoundingBox.x + allChildrenBoundingBox.width, allChildrenBoundingBox.y + allChildrenBoundingBox.height, 0); - let rightTopInParentSpace = new Vec3(); + const rightTopInParentSpace = new Vec3(); parentTransform.convertToNodeSpaceAR(rightTopInParentSpace, _tempPos); - vec3.set(rightTopInParentSpace, rightTopInParentSpace.x + this._paddingRight, rightTopInParentSpace.y + this._paddingTop, rightTopInParentSpace.z) + vec3.set(rightTopInParentSpace, rightTopInParentSpace.x + this._paddingRight, rightTopInParentSpace.y + this._paddingTop, rightTopInParentSpace.z); const newSize = cc.size(parseFloat((rightTopInParentSpace.x - leftBottomInParentSpace.x).toFixed(2)), parseFloat((rightTopInParentSpace.y - leftBottomInParentSpace.y).toFixed(2))); @@ -917,7 +958,7 @@ export class LayoutComponent extends Component { } } - private _doLayoutGridAxisHorizontal(layoutAnchor, layoutSize) { + private _doLayoutGridAxisHorizontal (layoutAnchor, layoutSize) { const baseWidth = layoutSize.width; let sign = 1; @@ -931,9 +972,10 @@ export class LayoutComponent extends Component { const self = this; - const fnPositionY = function (child, topOffset, row) { - return bottomBoundaryOfLayout + sign * (topOffset + child.anchorY * child.height * self._getUsedScaleValue(child.scaleY) + paddingY + row * this._spacingY); - }.bind(this); + const fnPositionY = (child: Node, topOffset: number, row: number) => { + return bottomBoundaryOfLayout + + sign * (topOffset + child.anchorY * child.height * self._getUsedScaleValue(child.getScale().y) + paddingY + row * this._spacingY); + }; let newHeight = 0; if (this._resizeMode === ResizeMode.CONTAINER) { @@ -959,7 +1001,7 @@ export class LayoutComponent extends Component { } } - private _doLayoutGridAxisVertical(layoutAnchor: Vec2, layoutSize: Size) { + private _doLayoutGridAxisVertical (layoutAnchor: Vec2, layoutSize: Size) { const baseHeight = layoutSize.height; let sign = 1; @@ -972,9 +1014,10 @@ export class LayoutComponent extends Component { } const self = this; - const fnPositionX = function (child, leftOffset, column) { - return leftBoundaryOfLayout + sign * (leftOffset + child.anchorX * child.width * self._getUsedScaleValue(child.scaleX) + paddingX + column * this._spacingX); - }.bind(this); + const fnPositionX = (child: Node, leftOffset: number, column: number) => { + return leftBoundaryOfLayout + + sign * (leftOffset + child.anchorX * child.width * self._getUsedScaleValue(child.getScale().x) + paddingX + column * this._spacingX); + }; let newWidth = 0; if (this._resizeMode === ResizeMode.CONTAINER) { @@ -999,7 +1042,7 @@ export class LayoutComponent extends Component { } } - private _doLayoutGrid() { + private _doLayoutGrid () { const layoutAnchor = this.node.getAnchorPoint(); const layoutSize = this.node.getContentSize(); @@ -1012,7 +1055,7 @@ export class LayoutComponent extends Component { } - private _getHorizontalBaseWidth(children: Node[]) { + private _getHorizontalBaseWidth (children: Node[]) { let newWidth = 0; let activeChildCount = 0; if (this._resizeMode === ResizeMode.CONTAINER) { @@ -1030,7 +1073,7 @@ export class LayoutComponent extends Component { return newWidth; } - private _getVerticalBaseHeight(children: Node[]) { + private _getVerticalBaseHeight (children: Node[]) { let newHeight = 0; let activeChildCount = 0; if (this._resizeMode === ResizeMode.CONTAINER) { @@ -1049,20 +1092,20 @@ export class LayoutComponent extends Component { return newHeight; } - private _doLayout() { + private _doLayout () { - if (this._N$layoutType=== Type.HORIZONTAL) { + if (this._N$layoutType === Type.HORIZONTAL) { const newWidth = this._getHorizontalBaseWidth(this.node.children); const fnPositionY = (child) => { - child.getPosition(_tempPos) + child.getPosition(_tempPos); return _tempPos.y; }; this._doLayoutHorizontally(newWidth, false, fnPositionY, true); this.node.width = newWidth; - } else if (this._N$layoutType=== Type.VERTICAL) { + } else if (this._N$layoutType === Type.VERTICAL) { const newHeight = this._getVerticalBaseHeight(this.node.children); const fnPositionX = (child) => { @@ -1073,44 +1116,24 @@ export class LayoutComponent extends Component { this._doLayoutVertically(newHeight, false, fnPositionX, true); this.node.height = newHeight; - } else if (this._N$layoutType=== Type.NONE) { + } else if (this._N$layoutType === Type.NONE) { if (this._resizeMode === ResizeMode.CONTAINER) { this._doLayoutBasic(); } - } else if (this._N$layoutType=== Type.GRID) { + } else if (this._N$layoutType === Type.GRID) { this._doLayoutGrid(); } } - private _getUsedScaleValue(value) { + private _getUsedScaleValue (value) { return this._affectedByScale ? Math.abs(value) : 1; } - /** - * !#en Perform the layout update - * !#zh 立即执行更新布局 - * - * @method updateLayout - * - * @example - * layout.type = cc.Layout.HORIZONTAL; - * layout.node.addChild(childNode); - * cc.log(childNode.x); // not yet changed - * layout.updateLayout(); - * cc.log(childNode.x); // changed - */ - public updateLayout() { - if (this._layoutDirty && this.node.children.length > 0) { - this._doLayout(); - this._layoutDirty = false; - } - } - - private _doLayoutDirty() { + private _doLayoutDirty () { this._layoutDirty = true; } - private _doScaleDirty() { + private _doScaleDirty () { this._layoutDirty = this._layoutDirty || this._affectedByScale; } diff --git a/cocos/3d/ui/components/mask-component.ts b/cocos/3d/ui/components/mask-component.ts index 9578661e0e..44feb29ce4 100644 --- a/cocos/3d/ui/components/mask-component.ts +++ b/cocos/3d/ui/components/mask-component.ts @@ -26,10 +26,10 @@ // import {SpriteFrame} from '../../../assets/CCSpriteFrame'; import { ccclass/*, executeInEditMode*/, executionOrder, menu/*, property*/ } from '../../../core/data/class-decorator'; -import { UI } from '../../../renderer/ui/ui'; // import { ccenum } from '../../../core/value-types/enum'; // import { clamp } from '../../../core/vmath'; -import { EventType } from '../../../scene-graph/node-event-enum'; +import { EventType } from '../../../core/platform/event-manager/event-enum'; +import { UI } from '../../../renderer/ui/ui'; import { Material } from '../../assets/material'; import { RenderableComponent } from '../../framework/renderable-component'; // import circle from '../../primitive/circle'; @@ -263,6 +263,10 @@ export class MaskComponent extends UIRenderComponent { } protected _canRender () { + if (!super._canRender()) { + return false; + } + return this._maskMaterial !== null && this._clearMaskMaterial !== null && this._renderPermit; } diff --git a/cocos/3d/ui/components/scroll-view-component.ts b/cocos/3d/ui/components/scroll-view-component.ts index f047808f83..15c2a5cf80 100644 --- a/cocos/3d/ui/components/scroll-view-component.ts +++ b/cocos/3d/ui/components/scroll-view-component.ts @@ -1202,7 +1202,7 @@ export class ScrollViewComponent extends ViewGroupComponent { return; } - const deltaMove = touch.getLocation().sub(touch.getStartLocation()); + const deltaMove = touch.getUILocation().sub(touch.getStartLocation()); // FIXME: touch move delta should be calculated by DPI. if (deltaMove.mag() > 7) { if (!this._touchMoved && event.target !== this.node) { @@ -1210,7 +1210,7 @@ export class ScrollViewComponent extends ViewGroupComponent { const cancelEvent = new EventTouch(event.getTouches(), event.bubbles); cancelEvent.type = NodeEvent.TOUCH_CANCEL; cancelEvent.touch = event.touch; - // cancelEvent.simulate = true; + cancelEvent.simulate = true; (event.target as Node)!.dispatchEvent(cancelEvent); this._touchMoved = true; } @@ -1255,7 +1255,7 @@ export class ScrollViewComponent extends ViewGroupComponent { } private _handleMoveLogic (touch: Touch) { - const delta = touch.getDelta(); + const delta = touch.getUIDelta(); vec3.set(this._deltaPos, delta.x, delta.y, 0); this._processDeltaMove(this._deltaPos); } @@ -1404,7 +1404,7 @@ export class ScrollViewComponent extends ViewGroupComponent { } private _handleReleaseLogic (touch) { - const delta = touch.getDelta(); + const delta = touch.getUIDelta(); vec3.set(this._deltaPos, delta.x, delta.y, 0); this._gatherTouchMove(this._deltaPos); this._processInertiaScroll(); diff --git a/cocos/3d/ui/components/slider-component.ts b/cocos/3d/ui/components/slider-component.ts index 83f9e7491e..ac7127014b 100644 --- a/cocos/3d/ui/components/slider-component.ts +++ b/cocos/3d/ui/components/slider-component.ts @@ -32,7 +32,7 @@ import Touch from '../../../core/platform/event-manager/CCTouch'; import { clamp01 } from '../../../core/utils/misc'; import { Enum, Vec3 } from '../../../core/value-types/index'; import { vec3 } from '../../../core/vmath'; -import { EventType } from '../../../scene-graph/node-event-enum'; +import { EventType } from '../../../core/platform/event-manager/event-enum'; import { SpriteComponent } from './sprite-component'; const _tempPos = new Vec3(); @@ -194,7 +194,7 @@ export class SliderComponent extends Component { this._dragging = true; this._touchHandle = true; - const touhPos = event.touch!.getLocation(); + const touhPos = event.touch!.getUILocation(); vec3.set(this._touchPos, touhPos.x, touhPos.y, 0); this._handle.node.uiTransfromComp.convertToNodeSpaceAR(this._offset, this._touchPos); @@ -255,7 +255,7 @@ export class SliderComponent extends Component { return; } - const touchPos = touch.getLocation(); + const touchPos = touch.getUILocation(); vec3.set(this._touchPos, touchPos.x, touchPos.y, 0); const localTouchPos = this.node.uiTransfromComp!.convertToNodeSpaceAR(_tempPos, this._touchPos); if (this.direction === Direction.Horizontal) { diff --git a/cocos/3d/ui/components/sprite-component.ts b/cocos/3d/ui/components/sprite-component.ts index c5470cd499..5af61f7098 100644 --- a/cocos/3d/ui/components/sprite-component.ts +++ b/cocos/3d/ui/components/sprite-component.ts @@ -27,11 +27,11 @@ import { SpriteFrame } from '../../../assets/CCSpriteFrame'; import { SpriteAtlas } from '../../../assets/sprite-atlas'; import { ccclass, executionOrder, menu, property } from '../../../core/data/class-decorator'; +import { EventType } from '../../../core/platform/event-manager/event-enum'; import { clampf } from '../../../core/utils/misc'; import { Vec2 } from '../../../core/value-types'; import { ccenum } from '../../../core/value-types/enum'; import { UI } from '../../../renderer/ui/ui'; -import { EventType } from '../../../scene-graph/node-event-enum'; import { UIRenderComponent } from './ui-render-component'; /** @@ -347,6 +347,17 @@ export class SpriteComponent extends UIRenderComponent { } } + get spriteAtlas() { + return this._atlas; + } + + @property({ + type: cc.SpriteAtlas, + }) + set spriteAtlas(value) { + this._atlas = value; + } + public static FillType = FillType; public static Type = SpriteType; public static SizeMode = SizeMode; diff --git a/cocos/3d/ui/components/ui-render-component.ts b/cocos/3d/ui/components/ui-render-component.ts index 9fe3daef68..467b05eb03 100644 --- a/cocos/3d/ui/components/ui-render-component.ts +++ b/cocos/3d/ui/components/ui-render-component.ts @@ -31,12 +31,12 @@ import { property, requireComponent, } from '../../../core/data/class-decorator'; +import { EventType} from '../../../core/platform/event-manager/event-enum'; import { ccenum } from '../../../core/value-types/enum'; import { Color } from '../../../core/value-types/index'; import { GFXBlendFactor } from '../../../gfx/define'; import { RenderData } from '../../../renderer/ui/renderData'; import { UI } from '../../../renderer/ui/ui'; -import { EventType} from '../../../scene-graph/node-event-enum'; import { Material } from '../../assets/material'; import { RenderableComponent } from '../../framework/renderable-component'; import { IAssembler, IAssemblerManager } from '../assembler/assembler'; @@ -61,6 +61,8 @@ ccenum(GFXBlendFactor); @executeInEditMode export class UIRenderComponent extends Component { + public static BlendState = GFXBlendFactor; + /** * !#en specify the source Blend Factor, this will generate a custom material object * please pay attention to the memory cost. diff --git a/cocos/3d/ui/components/ui-transfrom-component.ts b/cocos/3d/ui/components/ui-transfrom-component.ts index 496ce9f2c8..5767280682 100644 --- a/cocos/3d/ui/components/ui-transfrom-component.ts +++ b/cocos/3d/ui/components/ui-transfrom-component.ts @@ -1,9 +1,9 @@ import { Component} from '../../../components/component'; import { ccclass, executeInEditMode, executionOrder, menu, property } from '../../../core/data/class-decorator'; -import { EventListener } from '../../../core/platform/event-manager/CCEventListener'; +import { EventType } from '../../../core/platform/event-manager/event-enum'; +import { EventListener } from '../../../core/platform/event-manager/event-listener'; import { Mat4, Rect, Size, Vec2, Vec3 } from '../../../core/value-types'; import * as math from '../../../core/vmath/index'; -import { EventType } from '../../../scene-graph/node-event-enum'; import { CanvasComponent } from './canvas-component'; const _vec2a = new Vec2(); diff --git a/cocos/assets/CCSpriteFrame.ts b/cocos/assets/CCSpriteFrame.ts index 79d0c344c5..c8d4524ed9 100644 --- a/cocos/assets/CCSpriteFrame.ts +++ b/cocos/assets/CCSpriteFrame.ts @@ -436,16 +436,19 @@ export class SpriteFrame extends EventTargetFactory(Texture2D) { * @method clone * @return {SpriteFrame} */ - // TODO - // clone() { - // let cloneSprite = new SpriteFrame(/*this._texture || this._textureFilename,*/ this._rect, this._rotated, this._offset, this._originalSize); - // cloneSprite.setWrapMode(this._wrapS, this._wrapT); - // cloneSprite.setFilters(this._minFilter, this._magFilter); - // cloneSprite.setPremultiplyAlpha(this._premultiplyAlpha); - // cloneSprite.setAnisotropy(this._anisotropy); - // cloneSprite._mipmaps = this._mipmaps; - // return cloneSprite; - // } + + public clone () { + const cloneSprite = new SpriteFrame(); + cloneSprite.name = this.name; + cloneSprite.setOriginalSize(this._originalSize); + cloneSprite.setRect(this._rect); + const cap = this._capInsets; + cloneSprite._setBorder(cap[INSET_LEFT], cap[INSET_BOTTOM], cap[INSET_RIGHT], cap[INSET_TOP]); + cloneSprite.setOffset(this._offset); + cloneSprite._mipmaps = this._mipmaps; + cloneSprite.onLoaded(); + return cloneSprite; + } // /** // * !#en Set SpriteFrame with Texture, rect, rotated, offset and originalSize.
@@ -563,17 +566,12 @@ export class SpriteFrame extends EventTargetFactory(Texture2D) { maxX += rect.width; maxY += rect.height; } - // if (maxX > texture.width) { - // cc.errorID(3300, texture.url + '/' + this.name, maxX, texture.width); - // } - // if (maxY > texture.height) { - // cc.errorID(3400, texture.url + '/' + this.name, maxY, texture.height); - // } + if (maxX > texture.width) { - cc.errorID(3300, /*this.url*/ + '/' + this.name, maxX, this._originalSize.width); + cc.errorID(3300, texture.url + '/' + this.name, maxX, texture.width); } if (maxY > texture.height) { - cc.errorID(3400, /*this.url +*/ '/' + this.name, maxY, this._originalSize.height); + cc.errorID(3400, texture.url + '/' + this.name, maxY, texture.height); } } @@ -684,22 +682,12 @@ export class SpriteFrame extends EventTargetFactory(Texture2D) { // SERIALIZATION // @ts-ignore - // TODO: public _serialize (exporting) { const rect = this._rect; const offset = this._offset; const size = this._originalSize; let uuid = this._uuid; - // let texture = this._texture; - // if (texture) { - // uuid = texture._uuid; - // } - // if (!uuid) { - // let url = this._textureFilename; - // if (url) { - // uuid = Editor.Utils.UuidCache.urlToUuid(url); - // } - // } + if (uuid && exporting) { // @ts-ignore // TODO: @@ -780,18 +768,6 @@ export class SpriteFrame extends EventTargetFactory(Texture2D) { this._textureLoadedCallback(); } - - public copyWithZone (...args: any[]) { - // return this.clone(...args); - } - - public copy (...args: any[]) { - // return this.clone(...args); - } - - // public initWithTexture (...args: any[]) { - // return this.setTexture(...args); - // } } cc.SpriteFrame = SpriteFrame; diff --git a/cocos/components/component.d.ts b/cocos/components/component.d.ts index 33b0750f02..a4a59d0664 100644 --- a/cocos/components/component.d.ts +++ b/cocos/components/component.d.ts @@ -54,5 +54,4 @@ export class Component extends CCObject { // friend to class BaseNode public _id: string; public _enabled: boolean; - public _eventTargets: Array; } diff --git a/cocos/core/director.js b/cocos/core/director.js index 114c0fa5db..4f9ccd9d68 100644 --- a/cocos/core/director.js +++ b/cocos/core/director.js @@ -25,10 +25,9 @@ THE SOFTWARE. ****************************************************************************/ -import EventTarget from './event/event-target'; -import eventManager from './platform/event-manager/CCEventManager'; +import { EventTarget } from './event/event-target'; +import eventManager from './platform/event-manager/event-manager'; import { CCObject } from './data/object'; -import game from './game'; import Scheduler from './scheduler'; import { autoRelease } from '../load-pipeline/auto-release-utils'; import ComponentScheduler from '../scene-graph/component-scheduler'; @@ -38,6 +37,7 @@ import { PhysicsSystem } from '../3d/framework/physics/physics-system'; import { getClassByName } from './utils/js'; import { Root } from './root'; import { widgetManager } from '../3d/ui/components/widget-manager'; +import Game from './game'; // const ComponentScheduler = require('./component-scheduler'); // const NodeActivator = require('./node-activator'); @@ -151,16 +151,16 @@ class Director extends EventTarget { this._systems = []; var self = this; - game.on(game.EVENT_SHOW, function () { + cc.game.on(Game.EVENT_SHOW, function () { self._lastUpdate = performance.now(); }); - game.once(game.EVENT_ENGINE_INITED, this.init, this); + cc.game.once(Game.EVENT_ENGINE_INITED, this.init, this); } init () { - this._root = new Root(game._gfxDevice); + this._root = new Root(cc.game._gfxDevice); let rootInfo = {}; if(!this._root.initialize(rootInfo)) { return false; @@ -244,7 +244,7 @@ class Director extends EventTarget { * @deprecated since v2.0 */ convertToGL (uiPoint) { - var container = game.container; + var container = cc.game.container; var view = cc.view; var box = container.getBoundingClientRect(); var left = box.left + window.pageXOffset - container.clientLeft; @@ -266,7 +266,7 @@ class Director extends EventTarget { * @deprecated since v2.0 */ convertToUI (glPoint) { - var container = game.container; + var container = cc.game.container; var view = cc.view; var box = container.getBoundingClientRect(); var left = box.left + window.pageXOffset - container.clientLeft; @@ -411,8 +411,8 @@ class Director extends EventTarget { // Re-attach or replace persist nodes CC_BUILD && CC_DEBUG && console.time('AttachPersist'); - var persistNodeList = Object.keys(game._persistRootNodes).map(function (x) { - return game._persistRootNodes[x]; + var persistNodeList = Object.keys(cc.game._persistRootNodes).map(function (x) { + return cc.game._persistRootNodes[x]; }); for (let i = 0; i < persistNodeList.length; i++) { let node = persistNodeList[i]; @@ -499,7 +499,7 @@ class Director extends EventTarget { // @Scene loading section _getSceneUuid (key) { - var scenes = game._sceneInfos; + var scenes = cc.game._sceneInfos; if (typeof key === 'string') { if (!key.endsWith('.scene')) { key += '.scene'; @@ -756,7 +756,7 @@ class Director extends EventTarget { * @return {Number} */ getAnimationInterval () { - return 1000 / game.getFrameRate(); + return 1000 / cc.game.getFrameRate(); } /** @@ -767,7 +767,7 @@ class Director extends EventTarget { * @param {Number} value - The animation interval desired. */ setAnimationInterval (value) { - game.setFrameRate(Math.round(1000 / value)); + cc.game.setFrameRate(Math.round(1000 / value)); } /** @@ -1061,5 +1061,4 @@ Director.EVENT_AFTER_DRAW = "director_after_draw"; */ let director = cc.director = new Director(); cc.Director = Director; -cc.director = director; export default director; diff --git a/cocos/core/event/callbacks-invoker.js b/cocos/core/event/callbacks-invoker.ts similarity index 73% rename from cocos/core/event/callbacks-invoker.js rename to cocos/core/event/callbacks-invoker.ts index 5f05aec478..39760b9e7a 100644 --- a/cocos/core/event/callbacks-invoker.js +++ b/cocos/core/event/callbacks-invoker.ts @@ -27,18 +27,16 @@ import * as js from '../utils/js'; const fastRemoveAt = js.array.fastRemoveAt; -class CallbackList { - constructor () { - this.callbacks = []; - this.targets = []; // same length with callbacks, nullable - this.isInvoking = false; - this.containCanceled = false; - } +export class CallbackList { + public callbacks: Array = []; + public targets: Array = []; + public isInvoking = false; + public containCanceled = false; - removeBy (array, value) { - var callbacks = this.callbacks; - var targets = this.targets; - for (var i = 0; i < array.length; ++i) { + public removeBy (array: any[], value: any) { + const callbacks = this.callbacks; + const targets = this.targets; + for (let i = 0; i < array.length; ++i) { if (array[i] === value) { fastRemoveAt(callbacks, i); fastRemoveAt(targets, i); @@ -47,14 +45,14 @@ class CallbackList { } } - cancel (index) { + public cancel (index: number) { this.callbacks[index] = this.targets[index] = null; this.containCanceled = true; } - cancelAll () { - let callbacks = this.callbacks; - let targets = this.targets; + public cancelAll () { + const callbacks = this.callbacks; + const targets = this.targets; for (let i = 0; i < callbacks.length; i++) { callbacks[i] = targets[i] = null; } @@ -62,14 +60,14 @@ class CallbackList { } // filter all removed callbacks and compact array - purgeCanceled () { + public purgeCanceled () { this.removeBy(this.callbacks, null); this.containCanceled = false; } } const MAX_SIZE = 16; -let callbackListPool = new js.Pool(function (list) { +const callbackListPool = new js.Pool((list: CallbackList) => { list.callbacks.length = 0; list.targets.length = 0; list.isInvoking = false; @@ -86,25 +84,24 @@ callbackListPool.get = function () { * * @private */ -function CallbacksHandler () { - this._callbackTable = js.createMap(true); -} -CallbacksHandler.prototype = { - constructor: CallbacksHandler, + +export class CallbacksHandler{ + protected _callbackTable: Map = new Map(); + /** * @method add * @param {String} key * @param {Function} callback * @param {Object} [target] - can be null */ - add (key, callback, target) { - var list = this._callbackTable[key]; + public add (key, callback, target) { + let list = this._callbackTable[key]; if (!list) { list = this._callbackTable[key] = callbackListPool.get(); } list.callbacks.push(callback); list.targets.push(target || null); - }, + } /** * Check if the specified key has any registered callback. If a callback is also specified, @@ -115,19 +112,19 @@ CallbacksHandler.prototype = { * @param {Object} [target] * @return {Boolean} */ - hasEventListener (key, callback, target) { - var list = this._callbackTable[key]; + public hasEventListener (key: string, callback?: Function, target?: Object) { + const list = this._callbackTable[key]; if (!list) { return false; } // check any valid callback - var callbacks = list.callbacks; + const callbacks = list.callbacks; if (!callback) { // Make sure no cancelled callbacks if (list.isInvoking) { - for (let i = 0; i < callbacks.length; i++) { - if (callbacks[i]) { + for (const func of callbacks) { + if (func) { return true; } } @@ -138,25 +135,25 @@ CallbacksHandler.prototype = { } } - target = target || null; - var targets = list.targets; + target = target || undefined; + const targets = list.targets; for (let i = 0; i < callbacks.length; ++i) { if (callbacks[i] === callback && targets[i] === target) { return true; } } return false; - }, + } /** * Removes all callbacks registered in a certain event type or all callbacks registered with a certain target * @method removeAll * @param {String|Object} keyOrTarget - The event key to be removed or the target to be removed */ - removeAll (keyOrTarget) { + public removeAll (keyOrTarget?: string | Object) { if (typeof keyOrTarget === 'string') { // remove by key - let list = this._callbackTable[keyOrTarget]; + const list = this._callbackTable[keyOrTarget]; if (list) { if (list.isInvoking) { list.cancelAll(); @@ -169,10 +166,10 @@ CallbacksHandler.prototype = { } else if (keyOrTarget) { // remove by target - for (let key in this._callbackTable) { - let list = this._callbackTable[key]; + for (const key of Object.keys(this._callbackTable)) { + const list = this._callbackTable[key]; if (list.isInvoking) { - let targets = list.targets; + const targets = list.targets; for (let i = 0; i < targets.length; ++i) { if (targets[i] === keyOrTarget) { list.cancel(i); @@ -184,7 +181,7 @@ CallbacksHandler.prototype = { } } } - }, + } /** * @method remove @@ -192,13 +189,13 @@ CallbacksHandler.prototype = { * @param {Function} callback * @param {Object} [target] */ - remove (key, callback, target) { - var list = this._callbackTable[key]; + public remove (key: string, callback?: Function, target?: Object) { + const list = this._callbackTable[key]; if (list) { - target = target || null; - var callbacks = list.callbacks; - var targets = list.targets; - for (var i = 0; i < callbacks.length; ++i) { + target = target || undefined; + const callbacks = list.callbacks; + const targets = list.targets; + for (let i = 0; i < callbacks.length; ++i) { if (callbacks[i] === callback && targets[i] === target) { if (list.isInvoking) { list.cancel(i); @@ -212,7 +209,7 @@ CallbacksHandler.prototype = { } } } -}; +} /** * !#en The callbacks invoker to handle and invoke callbacks by key. @@ -221,11 +218,8 @@ CallbacksHandler.prototype = { * * @extends _CallbacksHandler */ -function CallbacksInvoker () { - CallbacksHandler.call(this); -} -js.extend(CallbacksInvoker, CallbacksHandler); -js.mixin(CallbacksInvoker.prototype, { + +export class CallbacksInvoker extends CallbacksHandler{ /** * @method emit * @param {String} key @@ -235,23 +229,23 @@ js.mixin(CallbacksInvoker.prototype, { * @param {any} [p4] * @param {any} [p5] */ - emit (key, p1, p2, p3, p4, p5) { - var list = this._callbackTable[key]; + public emit (key: string, ...args: any[]) { + const list = this._callbackTable[key]; if (list) { - var rootInvoker = !list.isInvoking; + const rootInvoker = !list.isInvoking; list.isInvoking = true; - var callbacks = list.callbacks; - var targets = list.targets; - for (var i = 0, len = callbacks.length; i < len; ++i) { - var callback = callbacks[i]; + const callbacks = list.callbacks; + const targets = list.targets; + for (let i = 0, len = callbacks.length; i < len; ++i) { + const callback = callbacks[i]; if (callback) { - var target = targets[i]; + const target = targets[i]; if (target) { - callback.call(target, p1, p2, p3, p4, p5); + callback.call(target, ...args); } else { - callback(p1, p2, p3, p4, p5); + callback(...args); } } } @@ -264,13 +258,8 @@ js.mixin(CallbacksInvoker.prototype, { } } } -}); +} if (CC_TEST) { cc._Test.CallbacksInvoker = CallbacksInvoker; } - -export { - CallbacksHandler, - CallbacksInvoker -}; diff --git a/cocos/core/event/event-target-factory.ts b/cocos/core/event/event-target-factory.ts index 1c9e6d159c..c089078e2a 100644 --- a/cocos/core/event/event-target-factory.ts +++ b/cocos/core/event/event-target-factory.ts @@ -177,6 +177,7 @@ export function EventTargetFactory> (b?: Base) { return EventTarget; } -interface ITargetImpl extends Object { +export interface ITargetImpl extends Object { __eventTargets?: Object[]; + node?: ITargetImpl; } diff --git a/cocos/core/event/event-target.js b/cocos/core/event/event-target.ts similarity index 84% rename from cocos/core/event/event-target.js rename to cocos/core/event/event-target.ts index 9013108e6a..fa4904a997 100644 --- a/cocos/core/event/event-target.js +++ b/cocos/core/event/event-target.ts @@ -25,6 +25,7 @@ ****************************************************************************/ import * as js from '../utils/js'; +import { ITargetImpl } from './../event/event-target-factory'; import {CallbacksInvoker} from './callbacks-invoker'; const fastRemove = js.array.fastRemove; @@ -56,11 +57,8 @@ const fastRemove = js.array.fastRemove; * @class EventTarget * @extends CallbacksInvoker */ -function EventTarget () { - CallbacksInvoker.call(this); -} -js.extend(EventTarget, CallbacksInvoker); -js.mixin(EventTarget.prototype, { + +export class EventTarget extends CallbacksInvoker { /** * !#en Checks whether the EventTarget object has any callback registered for a specific type of event. * !#zh 检查事件目标对象是否有为特定类型的事件注册的回调。 @@ -94,20 +92,26 @@ js.mixin(EventTarget.prototype, { * cc.log("fire in the hole"); * }, node); */ - on (type, callback, target) { + public on (type: string, callback: Function, target?: Object) { if (!callback) { cc.errorID(6800); return; } - if ( !this.hasEventListener(type, callback, target) ) { + if (!this.hasEventListener(type, callback, target)) { this.add(type, callback, target); - if (target && target.__eventTargets) - target.__eventTargets.push(this); + const targetImpl = target as ITargetImpl; + if (target) { + if (targetImpl.__eventTargets) { + targetImpl.__eventTargets.push(this); + } else if (targetImpl.node && targetImpl.node.__eventTargets) { + targetImpl.node.__eventTargets.push(this); + } + } } return callback; - }, + } /** * !#en @@ -130,18 +134,23 @@ js.mixin(EventTarget.prototype, { * // remove all fire event listeners * eventTarget.off('fire'); */ - off (type, callback, target) { + public off (type: string, callback?: Function, target?: Object) { if (!callback) { this.removeAll(type); } else { this.remove(type, callback, target); - if (target && target.__eventTargets) { - fastRemove(target.__eventTargets, this); + const targetImpl = target as ITargetImpl; + if (target) { + if (targetImpl.__eventTargets) { + fastRemove(targetImpl.__eventTargets, this); + } else if (targetImpl.node && targetImpl.node.__eventTargets) { + fastRemove(targetImpl.node.__eventTargets, this); + } } } - }, + } /** * !#en Removes all callbacks previously registered with the same target (passed as parameter). @@ -154,9 +163,9 @@ js.mixin(EventTarget.prototype, { * @method targetOff * @param {Object} target - The target to be searched for all related listeners */ - targetOff () { - this.removeAll(); - }, + public targetOff (keyOrTarget?: string | Object) { + this.removeAll(keyOrTarget); + } /** * !#en @@ -180,20 +189,20 @@ js.mixin(EventTarget.prototype, { * cc.log("this is the callback and will be invoked only once"); * }, node); */ - once (type, callback, target) { - var eventType_hasOnceListener = '__ONCE_FLAG:' + type; - var hasOnceListener = this.hasEventListener(eventType_hasOnceListener, callback, target); + public once (type: string, callback: Function, target?: Object) { + const eventType_hasOnceListener = '__ONCE_FLAG:' + type; + const hasOnceListener = this.hasEventListener(eventType_hasOnceListener, callback, target); if (!hasOnceListener) { - var self = this; - var onceWrapper = function (arg1, arg2, arg3, arg4, arg5) { + const self = this; + const onceWrapper = function (this: any, ...args: any[]) { self.off(type, onceWrapper, target); self.remove(eventType_hasOnceListener, callback, target); - callback.call(this, arg1, arg2, arg3, arg4, arg5); + callback.call(this, ...args); }; this.on(type, onceWrapper, target); this.add(eventType_hasOnceListener, callback, target); } - }, + } /** * !#en @@ -223,10 +232,9 @@ js.mixin(EventTarget.prototype, { * @method dispatchEvent * @param {Event} event */ - dispatchEvent (event) { - this.invoke(event.type, event); + public dispatchEvent (event) { + this.emit(event.type, event); } -}); +} cc.EventTarget = EventTarget; -export default EventTarget; diff --git a/cocos/core/event/event.ts b/cocos/core/event/event.ts index aa8f02e0ed..a65e67b912 100644 --- a/cocos/core/event/event.ts +++ b/cocos/core/event/event.ts @@ -222,4 +222,4 @@ export default class Event { } /* tslint:disable:no-string-literal */ -cc['Event'] = Event; +cc.Event = Event; diff --git a/cocos/core/event/index.js b/cocos/core/event/index.js index 298fb5ea72..37c4367a04 100644 --- a/cocos/core/event/index.js +++ b/cocos/core/event/index.js @@ -25,4 +25,4 @@ ****************************************************************************/ export { default as Event } from './event'; -export { default as EventTarget } from './event-target'; \ No newline at end of file +export { EventTarget } from './event-target'; diff --git a/cocos/core/game.js b/cocos/core/game.js index 8995ef694b..17347422dd 100644 --- a/cocos/core/game.js +++ b/cocos/core/game.js @@ -24,10 +24,9 @@ THE SOFTWARE. ****************************************************************************/ -import EventTarget from './event/event-target'; -import inputManager from './platform/event-manager/CCInputManager'; +import { EventTarget } from './event/event-target'; +import inputManager from './platform/event-manager/input-manager'; import * as debug from './platform/CCDebug'; -import { addon } from './utils/js'; /** * @module cc @@ -40,118 +39,48 @@ import { addon } from './utils/js'; * @static * @extends EventTarget */ -var game = { - /** - * !#en Event triggered when game hide to background. - * Please note that this event is not 100% guaranteed to be fired on Web platform, - * on native platforms, it corresponds to enter background event, os status bar or notification center may not trigger this event. - * !#zh 游戏进入后台时触发的事件。 - * 请注意,在 WEB 平台,这个事件不一定会 100% 触发,这完全取决于浏览器的回调行为。 - * 在原生平台,它对应的是应用被切换到后台事件,下拉菜单和上拉状态栏等不一定会触发这个事件,这取决于系统行为。 - * @property EVENT_HIDE - * @type {String} - * @example - * cc.game.on(cc.game.EVENT_HIDE, function () { - * cc.audioEngine.pauseMusic(); - * cc.audioEngine.pauseAllEffects(); - * }); - */ - EVENT_HIDE: "game_on_hide", - /** - * Event triggered when game back to foreground - * Please note that this event is not 100% guaranteed to be fired on Web platform, - * on native platforms, it corresponds to enter foreground event. - * !#zh 游戏进入前台运行时触发的事件。 - * 请注意,在 WEB 平台,这个事件不一定会 100% 触发,这完全取决于浏览器的回调行为。 - * 在原生平台,它对应的是应用被切换到前台事件。 - * @property EVENT_SHOW - * @constant - * @type {String} - */ - EVENT_SHOW: "game_on_show", - - /** - * Event triggered after game inited, at this point all engine objects and game scripts are loaded - * @property EVENT_GAME_INITED - * @constant - * @type {String} - */ - EVENT_GAME_INITED: "game_inited", - - /** - * Event triggered after engine inited, at this point you will be able to use all engine classes. - * It was defined as EVENT_RENDERER_INITED in cocos creator v1.x and renamed in v2.0 - * @property EVENT_ENGINE_INITED - * @constant - * @type {String} - */ - EVENT_ENGINE_INITED: "engine_inited", - // deprecated - EVENT_RENDERER_INITED: "engine_inited", - - /** - * Web Canvas 2d API as renderer backend - * @property RENDER_TYPE_CANVAS - * @constant - * @type {Number} - */ - RENDER_TYPE_CANVAS: 0, - /** - * WebGL API as renderer backend - * @property RENDER_TYPE_WEBGL - * @constant - * @type {Number} - */ - RENDER_TYPE_WEBGL: 1, - /** - * OpenGL API as renderer backend - * @property RENDER_TYPE_OPENGL - * @constant - * @type {Number} - */ - RENDER_TYPE_OPENGL: 2, - - _persistRootNodes: {}, +class Game extends EventTarget { + _persistRootNodes = {}; // states - _paused: true,//whether the game is paused - _configLoaded: false,//whether config loaded - _isCloning: false, // deserializing or instantiating - _prepared: false, //whether the engine has prepared - _rendererInitialized: false, + _paused = true;//whether the game is paused + _configLoaded = false;//whether config loaded + _isCloning = false; // deserializing or instantiating + _prepared = false; //whether the engine has prepared + _rendererInitialized = false; - _gfxDevice: null, + _gfxDevice = null; - _intervalId: null,//interval target of main + _intervalId = null;//interval target of main - _lastTime: null, - _frameTime: null, + _lastTime = null; + _frameTime = null; // Scenes list - _sceneInfos: [], + _sceneInfos = []; /** - * !#en The outer frame of the game canvas, parent of game container. + * !#en The outer frame of the game canvas; parent of game container. * !#zh 游戏画布的外框,container 的父容器。 * @property frame * @type {Object} */ - frame: null, + frame = null; /** * !#en The container of game canvas. * !#zh 游戏画布的容器。 * @property container * @type {HTMLDivElement} */ - container: null, + container = null; /** * !#en The canvas of the game. * !#zh 游戏的画布。 * @property canvas * @type {HTMLCanvasElement} */ - canvas: null, + canvas = null; /** * !#en The renderer backend of the game. @@ -159,7 +88,10 @@ var game = { * @property renderType * @type {Number} */ - renderType: -1, + renderType = -1; + + eventTargetOn = super.on; + eventTargetOnce = super.once; /** * !#en @@ -221,7 +153,7 @@ var game = { * @property config * @type {Object} */ - config: {}, + config = {}; /** * !#en Callback when the scripts of engine have been load. @@ -229,9 +161,9 @@ var game = { * @method onStart * @type {Function} */ - onStart: null, + onStart = null; - //@Public Methods + //@Methods // @Game play control /** @@ -240,7 +172,7 @@ var game = { * @method setFrameRate * @param {Number} frameRate */ - setFrameRate: function (frameRate) { + setFrameRate(frameRate) { var config = this.config; config.frameRate = frameRate; if (this._intervalId) @@ -249,7 +181,7 @@ var game = { this._paused = true; this._setAnimFrame(); this._runMainLoop(); - }, + } /** * !#en Get frame rate set for the game, it doesn't represent the real frame rate. @@ -257,18 +189,18 @@ var game = { * @method getFrameRate * @return {Number} frame rate */ - getFrameRate: function () { + getFrameRate() { return this.config.frameRate; - }, + } /** * !#en Run the game frame by frame. * !#zh 执行一帧游戏循环。 * @method step */ - step: function () { + step() { cc.director.mainLoop(); - }, + } /** * !#en Pause the game main loop. This will pause: @@ -277,14 +209,14 @@ var game = { * !#zh 暂停游戏主循环。包含:游戏逻辑,渲染,事件处理,背景音乐和所有音效。这点和只暂停游戏逻辑的 cc.director.pause 不同。 * @method pause */ - pause: function () { + pause() { if (this._paused) return; this._paused = true; // Pause main loop if (this._intervalId) window.cancelAnimFrame(this._intervalId); this._intervalId = 0; - }, + } /** * !#en Resume the game from pause. This will resume: @@ -292,12 +224,12 @@ var game = { * !#zh 恢复游戏主循环。包含:游戏逻辑,渲染,事件处理,背景音乐和所有音效。 * @method resume */ - resume: function () { + resume() { if (!this._paused) return; this._paused = false; // Resume main loop this._runMainLoop(); - }, + } /** * !#en Check whether the game is paused. @@ -305,19 +237,19 @@ var game = { * @method isPaused * @return {Boolean} */ - isPaused: function () { + isPaused() { return this._paused; - }, + } /** * !#en Restart game. * !#zh 重新开始游戏 * @method restart */ - restart: function () { + restart() { cc.director.once(cc.Director.EVENT_AFTER_DRAW, function () { - for (var id in game._persistRootNodes) { - game.removePersistRootNode(game._persistRootNodes[id]); + for (var id in cc.game._persistRootNodes) { + cc.game.removePersistRootNode(cc.game._persistRootNodes[id]); } // Clear scene @@ -327,24 +259,24 @@ var game = { cc.director.purgeDirector(); cc.director.reset(); - game.onStart(); + cc.game.onStart(); }); - }, + } /** * !#en End game, it will close the game window * !#zh 退出游戏 * @method end */ - end: function () { + end() { - if(this._gfxDevice) { + if (this._gfxDevice) { this._gfxDevice.destroy(); this._gfxDevice = null; } close(); - }, + } // @Game loading @@ -357,8 +289,8 @@ var game = { this._initEvents(); } - this.emit(this.EVENT_ENGINE_INITED); - }, + this.emit(Game.EVENT_ENGINE_INITED); + } _prepareFinished(cb) { this._prepared = true; @@ -372,13 +304,10 @@ var game = { this._setAnimFrame(); this._runMainLoop(); - this.emit(this.EVENT_GAME_INITED); + this.emit(Game.EVENT_GAME_INITED); if (cb) cb(); - }, - - eventTargetOn: EventTarget.prototype.on, - eventTargetOnce: EventTarget.prototype.once, + } /** * !#en @@ -403,13 +332,13 @@ var game = { */ on(type, callback, target) { // Make sure EVENT_ENGINE_INITED callbacks to be invoked - if (this._prepared && type === this.EVENT_ENGINE_INITED) { + if (this._prepared && type === Game.EVENT_ENGINE_INITED) { callback.call(target); } else { this.eventTargetOn(type, callback, target); } - }, + } /** * !#en * Register an callback of a specific event type on the game object, @@ -430,13 +359,13 @@ var game = { */ once(type, callback, target) { // Make sure EVENT_ENGINE_INITED callbacks to be invoked - if (this._prepared && type === this.EVENT_ENGINE_INITED) { + if (this._prepared && type === Game.EVENT_ENGINE_INITED) { callback.call(target); } else { this.eventTargetOnce(type, callback, target); } - }, + } /** * !#en Prepare game. @@ -463,7 +392,7 @@ var game = { else { this._prepareFinished(cb); } - }, + } /** * !#en Run game with configuration object and onStart function. @@ -472,11 +401,11 @@ var game = { * @param {Object} config - Pass configuration object or onStart function * @param {Function} onStart - function to be executed after game initialized */ - run: function (config, onStart) { + run(config, onStart) { this._initConfig(config); this.onStart = onStart; - this.prepare(game.onStart && game.onStart.bind(game)); - }, + this.prepare(cc.game.onStart && cc.game.onStart.bind(cc.game)); + } // @ Persist root node section /** @@ -489,7 +418,7 @@ var game = { * @method addPersistRootNode * @param {Node} node - The node to be made persistent */ - addPersistRootNode: function (node) { + addPersistRootNode(node) { if (!cc.Node.isNode(node) || !node.uuid) { cc.warnID(3800); return; @@ -513,7 +442,7 @@ var game = { this._persistRootNodes[id] = node; node._persistNode = true; } - }, + } /** * !#en Remove a persistent root node. @@ -521,13 +450,13 @@ var game = { * @method removePersistRootNode * @param {Node} node - The node to be removed from persistent node list */ - removePersistRootNode: function (node) { + removePersistRootNode(node) { var id = node.uuid || ''; if (node === this._persistRootNodes[id]) { delete this._persistRootNodes[id]; node._persistNode = false; } - }, + } /** * !#en Check whether the node is a persistent root node. @@ -536,16 +465,16 @@ var game = { * @param {Node} node - The node to be checked * @return {Boolean} */ - isPersistRootNode: function (node) { + isPersistRootNode(node) { return node._persistNode; - }, + } - //@Private Methods + //@Methods // @Time ticker section - _setAnimFrame: function () { + _setAnimFrame() { this._lastTime = new Date(); - var frameRate = game.config.frameRate; + var frameRate = cc.game.config.frameRate; this._frameTime = 1000 / frameRate; if (CC_JSB) { @@ -578,20 +507,20 @@ var game = { this._ctTime; } } - }, - _stTime: function (callback) { + } + _stTime(callback) { var currTime = new Date().getTime(); - var timeToCall = Math.max(0, game._frameTime - (currTime - game._lastTime)); + var timeToCall = Math.max(0, cc.game._frameTime - (currTime - cc.game._lastTime)); var id = window.setTimeout(function () { callback(); }, timeToCall); - game._lastTime = currTime + timeToCall; + cc.game._lastTime = currTime + timeToCall; return id; - }, - _ctTime: function (id) { + } + _ctTime(id) { window.clearTimeout(id); - }, + } //Run game. - _runMainLoop: function () { + _runMainLoop() { var self = this, callback, config = self.config, director = cc.director, skip = true, frameRate = config.frameRate; @@ -612,7 +541,7 @@ var game = { self._intervalId = window.requestAnimFrame(callback); self._paused = false; - }, + } // @Game loading section _initConfig(config) { @@ -644,7 +573,7 @@ var game = { this.config = config; this._configLoaded = true; - }, + } _determineRenderType() { let config = this.config, @@ -676,7 +605,7 @@ var game = { if (!supportRender) { throw new Error(debug.getError(3820, userRenderMode)); } - }, + } _initRenderer() { // Avoid setup to be called twice. @@ -800,9 +729,9 @@ var game = { }; this._rendererInitialized = true; - }, + } - _initEvents: function () { + _initEvents() { var win = window, hiddenPropName; // register system events @@ -824,13 +753,13 @@ var game = { function onHidden() { if (!hidden) { hidden = true; - game.emit(game.EVENT_HIDE); + cc.game.emit(Game.EVENT_HIDE); } } function onShown() { if (hidden) { hidden = false; - game.emit(game.EVENT_SHOW); + cc.game.emit(Game.EVENT_SHOW); } } @@ -875,17 +804,86 @@ var game = { document.addEventListener("pageshow", onShown); } - this.on(game.EVENT_HIDE, function () { - game.pause(); + this.on(Game.EVENT_HIDE, function () { + cc.game.pause(); }); - this.on(game.EVENT_SHOW, function () { - game.resume(); + this.on(Game.EVENT_SHOW, function () { + cc.game.resume(); }); } -}; +} -EventTarget.call(game); -addon(game, EventTarget.prototype); +/** + * !#en Event triggered when game hide to background. + * Please note that this event is not 100% guaranteed to be fired on Web platform, + * on native platforms, it corresponds to enter background event, os status bar or notification center may not trigger this event. + * !#zh 游戏进入后台时触发的事件。 + * 请注意,在 WEB 平台,这个事件不一定会 100% 触发,这完全取决于浏览器的回调行为。 + * 在原生平台,它对应的是应用被切换到后台事件,下拉菜单和上拉状态栏等不一定会触发这个事件,这取决于系统行为。 + * @property EVENT_HIDE + * @type {String} + * @example + * cc.game.on(Game.EVENT_HIDE, function () { + * cc.audioEngine.pauseMusic(); + * cc.audioEngine.pauseAllEffects(); + * }); + */ +Game.EVENT_HIDE = "game_on_hide"; -cc.game = game; -export default game; +/** + * Event triggered when game back to foreground + * Please note that this event is not 100% guaranteed to be fired on Web platform, + * on native platforms, it corresponds to enter foreground event. + * !#zh 游戏进入前台运行时触发的事件。 + * 请注意,在 WEB 平台,这个事件不一定会 100% 触发,这完全取决于浏览器的回调行为。 + * 在原生平台,它对应的是应用被切换到前台事件。 + * @property EVENT_SHOW + * @constant + * @type {String} + */ +Game.EVENT_SHOW = "game_on_show"; + +/** + * Event triggered after game inited, at this point all engine objects and game scripts are loaded + * @property EVENT_GAME_INITED + * @constant + * @type {String} + */ +Game.EVENT_GAME_INITED = "game_inited"; + +/** + * Event triggered after engine inited, at this point you will be able to use all engine classes. + * It was defined as EVENT_RENDERER_INITED in cocos creator v1.x and renamed in v2.0 + * @property EVENT_ENGINE_INITED + * @constant + * @type {String} + */ +Game.EVENT_ENGINE_INITED = "engine_inited"; +// deprecated +Game.EVENT_RENDERER_INITED = "engine_inited"; + +/** + * Web Canvas 2d API as renderer backend + * @property RENDER_TYPE_CANVAS + * @constant + * @type {Number} + */ +Game.RENDER_TYPE_CANVAS = 0; +/** + * WebGL API as renderer backend + * @property RENDER_TYPE_WEBGL + * @constant + * @type {Number} + */ +Game.RENDER_TYPE_WEBGL = 1; +/** + * OpenGL API as renderer backend + * @property RENDER_TYPE_OPENGL + * @constant + * @type {Number} + */ +Game.RENDER_TYPE_OPENGL = 2; + +cc.Game = Game; +cc.game = new Game(); +export default Game; diff --git a/cocos/core/platform/CCView.js b/cocos/core/platform/CCView.js index df8cd13661..d85e374de1 100644 --- a/cocos/core/platform/CCView.js +++ b/cocos/core/platform/CCView.js @@ -25,10 +25,10 @@ THE SOFTWARE. ****************************************************************************/ -import EventTarget from '../event/event-target'; +import { EventTarget } from '../event/event-target'; import '../data/class'; import macro from '../platform/CCMacro'; -import game from '../game'; +import Game from '../game'; import Size from '../value-types/size'; import Rect from '../value-types/rect'; @@ -161,7 +161,7 @@ class View extends EventTarget { _t._rpFixedHeight = new ResolutionPolicy(_strategyer.EQUAL_TO_FRAME, _strategy.FIXED_HEIGHT); _t._rpFixedWidth = new ResolutionPolicy(_strategyer.EQUAL_TO_FRAME, _strategy.FIXED_WIDTH); - game.once(game.EVENT_ENGINE_INITED, this.init, this); + cc.game.once(Game.EVENT_ENGINE_INITED, this.init, this); } init () { @@ -170,7 +170,7 @@ class View extends EventTarget { this._initFrameSize(); this.enableAntiAlias(true); - var w = game.canvas.width, h = game.canvas.height; + var w = cc.game.canvas.width, h = cc.game.canvas.height; this._designResolutionSize.width = w; this._designResolutionSize.height = h; this._originalDesignResolutionSize.width = w; @@ -197,7 +197,7 @@ class View extends EventTarget { // Check frame size changed or not var prevFrameW = view._frameSize.width, prevFrameH = view._frameSize.height, prevRotated = view._isRotated; if (cc.sys.isMobile) { - var containerStyle = game.container.style, + var containerStyle = cc.game.container.style, margin = containerStyle.margin; containerStyle.margin = '0'; containerStyle.display = 'none'; @@ -326,8 +326,8 @@ class View extends EventTarget { _initFrameSize () { var locFrameSize = this._frameSize; - var w = __BrowserGetter.availWidth(game.frame); - var h = __BrowserGetter.availHeight(game.frame); + var w = __BrowserGetter.availWidth(cc.game.frame); + var h = __BrowserGetter.availHeight(cc.game.frame); var isLandscape = w >= h; if (CC_EDITOR || !cc.sys.isMobile || @@ -335,17 +335,17 @@ class View extends EventTarget { (!isLandscape && this._orientation & macro.ORIENTATION_PORTRAIT)) { locFrameSize.width = w; locFrameSize.height = h; - game.container.style['-webkit-transform'] = 'rotate(0deg)'; - game.container.style.transform = 'rotate(0deg)'; + cc.game.container.style['-webkit-transform'] = 'rotate(0deg)'; + cc.game.container.style.transform = 'rotate(0deg)'; this._isRotated = false; } else { locFrameSize.width = h; locFrameSize.height = w; - game.container.style['-webkit-transform'] = 'rotate(90deg)'; - game.container.style.transform = 'rotate(90deg)'; - game.container.style['-webkit-transform-origin'] = '0px 0px 0px'; - game.container.style.transformOrigin = '0px 0px 0px'; + cc.game.container.style['-webkit-transform'] = 'rotate(90deg)'; + cc.game.container.style.transform = 'rotate(90deg)'; + cc.game.container.style['-webkit-transform-origin'] = '0px 0px 0px'; + cc.game.container.style.transformOrigin = '0px 0px 0px'; this._isRotated = true; // Fix for issue: https://github.com/cocos-creator/fireball/issues/8365 @@ -354,8 +354,8 @@ class View extends EventTarget { // Because 'transform' style adds canvas (the top-element of container) to a new stack context. // That causes the DOM Input was hidden under canvas. // This should be done after container rotated, instead of in style-mobile.css. - game.canvas.style['-webkit-transform'] = 'translateZ(0px)'; - game.canvas.style.transform = 'translateZ(0px)'; + cc.game.canvas.style['-webkit-transform'] = 'translateZ(0px)'; + cc.game.canvas.style.transform = 'translateZ(0px)'; } if (this._orientationChanging) { setTimeout(function () { @@ -471,7 +471,7 @@ class View extends EventTarget { return; } this._antiAliasEnabled = enabled; - if(game.renderType === game.RENDER_TYPE_WEBGL) { + if (cc.game.renderType === Game.RENDER_TYPE_WEBGL) { var cache = cc.loader._cache; for (var key in cache) { var item = cache[key]; @@ -487,8 +487,8 @@ class View extends EventTarget { } } } - else if(game.renderType === game.RENDER_TYPE_CANVAS) { - var ctx = game.canvas.getContext('2d'); + else if (cc.game.renderType === Game.RENDER_TYPE_CANVAS) { + var ctx = cc.game.canvas.getContext('2d'); ctx.imageSmoothingEnabled = enabled; ctx.mozImageSmoothingEnabled = enabled; } @@ -520,7 +520,7 @@ class View extends EventTarget { cc.sys.browserType !== cc.sys.BROWSER_TYPE_WECHAT) { // Automatically full screen when user touches on mobile version this._autoFullScreen = true; - cc.screen.autoFullScreen(game.frame); + cc.screen.autoFullScreen(cc.game.frame); } else { this._autoFullScreen = false; @@ -549,8 +549,8 @@ class View extends EventTarget { * @param {Number} height */ setCanvasSize (width, height) { - var canvas = game.canvas; - var container = game.container; + var canvas = cc.game.canvas; + var container = cc.game.container; //canvas.width = width * this._devicePixelRatio; //canvas.height = height * this._devicePixelRatio; @@ -579,7 +579,7 @@ class View extends EventTarget { * @return {Size} */ getCanvasSize () { - return cc.size(game.canvas.width, game.canvas.height); + return cc.size(cc.game.canvas.width, cc.game.canvas.height); } /** @@ -610,8 +610,8 @@ class View extends EventTarget { setFrameSize (width, height) { this._frameSize.width = width; this._frameSize.height = height; - game.frame.style.width = width + "px"; - game.frame.style.height = height + "px"; + cc.frame.style.width = width + "px"; + cc.game.frame.style.height = height + "px"; this._resizeEvent(); } @@ -840,7 +840,7 @@ class View extends EventTarget { */ setViewportInPoints (x, y, w, h) { var locScaleX = this._scaleX, locScaleY = this._scaleY; - game._renderContext.viewport((x * locScaleX + this._viewportRect.x), + cc.game._renderContext.viewport((x * locScaleX + this._viewportRect.x), (y * locScaleY + this._viewportRect.y), (w * locScaleX), (h * locScaleY)); @@ -863,7 +863,7 @@ class View extends EventTarget { let sy = Math.ceil(y * scaleY + this._viewportRect.y); let sw = Math.ceil(w * scaleX); let sh = Math.ceil(h * scaleY); - let gl = game._renderContext; + let gl = cc.game._renderContext; if (!_scissorRect) { var boxArr = gl.getParameter(gl.SCISSOR_BOX); @@ -888,7 +888,7 @@ class View extends EventTarget { * @return {Boolean} */ isScissorEnabled () { - return game._renderContext.isEnabled(gl.SCISSOR_TEST); + return cc.game._renderContext.isEnabled(gl.SCISSOR_TEST); } /** @@ -973,7 +973,7 @@ class View extends EventTarget { let x = this._devicePixelRatio * (tx - relatedPos.left); let y = this._devicePixelRatio * (relatedPos.top + relatedPos.height - ty); if (this._isRotated) { - result.x = game.canvas.width - y; + result.x = cc.game.canvas.width - y; result.y = x; } else { @@ -983,18 +983,34 @@ class View extends EventTarget { return result; } - _convertMouseToLocationInView (in_out_point, relatedPos) { - var viewport = this._viewportRect, _t = this; - in_out_point.x = ((_t._devicePixelRatio * (in_out_point.x - relatedPos.left)) - viewport.x) / _t._scaleX; - in_out_point.y = (_t._devicePixelRatio * (relatedPos.top + relatedPos.height - in_out_point.y) - viewport.y) / _t._scaleY; + _convertMouseToLocation(in_out_point, relatedPos){ + in_out_point.x = this._devicePixelRatio * (in_out_point.x - relatedPos.left); + in_out_point.y = this._devicePixelRatio * (relatedPos.top + relatedPos.height - in_out_point.y); } + // _convertMouseToLocationInView (in_out_point, relatedPos) { + // var viewport = this._viewportRect, _t = this; + // in_out_point.x = ((_t._devicePixelRatio * (in_out_point.x - relatedPos.left)) - viewport.x) / _t._scaleX; + // in_out_point.y = (_t._devicePixelRatio * (relatedPos.top + relatedPos.height - in_out_point.y) - viewport.y) / _t._scaleY; + // } + _convertPointWithScale (point) { var viewport = this._viewportRect; point.x = (point.x - viewport.x) / this._scaleX; point.y = (point.y - viewport.y) / this._scaleY; } + _convertTouchWidthScale(selTouch){ + const viewport = this._viewportRect; + const scaleX = this._scaleX; + const scaleY = this._scaleY; + + selTouch._point.x = (selTouch._point.x - viewport.x) / scaleX; + selTouch._point.y = (selTouch._point.y - viewport.y) / scaleY; + selTouch._prevPoint.x = (selTouch._prevPoint.x - viewport.x) / scaleX; + selTouch._prevPoint.y = (selTouch._prevPoint.y - viewport.y) / scaleY; + } + _convertTouchesWithScale (touches) { var viewport = this._viewportRect, scaleX = this._scaleX, scaleY = this._scaleY, selTouch, selPoint, selPrePoint; @@ -1067,7 +1083,7 @@ class ContainerStrategy { } _setupContainer (view, w, h) { - var locCanvas = game.canvas, locContainer = game.container; + var locCanvas = cc.game.canvas, locContainer = cc.game.container; if (cc.sys.platform !== cc.sys.WECHAT_GAME) { if (cc.sys.os === cc.sys.OS_ANDROID) { @@ -1090,14 +1106,14 @@ class ContainerStrategy { _fixContainer () { // Add container to document body - document.body.insertBefore(game.container, document.body.firstChild); + document.body.insertBefore(cc.game.container, document.body.firstChild); // Set body's width height to window's size, and forbid overflow, so that game will be centered var bs = document.body.style; bs.width = window.innerWidth + "px"; bs.height = window.innerHeight + "px"; bs.overflow = "hidden"; // Body size solution doesn't work on all mobile browser so this is the aleternative: fixed container - var contStyle = game.container.style; + var contStyle = cc.game.container.style; contStyle.position = "fixed"; contStyle.left = contStyle.top = "0px"; // Reposition body @@ -1130,7 +1146,7 @@ class ContentStrategy { contentW, contentH); // Translate the content - if (game.renderType === game.RENDER_TYPE_CANVAS){ + if (cc.game.renderType === Game.RENDER_TYPE_CANVAS){ //TODO: modify something for setTransform //game._renderContext.translate(viewport.x, viewport.y + contentH); } @@ -1185,7 +1201,7 @@ ContentStrategy.prototype.name = "ContentStrategy"; */ class EqualToFrame extends ContainerStrategy { apply (view) { - var frameH = view._frameSize.height, containerStyle = game.container.style; + var frameH = view._frameSize.height, containerStyle = cc.game.container.style; this._setupContainer(view, view._frameSize.width, view._frameSize.height); // Setup container's margin and padding if (view._isRotated) { @@ -1205,7 +1221,7 @@ ContentStrategy.prototype.name = "ContentStrategy"; */ class ProportionalToFrame extends ContainerStrategy { apply (view, designedResolution) { - var frameW = view._frameSize.width, frameH = view._frameSize.height, containerStyle = game.container.style, + var frameW = view._frameSize.width, frameH = view._frameSize.height, containerStyle = cc.game.container.style, designW = designedResolution.width, designH = designedResolution.height, scaleX = frameW / designW, scaleY = frameH / designH, containerW, containerH; @@ -1244,7 +1260,7 @@ ContentStrategy.prototype.name = "ContentStrategy"; // Content scale strategys class ExactFit extends ContentStrategy { apply (view, designedResolution) { - var containerW = game.canvas.width, containerH = game.canvas.height, + var containerW = cc.game.canvas.width, containerH = cc.game.canvas.height, scaleX = containerW / designedResolution.width, scaleY = containerH / designedResolution.height; return this._buildResult(containerW, containerH, containerW, containerH, scaleX, scaleY); @@ -1254,7 +1270,7 @@ ContentStrategy.prototype.name = "ContentStrategy"; class ShowAll extends ContentStrategy { apply (view, designedResolution) { - var containerW = game.canvas.width, containerH = game.canvas.height, + var containerW = cc.game.canvas.width, containerH = cc.game.canvas.height, designW = designedResolution.width, designH = designedResolution.height, scaleX = containerW / designW, scaleY = containerH / designH, scale = 0, contentW, contentH; @@ -1269,7 +1285,7 @@ ContentStrategy.prototype.name = "ContentStrategy"; class NoBorder extends ContentStrategy { apply (view, designedResolution) { - var containerW = game.canvas.width, containerH = game.canvas.height, + var containerW = cc.game.canvas.width, containerH = cc.game.canvas.height, designW = designedResolution.width, designH = designedResolution.height, scaleX = containerW / designW, scaleY = containerH / designH, scale, contentW, contentH; @@ -1284,7 +1300,7 @@ ContentStrategy.prototype.name = "ContentStrategy"; class FixedHeight extends ContentStrategy { apply (view, designedResolution) { - var containerW = game.canvas.width, containerH = game.canvas.height, + var containerW = cc.game.canvas.width, containerH = cc.game.canvas.height, designH = designedResolution.height, scale = containerH / designH, contentW = containerW, contentH = containerH; @@ -1295,7 +1311,7 @@ ContentStrategy.prototype.name = "ContentStrategy"; class FixedWidth extends ContentStrategy { apply (view, designedResolution) { - var containerW = game.canvas.width, containerH = game.canvas.height, + var containerW = cc.game.canvas.width, containerH = cc.game.canvas.height, designW = designedResolution.width, scale = containerW / designW, contentW = containerW, contentH = containerH; @@ -1342,7 +1358,7 @@ class ResolutionPolicy { } get canvasSize () { - return cc.v2(game.canvas.width, game.canvas.height); + return cc.v2(cc.game.canvas.width, cc.game.canvas.height); } /** diff --git a/cocos/core/platform/event-manager/CCEvent.ts b/cocos/core/platform/event-manager/CCEvent.ts index 0455463294..cc830e4c63 100644 --- a/cocos/core/platform/event-manager/CCEvent.ts +++ b/cocos/core/platform/event-manager/CCEvent.ts @@ -180,7 +180,7 @@ export class EventMouse extends Event { /** * !#en Returns cursor location. - * !#zh 获取鼠标位置对象,对象包含 x 和 y 属性。 + * !#zh 获取鼠标相对于左下角位置对象,对象包含 x 和 y 属性。 */ public getLocation () { return v2(this._x, this._y); @@ -194,6 +194,16 @@ export class EventMouse extends Event { return v2(this._x, cc.view._designResolutionSize.height - this._y); } + /** + * !#en Returns the current cursor location in ui coordinates. + * !#zh 获取当前事件在 UI 窗口内的坐标位置,对象包含 x 和 y 属性。 + */ + public getUILocation (){ + const pos = v2(this._x, this._y); + cc.view._convertPointWithScale(pos); + return pos; + } + public _setPrevCursor (x: number, y: number) { this._prevX = x; this._prevY = y; @@ -207,6 +217,16 @@ export class EventMouse extends Event { return v2(this._prevX, this._prevY); } + /** + * !#en Returns the previous touch location. + * !#zh 获取鼠标点击在上一次事件时的位置对象,对象包含 x 和 y 属性。 + */ + public getUIPreviousLocation () { + const pos = v2(this._prevX, this._prevY); + cc.view._convertPointWithScale(pos); + return pos; + } + /** * !#en Returns the delta distance from the previous location to current location. * !#zh 获取鼠标距离上一次事件移动的距离对象,对象包含 x 和 y 属性。 @@ -231,6 +251,30 @@ export class EventMouse extends Event { return this._y - this._prevY; } + /** + * !#en Returns the delta distance from the previous location to current location. + * !#zh 获取鼠标距离上一次事件移动的距离对象,对象包含 x 和 y 属性。 + */ + public getUIDelta () { + return v2((this._x - this._prevX) / cc.view.getScaleX(), (this._y - this._prevY) / cc.view.getScaleY()); + } + + /** + * !#en Returns the X axis delta distance from the previous location to current location. + * !#zh 获取鼠标距离上一次事件移动的 X 轴距离。 + */ + public getUIDeltaX () { + return (this._x - this._prevX) / cc.view.getScaleX(); + } + + /** + * !#en Returns the Y axis delta distance from the previous location to current location. + * !#zh 获取鼠标距离上一次事件移动的 Y 轴距离。 + */ + public getUIDeltaY () { + return (this._y - this._prevY) / cc.view.getScaleY(); + } + /** * !#en Sets mouse button. * !#zh 设置鼠标按键。 @@ -262,6 +306,24 @@ export class EventMouse extends Event { public getLocationY () { return this._y; } + + /** + * !#en Returns location X axis data. + * !#zh 获取鼠标当前位置 X 轴。 + */ + public getUILocationX () { + const viewport = cc.view.getViewportRect(); + return (this._x - viewport.x) / cc.view.getScaleX(); + } + + /** + * !#en Returns location Y axis data. + * !#zh 获取鼠标当前位置 Y 轴。 + */ + public getUILocationY () { + const viewport = cc.view.getViewportRect(); + return (this._y - viewport.y) / cc.view.getScaleY(); + } } /** @@ -312,6 +374,8 @@ export class EventTouch extends Event { public _eventCode: number = 0; + public simulate = false; + private _touches: Touch[]; /** diff --git a/cocos/core/platform/event-manager/CCTouch.ts b/cocos/core/platform/event-manager/CCTouch.ts index c53614c582..f62709b419 100644 --- a/cocos/core/platform/event-manager/CCTouch.ts +++ b/cocos/core/platform/event-manager/CCTouch.ts @@ -1,5 +1,6 @@ import { Vec2 } from '../../value-types'; import { v2 } from '../../value-types/vec2'; +import { vec2 } from '../../vmath'; /**************************************************************************** Copyright (c) 2013-2016 Chukong Technologies Inc. @@ -72,6 +73,34 @@ export default class Touch { return this._point.y; } + /** + * !#en Returns the current touch location in OpenGL coordinates.、 + * !#zh 获取当前触点位置。 + */ + public getUILocation () { + const pos = v2(this._point.x, this._point.y); + cc.view._convertPointWithScale(pos); + return pos; + } + + /** + * !#en Returns X axis location value. + * !#zh 获取当前触点 X 轴位置。 + */ + public getUILocationX () { + const viewport = cc.view.getViewportRect(); + return (this._point.x - viewport.x) / cc.view.getScaleX(); + } + + /** + * !#en Returns Y axis location value. + * !#zh 获取当前触点 Y 轴位置。 + */ + public getUILocationY () { + const viewport = cc.view.getViewportRect(); + return (this._point.y - viewport.y) / cc.view.getScaleY(); + } + /** * !#en Returns the previous touch location in OpenGL coordinates. * !#zh 获取触点在上一次事件时的位置对象,对象包含 x 和 y 属性。 @@ -80,6 +109,16 @@ export default class Touch { return v2(this._prevPoint.x, this._prevPoint.y); } + /** + * !#en Returns the previous touch location in OpenGL coordinates. + * !#zh 获取触点在上一次事件时的位置对象,对象包含 x 和 y 属性。 + */ + public getUIPreviousLocation () { + const pos = v2(this._prevPoint.x, this._prevPoint.y); + cc.view._convertPointWithScale(pos); + return pos; + } + /** * !#en Returns the start touch location in OpenGL coordinates. * !#zh 获获取触点落下时的位置对象,对象包含 x 和 y 属性。 @@ -96,6 +135,16 @@ export default class Touch { return this._point.sub(this._prevPoint); } + /** + * !#en Returns the delta distance from the previous touche to the current one in screen coordinates. + * !#zh 获取触点距离上一次事件移动的距离对象,对象包含 x 和 y 属性。 + */ + public getUIDelta () { + const scale = v2(cc.view.getScaleX(), cc.view.getScaleY()); + vec2.divide(scale, this._point.sub(this._prevPoint), scale); + return scale; + } + /** * !#en Returns the current touch location in screen coordinates. * !#zh 获取当前事件在游戏窗口内的坐标位置对象,对象包含 x 和 y 属性。 diff --git a/cocos/core/platform/event-manager/event-enum.ts b/cocos/core/platform/event-manager/event-enum.ts new file mode 100644 index 0000000000..a8d0ece382 --- /dev/null +++ b/cocos/core/platform/event-manager/event-enum.ts @@ -0,0 +1,212 @@ +import { ccenum } from '../../value-types/enum'; + +/** + * !#zh + * 一般用于系统事件或者节点事件的事件枚举 + */ +export enum EventType { + /** + * !#en The event type for press the key up event, you can use its value directly: 'keyup' + * !#zh 手指开始触摸事件 + * @property TOUCH_START + * @type {String} + * @static + */ + TOUCH_START = 'touch-start', + + /** + * !#en The event type for press the key up event, you can use its value directly: 'keyup' + * !#zh 手指开始触摸事件 + * @property TOUCH_MOVE + * @type {String} + * @static + */ + TOUCH_MOVE = 'touch-move', + + /** + * !#en The event type for press the key up event, you can use its value directly: 'keyup' + * !#zh 手指开始触摸事件 + * @property TOUCH_END + * @type {String} + * @static + */ + TOUCH_END = 'touch-end', + + /** + * !#en The event type for press the key up event, you can use its value directly: 'keyup' + * !#zh 手指开始触摸事件 + * @property TOUCH_CANCEL + * @type {String} + * @static + */ + TOUCH_CANCEL = 'touch-cancel', + + /** + * !#en The event type for press the key up event, you can use its value directly: 'keyup' + * !#zh 手指开始触摸事件 + * @property MOUSE_DOWN + * @type {String} + * @static + */ + MOUSE_DOWN = 'mouse-down', + + /** + * !#en The event type for press the key up event, you can use its value directly: 'keyup' + * !#zh 手指开始触摸事件 + * @property MOUSE_MOVE + * @type {String} + * @static + */ + MOUSE_MOVE = 'mouse-move', + + /** + * !#en The event type for press the key up event, you can use its value directly: 'keyup' + * !#zh 手指开始触摸事件 + * @property MOUSE_UP + * @type {String} + * @static + */ + MOUSE_UP = 'mouse-up', + + /** + * !#en The event type for press the key up event, you can use its value directly: 'keyup' + * !#zh 手指开始触摸事件 + * @property MOUSE_WHEEL + * @type {String} + * @static + */ + MOUSE_WHEEL = 'mouse-wheel', + + /** + * !#en The event type for press the devicemotion event, you can use its value directly: 'devicemotion' + * !#zh 鼠标进入事件 + * @property MOUSE_ENTER + * @type {String} + * @static + */ + MOUSE_ENTER = 'mouse-enter', + + /** + * !#en The event type for press the devicemotion event, you can use its value directly: 'devicemotion' + * !#zh 鼠标离开事件 + * @property MOUSE_LEAVE + * @type {String} + * @static + */ + MOUSE_LEAVE = 'mouse-leave', + + /** + * !#en The event type for press the key down event, you can use its value directly: 'keydown' + * !#zh 当按下按键时触发的事件 + * @property KEY_DOWN + * @type {String} + * @static + */ + KEY_DOWN = 'keydown', + + /** + * !#en The event type for press the key up event, you can use its value directly: 'keyup' + * !#zh 当松开按键时触发的事件 + * @property KEY_UP + * @type {String} + * @static + */ + KEY_UP = 'keyup', + + /** + * !#en The event type for press the devicemotion event, you can use its value directly: 'devicemotion' + * !#zh 重力感应 + * @property DEVICEMOTION + * @type {String} + * @static + */ + DEVICEMOTION = 'devicemotion', + + /** + * !#en The event type for press the devicemotion event, you can use its value directly: 'devicemotion' + * !#zh 节点改变位置、旋转或缩放事件 + * @property TRANSFORM_CHANGED + * @type {String} + * @static + */ + TRANSFORM_CHANGED = 'transform-changed', + + /** + * !#en The event type for press the devicemotion event, you can use its value directly: 'devicemotion' + * !#zh 节点位置改变事件 + * @property POSITION_PART + * @type {String} + * @static + */ + POSITION_PART = 'position-part', + + /** + * !#en The event type for press the devicemotion event, you can use its value directly: 'devicemotion' + * !#zh 节点旋转事件 + * @property ROTATION_PART + * @type {String} + * @static + */ + ROTATION_PART = 'rotation-part', + + /** + * !#en The event type for press the devicemotion event, you can use its value directly: 'devicemotion' + * !#zh 节点缩放事件 + * @property SCALE_PART + * @type {String} + * @static + */ + SCALE_PART = 'scale-part', + + /** + * !#en The event type for press the devicemotion event, you can use its value directly: 'devicemotion' + * !#zh + * @property SCENE_CHANGED_FOR_PERSISTS + * @type {String} + * @static + */ + SCENE_CHANGED_FOR_PERSISTS = 'scene-changed-for-persists', + + /** + * !#en The event type for size change events. + * Performance note, this event will be triggered every time corresponding properties being changed, + * if the event callback have heavy logic it may have great performance impact, try to avoid such scenario. + * !#zh 当节点尺寸改变时触发的事件。 + * 性能警告:这个事件会在每次对应的属性被修改时触发,如果事件回调损耗较高,有可能对性能有很大的负面影响,请尽量避免这种情况。 + * @property {String} SIZE_CHANGED + * @static + */ + SIZE_CHANGED = 'size-changed', + /** + * !#en The event type for anchor point change events. + * Performance note, this event will be triggered every time corresponding properties being changed, + * if the event callback have heavy logic it may have great performance impact, try to avoid such scenario. + * !#zh 当节点锚点改变时触发的事件。 + * 性能警告:这个事件会在每次对应的属性被修改时触发,如果事件回调损耗较高,有可能对性能有很大的负面影响,请尽量避免这种情况。 + * @property {String} ANCHOR_CHANGED + * @static + */ + ANCHOR_CHANGED = 'anchor-changed', + + /** + * !#en The event type for press the devicemotion event, you can use its value directly: 'devicemotion' + * !#zh 节点子类添加 + * @property CHILD_ADDED + * @type {String} + * @static + */ + CHILD_ADDED = 'child-added', + + /** + * !#en The event type for press the devicemotion event, you can use its value directly: 'devicemotion' + * !#zh 节点子类移除 + * @property CHILD_REMOVED + * @type {String} + * @static + */ + CHILD_REMOVED = 'child-removed', +} + +ccenum(EventType); + +cc.SystemEventType = EventType; diff --git a/cocos/core/platform/event-manager/CCEventListener.ts b/cocos/core/platform/event-manager/event-listener.ts similarity index 100% rename from cocos/core/platform/event-manager/CCEventListener.ts rename to cocos/core/platform/event-manager/event-listener.ts diff --git a/cocos/core/platform/event-manager/CCEventManager.ts b/cocos/core/platform/event-manager/event-manager.ts similarity index 99% rename from cocos/core/platform/event-manager/CCEventManager.ts rename to cocos/core/platform/event-manager/event-manager.ts index 4408278c4d..5f7f87bfbb 100644 --- a/cocos/core/platform/event-manager/CCEventManager.ts +++ b/cocos/core/platform/event-manager/event-manager.ts @@ -27,7 +27,7 @@ // tslint:disable:max-line-length import * as js from '../../utils/js'; -import { EventListener } from './CCEventListener'; +import { EventListener } from './event-listener'; const ListenerID = EventListener.ListenerID; // tslint:disable-next-line diff --git a/cocos/core/platform/event-manager/index.ts b/cocos/core/platform/event-manager/index.ts index fef8f81d68..24dd76162b 100644 --- a/cocos/core/platform/event-manager/index.ts +++ b/cocos/core/platform/event-manager/index.ts @@ -24,8 +24,8 @@ THE SOFTWARE. ****************************************************************************/ -export * from './CCEventManager'; -export * from './CCInputManager'; +export * from './event-manager'; +export * from './input-manager'; export * from './system-event'; export * from './CCEvent'; export * from './CCTouch'; diff --git a/cocos/core/platform/event-manager/CCInputManager.ts b/cocos/core/platform/event-manager/input-manager.ts similarity index 96% rename from cocos/core/platform/event-manager/CCInputManager.ts rename to cocos/core/platform/event-manager/input-manager.ts index 24cf0adf7c..d5e42080f6 100644 --- a/cocos/core/platform/event-manager/CCInputManager.ts +++ b/cocos/core/platform/event-manager/input-manager.ts @@ -24,13 +24,13 @@ THE SOFTWARE. ****************************************************************************/ +import { Vec2 } from '../../value-types/index'; import { rect } from '../../value-types/rect'; -import Vec2, { v2 } from '../../value-types/vec2'; import macro from '../CCMacro'; import sys from '../CCSys'; import { EventAcceleration, EventKeyboard, EventMouse, EventTouch } from './CCEvent'; -import eventManager from './CCEventManager'; import CCTouch from './CCTouch'; +import eventManager from './event-manager'; const TOUCH_TIMEOUT = macro.TOUCH_TIMEOUT; @@ -41,7 +41,7 @@ const LANDSCAPE_RIGHT = 90; let _didAccelerateFun; -const _vec2 = v2(); +const _vec2 = new Vec2(); interface IHTMLElementPosition { left: number; @@ -53,9 +53,10 @@ interface IHTMLElementPosition { interface IView { convertToLocationInView (tx: number, ty: number, elementPosition: IHTMLElementPosition, out?: Vec2): Vec2; - _convertMouseToLocationInView (point: Vec2, elementPosition: IHTMLElementPosition): void; + _convertMouseToLocation (point: Vec2, elementPosition: IHTMLElementPosition): void; + // _convertMouseToLocationInView (point: Vec2, elementPosition: IHTMLElementPosition): void; - _convertTouchesWithScale (touches: CCTouch[]): void; + // _convertTouchesWithScale (touches: CCTouch[]): void; } /** @@ -83,8 +84,8 @@ class InputManager { private _isRegisterEvent = false; - private _preTouchPoint = v2(0, 0); - private _prevMousePoint = v2(0, 0); + private _preTouchPoint = new Vec2(); + private _prevMousePoint = new Vec2(); private _preTouchPool: CCTouch[] = []; private _preTouchPoolPointer = 0; @@ -132,7 +133,7 @@ class InputManager { } } if (handleTouches.length > 0) { - this._glView!._convertTouchesWithScale(handleTouches); + // this._glView!._convertTouchesWithScale(handleTouches); const touchEvent = new EventTouch(handleTouches); touchEvent._eventCode = EventTouch.BEGAN; eventManager.dispatchEvent(touchEvent); @@ -161,7 +162,7 @@ class InputManager { } } if (handleTouches.length > 0) { - this._glView!._convertTouchesWithScale(handleTouches); + // this._glView!._convertTouchesWithScale(handleTouches); const touchEvent = new EventTouch(handleTouches); touchEvent._eventCode = EventTouch.MOVED; eventManager.dispatchEvent(touchEvent); @@ -171,7 +172,7 @@ class InputManager { public handleTouchesEnd (touches: CCTouch[]) { const handleTouches = this.getSetOfTouchesEndOrCancel(touches); if (handleTouches.length > 0) { - this._glView!._convertTouchesWithScale(handleTouches); + // this._glView!._convertTouchesWithScale(handleTouches); const touchEvent = new EventTouch(handleTouches); touchEvent._eventCode = EventTouch.ENDED; eventManager.dispatchEvent(touchEvent); @@ -182,7 +183,7 @@ class InputManager { public handleTouchesCancel (touches: CCTouch[]) { const handleTouches = this.getSetOfTouchesEndOrCancel(touches); if (handleTouches.length > 0) { - this._glView!._convertTouchesWithScale(handleTouches); + // this._glView!._convertTouchesWithScale(handleTouches); const touchEvent = new EventTouch(handleTouches); touchEvent._eventCode = EventTouch.CANCELLED; eventManager.dispatchEvent(touchEvent); @@ -309,7 +310,8 @@ class InputManager { mouseEvent._setPrevCursor(locPreMouse.x, locPreMouse.y); locPreMouse.x = location.x; locPreMouse.y = location.y; - this._glView!._convertMouseToLocationInView(locPreMouse, pos); + // this._glView!._convertMouseToLocationInView(locPreMouse, pos); + this._glView!._convertMouseToLocation(locPreMouse, pos); mouseEvent.setLocation(locPreMouse.x, locPreMouse.y); return mouseEvent; } @@ -493,6 +495,17 @@ class InputManager { this._accelCurTime += dt; } + /** + * set accelerometer interval value + * @method setAccelerometerInterval + * @param {Number} interval + */ + public setAccelerometerInterval (interval) { + if (this._accelInterval !== interval) { + this._accelInterval = interval; + } + } + private _getUnUsedIndex () { let temp = this._indexBitsUsed; const now = cc.sys.now(); @@ -529,17 +542,6 @@ class InputManager { this._indexBitsUsed &= temp; } - /** - * set accelerometer interval value - * @method setAccelerometerInterval - * @param {Number} interval - */ - private setAccelerometerInterval (interval) { - if (this._accelInterval !== interval) { - this._accelInterval = interval; - } - } - private _registerMouseEvents (element: HTMLElement, prohibition: boolean) { // HACK // - At the same time to trigger the ontouch event and onmouse event @@ -566,7 +568,7 @@ class InputManager { const position = this.getHTMLElementPosition(element); const location = this.getPointByEvent(event, position); const positionRect = rect(position.left, position.top, position.width, position.height); - if (!positionRect.contains(v2(location.x, location.y))) { + if (!positionRect.contains(new Vec2(location.x, location.y))) { this.handleTouchesEnd([this.getTouchByXY(location.x, location.y, position)]); const mouseEvent = this.getMouseEvent(location, position, EventMouse.UP); mouseEvent.setButton(event.button); diff --git a/cocos/core/platform/event-manager/system-event.js b/cocos/core/platform/event-manager/system-event.js deleted file mode 100644 index c9b25eb604..0000000000 --- a/cocos/core/platform/event-manager/system-event.js +++ /dev/null @@ -1,173 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013-2016 Chukong Technologies Inc. - Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - - http://www.cocos.com - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated engine source code (the "Software"), a limited, - worldwide, royalty-free, non-assignable, revocable and non-exclusive license - to use Cocos Creator solely to develop games on your target platforms. You shall - not use Cocos Creator software for developing other software or tools that's - used for developing games. You are not granted to publish, distribute, - sublicense, and/or sell copies of Cocos Creator. - - The software or tools in this License Agreement are licensed, not sold. - Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - -import Enum from '../../value-types/enum'; -import EventTarget from '../../event/event-target'; -import eventManager from './CCEventManager'; -import inputManger from './CCInputManager'; - -/** - * !#en The event type supported by SystemEvent - * !#zh SystemEvent 支持的事件类型 - * @class SystemEvent.EventType - * @static - * @namespace SystemEvent - */ -var EventType = Enum({ - /** - * !#en The event type for press the key down event, you can use its value directly: 'keydown' - * !#zh 当按下按键时触发的事件 - * @property KEY_DOWN - * @type {String} - * @static - */ - KEY_DOWN: 'keydown', - /** - * !#en The event type for press the key up event, you can use its value directly: 'keyup' - * !#zh 当松开按键时触发的事件 - * @property KEY_UP - * @type {String} - * @static - */ - KEY_UP: 'keyup', - /** - * !#en The event type for press the devicemotion event, you can use its value directly: 'devicemotion' - * !#zh 重力感应 - * @property DEVICEMOTION - * @type {String} - * @static - */ - DEVICEMOTION: 'devicemotion' - -}); - -var keyboardListener = null; -var accelerationListener = null; - -/** - * !#en The System event, it currently supports the key events and accelerometer events - * !#zh 系统事件,它目前支持按键事件和重力感应事件 - * @class SystemEvent - * @extends EventTarget - */ -export default class SystemEvent extends EventTarget { - name = 'SystemEvent'; - static EventType = EventType; - - /** - * !#en whether enable accelerometer event - * !#zh 是否启用加速度计事件 - * @method setAccelerometerEnabled - * @param {Boolean} isEnable - */ - setAccelerometerEnabled (isEnable) { - inputManger.setAccelerometerEnabled(isEnable); - } - - /** - * !#en set accelerometer interval value - * !#zh 设置加速度计间隔值 - * @method setAccelerometerInterval - * @param {Number} interval - */ - setAccelerometerInterval (interval) { - inputManger.setAccelerometerInterval(interval); - } - - on (type, callback, target) { - super.on(type, callback, target); - - // Keyboard - if (type === EventType.KEY_DOWN || type === EventType.KEY_UP) { - if (!keyboardListener) { - keyboardListener = cc.EventListener.create({ - event: cc.EventListener.KEYBOARD, - onKeyPressed (keyCode, event) { - event.type = EventType.KEY_DOWN; - cc.systemEvent.dispatchEvent(event); - }, - onKeyReleased (keyCode, event) { - event.type = EventType.KEY_UP; - cc.systemEvent.dispatchEvent(event); - } - }); - } - if (!eventManager.hasEventListener(cc.EventListener.ListenerID.KEYBOARD)) { - eventManager.addListener(keyboardListener, 1); - } - } - - // Acceleration - if (type === EventType.DEVICEMOTION) { - if (!accelerationListener) { - accelerationListener = cc.EventListener.create({ - event: cc.EventListener.ACCELERATION, - callback (acc, event) { - event.type = EventType.DEVICEMOTION; - cc.systemEvent.dispatchEvent(event); - } - }); - } - if (!eventManager.hasEventListener(cc.EventListener.ListenerID.ACCELERATION)) { - eventManager.addListener(accelerationListener, 1); - } - } - } - - off (type, callback, target) { - super.off(type, callback, target); - - // Keyboard - if (keyboardListener && (type === EventType.KEY_DOWN || type === EventType.KEY_UP)) { - var hasKeyDownEventListener = this.hasEventListener(EventType.KEY_DOWN); - var hasKeyUpEventListener = this.hasEventListener(EventType.KEY_UP); - if (!hasKeyDownEventListener && !hasKeyUpEventListener) { - eventManager.removeListener(keyboardListener); - } - } - - // Acceleration - if (accelerationListener && type === EventType.DEVICEMOTION) { - eventManager.removeListener(accelerationListener); - } - } -} - -cc.SystemEvent = SystemEvent; - -if (!CC_EDITOR) { -/** - * @module cc - */ - -/** - * !#en The System event singleton for global usage - * !#zh 系统事件单例,方便全局使用 - * @property systemEvent - * @type {SystemEvent} - */ - cc.systemEvent = new cc.SystemEvent(); -} \ No newline at end of file diff --git a/cocos/core/platform/event-manager/system-event.ts b/cocos/core/platform/event-manager/system-event.ts new file mode 100644 index 0000000000..b28caae96e --- /dev/null +++ b/cocos/core/platform/event-manager/system-event.ts @@ -0,0 +1,228 @@ +/**************************************************************************** + Copyright (c) 2013-2016 Chukong Technologies Inc. + Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + + https://www.cocos.com/ + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + 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 { EventTarget } from '../../event/event-target'; +import { EventType } from './event-enum'; +import { EventListener } from './event-listener'; +// import { ccenum } from '../../value-types/enum'; +import eventManager from './event-manager'; +import inputManager from './input-manager'; + +/** + * !#en + * The System event, it currently supports keyboard events and accelerometer events.
+ * You can get the SystemEvent instance with cc.systemEvent.
+ * example: + * ``` + * cc.systemEvent.on(cc.SystemEvent.EventType.DEVICEMOTION, this.onDeviceMotionEvent, this); + * cc.systemEvent.off(cc.SystemEvent.EventType.DEVICEMOTION, this.onDeviceMotionEvent, this); + * ``` + * !#zh + * 系统事件,它目前支持按键事件和重力感应事件。
+ * 你可以通过 cc.systemEvent 获取到 SystemEvent 的实例。
+ * 参考示例: + * ``` + * cc.systemEvent.on(cc.SystemEvent.EventType.DEVICEMOTION, this.onDeviceMotionEvent, this); + * cc.systemEvent.off(cc.SystemEvent.EventType.DEVICEMOTION, this.onDeviceMotionEvent, this); + * ``` + * @class SystemEvent + * @extends EventTarget + */ + +let keyboardListener: EventListener | null = null; +let accelerationListener: EventListener | null = null; +let touchListener: EventListener | null = null; +let mouseListener: EventListener | null = null; +export class SystemEvent extends EventTarget { + public static EventType = EventType; + constructor () { + super(); + } + /** + * !#en whether enable accelerometer event + * !#zh 是否启用加速度计事件 + * @method setAccelerometerEnabled + * @param {Boolean} isEnable + */ + public setAccelerometerEnabled (isEnable: boolean) { + if (CC_EDITOR) { + return; + } + inputManager.setAccelerometerEnabled(isEnable); + } + + /** + * !#en set accelerometer interval value + * !#zh 设置加速度计间隔值 + * @method setAccelerometerInterval + * @param {Number} interval + */ + public setAccelerometerInterval (interval: number) { + if (CC_EDITOR) { + return; + } + inputManager.setAccelerometerInterval(interval); + } + + public on (type: string, callback: Function, target?: Object) { + if (CC_EDITOR) { + return; + } + super.on(type, callback, target); + + // Keyboard + if (type === EventType.KEY_DOWN || type === EventType.KEY_UP) { + if (!keyboardListener) { + keyboardListener = EventListener.create({ + event: EventListener.KEYBOARD, + onKeyPressed (keyCode, event) { + event.type = EventType.KEY_DOWN; + cc.systemEvent.dispatchEvent(event); + }, + onKeyReleased (keyCode, event) { + event.type = EventType.KEY_UP; + cc.systemEvent.dispatchEvent(event); + }, + }); + } + if (!eventManager.hasEventListener(EventListener.ListenerID.KEYBOARD)) { + eventManager.addListener(keyboardListener, 256); + } + } + + // Acceleration + if (type === EventType.DEVICEMOTION) { + if (!accelerationListener) { + accelerationListener = EventListener.create({ + event: EventListener.ACCELERATION, + callback (acc, event) { + event.type = EventType.DEVICEMOTION; + cc.systemEvent.dispatchEvent(event); + }, + }); + } + if (!eventManager.hasEventListener(EventListener.ListenerID.ACCELERATION)) { + eventManager.addListener(accelerationListener!, 256); + } + } + + // touch + if (type === EventType.TOUCH_START || + type === EventType.TOUCH_MOVE || + type === EventType.TOUCH_END || + type === EventType.TOUCH_CANCEL + ) { + if (!touchListener) { + touchListener = EventListener.create({ + event: EventListener.TOUCH_ONE_BY_ONE, + onTouchBegan (event) { + event.type = EventType.TOUCH_START; + cc.systemEvent.dispatchEvent(event); + }, + onTouchMoved (event) { + event.type = EventType.TOUCH_MOVE; + cc.systemEvent.dispatchEvent(event); + }, + onTouchEnded (event) { + event.type = EventType.TOUCH_END; + cc.systemEvent.dispatchEvent(event); + }, + onTouchCancelled (event) { + event.type = EventType.TOUCH_CANCEL; + cc.systemEvent.dispatchEvent(event); + }, + }); + } + eventManager.addListener(touchListener, 256); + } + + // mouse + if (type === EventType.MOUSE_DOWN || + type === EventType.MOUSE_MOVE || + type === EventType.MOUSE_UP || + type === EventType.MOUSE_WHEEL + ) { + if (!mouseListener) { + mouseListener = EventListener.create({ + event: EventListener.MOUSE, + onMouseDown (event) { + event.type = EventType.MOUSE_DOWN; + cc.systemEvent.dispatchEvent(event); + }, + onMouseMove (event) { + event.type = EventType.MOUSE_MOVE; + cc.systemEvent.dispatchEvent(event); + }, + onMouseUp (event) { + event.type = EventType.MOUSE_UP; + cc.systemEvent.dispatchEvent(event); + }, + onMouseScroll (event) { + event.type = EventType.MOUSE_WHEEL; + cc.systemEvent.dispatchEvent(event); + }, + }); + } + eventManager.addListener(mouseListener, 256); + } + + return callback; + } + + public off (type: string, callback?: Function, target?: Object) { + if (CC_EDITOR) { + return; + } + super.off(type, callback, target); + + // Keyboard + if (keyboardListener && (type === EventType.KEY_DOWN || type === EventType.KEY_UP)) { + const hasKeyDownEventListener = this.hasEventListener(EventType.KEY_DOWN); + const hasKeyUpEventListener = this.hasEventListener(EventType.KEY_UP); + if (!hasKeyDownEventListener && !hasKeyUpEventListener) { + eventManager.removeListener(keyboardListener); + } + } + + // Acceleration + if (accelerationListener && type === EventType.DEVICEMOTION) { + eventManager.removeListener(accelerationListener); + } + } +} + +cc.SystemEvent = SystemEvent; +/** + * @module cc + */ + +/** + * !#en The System event singleton for global usage + * !#zh 系统事件单例,方便全局使用 + * @property systemEvent + * @type {SystemEvent} + */ +cc.systemEvent = new cc.SystemEvent(); diff --git a/cocos/renderer/ui/ui.ts b/cocos/renderer/ui/ui.ts index ff5ee7c24e..9c84806271 100644 --- a/cocos/renderer/ui/ui.ts +++ b/cocos/renderer/ui/ui.ts @@ -12,13 +12,8 @@ import { SpriteFrame } from '../../assets/CCSpriteFrame'; import { CachedArray } from '../../core/memop/cached-array'; import { Root } from '../../core/root'; import { GFXBindingLayout } from '../../gfx/binding-layout'; -import { GFXBuffer } from '../../gfx/buffer'; import { GFXCommandBuffer } from '../../gfx/command-buffer'; -import { - GFXBufferUsageBit, - GFXCommandBufferType, - GFXMemoryUsageBit, -} from '../../gfx/define'; +import { GFXCommandBufferType } from '../../gfx/define'; import { GFXDevice } from '../../gfx/device'; import { IGFXInputAttribute } from '../../gfx/input-assembler'; import { GFXPipelineState } from '../../gfx/pipeline-state'; @@ -30,7 +25,6 @@ import { RenderScene } from '../scene/render-scene'; import { UIBatchModel } from './ui-batch-model'; import { UIMaterial } from './ui-material'; -const _mat4Array = new Float32Array(16); export class UIDrawBatch { public camera: Camera | null = null; public bufferBatch: MeshBuffer | null = null; @@ -84,6 +78,7 @@ export class UI { return new UIDrawBatch(); }, 128); private _cmdBuff: GFXCommandBuffer | null = null; + // @ts-ignore private _scene: RenderScene; private _attributes: IGFXInputAttribute[] = []; private _meshBuffers: MeshBuffer[] = []; @@ -195,7 +190,7 @@ export class UI { this._screens.splice(idx, 1); } - let camera; + let camera: Camera | null; for (let i = idx; i < this._screens.length;) { camera = this._screens[i].camera; if (camera) { @@ -205,7 +200,6 @@ export class UI { } public update (dt: number) { - this._reset(); this._renderScreens(); // update buffers @@ -217,6 +211,7 @@ export class UI { } this.render(); + this._reset(); } public render () { @@ -319,7 +314,7 @@ export class UI { this._uiMaterials.clear(); } - private _walk (node: Node, fn1, fn2, level = 0, isRenderComp = false) { + private _walk (node: Node, fn1: (node: Node) => void, fn2: (node: Node) => void, level = 0) { let resortNodeList; const len = node.childrenCount; diff --git a/cocos/scene-graph/base-node.ts b/cocos/scene-graph/base-node.ts index 122f65d312..12ae03870c 100644 --- a/cocos/scene-graph/base-node.ts +++ b/cocos/scene-graph/base-node.ts @@ -27,10 +27,10 @@ import { Component } from '../components/component'; import { ccclass, property } from '../core/data/class-decorator'; import { CCObject } from '../core/data/object'; +import { EventType } from '../core/platform/event-manager/event-enum'; import IdGenerator from '../core/utils/id-generator'; import * as js from '../core/utils/js'; import { baseNodePolyfill } from './base-node-dev'; -import { EventType } from './node-event-enum'; type Constructor = new (...args: any[]) => T; diff --git a/cocos/scene-graph/node-event-enum.ts b/cocos/scene-graph/node-event-enum.ts deleted file mode 100644 index fd1d69f8f5..0000000000 --- a/cocos/scene-graph/node-event-enum.ts +++ /dev/null @@ -1,46 +0,0 @@ -import { ccenum } from '../core/value-types/enum'; - -export enum EventType { - TRANSFORM_CHANGED = 'transform-changed', - POSITION_PART = 'position-part', - ROTATION_PART = 'rotation-part', - SCALE_PART = 'scale-part', - - SCENE_CHANGED_FOR_PERSISTS = 'scene-changed-for-persists', - - TOUCH_START = 'touch-start', - TOUCH_MOVE = 'touch-move', - TOUCH_END = 'touch-end', - TOUCH_CANCEL = 'touch-cancel', - MOUSE_DOWN = 'mouse-down', - MOUSE_ENTER = 'mouse-enter', - MOUSE_MOVE = 'mouse-move', - MOUSE_LEAVE = 'mouse-leave', - MOUSE_UP = 'mouse-up', - MOUSE_WHEEL = 'mouse-wheel', - - /** - * !#en The event type for size change events. - * Performance note, this event will be triggered every time corresponding properties being changed, - * if the event callback have heavy logic it may have great performance impact, try to avoid such scenario. - * !#zh 当节点尺寸改变时触发的事件。 - * 性能警告:这个事件会在每次对应的属性被修改时触发,如果事件回调损耗较高,有可能对性能有很大的负面影响,请尽量避免这种情况。 - * @property {String} SIZE_CHANGED - * @static - */ - SIZE_CHANGED = 'size-changed', - /** - * !#en The event type for anchor point change events. - * Performance note, this event will be triggered every time corresponding properties being changed, - * if the event callback have heavy logic it may have great performance impact, try to avoid such scenario. - * !#zh 当节点锚点改变时触发的事件。 - * 性能警告:这个事件会在每次对应的属性被修改时触发,如果事件回调损耗较高,有可能对性能有很大的负面影响,请尽量避免这种情况。 - * @property {String} ANCHOR_CHANGED - * @static - */ - ANCHOR_CHANGED = 'anchor-changed', - CHILD_ADDED = 'child-added', - CHILD_REMOVED = 'child-removed', -} - -ccenum(EventType); diff --git a/cocos/scene-graph/node-event-processor.ts b/cocos/scene-graph/node-event-processor.ts index dfffaccfab..0719c9b0b2 100644 --- a/cocos/scene-graph/node-event-processor.ts +++ b/cocos/scene-graph/node-event-processor.ts @@ -1,15 +1,19 @@ -import { Component } from '../components/component'; -import EventTarget from '../core/event/event-target'; +import { EventTarget } from '../core/event/event-target'; +import { ITargetImpl } from '../core/event/event-target-factory'; import { eventManager } from '../core/platform/event-manager'; -import { EventListener } from '../core/platform/event-manager/CCEventListener'; import Touch from '../core/platform/event-manager/CCTouch'; +import { EventType } from '../core/platform/event-manager/event-enum'; +import { EventListener } from '../core/platform/event-manager/event-listener'; import { EventMouse, EventTouch} from '../core/platform/event-manager/index'; -import { array } from '../core/utils/js'; +import * as js from '../core/utils/js'; +import { Vec2 } from '../core/value-types'; import { Node } from './node'; -import { EventType } from './node-event-enum'; -const _cachedArray = new Array(16); +const fastRemove = js.array.fastRemove; + +const _cachedArray = new Array(16); let _currentHovered: Node | null = null; +let pos = new Vec2(); const _touchEvents = [ EventType.TOUCH_START.toString(), @@ -29,12 +33,13 @@ const _mouseEvents = [ // TODO: rearrange event function _touchStartHandler (this: EventListener, touch: Touch, event: EventTouch) { - const pos = touch.getLocation(); const node = this.owner as Node; - if (!node || ! node.uiTransfromComp){ + if (!node || !node.uiTransfromComp) { return false; } + pos = touch.getUILocation(); + if (node.uiTransfromComp.isHit(pos, this)) { event.type = EventType.TOUCH_START.toString(); event.touch = touch; @@ -59,12 +64,13 @@ function _touchMoveHandler (this: EventListener, touch: Touch, event: EventTouch } function _touchEndHandler (this: EventListener, touch: Touch, event: EventTouch) { - const pos = touch.getLocation(); const node = this.owner as Node; if (!node || !node.uiTransfromComp) { return; } + pos = touch.getUILocation(); + if (node.uiTransfromComp.isHit(pos, this)) { event.type = EventType.TOUCH_END.toString(); } else { @@ -88,12 +94,13 @@ function _touchCancelHandler (this: EventListener, touch: Touch, event: EventTou } function _mouseDownHandler (this: EventListener, event: EventMouse) { - const pos = event.getLocation(); const node = this.owner as Node; if (!node || !node.uiTransfromComp) { return; } + pos = event.getUILocation(); + if (node.uiTransfromComp.isHit(pos, this)) { event.type = EventType.MOUSE_DOWN.toString(); event.bubbles = true; @@ -102,12 +109,13 @@ function _mouseDownHandler (this: EventListener, event: EventMouse) { } function _mouseMoveHandler (this: EventListener, event: EventMouse) { - const pos = event.getLocation(); const node = this.owner as Node; - if (!node || !node.uiTransfromComp){ + if (!node || !node.uiTransfromComp) { return; } + pos = event.getUILocation(); + const hit = node.uiTransfromComp.isHit(pos, this); if (hit) { if (!this._previousIn) { @@ -143,12 +151,13 @@ function _mouseMoveHandler (this: EventListener, event: EventMouse) { } function _mouseUpHandler (this: EventListener, event: EventMouse) { - const pos = event.getLocation(); const node = this.owner as Node; if (!node || !node.uiTransfromComp) { return; } + pos = event.getUILocation(); + if (node.uiTransfromComp.isHit(pos, this)) { event.type = EventType.MOUSE_UP.toString(); event.bubbles = true; @@ -158,13 +167,14 @@ function _mouseUpHandler (this: EventListener, event: EventMouse) { } } -function _mouseWheelHandler (this: EventListener, event: EventTouch) { - const pos = event.getLocation(); +function _mouseWheelHandler (this: EventListener, event: EventMouse) { const node = this.owner as Node; if (!node || !node.uiTransfromComp) { return; } + pos = event.getUILocation(); + if (node.uiTransfromComp!.isHit(pos, this)) { event.type = EventType.MOUSE_WHEEL.toString(); event.bubbles = true; @@ -175,7 +185,7 @@ function _mouseWheelHandler (this: EventListener, event: EventTouch) { } function _doDispatchEvent (owner: Node, event: EventTouch) { - let target; + let target: Node; let i = 0; event.target = owner; @@ -186,10 +196,10 @@ function _doDispatchEvent (owner: Node, event: EventTouch) { event.eventPhase = 1; for (i = _cachedArray.length - 1; i >= 0; --i) { target = _cachedArray[i]; - if (target._capturingTargets) { + if (target.eventProcessor.capturingTargets) { event.currentTarget = target; // fire event - target._capturingTargets.emit(event.type, event, _cachedArray); + target.eventProcessor.capturingTargets.emit(event.type, event, _cachedArray); // check if propagation stopped if (event.propagationStopped) { _cachedArray.length = 0; @@ -217,10 +227,10 @@ function _doDispatchEvent (owner: Node, event: EventTouch) { event.eventPhase = 3; for (i = 0; i < _cachedArray.length; ++i) { target = _cachedArray[i]; - if (target._bubblingTargets) { + if (target.eventProcessor.bubblingTargets) { event.currentTarget = target; // fire event - target._bubblingTargets.emit(event.type, event); + target.eventProcessor.bubblingTargets.emit(event.type, event); // check if propagation stopped if (event.propagationStopped) { _cachedArray.length = 0; @@ -573,8 +583,13 @@ export class NodeEventProcessor { if (!listeners.hasEventListener(type, callback, target)) { listeners.add(type, callback, target); - if (target && (target as Component)._eventTargets) { - (target as Component)._eventTargets.push(this._node); + const targetImpl = target as ITargetImpl; + if (target) { + if (targetImpl.__eventTargets) { + targetImpl.__eventTargets.push(this); + } else if (targetImpl.node && targetImpl.node.__eventTargets) { + targetImpl.node.__eventTargets.push(this); + } } } @@ -600,8 +615,13 @@ export class NodeEventProcessor { if (listeners) { listeners.remove(type, callback, target); - if (target && (target as Component)._eventTargets) { - array.fastRemove((target as Component)._eventTargets, this); + const targetImpl = target as ITargetImpl; + if (target) { + if (targetImpl.__eventTargets) { + fastRemove(targetImpl.__eventTargets, this); + } else if (targetImpl.node && targetImpl.node.__eventTargets) { + fastRemove(targetImpl.node.__eventTargets, this); + } } } diff --git a/cocos/scene-graph/node.ts b/cocos/scene-graph/node.ts index 410a880a92..f3e31b3762 100644 --- a/cocos/scene-graph/node.ts +++ b/cocos/scene-graph/node.ts @@ -1,12 +1,12 @@ import { UITransformComponent } from '../3d/ui/components/ui-transfrom-component'; import { ccclass, property } from '../core/data/class-decorator'; +import { EventType } from '../core/platform/event-manager/event-enum'; import { Mat4, Quat, Vec3 } from '../core/value-types'; import Size from '../core/value-types/size'; import Vec2 from '../core/value-types/vec2'; import { mat4, quat, vec3 } from '../core/vmath'; import { BaseNode } from './base-node'; import { Layers } from './layers'; -import { EventType } from './node-event-enum'; const v3_a = new Vec3(); const q_a = new Quat(); diff --git a/scripts/generate-declaration-cli.js b/scripts/generate-declaration-cli.js new file mode 100644 index 0000000000..6f1d739b1d --- /dev/null +++ b/scripts/generate-declaration-cli.js @@ -0,0 +1,8 @@ +const { generate } = require('./generate-declaration'); +const { existsSync } = require('fs'); +const outputFiles = generate(); +if (!outputFiles || outputFiles.some((outputFile) => !existsSync(outputFile))) { + console.error(`Failed to generate declaration files.`); +} else { + console.log(`Generate successed. Files:\n${outputFiles.join('\n')}\n`); +} \ No newline at end of file diff --git a/scripts/generate-declaration.js b/scripts/generate-declaration.js index 8923a97b55..e2e21e15e0 100644 --- a/scripts/generate-declaration.js +++ b/scripts/generate-declaration.js @@ -1,23 +1,54 @@ -const { spawn } = require('child_process'); -const { join } = require('path'); +const { spawnSync } = require('child_process'); +const { join, extname, basename, dirname } = require('path'); +const { readFileSync, existsSync } = require('fs'); +const ts = require('typescript'); const tscExecutableName = process.platform === 'win32' ? 'tsc.cmd' : 'tsc'; const tscExecutablePath = join(__dirname, '..', 'node_modules', '.bin', tscExecutableName); -const tscConfigPath = join(__dirname, '..', 'tsconfig-gendecls.json'); +const tssConfigDir = join(__dirname, '..'); +const tscConfigPath = join(tssConfigDir, 'tsconfig-gendecls.json'); -const tsc = spawn(tscExecutablePath, [ - '-p', - tscConfigPath, -]); +function generate () { + const tscConfig = ts.readConfigFile(tscConfigPath, (path) => readFileSync(path).toString()); + if (tscConfig.error) { + console.error(`Bad tsconfig.json: ${tscConfig.error.messageText}`); + return undefined; + } -tsc.stdout.on('data', (data) => { - console.log(data.toString()); -}); + const outputJSPath = join(tssConfigDir, tscConfig.config.compilerOptions.outFile); + console.log(outputJSPath); -tsc.stderr.on('data', (data) => { - console.error(data.toString()); -}); + const extName = extname(outputJSPath); + if (extName !== '.js') { + console.error(`Unexpected output extension ${extName}, please check it.`); + return undefined; + } -tsc.on('exit', (code) => { - console.log(`Exited with code ${code}`); -}); + const dirName = dirname(outputJSPath); + const baseName = basename(outputJSPath, extName); + const destExtensions = [ + '.d.ts', + '.d.ts.map', + ]; + + const destFiles = destExtensions.map((destExtension) => { + const destFile = join(dirName, baseName + destExtension); + if (existsSync(destFile)) { + console.log(`Delete old ${destFile}.`); + } + return destFile; + }); + + console.log(`Generating...`); + + spawnSync(tscExecutablePath, [ + '-p', + tscConfigPath, + ], { + stdio: [ null, process.stdout, process.stderr ] + }); + + return destFiles; +} + +module.exports = { generate }; From 5f5db237ecf26a04915c2aeadd31372cfb953a61 Mon Sep 17 00:00:00 2001 From: Yun Hsiao Wu Date: Thu, 14 Mar 2019 15:27:38 +0800 Subject: [PATCH 2/5] sampler from texture (#4037) --- cocos/3d/assets/material.ts | 18 +- cocos/3d/assets/texture-cube.ts | 3 +- cocos/3d/builtin/effects.js | 38 +++-- cocos/3d/misc/utils.ts | 8 +- cocos/assets/texture-2d.ts | 1 - cocos/assets/texture-base.ts | 184 +++++++-------------- cocos/gfx/sampler.ts | 6 +- cocos/pipeline/forward/forward-pipeline.ts | 2 +- cocos/pipeline/render-pipeline.ts | 2 +- cocos/renderer/core/pass.ts | 30 +--- cocos/renderer/core/program-lib.ts | 15 +- cocos/renderer/core/sampler-lib.ts | 35 ++++ 12 files changed, 151 insertions(+), 191 deletions(-) create mode 100644 cocos/renderer/core/sampler-lib.ts diff --git a/cocos/3d/assets/material.ts b/cocos/3d/assets/material.ts index 0cf507d003..df04e08d80 100644 --- a/cocos/3d/assets/material.ts +++ b/cocos/3d/assets/material.ts @@ -29,6 +29,7 @@ import { GFXBindingType } from '../../gfx/define'; import { GFXTextureView } from '../../gfx/texture-view'; import { Effect } from '../../renderer/core/effect'; import { IDefineMap, Pass, PassOverrides } from '../../renderer/core/pass'; +import { samplerLib } from '../../renderer/core/sampler-lib'; import { builtinResMgr } from '../builtin'; import { RenderableComponent } from '../framework/renderable-component'; import { EffectAsset } from './effect-asset'; @@ -189,7 +190,7 @@ export class Material extends Asset { } else { this._passes[passIdx].overridePipelineStates(passInfos[passIdx], overrides); } - this._onPassChange(); + this._onPassesChange(); } public onLoaded () { @@ -220,7 +221,7 @@ export class Material extends Asset { } else { this._props.fill({}); } - this._onPassChange(); + this._onPassesChange(); } protected _uploadProperty (pass: Pass, name: string, val: any) { @@ -234,15 +235,20 @@ export class Material extends Asset { pass.setUniform(handle, val); } } else if (bindingType === GFXBindingType.SAMPLER) { - const textureView = val instanceof GFXTextureView ? val : val.getGFXTextureView(); - if (!textureView) { console.warn('texture asset incomplete!'); return false; } const binding = Pass.getBindingFromHandle(handle); - pass.bindTextureView(binding, textureView); + if (val instanceof GFXTextureView) { + pass.bindTextureView(binding, val); + } else { + const textureView = val.getGFXTextureView(); + if (!textureView) { console.warn('texture asset incomplete!'); return false; } + pass.bindTextureView(binding, textureView); + pass.bindSampler(binding, samplerLib.getSampler(cc.game._gfxDevice, val.getGFXSamplerInfo())); + } } return true; } - protected _onPassChange () { + protected _onPassesChange () { let str = ''; for (const pass of this._passes) { str += pass.serializePipelineStates(); diff --git a/cocos/3d/assets/texture-cube.ts b/cocos/3d/assets/texture-cube.ts index 2d10261ad1..bf04e9debc 100644 --- a/cocos/3d/assets/texture-cube.ts +++ b/cocos/3d/assets/texture-cube.ts @@ -110,8 +110,7 @@ export class TextureCube extends TextureBase { super(); } - onLoaded () { - super.onLoaded(); + public onLoaded () { this.mipmaps = this._mipmaps; } diff --git a/cocos/3d/builtin/effects.js b/cocos/3d/builtin/effects.js index e78843034e..084d5585e9 100644 --- a/cocos/3d/builtin/effects.js +++ b/cocos/3d/builtin/effects.js @@ -10,11 +10,11 @@ export default [ "name": "builtin-particle|particle-vs-legacy:lpvs_main|tinted-fs:add", "glsl3": { "vert": `\nprecision mediump float;\nuniform Constants {\n vec4 mainTiling_Offset;\n vec4 frameTile_velLenScale;\n};\nuniform CCGlobal {\n vec4 cc_time; \n vec4 cc_screenSize; \n vec4 cc_screenScale; \n 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 mat4 cc_matWorld;\n mat4 cc_matWorldIT;\n};\nout vec2 uv;\nout vec4 color;\nvoid computeVertPos(inout vec4 pos, vec2 vertOffset\n#if USE_BILLBOARD || USE_VERTICAL_BILLBOARD\n , mat4 view\n#endif\n#if USE_STRETCHED_BILLBOARD\n , vec3 eye\n , vec4 velocity\n , float velocityScale\n , float lengthScale\n , float size\n , float xIndex\n#endif\n) {\n#if USE_BILLBOARD\n vec3 camRight = normalize(vec3(view[0][0], view[1][0], view[2][0]));\n vec3 camUp = normalize(vec3(view[0][1], view[1][1], view[2][1]));\n pos.xyz += (camRight * vertOffset.x) + (camUp * vertOffset.y);\n#elif USE_STRETCHED_BILLBOARD\n vec3 camRight = normalize(cross(pos.xyz - eye, velocity.xyz));\n vec3 camUp = velocity.xyz * velocityScale + normalize(velocity.xyz) * lengthScale * size;\n pos.xyz += (camRight * abs(vertOffset.x) * sign(vertOffset.y)) - camUp * xIndex;\n#elif USE_HORIZONTAL_BILLBOARD\n vec3 camRight = vec3(1, 0, 0);\n vec3 camUp = vec3(0, 0, -1);\n pos.xyz += (camRight * vertOffset.x) + (camUp * vertOffset.y);\n#elif USE_VERTICAL_BILLBOARD\n vec3 camRight = normalize(vec3(view[0][0], view[1][0], view[2][0]));\n vec3 camUp = vec3(0, 1, 0);\n pos.xyz += (camRight * vertOffset.x) + (camUp * vertOffset.y);\n#else\n pos.x += vertOffset.x;\n pos.y += vertOffset.y;\n#endif\n}\nvec2 computeUV(float frameIndex, vec2 vertIndex, vec2 frameTile) {\n vec2 aniUV = vec2(0, floor(frameIndex * frameTile.y));\n aniUV.x = floor(frameIndex * frameTile.x * frameTile.y - aniUV.y * frameTile.x);\n \n vertIndex.x = 1. - vertIndex.x;\n return (aniUV.xy + vertIndex) / vec2(frameTile.x, frameTile.y);\n}\nvoid rotateCorner(inout vec2 corner, float angle) {\n float xOS = cos(angle) * corner.x - sin(angle) * corner.y;\n float yOS = sin(angle) * corner.x + cos(angle) * corner.y;\n corner.x = xOS;\n corner.y = yOS;\n}\nin vec3 a_position; \nin vec3 a_texCoord; \nin vec2 a_texCoord1; \nin vec4 a_color;\n#if USE_STRETCHED_BILLBOARD\nin vec3 a_color1; \n#endif\nvec4 lpvs_main() {\n vec4 pos = vec4(a_position, 1);\n#if USE_STRETCHED_BILLBOARD\n vec4 velocity = vec4(a_color1.xyz, 0);\n#endif\n#if !USE_WORLD_SPACE\n pos = cc_matWorld * pos;\n #if USE_STRETCHED_BILLBOARD\n velocity = cc_matWorld * velocity;\n #endif\n#endif\n vec2 cornerOffset = vec2((a_texCoord.xy - 0.5) * a_texCoord1.x);\n#if !USE_STRETCHED_BILLBOARD\n rotateCorner(cornerOffset, a_texCoord1.y);\n#endif\n computeVertPos(pos, cornerOffset\n #if USE_BILLBOARD || USE_VERTICAL_BILLBOARD\n , cc_matView\n #endif\n #if USE_STRETCHED_BILLBOARD\n , cc_cameraPos.xyz\n , velocity\n , frameTile_velLenScale.z\n , frameTile_velLenScale.w\n , a_texCoord1.x\n , a_texCoord.x\n #endif\n );\n pos = cc_matViewProj * pos;\n uv = computeUV(a_texCoord.z, a_texCoord.xy, frameTile_velLenScale.xy) * mainTiling_Offset.xy + mainTiling_Offset.zw;\n color = a_color;\n return pos;\n}\nvoid main() { gl_Position = lpvs_main(); }\n`, - "frag": `\nprecision mediump float;\nuniform CCGlobal {\n vec4 cc_time; \n vec4 cc_screenSize; \n vec4 cc_screenScale; \n 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{\n return pow(gamma, vec3(2.2));\n \n}\nvec3 LinearToSRGB(vec3 linear)\n{\n return pow(linear, vec3(0.454545));\n \n}\nvec4 PostProcess(vec4 color, float scale)\n{\n#if USE_HDR\n color.rgb = SRGBToLinear(color.rgb) * scale;\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 PostProcess(col, cc_exposure.w);\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 PostProcess(col, cc_exposure.w);\n}\nout vec4 cc_FragColor;\nvoid main() { cc_FragColor = add(); }\n` + "frag": `\nprecision mediump float;\nuniform CCGlobal {\n vec4 cc_time; \n vec4 cc_screenSize; \n vec4 cc_screenScale; \n 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{\n return pow(gamma, vec3(2.2));\n \n}\nvec3 LinearToSRGB(vec3 linear)\n{\n return pow(linear, vec3(0.454545));\n \n}\nvec4 PostProcess(vec4 color, float scale)\n{\n#if CC_USE_HDR\n color.rgb = SRGBToLinear(color.rgb) * scale;\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 PostProcess(col, cc_exposure.w);\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 PostProcess(col, cc_exposure.w);\n}\nout vec4 cc_FragColor;\nvoid main() { cc_FragColor = add(); }\n` }, "glsl1": { "vert": `\nprecision mediump float;\nuniform vec4 mainTiling_Offset;\nuniform vec4 frameTile_velLenScale;\nuniform vec4 cc_time;\nuniform vec4 cc_screenSize;\nuniform vec4 cc_screenScale;\nuniform mat4 cc_matView;\nuniform mat4 cc_matViewInv;\nuniform mat4 cc_matProj;\nuniform mat4 cc_matProjInv;\nuniform mat4 cc_matViewProj;\nuniform mat4 cc_matViewProjInv;\nuniform vec4 cc_cameraPos;\nuniform vec4 cc_exposure;\nuniform vec4 cc_mainLitDir;\nuniform vec4 cc_mainLitColor;\nuniform vec4 cc_ambientSky;\nuniform vec4 cc_ambientGround;\nuniform mat4 cc_matWorld;\nuniform mat4 cc_matWorldIT;\nvarying vec2 uv;\nvarying vec4 color;\nvoid computeVertPos(inout vec4 pos, vec2 vertOffset\n#if USE_BILLBOARD || USE_VERTICAL_BILLBOARD\n , mat4 view\n#endif\n#if USE_STRETCHED_BILLBOARD\n , vec3 eye\n , vec4 velocity\n , float velocityScale\n , float lengthScale\n , float size\n , float xIndex\n#endif\n) {\n#if USE_BILLBOARD\n vec3 camRight = normalize(vec3(view[0][0], view[1][0], view[2][0]));\n vec3 camUp = normalize(vec3(view[0][1], view[1][1], view[2][1]));\n pos.xyz += (camRight * vertOffset.x) + (camUp * vertOffset.y);\n#elif USE_STRETCHED_BILLBOARD\n vec3 camRight = normalize(cross(pos.xyz - eye, velocity.xyz));\n vec3 camUp = velocity.xyz * velocityScale + normalize(velocity.xyz) * lengthScale * size;\n pos.xyz += (camRight * abs(vertOffset.x) * sign(vertOffset.y)) - camUp * xIndex;\n#elif USE_HORIZONTAL_BILLBOARD\n vec3 camRight = vec3(1, 0, 0);\n vec3 camUp = vec3(0, 0, -1);\n pos.xyz += (camRight * vertOffset.x) + (camUp * vertOffset.y);\n#elif USE_VERTICAL_BILLBOARD\n vec3 camRight = normalize(vec3(view[0][0], view[1][0], view[2][0]));\n vec3 camUp = vec3(0, 1, 0);\n pos.xyz += (camRight * vertOffset.x) + (camUp * vertOffset.y);\n#else\n pos.x += vertOffset.x;\n pos.y += vertOffset.y;\n#endif\n}\nvec2 computeUV(float frameIndex, vec2 vertIndex, vec2 frameTile) {\n vec2 aniUV = vec2(0, floor(frameIndex * frameTile.y));\n aniUV.x = floor(frameIndex * frameTile.x * frameTile.y - aniUV.y * frameTile.x);\n \n vertIndex.x = 1. - vertIndex.x;\n return (aniUV.xy + vertIndex) / vec2(frameTile.x, frameTile.y);\n}\nvoid rotateCorner(inout vec2 corner, float angle) {\n float xOS = cos(angle) * corner.x - sin(angle) * corner.y;\n float yOS = sin(angle) * corner.x + cos(angle) * corner.y;\n corner.x = xOS;\n corner.y = yOS;\n}\nattribute vec3 a_position; \nattribute vec3 a_texCoord; \nattribute vec2 a_texCoord1; \nattribute vec4 a_color;\n#if USE_STRETCHED_BILLBOARD\nattribute vec3 a_color1; \n#endif\nvec4 lpvs_main() {\n vec4 pos = vec4(a_position, 1);\n#if USE_STRETCHED_BILLBOARD\n vec4 velocity = vec4(a_color1.xyz, 0);\n#endif\n#if !USE_WORLD_SPACE\n pos = cc_matWorld * pos;\n #if USE_STRETCHED_BILLBOARD\n velocity = cc_matWorld * velocity;\n #endif\n#endif\n vec2 cornerOffset = vec2((a_texCoord.xy - 0.5) * a_texCoord1.x);\n#if !USE_STRETCHED_BILLBOARD\n rotateCorner(cornerOffset, a_texCoord1.y);\n#endif\n computeVertPos(pos, cornerOffset\n #if USE_BILLBOARD || USE_VERTICAL_BILLBOARD\n , cc_matView\n #endif\n #if USE_STRETCHED_BILLBOARD\n , cc_cameraPos.xyz\n , velocity\n , frameTile_velLenScale.z\n , frameTile_velLenScale.w\n , a_texCoord1.x\n , a_texCoord.x\n #endif\n );\n pos = cc_matViewProj * pos;\n uv = computeUV(a_texCoord.z, a_texCoord.xy, frameTile_velLenScale.xy) * mainTiling_Offset.xy + mainTiling_Offset.zw;\n color = a_color;\n return pos;\n}\nvoid main() { gl_Position = lpvs_main(); }\n`, - "frag": `\nprecision mediump float;\nuniform vec4 cc_time;\nuniform vec4 cc_screenSize;\nuniform vec4 cc_screenScale;\nuniform mat4 cc_matView;\nuniform mat4 cc_matViewInv;\nuniform mat4 cc_matProj;\nuniform mat4 cc_matProjInv;\nuniform mat4 cc_matViewProj;\nuniform mat4 cc_matViewProjInv;\nuniform vec4 cc_cameraPos;\nuniform vec4 cc_exposure;\nuniform vec4 cc_mainLitDir;\nuniform vec4 cc_mainLitColor;\nuniform vec4 cc_ambientSky;\nuniform vec4 cc_ambientGround;\nvec3 SRGBToLinear(vec3 gamma)\n{\n return pow(gamma, vec3(2.2));\n \n}\nvec3 LinearToSRGB(vec3 linear)\n{\n return pow(linear, vec3(0.454545));\n \n}\nvec4 PostProcess(vec4 color, float scale)\n{\n#if USE_HDR\n color.rgb = SRGBToLinear(color.rgb) * scale;\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 PostProcess(col, cc_exposure.w);\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 PostProcess(col, cc_exposure.w);\n}\nvoid main() { gl_FragColor = add(); }\n` + "frag": `\nprecision mediump float;\nuniform vec4 cc_time;\nuniform vec4 cc_screenSize;\nuniform vec4 cc_screenScale;\nuniform mat4 cc_matView;\nuniform mat4 cc_matViewInv;\nuniform mat4 cc_matProj;\nuniform mat4 cc_matProjInv;\nuniform mat4 cc_matViewProj;\nuniform mat4 cc_matViewProjInv;\nuniform vec4 cc_cameraPos;\nuniform vec4 cc_exposure;\nuniform vec4 cc_mainLitDir;\nuniform vec4 cc_mainLitColor;\nuniform vec4 cc_ambientSky;\nuniform vec4 cc_ambientGround;\nvec3 SRGBToLinear(vec3 gamma)\n{\n return pow(gamma, vec3(2.2));\n \n}\nvec3 LinearToSRGB(vec3 linear)\n{\n return pow(linear, vec3(0.454545));\n \n}\nvec4 PostProcess(vec4 color, float scale)\n{\n#if CC_USE_HDR\n color.rgb = SRGBToLinear(color.rgb) * scale;\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 PostProcess(col, cc_exposure.w);\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 PostProcess(col, cc_exposure.w);\n}\nvoid main() { gl_FragColor = add(); }\n` }, "builtins": {"globals":{"blocks":["CCGlobal"], "samplers":[]}, "locals":{"blocks":["CCLocal"], "samplers":[]}}, "defines": [ @@ -23,7 +23,7 @@ export default [ {"name":"USE_HORIZONTAL_BILLBOARD", "type":"boolean", "defines":[]}, {"name":"USE_VERTICAL_BILLBOARD", "type":"boolean", "defines":[]}, {"name":"USE_WORLD_SPACE", "type":"boolean", "defines":[]}, - {"name":"USE_HDR", "type":"boolean", "defines":[]} + {"name":"CC_USE_HDR", "type":"boolean", "defines":[]} ], "blocks": [ {"name": "Constants", "size": 32, "defines": [], "binding": 0, "members": [ @@ -51,15 +51,15 @@ export default [ "name": "builtin-skybox|sky-vs:vert|sky-fs:frag", "glsl3": { "vert": `\nprecision mediump float;\nin vec3 a_position;\nuniform CCGlobal {\n vec4 cc_time; \n vec4 cc_screenSize; \n vec4 cc_screenScale; \n 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};\nout vec3 viewDir;\nvec4 vert () {\n mat4 matViewRotOnly = mat4(mat3(cc_matView));\n vec4 clipPos = cc_matProj * matViewRotOnly * vec4(a_position, 1.0);\n viewDir = a_position;\n vec4 pos = clipPos;\n pos.z = clipPos.w * 0.99999;\n return pos;\n}\nvoid main() { gl_Position = vert(); }\n`, - "frag": `\nprecision mediump float;\nin vec3 viewDir;\nuniform samplerCube cubeMap;\nvec3 unpackNormal(vec4 nmap) {\n return nmap.xyz * 2.0 - 1.0;\n}\nvec3 unpackRGBE(vec4 rgbe) {\n return rgbe.rgb * pow(2.0, rgbe.a * 255.0 - 128.0);\n}\nuniform CCGlobal {\n vec4 cc_time; \n vec4 cc_screenSize; \n vec4 cc_screenScale; \n 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{\n return pow(gamma, vec3(2.2));\n \n}\nvec3 LinearToSRGB(vec3 linear)\n{\n return pow(linear, vec3(0.454545));\n \n}\nvec4 PostProcess(vec4 color, float scale)\n{\n#if USE_HDR\n color.rgb = SRGBToLinear(color.rgb) * scale;\n#endif\n return color;\n}\nvec4 frag () {\n#if USE_RGBE_CUBEMAP\n vec3 c = unpackRGBE(texture(cubeMap, viewDir));\n c = LinearToSRGB(c / (1.0 + c));\n vec4 o = vec4(c, 1.0);\n#else\n vec4 o = texture(cubeMap, viewDir);\n#endif\n return PostProcess(o, cc_exposure.w);\n}\nout vec4 cc_FragColor;\nvoid main() { cc_FragColor = frag(); }\n` + "frag": `\nprecision mediump float;\nin vec3 viewDir;\nuniform samplerCube cubeMap;\nvec3 unpackNormal(vec4 nmap) {\n return nmap.xyz * 2.0 - 1.0;\n}\nvec3 unpackRGBE(vec4 rgbe) {\n return rgbe.rgb * pow(2.0, rgbe.a * 255.0 - 128.0);\n}\nuniform CCGlobal {\n vec4 cc_time; \n vec4 cc_screenSize; \n vec4 cc_screenScale; \n 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{\n return pow(gamma, vec3(2.2));\n \n}\nvec3 LinearToSRGB(vec3 linear)\n{\n return pow(linear, vec3(0.454545));\n \n}\nvec4 PostProcess(vec4 color, float scale)\n{\n#if CC_USE_HDR\n color.rgb = SRGBToLinear(color.rgb) * scale;\n#endif\n return color;\n}\nvec4 frag () {\n#if USE_RGBE_CUBEMAP\n vec3 c = unpackRGBE(texture(cubeMap, viewDir));\n c = LinearToSRGB(c / (1.0 + c));\n vec4 o = vec4(c, 1.0);\n#else\n vec4 o = texture(cubeMap, viewDir);\n#endif\n return PostProcess(o, cc_exposure.w);\n}\nout vec4 cc_FragColor;\nvoid main() { cc_FragColor = frag(); }\n` }, "glsl1": { "vert": `\nprecision mediump float;\nattribute vec3 a_position;\nuniform vec4 cc_time;\nuniform vec4 cc_screenSize;\nuniform vec4 cc_screenScale;\nuniform mat4 cc_matView;\nuniform mat4 cc_matViewInv;\nuniform mat4 cc_matProj;\nuniform mat4 cc_matProjInv;\nuniform mat4 cc_matViewProj;\nuniform mat4 cc_matViewProjInv;\nuniform vec4 cc_cameraPos;\nuniform vec4 cc_exposure;\nuniform vec4 cc_mainLitDir;\nuniform vec4 cc_mainLitColor;\nuniform vec4 cc_ambientSky;\nuniform vec4 cc_ambientGround;\nvarying vec3 viewDir;\nvec4 vert () {\n mat4 matViewRotOnly = mat4(mat3(cc_matView));\n vec4 clipPos = cc_matProj * matViewRotOnly * vec4(a_position, 1.0);\n viewDir = a_position;\n vec4 pos = clipPos;\n pos.z = clipPos.w * 0.99999;\n return pos;\n}\nvoid main() { gl_Position = vert(); }\n`, - "frag": `\nprecision mediump float;\nvarying vec3 viewDir;\nuniform samplerCube cubeMap;\nvec3 unpackNormal(vec4 nmap) {\n return nmap.xyz * 2.0 - 1.0;\n}\nvec3 unpackRGBE(vec4 rgbe) {\n return rgbe.rgb * pow(2.0, rgbe.a * 255.0 - 128.0);\n}\nuniform vec4 cc_time;\nuniform vec4 cc_screenSize;\nuniform vec4 cc_screenScale;\nuniform mat4 cc_matView;\nuniform mat4 cc_matViewInv;\nuniform mat4 cc_matProj;\nuniform mat4 cc_matProjInv;\nuniform mat4 cc_matViewProj;\nuniform mat4 cc_matViewProjInv;\nuniform vec4 cc_cameraPos;\nuniform vec4 cc_exposure;\nuniform vec4 cc_mainLitDir;\nuniform vec4 cc_mainLitColor;\nuniform vec4 cc_ambientSky;\nuniform vec4 cc_ambientGround;\nvec3 SRGBToLinear(vec3 gamma)\n{\n return pow(gamma, vec3(2.2));\n \n}\nvec3 LinearToSRGB(vec3 linear)\n{\n return pow(linear, vec3(0.454545));\n \n}\nvec4 PostProcess(vec4 color, float scale)\n{\n#if USE_HDR\n color.rgb = SRGBToLinear(color.rgb) * scale;\n#endif\n return color;\n}\nvec4 frag () {\n#if USE_RGBE_CUBEMAP\n vec3 c = unpackRGBE(textureCube(cubeMap, viewDir));\n c = LinearToSRGB(c / (1.0 + c));\n vec4 o = vec4(c, 1.0);\n#else\n vec4 o = textureCube(cubeMap, viewDir);\n#endif\n return PostProcess(o, cc_exposure.w);\n}\nvoid main() { gl_FragColor = frag(); }\n` + "frag": `\nprecision mediump float;\nvarying vec3 viewDir;\nuniform samplerCube cubeMap;\nvec3 unpackNormal(vec4 nmap) {\n return nmap.xyz * 2.0 - 1.0;\n}\nvec3 unpackRGBE(vec4 rgbe) {\n return rgbe.rgb * pow(2.0, rgbe.a * 255.0 - 128.0);\n}\nuniform vec4 cc_time;\nuniform vec4 cc_screenSize;\nuniform vec4 cc_screenScale;\nuniform mat4 cc_matView;\nuniform mat4 cc_matViewInv;\nuniform mat4 cc_matProj;\nuniform mat4 cc_matProjInv;\nuniform mat4 cc_matViewProj;\nuniform mat4 cc_matViewProjInv;\nuniform vec4 cc_cameraPos;\nuniform vec4 cc_exposure;\nuniform vec4 cc_mainLitDir;\nuniform vec4 cc_mainLitColor;\nuniform vec4 cc_ambientSky;\nuniform vec4 cc_ambientGround;\nvec3 SRGBToLinear(vec3 gamma)\n{\n return pow(gamma, vec3(2.2));\n \n}\nvec3 LinearToSRGB(vec3 linear)\n{\n return pow(linear, vec3(0.454545));\n \n}\nvec4 PostProcess(vec4 color, float scale)\n{\n#if CC_USE_HDR\n color.rgb = SRGBToLinear(color.rgb) * scale;\n#endif\n return color;\n}\nvec4 frag () {\n#if USE_RGBE_CUBEMAP\n vec3 c = unpackRGBE(textureCube(cubeMap, viewDir));\n c = LinearToSRGB(c / (1.0 + c));\n vec4 o = vec4(c, 1.0);\n#else\n vec4 o = textureCube(cubeMap, viewDir);\n#endif\n return PostProcess(o, cc_exposure.w);\n}\nvoid main() { gl_FragColor = frag(); }\n` }, "builtins": {"globals":{"blocks":["CCGlobal"], "samplers":[]}, "locals":{"blocks":[], "samplers":[]}}, "defines": [ - {"name":"USE_HDR", "type":"boolean", "defines":[]}, + {"name":"CC_USE_HDR", "type":"boolean", "defines":[]}, {"name":"USE_RGBE_CUBEMAP", "type":"boolean", "defines":[]} ], "blocks": [], @@ -106,11 +106,11 @@ export default [ "name": "builtin-standard|standard-vs:vert|standard-fs:frag", "glsl3": { "vert": `\nprecision mediump float;\nuniform CCGlobal {\n vec4 cc_time; \n vec4 cc_screenSize; \n vec4 cc_screenScale; \n 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 mat4 cc_matWorld;\n mat4 cc_matWorldIT;\n};\nuniform Constants {\n vec4 tilingOffset;\n vec4 albedo;\n vec4 albedoScale; \n vec4 pbrParams; \n vec4 pbrScale; \n vec4 emissive;\n vec4 emissiveScale;\n};\n#if CC_USE_SKINNING\nin vec4 a_weights;\nin vec4 a_joints;\nuniform CCSkinning {\n mat4 cc_matJoint[128];\n vec4 cc_jointsTextureSize;\n};\n#if CC_USE_JOINTS_TEXTURE\nuniform sampler2D cc_jointsTexture;\nmat4 getBoneMatrix(const in float i) {\n float size = cc_jointsTextureSize.x;\n float j = i * 4.0;\n float x = mod(j, size);\n float y = floor(j / size);\n float dx = 1.0 / size;\n float dy = 1.0 / size;\n y = dy * (y + 0.5);\n vec4 v1 = texture(cc_jointsTexture, vec2(dx * (x + 0.5), y));\n vec4 v2 = texture(cc_jointsTexture, vec2(dx * (x + 1.5), y));\n vec4 v3 = texture(cc_jointsTexture, vec2(dx * (x + 2.5), y));\n vec4 v4 = texture(cc_jointsTexture, vec2(dx * (x + 3.5), y));\n return mat4(v1, v2, v3, v4);\n}\n#else\nmat4 getBoneMatrix(const in float i) {\n return cc_matJoint[int(i)];\n}\n#endif\nmat4 skinMatrix() {\n return\n getBoneMatrix(a_joints.x) * a_weights.x +\n getBoneMatrix(a_joints.y) * a_weights.y +\n getBoneMatrix(a_joints.z) * a_weights.z +\n getBoneMatrix(a_joints.w) * a_weights.w;\n}\nvoid skinVertex(inout vec4 a1) {\n mat4 m = skinMatrix();\n a1 = m * a1;\n}\nvoid skinVertex(inout vec4 a1, inout vec4 a2) {\n mat4 m = skinMatrix();\n a1 = m * a1;\n a2 = m * a2;\n}\nvoid skinVertex(inout vec4 a1, inout vec4 a2, inout vec4 a3) {\n mat4 m = skinMatrix();\n a1 = m * a1;\n a2 = m * a2;\n a3 = m * a3;\n}\n#endif\nin vec3 a_position;\nin vec3 a_normal;\nout vec3 v_worldPos;\nout vec3 v_worldNormal;\n#if USE_ALBEDO_MAP || USE_NORMAL_MAP || USE_PBR_MAP || USE_EMISSIVE_MAP\n in vec2 a_texCoord;\n out vec2 v_uv;\n#endif\nvec4 vert () {\n vec4 pos = vec4(a_position, 1.0);\n vec4 normal = vec4(a_normal, 0.0);\n #if CC_USE_SKINNING\n skinVertex(pos, normal);\n #endif\n v_worldPos = (cc_matWorld * pos).xyz;\n v_worldNormal = (cc_matWorldIT * normal).xyz;\n #if USE_ALBEDO_MAP || USE_NORMAL_MAP || USE_PBR_MAP || USE_EMISSIVE_MAP\n v_uv = a_texCoord * tilingOffset.xy + tilingOffset.zw;\n #endif\n return cc_matViewProj * cc_matWorld * pos;\n}\nvoid main() { gl_Position = vert(); }\n`, - "frag": `\nprecision mediump float;\nuniform CCGlobal {\n vec4 cc_time; \n vec4 cc_screenSize; \n vec4 cc_screenScale; \n 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#define MAX_LIGHTS 2\nuniform CCForwardLight {\n vec4 cc_sphereLitPos[2]; \n vec4 cc_sphereLitSizeRange[2]; \n vec4 cc_sphereLitColor[2]; \n vec4 cc_spotLitPosSize[2]; \n vec4 cc_spotLitDirRange[2]; \n vec4 cc_spotLitColor[2]; \n};\n#define PI 3.14159265359\n#define PI2 6.28318530718\n#define EPSILON 1e-6\n#define LOG2 1.442695\n#define saturate(a) clamp( a, 0.0, 1.0 )\n#define FP_MAX = 65504.0;\n#define FP_SCALE (1.0/1024.0);\n#define FP_SCALE_INV 1024.0;\nvec3 SRGBToLinear(vec3 gamma)\n{\n return pow(gamma, vec3(2.2));\n \n}\nvec3 LinearToSRGB(vec3 linear)\n{\n return pow(linear, vec3(0.454545));\n \n}\nfloat SmoothDistAtt(float distSqr, float invSqrAttRadius)\n{\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 GetDistAtt(float distSqr, float invSqrAttRadius)\n{\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{\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{\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{\n return (roughness*0.25 + 0.25) * GGXMobile(roughness, NoH, H, N);\n}\nvec3 BRDFApprox(vec3 specular, float roughness, float NoV)\n{\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}\nuniform Constants {\n vec4 tilingOffset;\n vec4 albedo;\n vec4 albedoScale; \n vec4 pbrParams; \n vec4 pbrScale; \n vec4 emissive;\n vec4 emissiveScale;\n};\nin vec3 v_worldPos;\nin vec3 v_worldNormal;\n#if USE_ALBEDO_MAP || USE_NORMAL_MAP || USE_PBR_MAP || USE_EMISSIVE_MAP\n in vec2 v_uv;\n#endif\n#if USE_ALBEDO_MAP\n uniform sampler2D albedoMap;\n#endif\n#if USE_NORMAL_MAP\n uniform sampler2D normalMap;\n#endif\n#if USE_PBR_MAP\n uniform sampler2D pbrMap;\n#endif\n#if USE_EMISSIVE_MAP\n uniform sampler2D emissiveMap;\n#endif\n#ifdef USE_IBL\n uniform samplerCube envMap;\n#endif\n#if USE_NORMAL_MAP\n vec3 getNormal(vec3 pos, vec3 normal) {\n vec3 q0 = vec3( dFdx( pos.x ), dFdx( pos.y ), dFdx( pos.z ) );\n vec3 q1 = vec3( dFdy( pos.x ), dFdy( pos.y ), dFdy( pos.z ) );\n vec2 st0 = dFdx( v_uv.st );\n vec2 st1 = dFdy( v_uv.st );\n vec3 S = normalize( q0 * st1.t - q1 * st0.t );\n vec3 T = normalize( -q0 * st1.s + q1 * st0.s );\n vec3 N = normal;\n vec3 mapN = texture(normalMap, v_uv).rgb * 2.0 - 1.0;\n mapN.xy = 1.0 * mapN.xy;\n mat3 tsn = mat3( S, T, N );\n return normalize( tsn * mapN );\n }\n#endif\nvec4 frag () {\n #if USE_ALBEDO_MAP\n vec4 baseColor = texture(albedoMap, v_uv);\n #else\n vec4 baseColor = albedo;\n #endif\n baseColor.rgb *= albedoScale.rgb;\n baseColor.rgb = SRGBToLinear(baseColor.rgb);\n #if USE_ALPHA_TEST\n if(baseColor.a < albedoScale.a)\n discard;\n #endif\n vec3 N = normalize(v_worldNormal);\n #if USE_NORMAL_MAP\n N = getNormal(v_worldPos, N);\n #endif\n #if USE_PBR_MAP\n vec4 pbr = texture(pbrMap, v_uv);\n #else\n vec4 pbr = pbrParams;\n #endif\n pbr *= pbrScale;\n float roughness = clamp(pbr.r, 0.04, 1.0);\n float metallic = clamp(pbr.g, 0.0, 1.0);\n vec3 diffuse = baseColor.rgb * 0.96 * (1.0 - metallic);\n vec3 specular = mix(vec3(0.04), baseColor.rgb, metallic);\n vec3 V = normalize(cc_cameraPos.xyz - v_worldPos);\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, roughness, NV);\n vec3 specularContrib = specular * CalcSpecular(roughness, NH, H, N);\n vec3 diffuseContrib = diffuse / 3.14159265359;\n vec3 finalColor = NL * cc_mainLitColor.rgb * cc_mainLitColor.w * (diffuseContrib + specularContrib);\n for (int i = 0; i < 2; i++) {\n \n vec3 PLU = cc_sphereLitPos[i].xyz - v_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 pDistSqr = dot(PLU, PLU);\n float litRadius = cc_sphereLitSizeRange[i].x;\n float litRadiusSqr = litRadius * litRadius;\n float illum = 3.14159265359 * (litRadiusSqr / max(litRadiusSqr , pDistSqr));\n float pInvSqrAttRadius = 1.0 / max(cc_sphereLitSizeRange[i].y, 0.01);\n pInvSqrAttRadius *= pInvSqrAttRadius;\n float pAtt = SmoothDistAtt(pDistSqr, pInvSqrAttRadius);\n vec3 pSpec = specular * CalcSpecular(roughness, PNH, PH, N);\n finalColor += PNL * cc_sphereLitColor[i].rgb * cc_sphereLitColor[i].w * illum * pAtt * (diffuseContrib + pSpec);\n vec3 SLU = cc_spotLitPosSize[i].xyz - v_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 cosConeAngle = max(dot(-cc_spotLitDirRange[i].xyz, SL), 0.01);\n float sInvSqrAttRadius = 1.0 / max(cc_spotLitDirRange[i].w, 0.01);\n float sDistSqr = dot(SLU, SLU);\n float sAtt = GetDistAtt(sDistSqr, sInvSqrAttRadius);\n sAtt *= cosConeAngle;\n vec3 sSpec = specular * CalcSpecular(roughness, SNH, SH, N);\n finalColor += SNL * cc_spotLitColor[i].rgb * cc_spotLitColor[i].w * sAtt * (diffuseContrib + sSpec);\n }\n float fAmb = dot(N, vec3(0.0, -1.0, 0.0)) * 0.5 + 0.5;\n vec3 ambDiff = mix(cc_ambientSky.rgb, cc_ambientGround.rgb, fAmb) * cc_ambientSky.w;\n finalColor += (ambDiff.rgb * diffuse);\n#if USE_IBL\n vec3 R = normalize(reflect(-V, N));\n vec4 env = texture(envMap, R);\n env.rgb = SRGBToLinear(env.rgb) * cc_ambientSky.w;\n finalColor += (env.rgb * specular);\n#endif\n#if USE_HDR\n finalColor *= (1.0/1024.0);;\n#else\n finalColor *= cc_exposure.x;\n finalColor = LinearToSRGB(finalColor);\n#endif\n return vec4(finalColor, baseColor.a);\n}\nout vec4 cc_FragColor;\nvoid main() { cc_FragColor = frag(); }\n` + "frag": `\nprecision mediump float;\nuniform CCGlobal {\n vec4 cc_time; \n vec4 cc_screenSize; \n vec4 cc_screenScale; \n 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#define MAX_LIGHTS 2\nuniform CCForwardLight {\n vec4 cc_sphereLitPos[2]; \n vec4 cc_sphereLitSizeRange[2]; \n vec4 cc_sphereLitColor[2]; \n vec4 cc_spotLitPosSize[2]; \n vec4 cc_spotLitDirRange[2]; \n vec4 cc_spotLitColor[2]; \n};\n#define PI 3.14159265359\n#define PI2 6.28318530718\n#define EPSILON 1e-6\n#define LOG2 1.442695\n#define saturate(a) clamp( a, 0.0, 1.0 )\n#define FP_MAX = 65504.0;\n#define FP_SCALE (1.0/1024.0);\n#define FP_SCALE_INV 1024.0;\nvec3 SRGBToLinear(vec3 gamma)\n{\n return pow(gamma, vec3(2.2));\n \n}\nvec3 LinearToSRGB(vec3 linear)\n{\n return pow(linear, vec3(0.454545));\n \n}\nfloat SmoothDistAtt(float distSqr, float invSqrAttRadius)\n{\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 GetDistAtt(float distSqr, float invSqrAttRadius)\n{\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{\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{\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{\n return (roughness*0.25 + 0.25) * GGXMobile(roughness, NoH, H, N);\n}\nvec3 BRDFApprox(vec3 specular, float roughness, float NoV)\n{\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}\nuniform Constants {\n vec4 tilingOffset;\n vec4 albedo;\n vec4 albedoScale; \n vec4 pbrParams; \n vec4 pbrScale; \n vec4 emissive;\n vec4 emissiveScale;\n};\nin vec3 v_worldPos;\nin vec3 v_worldNormal;\n#if USE_ALBEDO_MAP || USE_NORMAL_MAP || USE_PBR_MAP || USE_EMISSIVE_MAP\n in vec2 v_uv;\n#endif\n#if USE_ALBEDO_MAP\n uniform sampler2D albedoMap;\n#endif\n#if USE_NORMAL_MAP\n uniform sampler2D normalMap;\n#endif\n#if USE_PBR_MAP\n uniform sampler2D pbrMap;\n#endif\n#if USE_EMISSIVE_MAP\n uniform sampler2D emissiveMap;\n#endif\n#ifdef USE_IBL\n uniform samplerCube envMap;\n#endif\n#if USE_NORMAL_MAP\n vec3 getNormal(vec3 pos, vec3 normal) {\n vec3 q0 = vec3( dFdx( pos.x ), dFdx( pos.y ), dFdx( pos.z ) );\n vec3 q1 = vec3( dFdy( pos.x ), dFdy( pos.y ), dFdy( pos.z ) );\n vec2 st0 = dFdx( v_uv.st );\n vec2 st1 = dFdy( v_uv.st );\n vec3 S = normalize( q0 * st1.t - q1 * st0.t );\n vec3 T = normalize( -q0 * st1.s + q1 * st0.s );\n vec3 N = normal;\n vec3 mapN = texture(normalMap, v_uv).rgb * 2.0 - 1.0;\n mapN.xy = 1.0 * mapN.xy;\n mat3 tsn = mat3( S, T, N );\n return normalize( tsn * mapN );\n }\n#endif\nvec4 frag () {\n #if USE_ALBEDO_MAP\n vec4 baseColor = texture(albedoMap, v_uv);\n #else\n vec4 baseColor = albedo;\n #endif\n baseColor.rgb *= albedoScale.rgb;\n baseColor.rgb = SRGBToLinear(baseColor.rgb);\n #if USE_ALPHA_TEST\n if(baseColor.a < albedoScale.a)\n discard;\n #endif\n vec3 N = normalize(v_worldNormal);\n #if USE_NORMAL_MAP\n N = getNormal(v_worldPos, N);\n #endif\n #if USE_PBR_MAP\n vec4 pbr = texture(pbrMap, v_uv);\n #else\n vec4 pbr = pbrParams;\n #endif\n pbr *= pbrScale;\n float roughness = clamp(pbr.ROUGHNESS_CHANNEL, 0.04, 1.0);\n float metallic = clamp(pbr.METALLIC_CHANNEL, 0.0, 1.0);\n vec3 diffuse = baseColor.rgb * 0.96 * (1.0 - metallic);\n vec3 specular = mix(vec3(0.04), baseColor.rgb, metallic);\n vec3 V = normalize(cc_cameraPos.xyz - v_worldPos);\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, roughness, NV);\n vec3 specularContrib = specular * CalcSpecular(roughness, NH, H, N);\n vec3 diffuseContrib = diffuse / 3.14159265359;\n vec3 finalColor = NL * cc_mainLitColor.rgb * cc_mainLitColor.w * (diffuseContrib + specularContrib);\n for (int i = 0; i < 2; i++) {\n \n vec3 PLU = cc_sphereLitPos[i].xyz - v_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 pDistSqr = dot(PLU, PLU);\n float litRadius = cc_sphereLitSizeRange[i].x;\n float litRadiusSqr = litRadius * litRadius;\n float illum = 3.14159265359 * (litRadiusSqr / max(litRadiusSqr , pDistSqr));\n float pInvSqrAttRadius = 1.0 / max(cc_sphereLitSizeRange[i].y, 0.01);\n pInvSqrAttRadius *= pInvSqrAttRadius;\n float pAtt = SmoothDistAtt(pDistSqr, pInvSqrAttRadius);\n vec3 pSpec = specular * CalcSpecular(roughness, PNH, PH, N);\n finalColor += PNL * cc_sphereLitColor[i].rgb * cc_sphereLitColor[i].w * illum * pAtt * (diffuseContrib + pSpec);\n vec3 SLU = cc_spotLitPosSize[i].xyz - v_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 cosConeAngle = max(dot(-cc_spotLitDirRange[i].xyz, SL), 0.01);\n float sInvSqrAttRadius = 1.0 / max(cc_spotLitDirRange[i].w, 0.01);\n float sDistSqr = dot(SLU, SLU);\n float sAtt = GetDistAtt(sDistSqr, sInvSqrAttRadius);\n sAtt *= cosConeAngle;\n vec3 sSpec = specular * CalcSpecular(roughness, SNH, SH, N);\n finalColor += SNL * cc_spotLitColor[i].rgb * cc_spotLitColor[i].w * sAtt * (diffuseContrib + sSpec);\n }\n float fAmb = dot(N, vec3(0.0, -1.0, 0.0)) * 0.5 + 0.5;\n vec3 ambDiff = mix(cc_ambientSky.rgb, cc_ambientGround.rgb, fAmb) * cc_ambientSky.w;\n finalColor += (ambDiff.rgb * diffuse);\n#if USE_IBL\n vec3 R = normalize(reflect(-V, N));\n vec4 env = texture(envMap, R);\n env.rgb = SRGBToLinear(env.rgb) * cc_ambientSky.w;\n finalColor += (env.rgb * specular);\n#endif\n#if CC_USE_HDR\n finalColor *= (1.0/1024.0);;\n#else\n finalColor *= cc_exposure.x;\n finalColor = LinearToSRGB(finalColor);\n#endif\n return vec4(finalColor, baseColor.a);\n}\nout vec4 cc_FragColor;\nvoid main() { cc_FragColor = frag(); }\n` }, "glsl1": { "vert": `\nprecision mediump float;\nuniform vec4 cc_time;\nuniform vec4 cc_screenSize;\nuniform vec4 cc_screenScale;\nuniform mat4 cc_matView;\nuniform mat4 cc_matViewInv;\nuniform mat4 cc_matProj;\nuniform mat4 cc_matProjInv;\nuniform mat4 cc_matViewProj;\nuniform mat4 cc_matViewProjInv;\nuniform vec4 cc_cameraPos;\nuniform vec4 cc_exposure;\nuniform vec4 cc_mainLitDir;\nuniform vec4 cc_mainLitColor;\nuniform vec4 cc_ambientSky;\nuniform vec4 cc_ambientGround;\nuniform mat4 cc_matWorld;\nuniform mat4 cc_matWorldIT;\nuniform vec4 tilingOffset;\nuniform vec4 albedo;\nuniform vec4 albedoScale;\nuniform vec4 pbrParams;\nuniform vec4 pbrScale;\nuniform vec4 emissive;\nuniform vec4 emissiveScale;\n#if CC_USE_SKINNING\nattribute vec4 a_weights;\nattribute vec4 a_joints;\nuniform mat4 cc_matJoint[128];\nuniform vec4 cc_jointsTextureSize;\n#if CC_USE_JOINTS_TEXTURE\nuniform sampler2D cc_jointsTexture;\nmat4 getBoneMatrix(const in float i) {\n float size = cc_jointsTextureSize.x;\n float j = i * 4.0;\n float x = mod(j, size);\n float y = floor(j / size);\n float dx = 1.0 / size;\n float dy = 1.0 / size;\n y = dy * (y + 0.5);\n vec4 v1 = texture2D(cc_jointsTexture, vec2(dx * (x + 0.5), y));\n vec4 v2 = texture2D(cc_jointsTexture, vec2(dx * (x + 1.5), y));\n vec4 v3 = texture2D(cc_jointsTexture, vec2(dx * (x + 2.5), y));\n vec4 v4 = texture2D(cc_jointsTexture, vec2(dx * (x + 3.5), y));\n return mat4(v1, v2, v3, v4);\n}\n#else\nmat4 getBoneMatrix(const in float i) {\n return cc_matJoint[int(i)];\n}\n#endif\nmat4 skinMatrix() {\n return\n getBoneMatrix(a_joints.x) * a_weights.x +\n getBoneMatrix(a_joints.y) * a_weights.y +\n getBoneMatrix(a_joints.z) * a_weights.z +\n getBoneMatrix(a_joints.w) * a_weights.w;\n}\nvoid skinVertex(inout vec4 a1) {\n mat4 m = skinMatrix();\n a1 = m * a1;\n}\nvoid skinVertex(inout vec4 a1, inout vec4 a2) {\n mat4 m = skinMatrix();\n a1 = m * a1;\n a2 = m * a2;\n}\nvoid skinVertex(inout vec4 a1, inout vec4 a2, inout vec4 a3) {\n mat4 m = skinMatrix();\n a1 = m * a1;\n a2 = m * a2;\n a3 = m * a3;\n}\n#endif\nattribute vec3 a_position;\nattribute vec3 a_normal;\nvarying vec3 v_worldPos;\nvarying vec3 v_worldNormal;\n#if USE_ALBEDO_MAP || USE_NORMAL_MAP || USE_PBR_MAP || USE_EMISSIVE_MAP\n attribute vec2 a_texCoord;\n varying vec2 v_uv;\n#endif\nvec4 vert () {\n vec4 pos = vec4(a_position, 1.0);\n vec4 normal = vec4(a_normal, 0.0);\n #if CC_USE_SKINNING\n skinVertex(pos, normal);\n #endif\n v_worldPos = (cc_matWorld * pos).xyz;\n v_worldNormal = (cc_matWorldIT * normal).xyz;\n #if USE_ALBEDO_MAP || USE_NORMAL_MAP || USE_PBR_MAP || USE_EMISSIVE_MAP\n v_uv = a_texCoord * tilingOffset.xy + tilingOffset.zw;\n #endif\n return cc_matViewProj * cc_matWorld * pos;\n}\nvoid main() { gl_Position = vert(); }\n`, - "frag": `\nprecision mediump float;\nuniform vec4 cc_time;\nuniform vec4 cc_screenSize;\nuniform vec4 cc_screenScale;\nuniform mat4 cc_matView;\nuniform mat4 cc_matViewInv;\nuniform mat4 cc_matProj;\nuniform mat4 cc_matProjInv;\nuniform mat4 cc_matViewProj;\nuniform mat4 cc_matViewProjInv;\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#define MAX_LIGHTS 2\nuniform vec4 cc_sphereLitPos[2];\nuniform vec4 cc_sphereLitSizeRange[2];\nuniform vec4 cc_sphereLitColor[2];\nuniform vec4 cc_spotLitPosSize[2];\nuniform vec4 cc_spotLitDirRange[2];\nuniform vec4 cc_spotLitColor[2];\n#define PI 3.14159265359\n#define PI2 6.28318530718\n#define EPSILON 1e-6\n#define LOG2 1.442695\n#define saturate(a) clamp( a, 0.0, 1.0 )\n#define FP_MAX = 65504.0;\n#define FP_SCALE (1.0/1024.0);\n#define FP_SCALE_INV 1024.0;\nvec3 SRGBToLinear(vec3 gamma)\n{\n return pow(gamma, vec3(2.2));\n \n}\nvec3 LinearToSRGB(vec3 linear)\n{\n return pow(linear, vec3(0.454545));\n \n}\nfloat SmoothDistAtt(float distSqr, float invSqrAttRadius)\n{\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 GetDistAtt(float distSqr, float invSqrAttRadius)\n{\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{\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{\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{\n return (roughness*0.25 + 0.25) * GGXMobile(roughness, NoH, H, N);\n}\nvec3 BRDFApprox(vec3 specular, float roughness, float NoV)\n{\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}\nuniform vec4 tilingOffset;\nuniform vec4 albedo;\nuniform vec4 albedoScale;\nuniform vec4 pbrParams;\nuniform vec4 pbrScale;\nuniform vec4 emissive;\nuniform vec4 emissiveScale;\nvarying vec3 v_worldPos;\nvarying vec3 v_worldNormal;\n#if USE_ALBEDO_MAP || USE_NORMAL_MAP || USE_PBR_MAP || USE_EMISSIVE_MAP\n varying vec2 v_uv;\n#endif\n#if USE_ALBEDO_MAP\n uniform sampler2D albedoMap;\n#endif\n#if USE_NORMAL_MAP\n uniform sampler2D normalMap;\n#endif\n#if USE_PBR_MAP\n uniform sampler2D pbrMap;\n#endif\n#if USE_EMISSIVE_MAP\n uniform sampler2D emissiveMap;\n#endif\n#ifdef USE_IBL\n uniform samplerCube envMap;\n#endif\n#if USE_NORMAL_MAP\n vec3 getNormal(vec3 pos, vec3 normal) {\n vec3 q0 = vec3( dFdx( pos.x ), dFdx( pos.y ), dFdx( pos.z ) );\n vec3 q1 = vec3( dFdy( pos.x ), dFdy( pos.y ), dFdy( pos.z ) );\n vec2 st0 = dFdx( v_uv.st );\n vec2 st1 = dFdy( v_uv.st );\n vec3 S = normalize( q0 * st1.t - q1 * st0.t );\n vec3 T = normalize( -q0 * st1.s + q1 * st0.s );\n vec3 N = normal;\n vec3 mapN = texture2D(normalMap, v_uv).rgb * 2.0 - 1.0;\n mapN.xy = 1.0 * mapN.xy;\n mat3 tsn = mat3( S, T, N );\n return normalize( tsn * mapN );\n }\n#endif\nvec4 frag () {\n #if USE_ALBEDO_MAP\n vec4 baseColor = texture2D(albedoMap, v_uv);\n #else\n vec4 baseColor = albedo;\n #endif\n baseColor.rgb *= albedoScale.rgb;\n baseColor.rgb = SRGBToLinear(baseColor.rgb);\n #if USE_ALPHA_TEST\n if(baseColor.a < albedoScale.a)\n discard;\n #endif\n vec3 N = normalize(v_worldNormal);\n #if USE_NORMAL_MAP\n N = getNormal(v_worldPos, N);\n #endif\n #if USE_PBR_MAP\n vec4 pbr = texture2D(pbrMap, v_uv);\n #else\n vec4 pbr = pbrParams;\n #endif\n pbr *= pbrScale;\n float roughness = clamp(pbr.r, 0.04, 1.0);\n float metallic = clamp(pbr.g, 0.0, 1.0);\n vec3 diffuse = baseColor.rgb * 0.96 * (1.0 - metallic);\n vec3 specular = mix(vec3(0.04), baseColor.rgb, metallic);\n vec3 V = normalize(cc_cameraPos.xyz - v_worldPos);\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, roughness, NV);\n vec3 specularContrib = specular * CalcSpecular(roughness, NH, H, N);\n vec3 diffuseContrib = diffuse / 3.14159265359;\n vec3 finalColor = NL * cc_mainLitColor.rgb * cc_mainLitColor.w * (diffuseContrib + specularContrib);\n for (int i = 0; i < 2; i++) {\n \n vec3 PLU = cc_sphereLitPos[i].xyz - v_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 pDistSqr = dot(PLU, PLU);\n float litRadius = cc_sphereLitSizeRange[i].x;\n float litRadiusSqr = litRadius * litRadius;\n float illum = 3.14159265359 * (litRadiusSqr / max(litRadiusSqr , pDistSqr));\n float pInvSqrAttRadius = 1.0 / max(cc_sphereLitSizeRange[i].y, 0.01);\n pInvSqrAttRadius *= pInvSqrAttRadius;\n float pAtt = SmoothDistAtt(pDistSqr, pInvSqrAttRadius);\n vec3 pSpec = specular * CalcSpecular(roughness, PNH, PH, N);\n finalColor += PNL * cc_sphereLitColor[i].rgb * cc_sphereLitColor[i].w * illum * pAtt * (diffuseContrib + pSpec);\n vec3 SLU = cc_spotLitPosSize[i].xyz - v_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 cosConeAngle = max(dot(-cc_spotLitDirRange[i].xyz, SL), 0.01);\n float sInvSqrAttRadius = 1.0 / max(cc_spotLitDirRange[i].w, 0.01);\n float sDistSqr = dot(SLU, SLU);\n float sAtt = GetDistAtt(sDistSqr, sInvSqrAttRadius);\n sAtt *= cosConeAngle;\n vec3 sSpec = specular * CalcSpecular(roughness, SNH, SH, N);\n finalColor += SNL * cc_spotLitColor[i].rgb * cc_spotLitColor[i].w * sAtt * (diffuseContrib + sSpec);\n }\n float fAmb = dot(N, vec3(0.0, -1.0, 0.0)) * 0.5 + 0.5;\n vec3 ambDiff = mix(cc_ambientSky.rgb, cc_ambientGround.rgb, fAmb) * cc_ambientSky.w;\n finalColor += (ambDiff.rgb * diffuse);\n#if USE_IBL\n vec3 R = normalize(reflect(-V, N));\n vec4 env = textureCube(envMap, R);\n env.rgb = SRGBToLinear(env.rgb) * cc_ambientSky.w;\n finalColor += (env.rgb * specular);\n#endif\n#if USE_HDR\n finalColor *= (1.0/1024.0);;\n#else\n finalColor *= cc_exposure.x;\n finalColor = LinearToSRGB(finalColor);\n#endif\n return vec4(finalColor, baseColor.a);\n}\nvoid main() { gl_FragColor = frag(); }\n` + "frag": `\nprecision mediump float;\nuniform vec4 cc_time;\nuniform vec4 cc_screenSize;\nuniform vec4 cc_screenScale;\nuniform mat4 cc_matView;\nuniform mat4 cc_matViewInv;\nuniform mat4 cc_matProj;\nuniform mat4 cc_matProjInv;\nuniform mat4 cc_matViewProj;\nuniform mat4 cc_matViewProjInv;\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#define MAX_LIGHTS 2\nuniform vec4 cc_sphereLitPos[2];\nuniform vec4 cc_sphereLitSizeRange[2];\nuniform vec4 cc_sphereLitColor[2];\nuniform vec4 cc_spotLitPosSize[2];\nuniform vec4 cc_spotLitDirRange[2];\nuniform vec4 cc_spotLitColor[2];\n#define PI 3.14159265359\n#define PI2 6.28318530718\n#define EPSILON 1e-6\n#define LOG2 1.442695\n#define saturate(a) clamp( a, 0.0, 1.0 )\n#define FP_MAX = 65504.0;\n#define FP_SCALE (1.0/1024.0);\n#define FP_SCALE_INV 1024.0;\nvec3 SRGBToLinear(vec3 gamma)\n{\n return pow(gamma, vec3(2.2));\n \n}\nvec3 LinearToSRGB(vec3 linear)\n{\n return pow(linear, vec3(0.454545));\n \n}\nfloat SmoothDistAtt(float distSqr, float invSqrAttRadius)\n{\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 GetDistAtt(float distSqr, float invSqrAttRadius)\n{\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{\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{\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{\n return (roughness*0.25 + 0.25) * GGXMobile(roughness, NoH, H, N);\n}\nvec3 BRDFApprox(vec3 specular, float roughness, float NoV)\n{\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}\nuniform vec4 tilingOffset;\nuniform vec4 albedo;\nuniform vec4 albedoScale;\nuniform vec4 pbrParams;\nuniform vec4 pbrScale;\nuniform vec4 emissive;\nuniform vec4 emissiveScale;\nvarying vec3 v_worldPos;\nvarying vec3 v_worldNormal;\n#if USE_ALBEDO_MAP || USE_NORMAL_MAP || USE_PBR_MAP || USE_EMISSIVE_MAP\n varying vec2 v_uv;\n#endif\n#if USE_ALBEDO_MAP\n uniform sampler2D albedoMap;\n#endif\n#if USE_NORMAL_MAP\n uniform sampler2D normalMap;\n#endif\n#if USE_PBR_MAP\n uniform sampler2D pbrMap;\n#endif\n#if USE_EMISSIVE_MAP\n uniform sampler2D emissiveMap;\n#endif\n#ifdef USE_IBL\n uniform samplerCube envMap;\n#endif\n#if USE_NORMAL_MAP\n vec3 getNormal(vec3 pos, vec3 normal) {\n vec3 q0 = vec3( dFdx( pos.x ), dFdx( pos.y ), dFdx( pos.z ) );\n vec3 q1 = vec3( dFdy( pos.x ), dFdy( pos.y ), dFdy( pos.z ) );\n vec2 st0 = dFdx( v_uv.st );\n vec2 st1 = dFdy( v_uv.st );\n vec3 S = normalize( q0 * st1.t - q1 * st0.t );\n vec3 T = normalize( -q0 * st1.s + q1 * st0.s );\n vec3 N = normal;\n vec3 mapN = texture2D(normalMap, v_uv).rgb * 2.0 - 1.0;\n mapN.xy = 1.0 * mapN.xy;\n mat3 tsn = mat3( S, T, N );\n return normalize( tsn * mapN );\n }\n#endif\nvec4 frag () {\n #if USE_ALBEDO_MAP\n vec4 baseColor = texture2D(albedoMap, v_uv);\n #else\n vec4 baseColor = albedo;\n #endif\n baseColor.rgb *= albedoScale.rgb;\n baseColor.rgb = SRGBToLinear(baseColor.rgb);\n #if USE_ALPHA_TEST\n if(baseColor.a < albedoScale.a)\n discard;\n #endif\n vec3 N = normalize(v_worldNormal);\n #if USE_NORMAL_MAP\n N = getNormal(v_worldPos, N);\n #endif\n #if USE_PBR_MAP\n vec4 pbr = texture2D(pbrMap, v_uv);\n #else\n vec4 pbr = pbrParams;\n #endif\n pbr *= pbrScale;\n float roughness = clamp(pbr.ROUGHNESS_CHANNEL, 0.04, 1.0);\n float metallic = clamp(pbr.METALLIC_CHANNEL, 0.0, 1.0);\n vec3 diffuse = baseColor.rgb * 0.96 * (1.0 - metallic);\n vec3 specular = mix(vec3(0.04), baseColor.rgb, metallic);\n vec3 V = normalize(cc_cameraPos.xyz - v_worldPos);\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, roughness, NV);\n vec3 specularContrib = specular * CalcSpecular(roughness, NH, H, N);\n vec3 diffuseContrib = diffuse / 3.14159265359;\n vec3 finalColor = NL * cc_mainLitColor.rgb * cc_mainLitColor.w * (diffuseContrib + specularContrib);\n for (int i = 0; i < 2; i++) {\n \n vec3 PLU = cc_sphereLitPos[i].xyz - v_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 pDistSqr = dot(PLU, PLU);\n float litRadius = cc_sphereLitSizeRange[i].x;\n float litRadiusSqr = litRadius * litRadius;\n float illum = 3.14159265359 * (litRadiusSqr / max(litRadiusSqr , pDistSqr));\n float pInvSqrAttRadius = 1.0 / max(cc_sphereLitSizeRange[i].y, 0.01);\n pInvSqrAttRadius *= pInvSqrAttRadius;\n float pAtt = SmoothDistAtt(pDistSqr, pInvSqrAttRadius);\n vec3 pSpec = specular * CalcSpecular(roughness, PNH, PH, N);\n finalColor += PNL * cc_sphereLitColor[i].rgb * cc_sphereLitColor[i].w * illum * pAtt * (diffuseContrib + pSpec);\n vec3 SLU = cc_spotLitPosSize[i].xyz - v_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 cosConeAngle = max(dot(-cc_spotLitDirRange[i].xyz, SL), 0.01);\n float sInvSqrAttRadius = 1.0 / max(cc_spotLitDirRange[i].w, 0.01);\n float sDistSqr = dot(SLU, SLU);\n float sAtt = GetDistAtt(sDistSqr, sInvSqrAttRadius);\n sAtt *= cosConeAngle;\n vec3 sSpec = specular * CalcSpecular(roughness, SNH, SH, N);\n finalColor += SNL * cc_spotLitColor[i].rgb * cc_spotLitColor[i].w * sAtt * (diffuseContrib + sSpec);\n }\n float fAmb = dot(N, vec3(0.0, -1.0, 0.0)) * 0.5 + 0.5;\n vec3 ambDiff = mix(cc_ambientSky.rgb, cc_ambientGround.rgb, fAmb) * cc_ambientSky.w;\n finalColor += (ambDiff.rgb * diffuse);\n#if USE_IBL\n vec3 R = normalize(reflect(-V, N));\n vec4 env = textureCube(envMap, R);\n env.rgb = SRGBToLinear(env.rgb) * cc_ambientSky.w;\n finalColor += (env.rgb * specular);\n#endif\n#if CC_USE_HDR\n finalColor *= (1.0/1024.0);;\n#else\n finalColor *= cc_exposure.x;\n finalColor = LinearToSRGB(finalColor);\n#endif\n return vec4(finalColor, baseColor.a);\n}\nvoid main() { gl_FragColor = frag(); }\n` }, "builtins": {"globals":{"blocks":["CCGlobal"], "samplers":[]}, "locals":{"blocks":["CCLocal", "CCSkinning", "CCForwardLight"], "samplers":["cc_jointsTexture"]}}, "defines": [ @@ -121,8 +121,10 @@ export default [ {"name":"USE_PBR_MAP", "type":"boolean", "defines":[]}, {"name":"USE_EMISSIVE_MAP", "type":"boolean", "defines":[]}, {"name":"USE_IBL", "type":"boolean", "defines":[]}, + {"name":"ROUGHNESS_CHANNEL", "type":"string", "options":["r", "g", "b", "a"]}, + {"name":"METALLIC_CHANNEL", "type":"string", "options":["r", "g", "b", "a"]}, {"name":"USE_ALPHA_TEST", "type":"boolean", "defines":[]}, - {"name":"USE_HDR", "type":"boolean", "defines":[]} + {"name":"CC_USE_HDR", "type":"boolean", "defines":[]} ], "blocks": [ {"name": "Constants", "size": 112, "defines": [], "binding": 0, "members": [ @@ -148,11 +150,11 @@ export default [ "name": "builtin-standard|planar-shadow-vs:vert|planar-shadow-fs:frag", "glsl3": { "vert": `\nprecision highp float;\nuniform CCGlobal {\n vec4 cc_time; \n vec4 cc_screenSize; \n vec4 cc_screenScale; \n 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 mat4 cc_matWorld;\n mat4 cc_matWorldIT;\n};\nuniform CCShadow {\n mat4 cc_matLightPlaneProj;\n vec4 cc_shadowColor;\n};\nin vec3 a_position;\nvec4 vert () {\n vec4 pos = vec4(a_position, 1);\n return cc_matViewProj * cc_matLightPlaneProj * cc_matWorld * pos;\n}\nvoid main() { gl_Position = vert(); }\n`, - "frag": `\nprecision highp float;\nuniform CCShadow {\n mat4 cc_matLightPlaneProj;\n vec4 cc_shadowColor;\n};\nvec4 frag () {\n return CCShadowColor;\n}\nout vec4 cc_FragColor;\nvoid main() { cc_FragColor = frag(); }\n` + "frag": `\nprecision highp float;\nuniform CCShadow {\n mat4 cc_matLightPlaneProj;\n vec4 cc_shadowColor;\n};\nvec4 frag () {\n return cc_shadowColor;\n}\nout vec4 cc_FragColor;\nvoid main() { cc_FragColor = frag(); }\n` }, "glsl1": { "vert": `\nprecision highp float;\nuniform vec4 cc_time;\nuniform vec4 cc_screenSize;\nuniform vec4 cc_screenScale;\nuniform mat4 cc_matView;\nuniform mat4 cc_matViewInv;\nuniform mat4 cc_matProj;\nuniform mat4 cc_matProjInv;\nuniform mat4 cc_matViewProj;\nuniform mat4 cc_matViewProjInv;\nuniform vec4 cc_cameraPos;\nuniform vec4 cc_exposure;\nuniform vec4 cc_mainLitDir;\nuniform vec4 cc_mainLitColor;\nuniform vec4 cc_ambientSky;\nuniform vec4 cc_ambientGround;\nuniform mat4 cc_matWorld;\nuniform mat4 cc_matWorldIT;\nuniform mat4 cc_matLightPlaneProj;\nuniform vec4 cc_shadowColor;\nattribute vec3 a_position;\nvec4 vert () {\n vec4 pos = vec4(a_position, 1);\n return cc_matViewProj * cc_matLightPlaneProj * cc_matWorld * pos;\n}\nvoid main() { gl_Position = vert(); }\n`, - "frag": `\nprecision highp float;\nuniform mat4 cc_matLightPlaneProj;\nuniform vec4 cc_shadowColor;\nvec4 frag () {\n return CCShadowColor;\n}\nvoid main() { gl_FragColor = frag(); }\n` + "frag": `\nprecision highp float;\nuniform mat4 cc_matLightPlaneProj;\nuniform vec4 cc_shadowColor;\nvec4 frag () {\n return cc_shadowColor;\n}\nvoid main() { gl_FragColor = frag(); }\n` }, "builtins": {"globals":{"blocks":["CCGlobal", "CCShadow"], "samplers":[]}, "locals":{"blocks":["CCLocal"], "samplers":[]}}, "defines": [], @@ -165,22 +167,22 @@ export default [ { "name": "builtin-tonemap", "techniques": [ - {"name":"tonemap", "passes":[{"depthStencilState":{"depthTest":false, "depthWrite":false}, "program":"builtin-tonemap|tonemap-vs:vert|tonemap-fs:frag", "properties":{"u_texSampler":{"type":29, "sampler":{"minFilter":2, "magFilter":2, "mipFilter":0}}}}]} + {"name":"tonemap", "passes":[{"depthStencilState":{"depthTest":false, "depthWrite":false}, "program":"builtin-tonemap|tonemap-vs:vert|tonemap-fs:frag", "properties":{"u_texSampler":{"type":29}}}]} ], "shaders": [ { "name": "builtin-tonemap|tonemap-vs:vert|tonemap-fs:frag", "glsl3": { "vert": `\nprecision highp float;\n#define PI 3.14159265359\n#define PI2 6.28318530718\n#define EPSILON 1e-6\n#define LOG2 1.442695\n#define saturate(a) clamp( a, 0.0, 1.0 )\n#define FP_MAX = 65504.0;\n#define FP_SCALE (1.0/1024.0);\n#define FP_SCALE_INV 1024.0;\nuniform CCGlobal {\n vec4 cc_time; \n vec4 cc_screenSize; \n vec4 cc_screenScale; \n 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};\nin vec2 a_position;\nin vec2 a_texCoord;\nout vec2 v_uv;\nvec4 vert () {\n vec4 pos = vec4(a_position, 0, 1);\n v_uv = a_texCoord * cc_screenScale.xy;\n return pos;\n}\nvoid main() { gl_Position = vert(); }\n`, - "frag": `\nprecision highp float;\nuniform CCGlobal {\n vec4 cc_time; \n vec4 cc_screenSize; \n vec4 cc_screenScale; \n 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#define PI 3.14159265359\n#define PI2 6.28318530718\n#define EPSILON 1e-6\n#define LOG2 1.442695\n#define saturate(a) clamp( a, 0.0, 1.0 )\n#define FP_MAX = 65504.0;\n#define FP_SCALE (1.0/1024.0);\n#define FP_SCALE_INV 1024.0;\nfloat ComputeEV100(float aperture, float shutterTime, float iso, float ec) {\n return log2((aperture * aperture) / shutterTime * 100.0 / iso) - ec;\n}\nfloat ComputeExposure(float ev100) {\n return 0.833333 / pow(2.0, ev100);\n}\nvec3 SRGBToLinear(vec3 gamma)\n{\n return pow(gamma, vec3(2.2));\n \n}\nvec3 LinearToSRGB(vec3 linear)\n{\n return pow(linear, vec3(0.454545));\n \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}\nin vec2 v_uv;\nuniform sampler2D u_texSampler;\nvec4 frag () {\n vec4 o = texture(u_texSampler, v_uv);\n#if USE_HDR\n o.rgb *= cc_exposure.x * 1024.0;;\n o.rgb = ACESToneMap(o.rgb);\n o.rgb = LinearToSRGB(o.rgb);\n#endif\n return o;\n}\nout vec4 cc_FragColor;\nvoid main() { cc_FragColor = frag(); }\n` + "frag": `\nprecision highp float;\nuniform CCGlobal {\n vec4 cc_time; \n vec4 cc_screenSize; \n vec4 cc_screenScale; \n 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#define PI 3.14159265359\n#define PI2 6.28318530718\n#define EPSILON 1e-6\n#define LOG2 1.442695\n#define saturate(a) clamp( a, 0.0, 1.0 )\n#define FP_MAX = 65504.0;\n#define FP_SCALE (1.0/1024.0);\n#define FP_SCALE_INV 1024.0;\nfloat ComputeEV100(float aperture, float shutterTime, float iso, float ec) {\n return log2((aperture * aperture) / shutterTime * 100.0 / iso) - ec;\n}\nfloat ComputeExposure(float ev100) {\n return 0.833333 / pow(2.0, ev100);\n}\nvec3 SRGBToLinear(vec3 gamma)\n{\n return pow(gamma, vec3(2.2));\n \n}\nvec3 LinearToSRGB(vec3 linear)\n{\n return pow(linear, vec3(0.454545));\n \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}\nin vec2 v_uv;\nuniform sampler2D u_texSampler;\nvec4 frag () {\n vec4 o = texture(u_texSampler, v_uv);\n#if CC_USE_HDR\n o.rgb *= cc_exposure.x * 1024.0;;\n o.rgb = ACESToneMap(o.rgb);\n o.rgb = LinearToSRGB(o.rgb);\n#endif\n return o;\n}\nout vec4 cc_FragColor;\nvoid main() { cc_FragColor = frag(); }\n` }, "glsl1": { "vert": `\nprecision highp float;\n#define PI 3.14159265359\n#define PI2 6.28318530718\n#define EPSILON 1e-6\n#define LOG2 1.442695\n#define saturate(a) clamp( a, 0.0, 1.0 )\n#define FP_MAX = 65504.0;\n#define FP_SCALE (1.0/1024.0);\n#define FP_SCALE_INV 1024.0;\nuniform vec4 cc_time;\nuniform vec4 cc_screenSize;\nuniform vec4 cc_screenScale;\nuniform mat4 cc_matView;\nuniform mat4 cc_matViewInv;\nuniform mat4 cc_matProj;\nuniform mat4 cc_matProjInv;\nuniform mat4 cc_matViewProj;\nuniform mat4 cc_matViewProjInv;\nuniform vec4 cc_cameraPos;\nuniform vec4 cc_exposure;\nuniform vec4 cc_mainLitDir;\nuniform vec4 cc_mainLitColor;\nuniform vec4 cc_ambientSky;\nuniform vec4 cc_ambientGround;\nattribute vec2 a_position;\nattribute vec2 a_texCoord;\nvarying vec2 v_uv;\nvec4 vert () {\n vec4 pos = vec4(a_position, 0, 1);\n v_uv = a_texCoord * cc_screenScale.xy;\n return pos;\n}\nvoid main() { gl_Position = vert(); }\n`, - "frag": `\nprecision highp float;\nuniform vec4 cc_time;\nuniform vec4 cc_screenSize;\nuniform vec4 cc_screenScale;\nuniform mat4 cc_matView;\nuniform mat4 cc_matViewInv;\nuniform mat4 cc_matProj;\nuniform mat4 cc_matProjInv;\nuniform mat4 cc_matViewProj;\nuniform mat4 cc_matViewProjInv;\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#define PI 3.14159265359\n#define PI2 6.28318530718\n#define EPSILON 1e-6\n#define LOG2 1.442695\n#define saturate(a) clamp( a, 0.0, 1.0 )\n#define FP_MAX = 65504.0;\n#define FP_SCALE (1.0/1024.0);\n#define FP_SCALE_INV 1024.0;\nfloat ComputeEV100(float aperture, float shutterTime, float iso, float ec) {\n return log2((aperture * aperture) / shutterTime * 100.0 / iso) - ec;\n}\nfloat ComputeExposure(float ev100) {\n return 0.833333 / pow(2.0, ev100);\n}\nvec3 SRGBToLinear(vec3 gamma)\n{\n return pow(gamma, vec3(2.2));\n \n}\nvec3 LinearToSRGB(vec3 linear)\n{\n return pow(linear, vec3(0.454545));\n \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}\nvarying vec2 v_uv;\nuniform sampler2D u_texSampler;\nvec4 frag () {\n vec4 o = texture2D(u_texSampler, v_uv);\n#if USE_HDR\n o.rgb *= cc_exposure.x * 1024.0;;\n o.rgb = ACESToneMap(o.rgb);\n o.rgb = LinearToSRGB(o.rgb);\n#endif\n return o;\n}\nvoid main() { gl_FragColor = frag(); }\n` + "frag": `\nprecision highp float;\nuniform vec4 cc_time;\nuniform vec4 cc_screenSize;\nuniform vec4 cc_screenScale;\nuniform mat4 cc_matView;\nuniform mat4 cc_matViewInv;\nuniform mat4 cc_matProj;\nuniform mat4 cc_matProjInv;\nuniform mat4 cc_matViewProj;\nuniform mat4 cc_matViewProjInv;\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#define PI 3.14159265359\n#define PI2 6.28318530718\n#define EPSILON 1e-6\n#define LOG2 1.442695\n#define saturate(a) clamp( a, 0.0, 1.0 )\n#define FP_MAX = 65504.0;\n#define FP_SCALE (1.0/1024.0);\n#define FP_SCALE_INV 1024.0;\nfloat ComputeEV100(float aperture, float shutterTime, float iso, float ec) {\n return log2((aperture * aperture) / shutterTime * 100.0 / iso) - ec;\n}\nfloat ComputeExposure(float ev100) {\n return 0.833333 / pow(2.0, ev100);\n}\nvec3 SRGBToLinear(vec3 gamma)\n{\n return pow(gamma, vec3(2.2));\n \n}\nvec3 LinearToSRGB(vec3 linear)\n{\n return pow(linear, vec3(0.454545));\n \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}\nvarying vec2 v_uv;\nuniform sampler2D u_texSampler;\nvec4 frag () {\n vec4 o = texture2D(u_texSampler, v_uv);\n#if CC_USE_HDR\n o.rgb *= cc_exposure.x * 1024.0;;\n o.rgb = ACESToneMap(o.rgb);\n o.rgb = LinearToSRGB(o.rgb);\n#endif\n return o;\n}\nvoid main() { gl_FragColor = frag(); }\n` }, "builtins": {"globals":{"blocks":["CCGlobal"], "samplers":[]}, "locals":{"blocks":[], "samplers":[]}}, "defines": [ - {"name":"USE_HDR", "type":"boolean", "defines":[]} + {"name":"CC_USE_HDR", "type":"boolean", "defines":[]} ], "blocks": [], "samplers": [ @@ -200,18 +202,18 @@ export default [ "name": "builtin-unlit|unlit-vs:vert|unlit-fs:frag", "glsl3": { "vert": `\nprecision mediump float;\nuniform CCGlobal {\n vec4 cc_time; \n vec4 cc_screenSize; \n vec4 cc_screenScale; \n 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 mat4 cc_matWorld;\n mat4 cc_matWorldIT;\n};\n#if CC_USE_SKINNING\nin vec4 a_weights;\nin vec4 a_joints;\nuniform CCSkinning {\n mat4 cc_matJoint[128];\n vec4 cc_jointsTextureSize;\n};\n#if CC_USE_JOINTS_TEXTURE\nuniform sampler2D cc_jointsTexture;\nmat4 getBoneMatrix(const in float i) {\n float size = cc_jointsTextureSize.x;\n float j = i * 4.0;\n float x = mod(j, size);\n float y = floor(j / size);\n float dx = 1.0 / size;\n float dy = 1.0 / size;\n y = dy * (y + 0.5);\n vec4 v1 = texture(cc_jointsTexture, vec2(dx * (x + 0.5), y));\n vec4 v2 = texture(cc_jointsTexture, vec2(dx * (x + 1.5), y));\n vec4 v3 = texture(cc_jointsTexture, vec2(dx * (x + 2.5), y));\n vec4 v4 = texture(cc_jointsTexture, vec2(dx * (x + 3.5), y));\n return mat4(v1, v2, v3, v4);\n}\n#else\nmat4 getBoneMatrix(const in float i) {\n return cc_matJoint[int(i)];\n}\n#endif\nmat4 skinMatrix() {\n return\n getBoneMatrix(a_joints.x) * a_weights.x +\n getBoneMatrix(a_joints.y) * a_weights.y +\n getBoneMatrix(a_joints.z) * a_weights.z +\n getBoneMatrix(a_joints.w) * a_weights.w;\n}\nvoid skinVertex(inout vec4 a1) {\n mat4 m = skinMatrix();\n a1 = m * a1;\n}\nvoid skinVertex(inout vec4 a1, inout vec4 a2) {\n mat4 m = skinMatrix();\n a1 = m * a1;\n a2 = m * a2;\n}\nvoid skinVertex(inout vec4 a1, inout vec4 a2, inout vec4 a3) {\n mat4 m = skinMatrix();\n a1 = m * a1;\n a2 = m * a2;\n a3 = m * a3;\n}\n#endif\nin vec3 a_position;\n#if USE_TEXTURE\n in vec2 a_texCoord;\n out vec2 uv0;\n uniform TexCoords {\n vec4 tilingOffset;\n };\n#endif\nvec4 vert () {\n vec4 pos = vec4(a_position, 1);\n #if CC_USE_SKINNING\n skinVertex(pos);\n #endif\n pos = cc_matViewProj * cc_matWorld * pos;\n #if USE_TEXTURE\n uv0 = a_texCoord * tilingOffset.xy + tilingOffset.zw;\n #endif\n return pos;\n}\nvoid main() { gl_Position = vert(); }\n`, - "frag": `\nprecision mediump float;\nuniform CCGlobal {\n vec4 cc_time; \n vec4 cc_screenSize; \n vec4 cc_screenScale; \n 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{\n return pow(gamma, vec3(2.2));\n \n}\nvec3 LinearToSRGB(vec3 linear)\n{\n return pow(linear, vec3(0.454545));\n \n}\nvec4 PostProcess(vec4 color, float scale)\n{\n#if USE_HDR\n color.rgb = SRGBToLinear(color.rgb) * scale;\n#endif\n return color;\n}\n#if USE_TEXTURE\n in vec2 uv0;\n uniform sampler2D mainTexture;\n#endif\n#if USE_COLOR\n uniform Constant {\n vec4 color;\n };\n#endif\nvec4 frag () {\n vec4 o = vec4(1, 1, 1, 1);\n #if USE_TEXTURE\n o *= texture(mainTexture, uv0);\n #endif\n #if USE_COLOR\n o *= color;\n #endif\n return PostProcess(o, cc_exposure.w);\n}\nout vec4 cc_FragColor;\nvoid main() { cc_FragColor = frag(); }\n` + "frag": `\nprecision mediump float;\nuniform CCGlobal {\n vec4 cc_time; \n vec4 cc_screenSize; \n vec4 cc_screenScale; \n 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{\n return pow(gamma, vec3(2.2));\n \n}\nvec3 LinearToSRGB(vec3 linear)\n{\n return pow(linear, vec3(0.454545));\n \n}\nvec4 PostProcess(vec4 color, float scale)\n{\n#if CC_USE_HDR\n color.rgb = SRGBToLinear(color.rgb) * scale;\n#endif\n return color;\n}\n#if USE_TEXTURE\n in vec2 uv0;\n uniform sampler2D mainTexture;\n#endif\n#if USE_COLOR\n uniform Constant {\n vec4 color;\n };\n#endif\nvec4 frag () {\n vec4 o = vec4(1, 1, 1, 1);\n #if USE_TEXTURE\n o *= texture(mainTexture, uv0);\n #endif\n #if USE_COLOR\n o *= color;\n #endif\n return PostProcess(o, cc_exposure.w);\n}\nout vec4 cc_FragColor;\nvoid main() { cc_FragColor = frag(); }\n` }, "glsl1": { "vert": `\nprecision mediump float;\nuniform vec4 cc_time;\nuniform vec4 cc_screenSize;\nuniform vec4 cc_screenScale;\nuniform mat4 cc_matView;\nuniform mat4 cc_matViewInv;\nuniform mat4 cc_matProj;\nuniform mat4 cc_matProjInv;\nuniform mat4 cc_matViewProj;\nuniform mat4 cc_matViewProjInv;\nuniform vec4 cc_cameraPos;\nuniform vec4 cc_exposure;\nuniform vec4 cc_mainLitDir;\nuniform vec4 cc_mainLitColor;\nuniform vec4 cc_ambientSky;\nuniform vec4 cc_ambientGround;\nuniform mat4 cc_matWorld;\nuniform mat4 cc_matWorldIT;\n#if CC_USE_SKINNING\nattribute vec4 a_weights;\nattribute vec4 a_joints;\nuniform mat4 cc_matJoint[128];\nuniform vec4 cc_jointsTextureSize;\n#if CC_USE_JOINTS_TEXTURE\nuniform sampler2D cc_jointsTexture;\nmat4 getBoneMatrix(const in float i) {\n float size = cc_jointsTextureSize.x;\n float j = i * 4.0;\n float x = mod(j, size);\n float y = floor(j / size);\n float dx = 1.0 / size;\n float dy = 1.0 / size;\n y = dy * (y + 0.5);\n vec4 v1 = texture2D(cc_jointsTexture, vec2(dx * (x + 0.5), y));\n vec4 v2 = texture2D(cc_jointsTexture, vec2(dx * (x + 1.5), y));\n vec4 v3 = texture2D(cc_jointsTexture, vec2(dx * (x + 2.5), y));\n vec4 v4 = texture2D(cc_jointsTexture, vec2(dx * (x + 3.5), y));\n return mat4(v1, v2, v3, v4);\n}\n#else\nmat4 getBoneMatrix(const in float i) {\n return cc_matJoint[int(i)];\n}\n#endif\nmat4 skinMatrix() {\n return\n getBoneMatrix(a_joints.x) * a_weights.x +\n getBoneMatrix(a_joints.y) * a_weights.y +\n getBoneMatrix(a_joints.z) * a_weights.z +\n getBoneMatrix(a_joints.w) * a_weights.w;\n}\nvoid skinVertex(inout vec4 a1) {\n mat4 m = skinMatrix();\n a1 = m * a1;\n}\nvoid skinVertex(inout vec4 a1, inout vec4 a2) {\n mat4 m = skinMatrix();\n a1 = m * a1;\n a2 = m * a2;\n}\nvoid skinVertex(inout vec4 a1, inout vec4 a2, inout vec4 a3) {\n mat4 m = skinMatrix();\n a1 = m * a1;\n a2 = m * a2;\n a3 = m * a3;\n}\n#endif\nattribute vec3 a_position;\n#if USE_TEXTURE\n attribute vec2 a_texCoord;\n varying vec2 uv0;\n uniform vec4 tilingOffset;\n#endif\nvec4 vert () {\n vec4 pos = vec4(a_position, 1);\n #if CC_USE_SKINNING\n skinVertex(pos);\n #endif\n pos = cc_matViewProj * cc_matWorld * pos;\n #if USE_TEXTURE\n uv0 = a_texCoord * tilingOffset.xy + tilingOffset.zw;\n #endif\n return pos;\n}\nvoid main() { gl_Position = vert(); }\n`, - "frag": `\nprecision mediump float;\nuniform vec4 cc_time;\nuniform vec4 cc_screenSize;\nuniform vec4 cc_screenScale;\nuniform mat4 cc_matView;\nuniform mat4 cc_matViewInv;\nuniform mat4 cc_matProj;\nuniform mat4 cc_matProjInv;\nuniform mat4 cc_matViewProj;\nuniform mat4 cc_matViewProjInv;\nuniform vec4 cc_cameraPos;\nuniform vec4 cc_exposure;\nuniform vec4 cc_mainLitDir;\nuniform vec4 cc_mainLitColor;\nuniform vec4 cc_ambientSky;\nuniform vec4 cc_ambientGround;\nvec3 SRGBToLinear(vec3 gamma)\n{\n return pow(gamma, vec3(2.2));\n \n}\nvec3 LinearToSRGB(vec3 linear)\n{\n return pow(linear, vec3(0.454545));\n \n}\nvec4 PostProcess(vec4 color, float scale)\n{\n#if USE_HDR\n color.rgb = SRGBToLinear(color.rgb) * scale;\n#endif\n return color;\n}\n#if USE_TEXTURE\n varying vec2 uv0;\n uniform sampler2D mainTexture;\n#endif\n#if USE_COLOR\n uniform vec4 color;\n#endif\nvec4 frag () {\n vec4 o = vec4(1, 1, 1, 1);\n #if USE_TEXTURE\n o *= texture2D(mainTexture, uv0);\n #endif\n #if USE_COLOR\n o *= color;\n #endif\n return PostProcess(o, cc_exposure.w);\n}\nvoid main() { gl_FragColor = frag(); }\n` + "frag": `\nprecision mediump float;\nuniform vec4 cc_time;\nuniform vec4 cc_screenSize;\nuniform vec4 cc_screenScale;\nuniform mat4 cc_matView;\nuniform mat4 cc_matViewInv;\nuniform mat4 cc_matProj;\nuniform mat4 cc_matProjInv;\nuniform mat4 cc_matViewProj;\nuniform mat4 cc_matViewProjInv;\nuniform vec4 cc_cameraPos;\nuniform vec4 cc_exposure;\nuniform vec4 cc_mainLitDir;\nuniform vec4 cc_mainLitColor;\nuniform vec4 cc_ambientSky;\nuniform vec4 cc_ambientGround;\nvec3 SRGBToLinear(vec3 gamma)\n{\n return pow(gamma, vec3(2.2));\n \n}\nvec3 LinearToSRGB(vec3 linear)\n{\n return pow(linear, vec3(0.454545));\n \n}\nvec4 PostProcess(vec4 color, float scale)\n{\n#if CC_USE_HDR\n color.rgb = SRGBToLinear(color.rgb) * scale;\n#endif\n return color;\n}\n#if USE_TEXTURE\n varying vec2 uv0;\n uniform sampler2D mainTexture;\n#endif\n#if USE_COLOR\n uniform vec4 color;\n#endif\nvec4 frag () {\n vec4 o = vec4(1, 1, 1, 1);\n #if USE_TEXTURE\n o *= texture2D(mainTexture, uv0);\n #endif\n #if USE_COLOR\n o *= color;\n #endif\n return PostProcess(o, cc_exposure.w);\n}\nvoid main() { gl_FragColor = frag(); }\n` }, "builtins": {"globals":{"blocks":["CCGlobal"], "samplers":[]}, "locals":{"blocks":["CCLocal", "CCSkinning"], "samplers":["cc_jointsTexture"]}}, "defines": [ {"name":"CC_USE_SKINNING", "type":"boolean", "defines":[]}, {"name":"CC_USE_JOINTS_TEXTURE", "type":"boolean", "defines":["CC_USE_SKINNING"]}, {"name":"USE_TEXTURE", "type":"boolean", "defines":[]}, - {"name":"USE_HDR", "type":"boolean", "defines":[]}, + {"name":"CC_USE_HDR", "type":"boolean", "defines":[]}, {"name":"USE_COLOR", "type":"boolean", "defines":[]} ], "blocks": [ diff --git a/cocos/3d/misc/utils.ts b/cocos/3d/misc/utils.ts index 05a64fe5a8..2150446047 100644 --- a/cocos/3d/misc/utils.ts +++ b/cocos/3d/misc/utils.ts @@ -6,7 +6,7 @@ import { AttributeBaseType, AttributeType, import { IGeometry } from '../primitive/define'; const copyAttribute = (attribute: IVertexAttribute) => Object.assign({}, attribute); -export function createMesh (geometry: IGeometry) { +export function createMesh (geometry: IGeometry, out?: Mesh) { // Collect attributes and calculate length of result vertex buffer. const attributes: IVertexAttribute[] = []; let stride = 0; @@ -103,10 +103,10 @@ export function createMesh (geometry: IGeometry) { }; // Create mesh. - const mesh = new Mesh(); - mesh.assign(meshStruct, new Uint8Array(bufferBlob.getCombined())); + if (!out) { out = new Mesh(); } + out.assign(meshStruct, new Uint8Array(bufferBlob.getCombined())); - return mesh; + return out; } /** diff --git a/cocos/assets/texture-2d.ts b/cocos/assets/texture-2d.ts index 27fe99c068..9c85aa053b 100644 --- a/cocos/assets/texture-2d.ts +++ b/cocos/assets/texture-2d.ts @@ -78,7 +78,6 @@ export class Texture2D extends TextureBase { } public onLoaded () { - super.onLoaded(); this.mipmaps = this._mipmaps; } diff --git a/cocos/assets/texture-base.ts b/cocos/assets/texture-base.ts index f44f012c10..4b8ea5aede 100644 --- a/cocos/assets/texture-base.ts +++ b/cocos/assets/texture-base.ts @@ -27,15 +27,13 @@ import {ccclass, property} from '../core/data/class-decorator'; import { EventTargetFactory } from '../core/event/event-target-factory'; import IDGenerator from '../core/utils/id-generator'; -import { ccenum } from '../core/value-types/enum'; import { GFXAddress, GFXBufferTextureCopy, GFXFilter, GFXFormat, GFXTextureFlagBit, GFXTextureType, GFXTextureUsageBit, GFXTextureViewType } from '../gfx/define'; import { GFXDevice } from '../gfx/device'; -import { GFXSampler } from '../gfx/sampler'; import { GFXTexture, IGFXTextureInfo } from '../gfx/texture'; import { GFXTextureView, IGFXTextureViewInfo } from '../gfx/texture-view'; import { Asset } from './asset'; -import { ImageAsset, ImageSource } from './image-asset'; +import { ImageAsset } from './image-asset'; const CHAR_CODE_1 = 49; // '1' @@ -101,11 +99,6 @@ export enum PixelFormat { */ RGBA_PVRTC_4BPPV1 = GFXFormat.PVRTC_RGBA4, } -ccenum(PixelFormat); - -function toGfxFormat (pixelFormat: PixelFormat) { - return pixelFormat as unknown as GFXFormat; -} /** * The texture wrap mode. @@ -129,11 +122,6 @@ export enum WrapMode { */ CLAMP_TO_BORDER = GFXAddress.BORDER, } -ccenum(WrapMode); - -function toGfxAddressMode (wrapMode: WrapMode) { - return wrapMode as unknown as GFXAddress; -} /** * The texture filter mode @@ -149,11 +137,6 @@ export enum Filter { */ NEAREST = GFXFilter.POINT, } -ccenum(Filter); - -function toGfxFilterMode (filter: Filter) { - return filter as unknown as GFXFilter; -} @ccclass('cc.TextureBase') export class TextureBase extends EventTargetFactory(Asset) { @@ -196,6 +179,39 @@ export class TextureBase extends EventTargetFactory(Asset) { return texture._format >= PixelFormat.RGB_PVRTC_2BPPV1 && texture._format <= PixelFormat.RGBA_PVRTC_4BPPV1; } + @property + protected _genMipmap = false; + + @property + protected _format: number = PixelFormat.RGBA8888; + + @property + protected _premultiplyAlpha = false; + + @property + protected _flipY = false; + + @property + protected _minFilter: number = Filter.LINEAR; + + @property + protected _magFilter: number = Filter.LINEAR; + + @property + protected _mipFilter: number = Filter.LINEAR; + + @property + protected _wrapU: number = WrapMode.REPEAT; + + @property + protected _wrapV: number = WrapMode.REPEAT; + + @property + protected _wrapW: number = WrapMode.REPEAT; + + @property + protected _anisotropy = 16; + protected _texture: GFXTexture | null = null; protected _textureView: GFXTextureView | null = null; @@ -206,40 +222,10 @@ export class TextureBase extends EventTargetFactory(Asset) { private _mipmapLevel: number = 1; - @property - private _genMipmap = false; - - @property - private _format: PixelFormat = PixelFormat.RGBA8888; - - @property - private _premultiplyAlpha = false; - - @property - private _flipY = false; - - @property - private _minFilter = Filter.LINEAR; - - @property - private _magFilter = Filter.LINEAR; - - @property - private _mipFilter = Filter.LINEAR; - - @property - private _wrapS: WrapMode = WrapMode.CLAMP_TO_EDGE; - - @property - private _wrapT: WrapMode = WrapMode.CLAMP_TO_EDGE; - - @property - private _anisotropy = 1; - - private _sampler: GFXSampler | null = null; - private _id: string; + private _samplerInfo: number[] = []; + protected constructor (flipY: boolean = false) { super(); @@ -262,7 +248,6 @@ export class TextureBase extends EventTargetFactory(Asset) { this._potientialHeight = height; this._format = format; this._mipmapLevel = mipmapLevel; - this._updateSampler(); this._recreateTexture(); } @@ -323,15 +308,14 @@ export class TextureBase extends EventTargetFactory(Asset) { * If the texture size is NPOT (non power of 2), then in can only use gl.CLAMP_TO_EDGE in gl.TEXTURE_WRAP_{S,T}. * !#zh 设置纹理包装模式。 * 若纹理贴图尺寸是 NPOT(non power of 2),则只能使用 Texture2D.WrapMode.CLAMP_TO_EDGE。 - * @param wrapS - * @param wrapT + * @param wrapU + * @param wrapV */ - public setWrapMode (wrapS: WrapMode, wrapT: WrapMode) { - if (this._wrapS !== wrapS || this._wrapT !== wrapT) { - this._wrapS = wrapS; - this._wrapT = wrapT; - this._updateSampler(); - } + public setWrapMode (wrapU: WrapMode, wrapV: WrapMode, wrapW?: WrapMode) { + if (wrapU !== this._wrapU) { this._wrapU = wrapU; this._samplerInfo[3] = wrapU; } + if (wrapV !== this._wrapV) { this._wrapV = wrapV; this._samplerInfo[4] = wrapV; } + if (wrapW === undefined) { return; } + if (wrapW !== this._wrapW) { this._wrapW = wrapW; this._samplerInfo[5] = wrapW; } } /** @@ -341,11 +325,8 @@ export class TextureBase extends EventTargetFactory(Asset) { * @param magFilter */ public setFilters (minFilter: Filter, magFilter: Filter) { - if (this._minFilter !== minFilter || this._magFilter !== magFilter) { - this._minFilter = minFilter; - this._magFilter = magFilter; - this._updateSampler(); - } + if (minFilter !== this._minFilter) { this._minFilter = minFilter; this._samplerInfo[0] = minFilter; } + if (magFilter !== this._magFilter) { this._magFilter = magFilter; this._samplerInfo[1] = magFilter; } } /** @@ -354,10 +335,7 @@ export class TextureBase extends EventTargetFactory(Asset) { * @param mipFilter */ public setMipFilter (mipFilter: Filter) { - if (this._mipFilter !== mipFilter) { - this._mipFilter = mipFilter; - this._updateSampler(); - } + if (mipFilter !== this._mipFilter) { this._mipFilter = mipFilter; this._samplerInfo[2] = mipFilter; } } /** @@ -367,10 +345,7 @@ export class TextureBase extends EventTargetFactory(Asset) { * @param flipY */ public setFlipY (flipY: boolean) { - if (this._flipY !== flipY) { - this._flipY = flipY; - this._updateSampler(); - } + this._flipY = flipY; } /** @@ -380,10 +355,7 @@ export class TextureBase extends EventTargetFactory(Asset) { * @param premultiply */ public setPremultiplyAlpha (premultiply: boolean) { - if (this._premultiplyAlpha !== premultiply) { - this._premultiplyAlpha = premultiply; - this._updateSampler(); - } + this._premultiplyAlpha = premultiply; } /** @@ -392,10 +364,7 @@ export class TextureBase extends EventTargetFactory(Asset) { * @param anisotropy */ public setAnisotropy (anisotropy: number) { - if (this._anisotropy !== anisotropy) { - this._anisotropy = anisotropy; - this._updateSampler(); - } + if (anisotropy !== this._anisotropy) { this._anisotropy = anisotropy; this._samplerInfo[6] = anisotropy; } } /** @@ -415,10 +384,6 @@ export class TextureBase extends EventTargetFactory(Asset) { public destroy () { this._destroyTexture(); - if (this._sampler) { - this._sampler.destroy(); - } - return true; } @@ -430,8 +395,8 @@ export class TextureBase extends EventTargetFactory(Asset) { return this._textureView; } - public getGFXSampler () { - return this._sampler; + public getGFXSamplerInfo () { + return this._samplerInfo; } // SERIALIZATION @@ -441,7 +406,7 @@ export class TextureBase extends EventTargetFactory(Asset) { */ public _serialize (): any { return this._minFilter + ',' + this._magFilter + ',' + - this._wrapS + ',' + this._wrapT + ',' + + this._wrapU + ',' + this._wrapV + ',' + (this._premultiplyAlpha ? 1 : 0) + ',' + this._mipFilter + ',' + this._anisotropy + ',' + (this._flipY ? 1 : 0) + ',' + @@ -458,17 +423,15 @@ export class TextureBase extends EventTargetFactory(Asset) { fields.unshift(''); if (fields.length >= 6) { // decode filters - this._minFilter = parseInt(fields[1], undefined); - this._magFilter = parseInt(fields[2], undefined); + this.setFilters(parseInt(fields[1]), parseInt(fields[2])); // decode wraps - this._wrapS = parseInt(fields[3], undefined); - this._wrapT = parseInt(fields[4], undefined); + this.setWrapMode(parseInt(fields[3]), parseInt(fields[4])); // decode premultiply alpha this._premultiplyAlpha = fields[5].charCodeAt(0) === CHAR_CODE_1; } if (fields.length >= 8) { - this._mipFilter = parseInt(fields[6], undefined); - this._anisotropy = parseInt(fields[7], undefined); + this.setMipFilter(parseInt(fields[6])); + this.setAnisotropy(parseInt(fields[7])); } if (fields.length >= 10) { this._flipY = fields[8].charCodeAt(0) === CHAR_CODE_1; @@ -476,10 +439,6 @@ export class TextureBase extends EventTargetFactory(Asset) { } } - public onLoaded () { - this._updateSampler(); - } - /** * Updates mipmaps at level 0. */ @@ -508,10 +467,6 @@ export class TextureBase extends EventTargetFactory(Asset) { } } - protected _getGfxFormat () { - return toGfxFormat(this._format); - } - protected _assignImage (image: ImageAsset, level: number, arrayIndex?: number) { const upload = () => { if (!image.data) { @@ -582,7 +537,7 @@ export class TextureBase extends EventTargetFactory(Asset) { return { type: GFXTextureType.TEX2D, usage: GFXTextureUsageBit.SAMPLED | GFXTextureUsageBit.TRANSFER_DST, - format: toGfxFormat(this._format), + format: this._format, width: this._potientialWidth, height: this._potientialHeight, mipLevel: this._mipmapLevel, @@ -594,7 +549,7 @@ export class TextureBase extends EventTargetFactory(Asset) { return { texture: this._texture!, type: GFXTextureViewType.TV2D, - format: this._getGfxFormat(), + format: this._format, }; } @@ -622,27 +577,6 @@ export class TextureBase extends EventTargetFactory(Asset) { this._texture = null; } } - - private _updateSampler () { - if (this._sampler) { - this._sampler.destroy(); - } - - const gfxDevice = this._getGlobalDevice(); - if (!gfxDevice) { - return; - } - - this._sampler = gfxDevice.createSampler({ - name: `Sampler of ${this.name}`, - minFilter: toGfxFilterMode(this._minFilter), - magFilter: toGfxFilterMode(this._magFilter), - addressU: toGfxAddressMode(this._wrapS), - addressV: toGfxAddressMode(this._wrapT), - maxAnisotropy: this._anisotropy, - }); - } } -/* tslint:disable:no-string-literal */ -cc['TextureBase'] = TextureBase; +cc.TextureBase = TextureBase; diff --git a/cocos/gfx/sampler.ts b/cocos/gfx/sampler.ts index 6d15745105..cc2f20148b 100644 --- a/cocos/gfx/sampler.ts +++ b/cocos/gfx/sampler.ts @@ -22,9 +22,9 @@ export class GFXSamplerState { public minFilter: GFXFilter = GFXFilter.LINEAR; public magFilter: GFXFilter = GFXFilter.LINEAR; public mipFilter: GFXFilter = GFXFilter.NONE; - public addressU: GFXAddress = GFXAddress.CLAMP; - public addressV: GFXAddress = GFXAddress.CLAMP; - public addressW: GFXAddress = GFXAddress.CLAMP; + public addressU: GFXAddress = GFXAddress.WRAP; + public addressV: GFXAddress = GFXAddress.WRAP; + public addressW: GFXAddress = GFXAddress.WRAP; public maxAnisotropy: number = 16; public cmpFunc: GFXComparisonFunc = GFXComparisonFunc.NEVER; public borderColor: IGFXColor = { r: 0, g: 0, b: 0, a: 0 }; diff --git a/cocos/pipeline/forward/forward-pipeline.ts b/cocos/pipeline/forward/forward-pipeline.ts index c693abe5ff..087939b9eb 100644 --- a/cocos/pipeline/forward/forward-pipeline.ts +++ b/cocos/pipeline/forward/forward-pipeline.ts @@ -83,7 +83,7 @@ export class ForwardPipeline extends RenderPipeline { this.addRenderPass(RenderPassStage.DEFAULT, windowPass); - this._macros.USE_HDR = this._isHDR; + this._macros.CC_USE_HDR = this._isHDR; // create flows this.createFlow(ForwardFlow, { diff --git a/cocos/pipeline/render-pipeline.ts b/cocos/pipeline/render-pipeline.ts index 4f3d3b467f..832fd76881 100644 --- a/cocos/pipeline/render-pipeline.ts +++ b/cocos/pipeline/render-pipeline.ts @@ -233,7 +233,7 @@ export abstract class RenderPipeline { // colorFmt = GFXFormat.RGBA16F; - console.info('USE_HDR: ' + this._isHDR); + console.info('CC_USE_HDR: ' + this._isHDR); console.info('Shading Color Format: ' + GFXFormatInfos[colorFmt].name); console.info('Shading Depth Format: ' + GFXFormatInfos[depthStencilFmt].name); diff --git a/cocos/renderer/core/pass.ts b/cocos/renderer/core/pass.ts index 6c99aa61ef..a4b4b406a7 100644 --- a/cocos/renderer/core/pass.ts +++ b/cocos/renderer/core/pass.ts @@ -13,12 +13,13 @@ import { GFXPipelineLayout } from '../../gfx/pipeline-layout'; import { GFXBlendState, GFXBlendTarget, GFXDepthStencilState, GFXInputState, GFXPipelineState, GFXRasterizerState } from '../../gfx/pipeline-state'; import { GFXRenderPass } from '../../gfx/render-pass'; -import { GFXSampler, IGFXSamplerInfo } from '../../gfx/sampler'; +import { GFXSampler } from '../../gfx/sampler'; import { GFXShader } from '../../gfx/shader'; import { GFXTextureView } from '../../gfx/texture-view'; import { RenderPassStage, RenderPriority } from '../../pipeline/define'; import { RenderPipeline } from '../../pipeline/render-pipeline'; import { programLib } from './program-lib'; +import { samplerLib } from './sampler-lib'; export interface IDefineMap { [name: string]: number | boolean | string; } export interface IPassInfoFull extends IPassInfo { @@ -170,13 +171,12 @@ export class Pass { for (const u of shaderInfo.samplers) { this._handleMap[u.name] = genHandle(GFXBindingType.SAMPLER, u.type, u.binding); const inf = info.properties && info.properties[u.name]; - const samplerInfo = Object.assign({}, inf && inf.sampler); - const sampler = getSampler(device, samplerInfo); - if (sampler) { this._samplers[u.binding] = sampler; } - else { console.error('create sampler failed.'); } const texName = inf && inf.value ? inf.value + '-texture' : _type2default[u.type]; const texture = builtinResMgr.get(texName); - if (texture) { this._textureViews[u.binding] = texture.getGFXTextureView()!; } + if (texture) { + this._textureViews[u.binding] = texture.getGFXTextureView()!; + this._samplers[u.binding] = samplerLib.getSampler(device, texture.getGFXSamplerInfo()); + } else { console.warn('illegal texture default value ' + texName); } } @@ -408,21 +408,3 @@ const serializeDepthStencilState = (dss: GFXDepthStencilState) => { res += `,${dss.stencilFailOpBack},${dss.stencilZFailOpBack},${dss.stencilPassOpBack},${dss.stencilWriteMaskBack}`; return res; }; - -const samplerLib = new Map(); -const getSampler = (() => { - const serializeObject = (info: Object) => { - let res = ''; - for (const key of Object.keys(info).sort()) { - const value = info[key]; - res += `${key}:${typeof value === 'object' ? serializeObject(value) : value},`; - } - return res; - }; - return (device: GFXDevice, info: IGFXSamplerInfo) => { - const s = serializeObject(info); - let res = samplerLib.get(s); - if (!res) { res = device.createSampler(info); samplerLib.set(s, res); } - return res; - }; -})(); diff --git a/cocos/renderer/core/program-lib.ts b/cocos/renderer/core/program-lib.ts index 7732564082..3a5129ccd9 100644 --- a/cocos/renderer/core/program-lib.ts +++ b/cocos/renderer/core/program-lib.ts @@ -24,18 +24,21 @@ export interface IDefineValue { result: string | number; } -const mapDefine = (def: number | string | boolean) => { - switch (typeof def) { +const mapDefine = (info: IDefineInfo, def: number | string | boolean) => { + switch (info.type) { case 'boolean': return def ? 1 : 0; - case 'string': case 'number': return def; + case 'string': return def !== undefined ? def as string : info.options![0]; + case 'number': return def !== undefined ? def as number : info.range![0]; } - return 0; + console.warn(`unknown define type '${info.type}'`); + return -1; // should neven happen }; const prepareDefines = (defs: IDefineMap, tDefs: IDefineInfo[]) => { const defines: IDefineValue[] = []; - for (const { name } of tDefs) { - const result = mapDefine(defs[name]); + for (const tmpl of tDefs) { + const name = tmpl.name; + const result = mapDefine(tmpl, defs[name]); defines.push({ name, result }); } return defines; diff --git a/cocos/renderer/core/sampler-lib.ts b/cocos/renderer/core/sampler-lib.ts new file mode 100644 index 0000000000..db37cac841 --- /dev/null +++ b/cocos/renderer/core/sampler-lib.ts @@ -0,0 +1,35 @@ +// Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + +import { GFXDevice } from '../../gfx/device'; +import { GFXSampler, IGFXSamplerInfo } from '../../gfx/sampler'; + +const gfxInfo: IGFXSamplerInfo = {}; + +class SamplerLib { + protected _cache: Record = {}; + + public getSampler (device: GFXDevice, info: number[]) { + const hash = info.toString(); + const cache = this._cache[hash]; + if (cache) { return cache; } + gfxInfo.minFilter = info[0]; + gfxInfo.magFilter = info[1]; + gfxInfo.mipFilter = info[2]; + gfxInfo.addressU = info[3]; + gfxInfo.addressV = info[4]; + gfxInfo.addressW = info[5]; + gfxInfo.maxAnisotropy = info[6]; + if (info.length > 7) { + gfxInfo.cmpFunc = info[7]; + gfxInfo.borderColor = { r: info[8], g: info[9], b: info[10], a: info[11] }; + gfxInfo.minLOD = info[12]; + gfxInfo.maxLOD = info[13]; + gfxInfo.mipLODBias = info[14]; + } + const sampler = this._cache[hash] = device.createSampler(gfxInfo); + return sampler; + } +} + +export const samplerLib = new SamplerLib(); +cc.samplerLib = samplerLib; From dc7c0a91b635cc5dc3bca408bc51a3f0c163ab8f Mon Sep 17 00:00:00 2001 From: jerrywwl Date: Thu, 14 Mar 2019 19:21:34 +0800 Subject: [PATCH 3/5] fix rendering error --- cocos/3d/builtin/effects.js | 28 ++++++++++++++-------------- cocos/pipeline/render-pipeline.ts | 2 +- cocos/pipeline/ui/ui-pipeline.ts | 14 +++++++++++--- 3 files changed, 26 insertions(+), 18 deletions(-) diff --git a/cocos/3d/builtin/effects.js b/cocos/3d/builtin/effects.js index 084d5585e9..3e247da122 100644 --- a/cocos/3d/builtin/effects.js +++ b/cocos/3d/builtin/effects.js @@ -10,11 +10,11 @@ export default [ "name": "builtin-particle|particle-vs-legacy:lpvs_main|tinted-fs:add", "glsl3": { "vert": `\nprecision mediump float;\nuniform Constants {\n vec4 mainTiling_Offset;\n vec4 frameTile_velLenScale;\n};\nuniform CCGlobal {\n vec4 cc_time; \n vec4 cc_screenSize; \n vec4 cc_screenScale; \n 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 mat4 cc_matWorld;\n mat4 cc_matWorldIT;\n};\nout vec2 uv;\nout vec4 color;\nvoid computeVertPos(inout vec4 pos, vec2 vertOffset\n#if USE_BILLBOARD || USE_VERTICAL_BILLBOARD\n , mat4 view\n#endif\n#if USE_STRETCHED_BILLBOARD\n , vec3 eye\n , vec4 velocity\n , float velocityScale\n , float lengthScale\n , float size\n , float xIndex\n#endif\n) {\n#if USE_BILLBOARD\n vec3 camRight = normalize(vec3(view[0][0], view[1][0], view[2][0]));\n vec3 camUp = normalize(vec3(view[0][1], view[1][1], view[2][1]));\n pos.xyz += (camRight * vertOffset.x) + (camUp * vertOffset.y);\n#elif USE_STRETCHED_BILLBOARD\n vec3 camRight = normalize(cross(pos.xyz - eye, velocity.xyz));\n vec3 camUp = velocity.xyz * velocityScale + normalize(velocity.xyz) * lengthScale * size;\n pos.xyz += (camRight * abs(vertOffset.x) * sign(vertOffset.y)) - camUp * xIndex;\n#elif USE_HORIZONTAL_BILLBOARD\n vec3 camRight = vec3(1, 0, 0);\n vec3 camUp = vec3(0, 0, -1);\n pos.xyz += (camRight * vertOffset.x) + (camUp * vertOffset.y);\n#elif USE_VERTICAL_BILLBOARD\n vec3 camRight = normalize(vec3(view[0][0], view[1][0], view[2][0]));\n vec3 camUp = vec3(0, 1, 0);\n pos.xyz += (camRight * vertOffset.x) + (camUp * vertOffset.y);\n#else\n pos.x += vertOffset.x;\n pos.y += vertOffset.y;\n#endif\n}\nvec2 computeUV(float frameIndex, vec2 vertIndex, vec2 frameTile) {\n vec2 aniUV = vec2(0, floor(frameIndex * frameTile.y));\n aniUV.x = floor(frameIndex * frameTile.x * frameTile.y - aniUV.y * frameTile.x);\n \n vertIndex.x = 1. - vertIndex.x;\n return (aniUV.xy + vertIndex) / vec2(frameTile.x, frameTile.y);\n}\nvoid rotateCorner(inout vec2 corner, float angle) {\n float xOS = cos(angle) * corner.x - sin(angle) * corner.y;\n float yOS = sin(angle) * corner.x + cos(angle) * corner.y;\n corner.x = xOS;\n corner.y = yOS;\n}\nin vec3 a_position; \nin vec3 a_texCoord; \nin vec2 a_texCoord1; \nin vec4 a_color;\n#if USE_STRETCHED_BILLBOARD\nin vec3 a_color1; \n#endif\nvec4 lpvs_main() {\n vec4 pos = vec4(a_position, 1);\n#if USE_STRETCHED_BILLBOARD\n vec4 velocity = vec4(a_color1.xyz, 0);\n#endif\n#if !USE_WORLD_SPACE\n pos = cc_matWorld * pos;\n #if USE_STRETCHED_BILLBOARD\n velocity = cc_matWorld * velocity;\n #endif\n#endif\n vec2 cornerOffset = vec2((a_texCoord.xy - 0.5) * a_texCoord1.x);\n#if !USE_STRETCHED_BILLBOARD\n rotateCorner(cornerOffset, a_texCoord1.y);\n#endif\n computeVertPos(pos, cornerOffset\n #if USE_BILLBOARD || USE_VERTICAL_BILLBOARD\n , cc_matView\n #endif\n #if USE_STRETCHED_BILLBOARD\n , cc_cameraPos.xyz\n , velocity\n , frameTile_velLenScale.z\n , frameTile_velLenScale.w\n , a_texCoord1.x\n , a_texCoord.x\n #endif\n );\n pos = cc_matViewProj * pos;\n uv = computeUV(a_texCoord.z, a_texCoord.xy, frameTile_velLenScale.xy) * mainTiling_Offset.xy + mainTiling_Offset.zw;\n color = a_color;\n return pos;\n}\nvoid main() { gl_Position = lpvs_main(); }\n`, - "frag": `\nprecision mediump float;\nuniform CCGlobal {\n vec4 cc_time; \n vec4 cc_screenSize; \n vec4 cc_screenScale; \n 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{\n return pow(gamma, vec3(2.2));\n \n}\nvec3 LinearToSRGB(vec3 linear)\n{\n return pow(linear, vec3(0.454545));\n \n}\nvec4 PostProcess(vec4 color, float scale)\n{\n#if CC_USE_HDR\n color.rgb = SRGBToLinear(color.rgb) * scale;\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 PostProcess(col, cc_exposure.w);\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 PostProcess(col, cc_exposure.w);\n}\nout vec4 cc_FragColor;\nvoid main() { cc_FragColor = add(); }\n` + "frag": `\nprecision mediump float;\nuniform CCGlobal {\n vec4 cc_time; \n vec4 cc_screenSize; \n vec4 cc_screenScale; \n 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};\nvec4 PostProcess(vec4 color, float scale, float isHDR)\n{\n#if CC_USE_HDR\n color.rgb = mix(color.rgb, pow(color.rgb, vec3(2.2)) * scale, vec3(isHDR));\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 PostProcess(col, cc_exposure.w, cc_exposure.z);\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 PostProcess(col, cc_exposure.w, cc_exposure.z);\n}\nout vec4 cc_FragColor;\nvoid main() { cc_FragColor = add(); }\n` }, "glsl1": { "vert": `\nprecision mediump float;\nuniform vec4 mainTiling_Offset;\nuniform vec4 frameTile_velLenScale;\nuniform vec4 cc_time;\nuniform vec4 cc_screenSize;\nuniform vec4 cc_screenScale;\nuniform mat4 cc_matView;\nuniform mat4 cc_matViewInv;\nuniform mat4 cc_matProj;\nuniform mat4 cc_matProjInv;\nuniform mat4 cc_matViewProj;\nuniform mat4 cc_matViewProjInv;\nuniform vec4 cc_cameraPos;\nuniform vec4 cc_exposure;\nuniform vec4 cc_mainLitDir;\nuniform vec4 cc_mainLitColor;\nuniform vec4 cc_ambientSky;\nuniform vec4 cc_ambientGround;\nuniform mat4 cc_matWorld;\nuniform mat4 cc_matWorldIT;\nvarying vec2 uv;\nvarying vec4 color;\nvoid computeVertPos(inout vec4 pos, vec2 vertOffset\n#if USE_BILLBOARD || USE_VERTICAL_BILLBOARD\n , mat4 view\n#endif\n#if USE_STRETCHED_BILLBOARD\n , vec3 eye\n , vec4 velocity\n , float velocityScale\n , float lengthScale\n , float size\n , float xIndex\n#endif\n) {\n#if USE_BILLBOARD\n vec3 camRight = normalize(vec3(view[0][0], view[1][0], view[2][0]));\n vec3 camUp = normalize(vec3(view[0][1], view[1][1], view[2][1]));\n pos.xyz += (camRight * vertOffset.x) + (camUp * vertOffset.y);\n#elif USE_STRETCHED_BILLBOARD\n vec3 camRight = normalize(cross(pos.xyz - eye, velocity.xyz));\n vec3 camUp = velocity.xyz * velocityScale + normalize(velocity.xyz) * lengthScale * size;\n pos.xyz += (camRight * abs(vertOffset.x) * sign(vertOffset.y)) - camUp * xIndex;\n#elif USE_HORIZONTAL_BILLBOARD\n vec3 camRight = vec3(1, 0, 0);\n vec3 camUp = vec3(0, 0, -1);\n pos.xyz += (camRight * vertOffset.x) + (camUp * vertOffset.y);\n#elif USE_VERTICAL_BILLBOARD\n vec3 camRight = normalize(vec3(view[0][0], view[1][0], view[2][0]));\n vec3 camUp = vec3(0, 1, 0);\n pos.xyz += (camRight * vertOffset.x) + (camUp * vertOffset.y);\n#else\n pos.x += vertOffset.x;\n pos.y += vertOffset.y;\n#endif\n}\nvec2 computeUV(float frameIndex, vec2 vertIndex, vec2 frameTile) {\n vec2 aniUV = vec2(0, floor(frameIndex * frameTile.y));\n aniUV.x = floor(frameIndex * frameTile.x * frameTile.y - aniUV.y * frameTile.x);\n \n vertIndex.x = 1. - vertIndex.x;\n return (aniUV.xy + vertIndex) / vec2(frameTile.x, frameTile.y);\n}\nvoid rotateCorner(inout vec2 corner, float angle) {\n float xOS = cos(angle) * corner.x - sin(angle) * corner.y;\n float yOS = sin(angle) * corner.x + cos(angle) * corner.y;\n corner.x = xOS;\n corner.y = yOS;\n}\nattribute vec3 a_position; \nattribute vec3 a_texCoord; \nattribute vec2 a_texCoord1; \nattribute vec4 a_color;\n#if USE_STRETCHED_BILLBOARD\nattribute vec3 a_color1; \n#endif\nvec4 lpvs_main() {\n vec4 pos = vec4(a_position, 1);\n#if USE_STRETCHED_BILLBOARD\n vec4 velocity = vec4(a_color1.xyz, 0);\n#endif\n#if !USE_WORLD_SPACE\n pos = cc_matWorld * pos;\n #if USE_STRETCHED_BILLBOARD\n velocity = cc_matWorld * velocity;\n #endif\n#endif\n vec2 cornerOffset = vec2((a_texCoord.xy - 0.5) * a_texCoord1.x);\n#if !USE_STRETCHED_BILLBOARD\n rotateCorner(cornerOffset, a_texCoord1.y);\n#endif\n computeVertPos(pos, cornerOffset\n #if USE_BILLBOARD || USE_VERTICAL_BILLBOARD\n , cc_matView\n #endif\n #if USE_STRETCHED_BILLBOARD\n , cc_cameraPos.xyz\n , velocity\n , frameTile_velLenScale.z\n , frameTile_velLenScale.w\n , a_texCoord1.x\n , a_texCoord.x\n #endif\n );\n pos = cc_matViewProj * pos;\n uv = computeUV(a_texCoord.z, a_texCoord.xy, frameTile_velLenScale.xy) * mainTiling_Offset.xy + mainTiling_Offset.zw;\n color = a_color;\n return pos;\n}\nvoid main() { gl_Position = lpvs_main(); }\n`, - "frag": `\nprecision mediump float;\nuniform vec4 cc_time;\nuniform vec4 cc_screenSize;\nuniform vec4 cc_screenScale;\nuniform mat4 cc_matView;\nuniform mat4 cc_matViewInv;\nuniform mat4 cc_matProj;\nuniform mat4 cc_matProjInv;\nuniform mat4 cc_matViewProj;\nuniform mat4 cc_matViewProjInv;\nuniform vec4 cc_cameraPos;\nuniform vec4 cc_exposure;\nuniform vec4 cc_mainLitDir;\nuniform vec4 cc_mainLitColor;\nuniform vec4 cc_ambientSky;\nuniform vec4 cc_ambientGround;\nvec3 SRGBToLinear(vec3 gamma)\n{\n return pow(gamma, vec3(2.2));\n \n}\nvec3 LinearToSRGB(vec3 linear)\n{\n return pow(linear, vec3(0.454545));\n \n}\nvec4 PostProcess(vec4 color, float scale)\n{\n#if CC_USE_HDR\n color.rgb = SRGBToLinear(color.rgb) * scale;\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 PostProcess(col, cc_exposure.w);\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 PostProcess(col, cc_exposure.w);\n}\nvoid main() { gl_FragColor = add(); }\n` + "frag": `\nprecision mediump float;\nuniform vec4 cc_time;\nuniform vec4 cc_screenSize;\nuniform vec4 cc_screenScale;\nuniform mat4 cc_matView;\nuniform mat4 cc_matViewInv;\nuniform mat4 cc_matProj;\nuniform mat4 cc_matProjInv;\nuniform mat4 cc_matViewProj;\nuniform mat4 cc_matViewProjInv;\nuniform vec4 cc_cameraPos;\nuniform vec4 cc_exposure;\nuniform vec4 cc_mainLitDir;\nuniform vec4 cc_mainLitColor;\nuniform vec4 cc_ambientSky;\nuniform vec4 cc_ambientGround;\nvec4 PostProcess(vec4 color, float scale, float isHDR)\n{\n#if CC_USE_HDR\n color.rgb = mix(color.rgb, pow(color.rgb, vec3(2.2)) * scale, vec3(isHDR));\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 PostProcess(col, cc_exposure.w, cc_exposure.z);\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 PostProcess(col, cc_exposure.w, cc_exposure.z);\n}\nvoid main() { gl_FragColor = add(); }\n` }, "builtins": {"globals":{"blocks":["CCGlobal"], "samplers":[]}, "locals":{"blocks":["CCLocal"], "samplers":[]}}, "defines": [ @@ -51,11 +51,11 @@ export default [ "name": "builtin-skybox|sky-vs:vert|sky-fs:frag", "glsl3": { "vert": `\nprecision mediump float;\nin vec3 a_position;\nuniform CCGlobal {\n vec4 cc_time; \n vec4 cc_screenSize; \n vec4 cc_screenScale; \n 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};\nout vec3 viewDir;\nvec4 vert () {\n mat4 matViewRotOnly = mat4(mat3(cc_matView));\n vec4 clipPos = cc_matProj * matViewRotOnly * vec4(a_position, 1.0);\n viewDir = a_position;\n vec4 pos = clipPos;\n pos.z = clipPos.w * 0.99999;\n return pos;\n}\nvoid main() { gl_Position = vert(); }\n`, - "frag": `\nprecision mediump float;\nin vec3 viewDir;\nuniform samplerCube cubeMap;\nvec3 unpackNormal(vec4 nmap) {\n return nmap.xyz * 2.0 - 1.0;\n}\nvec3 unpackRGBE(vec4 rgbe) {\n return rgbe.rgb * pow(2.0, rgbe.a * 255.0 - 128.0);\n}\nuniform CCGlobal {\n vec4 cc_time; \n vec4 cc_screenSize; \n vec4 cc_screenScale; \n 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{\n return pow(gamma, vec3(2.2));\n \n}\nvec3 LinearToSRGB(vec3 linear)\n{\n return pow(linear, vec3(0.454545));\n \n}\nvec4 PostProcess(vec4 color, float scale)\n{\n#if CC_USE_HDR\n color.rgb = SRGBToLinear(color.rgb) * scale;\n#endif\n return color;\n}\nvec4 frag () {\n#if USE_RGBE_CUBEMAP\n vec3 c = unpackRGBE(texture(cubeMap, viewDir));\n c = LinearToSRGB(c / (1.0 + c));\n vec4 o = vec4(c, 1.0);\n#else\n vec4 o = texture(cubeMap, viewDir);\n#endif\n return PostProcess(o, cc_exposure.w);\n}\nout vec4 cc_FragColor;\nvoid main() { cc_FragColor = frag(); }\n` + "frag": `\nprecision mediump float;\nin vec3 viewDir;\nuniform samplerCube cubeMap;\nvec3 unpackNormal(vec4 nmap) {\n return nmap.xyz * 2.0 - 1.0;\n}\nvec3 unpackRGBE(vec4 rgbe) {\n return rgbe.rgb * pow(2.0, rgbe.a * 255.0 - 128.0);\n}\nuniform CCGlobal {\n vec4 cc_time; \n vec4 cc_screenSize; \n vec4 cc_screenScale; \n 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};\nvec4 PostProcess(vec4 color, float scale, float isHDR)\n{\n#if CC_USE_HDR\n color.rgb = mix(color.rgb, pow(color.rgb, vec3(2.2)) * scale, vec3(isHDR));\n#endif\n return color;\n}\nvec4 frag () {\n#if USE_RGBE_CUBEMAP\n vec3 c = unpackRGBE(texture(cubeMap, viewDir));\n c = LinearToSRGB(c / (1.0 + c));\n vec4 o = vec4(c, 1.0);\n#else\n vec4 o = texture(cubeMap, viewDir);\n#endif\n return PostProcess(o, cc_exposure.w, cc_exposure.z);\n}\nout vec4 cc_FragColor;\nvoid main() { cc_FragColor = frag(); }\n` }, "glsl1": { "vert": `\nprecision mediump float;\nattribute vec3 a_position;\nuniform vec4 cc_time;\nuniform vec4 cc_screenSize;\nuniform vec4 cc_screenScale;\nuniform mat4 cc_matView;\nuniform mat4 cc_matViewInv;\nuniform mat4 cc_matProj;\nuniform mat4 cc_matProjInv;\nuniform mat4 cc_matViewProj;\nuniform mat4 cc_matViewProjInv;\nuniform vec4 cc_cameraPos;\nuniform vec4 cc_exposure;\nuniform vec4 cc_mainLitDir;\nuniform vec4 cc_mainLitColor;\nuniform vec4 cc_ambientSky;\nuniform vec4 cc_ambientGround;\nvarying vec3 viewDir;\nvec4 vert () {\n mat4 matViewRotOnly = mat4(mat3(cc_matView));\n vec4 clipPos = cc_matProj * matViewRotOnly * vec4(a_position, 1.0);\n viewDir = a_position;\n vec4 pos = clipPos;\n pos.z = clipPos.w * 0.99999;\n return pos;\n}\nvoid main() { gl_Position = vert(); }\n`, - "frag": `\nprecision mediump float;\nvarying vec3 viewDir;\nuniform samplerCube cubeMap;\nvec3 unpackNormal(vec4 nmap) {\n return nmap.xyz * 2.0 - 1.0;\n}\nvec3 unpackRGBE(vec4 rgbe) {\n return rgbe.rgb * pow(2.0, rgbe.a * 255.0 - 128.0);\n}\nuniform vec4 cc_time;\nuniform vec4 cc_screenSize;\nuniform vec4 cc_screenScale;\nuniform mat4 cc_matView;\nuniform mat4 cc_matViewInv;\nuniform mat4 cc_matProj;\nuniform mat4 cc_matProjInv;\nuniform mat4 cc_matViewProj;\nuniform mat4 cc_matViewProjInv;\nuniform vec4 cc_cameraPos;\nuniform vec4 cc_exposure;\nuniform vec4 cc_mainLitDir;\nuniform vec4 cc_mainLitColor;\nuniform vec4 cc_ambientSky;\nuniform vec4 cc_ambientGround;\nvec3 SRGBToLinear(vec3 gamma)\n{\n return pow(gamma, vec3(2.2));\n \n}\nvec3 LinearToSRGB(vec3 linear)\n{\n return pow(linear, vec3(0.454545));\n \n}\nvec4 PostProcess(vec4 color, float scale)\n{\n#if CC_USE_HDR\n color.rgb = SRGBToLinear(color.rgb) * scale;\n#endif\n return color;\n}\nvec4 frag () {\n#if USE_RGBE_CUBEMAP\n vec3 c = unpackRGBE(textureCube(cubeMap, viewDir));\n c = LinearToSRGB(c / (1.0 + c));\n vec4 o = vec4(c, 1.0);\n#else\n vec4 o = textureCube(cubeMap, viewDir);\n#endif\n return PostProcess(o, cc_exposure.w);\n}\nvoid main() { gl_FragColor = frag(); }\n` + "frag": `\nprecision mediump float;\nvarying vec3 viewDir;\nuniform samplerCube cubeMap;\nvec3 unpackNormal(vec4 nmap) {\n return nmap.xyz * 2.0 - 1.0;\n}\nvec3 unpackRGBE(vec4 rgbe) {\n return rgbe.rgb * pow(2.0, rgbe.a * 255.0 - 128.0);\n}\nuniform vec4 cc_time;\nuniform vec4 cc_screenSize;\nuniform vec4 cc_screenScale;\nuniform mat4 cc_matView;\nuniform mat4 cc_matViewInv;\nuniform mat4 cc_matProj;\nuniform mat4 cc_matProjInv;\nuniform mat4 cc_matViewProj;\nuniform mat4 cc_matViewProjInv;\nuniform vec4 cc_cameraPos;\nuniform vec4 cc_exposure;\nuniform vec4 cc_mainLitDir;\nuniform vec4 cc_mainLitColor;\nuniform vec4 cc_ambientSky;\nuniform vec4 cc_ambientGround;\nvec4 PostProcess(vec4 color, float scale, float isHDR)\n{\n#if CC_USE_HDR\n color.rgb = mix(color.rgb, pow(color.rgb, vec3(2.2)) * scale, vec3(isHDR));\n#endif\n return color;\n}\nvec4 frag () {\n#if USE_RGBE_CUBEMAP\n vec3 c = unpackRGBE(textureCube(cubeMap, viewDir));\n c = LinearToSRGB(c / (1.0 + c));\n vec4 o = vec4(c, 1.0);\n#else\n vec4 o = textureCube(cubeMap, viewDir);\n#endif\n return PostProcess(o, cc_exposure.w, cc_exposure.z);\n}\nvoid main() { gl_FragColor = frag(); }\n` }, "builtins": {"globals":{"blocks":["CCGlobal"], "samplers":[]}, "locals":{"blocks":[], "samplers":[]}}, "defines": [ @@ -80,14 +80,16 @@ export default [ "name": "builtin-sprite|sprite-vs:vert|sprite-fs:frag", "glsl3": { "vert": `\nprecision mediump float;\nuniform CCGlobal {\n vec4 cc_time; \n vec4 cc_screenSize; \n vec4 cc_screenScale; \n 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};\nin vec3 a_position;\nin vec2 a_texCoord;\nin vec4 a_color;\nout vec2 uv0;\nout vec4 color;\nvec4 vert () {\n vec4 pos = vec4(a_position, 1);\n pos = cc_matViewProj * pos;\n uv0 = a_texCoord;\n color = a_color;\n return pos;\n}\nvoid main() { gl_Position = vert(); }\n`, - "frag": `\nprecision mediump float;\nin vec2 uv0;\nin vec4 color;\nuniform sampler2D mainTexture;\nvec4 frag () {\n vec4 o = vec4(1, 1, 1, 1);\n o *= texture(mainTexture, uv0);\n o *= color;\n return o;\n}\nout vec4 cc_FragColor;\nvoid main() { cc_FragColor = frag(); }\n` + "frag": `\nprecision mediump float;\nuniform CCGlobal {\n vec4 cc_time; \n vec4 cc_screenSize; \n vec4 cc_screenScale; \n 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};\nvec4 PostProcess(vec4 color, float scale, float isHDR)\n{\n#if CC_USE_HDR\n color.rgb = mix(color.rgb, pow(color.rgb, vec3(2.2)) * scale, vec3(isHDR));\n#endif\n return color;\n}\nin vec2 uv0;\nin vec4 color;\nuniform sampler2D mainTexture;\nvec4 frag () {\n vec4 o = vec4(1, 1, 1, 1);\n o *= texture(mainTexture, uv0);\n o *= color;\n return PostProcess(o, cc_exposure.w, cc_exposure.z);\n}\nout vec4 cc_FragColor;\nvoid main() { cc_FragColor = frag(); }\n` }, "glsl1": { "vert": `\nprecision mediump float;\nuniform vec4 cc_time;\nuniform vec4 cc_screenSize;\nuniform vec4 cc_screenScale;\nuniform mat4 cc_matView;\nuniform mat4 cc_matViewInv;\nuniform mat4 cc_matProj;\nuniform mat4 cc_matProjInv;\nuniform mat4 cc_matViewProj;\nuniform mat4 cc_matViewProjInv;\nuniform vec4 cc_cameraPos;\nuniform vec4 cc_exposure;\nuniform vec4 cc_mainLitDir;\nuniform vec4 cc_mainLitColor;\nuniform vec4 cc_ambientSky;\nuniform vec4 cc_ambientGround;\nattribute vec3 a_position;\nattribute vec2 a_texCoord;\nattribute vec4 a_color;\nvarying vec2 uv0;\nvarying vec4 color;\nvec4 vert () {\n vec4 pos = vec4(a_position, 1);\n pos = cc_matViewProj * pos;\n uv0 = a_texCoord;\n color = a_color;\n return pos;\n}\nvoid main() { gl_Position = vert(); }\n`, - "frag": `\nprecision mediump float;\nvarying vec2 uv0;\nvarying vec4 color;\nuniform sampler2D mainTexture;\nvec4 frag () {\n vec4 o = vec4(1, 1, 1, 1);\n o *= texture2D(mainTexture, uv0);\n o *= color;\n return o;\n}\nvoid main() { gl_FragColor = frag(); }\n` + "frag": `\nprecision mediump float;\nuniform vec4 cc_time;\nuniform vec4 cc_screenSize;\nuniform vec4 cc_screenScale;\nuniform mat4 cc_matView;\nuniform mat4 cc_matViewInv;\nuniform mat4 cc_matProj;\nuniform mat4 cc_matProjInv;\nuniform mat4 cc_matViewProj;\nuniform mat4 cc_matViewProjInv;\nuniform vec4 cc_cameraPos;\nuniform vec4 cc_exposure;\nuniform vec4 cc_mainLitDir;\nuniform vec4 cc_mainLitColor;\nuniform vec4 cc_ambientSky;\nuniform vec4 cc_ambientGround;\nvec4 PostProcess(vec4 color, float scale, float isHDR)\n{\n#if CC_USE_HDR\n color.rgb = mix(color.rgb, pow(color.rgb, vec3(2.2)) * scale, vec3(isHDR));\n#endif\n return color;\n}\nvarying vec2 uv0;\nvarying vec4 color;\nuniform sampler2D mainTexture;\nvec4 frag () {\n vec4 o = vec4(1, 1, 1, 1);\n o *= texture2D(mainTexture, uv0);\n o *= color;\n return PostProcess(o, cc_exposure.w, cc_exposure.z);\n}\nvoid main() { gl_FragColor = frag(); }\n` }, "builtins": {"globals":{"blocks":["CCGlobal"], "samplers":[]}, "locals":{"blocks":[], "samplers":[]}}, - "defines": [], + "defines": [ + {"name":"CC_USE_HDR", "type":"boolean", "defines":[]} + ], "blocks": [], "samplers": [ {"name":"mainTexture", "type":29, "count":1, "defines":[], "binding":0} @@ -106,11 +108,11 @@ export default [ "name": "builtin-standard|standard-vs:vert|standard-fs:frag", "glsl3": { "vert": `\nprecision mediump float;\nuniform CCGlobal {\n vec4 cc_time; \n vec4 cc_screenSize; \n vec4 cc_screenScale; \n 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 mat4 cc_matWorld;\n mat4 cc_matWorldIT;\n};\nuniform Constants {\n vec4 tilingOffset;\n vec4 albedo;\n vec4 albedoScale; \n vec4 pbrParams; \n vec4 pbrScale; \n vec4 emissive;\n vec4 emissiveScale;\n};\n#if CC_USE_SKINNING\nin vec4 a_weights;\nin vec4 a_joints;\nuniform CCSkinning {\n mat4 cc_matJoint[128];\n vec4 cc_jointsTextureSize;\n};\n#if CC_USE_JOINTS_TEXTURE\nuniform sampler2D cc_jointsTexture;\nmat4 getBoneMatrix(const in float i) {\n float size = cc_jointsTextureSize.x;\n float j = i * 4.0;\n float x = mod(j, size);\n float y = floor(j / size);\n float dx = 1.0 / size;\n float dy = 1.0 / size;\n y = dy * (y + 0.5);\n vec4 v1 = texture(cc_jointsTexture, vec2(dx * (x + 0.5), y));\n vec4 v2 = texture(cc_jointsTexture, vec2(dx * (x + 1.5), y));\n vec4 v3 = texture(cc_jointsTexture, vec2(dx * (x + 2.5), y));\n vec4 v4 = texture(cc_jointsTexture, vec2(dx * (x + 3.5), y));\n return mat4(v1, v2, v3, v4);\n}\n#else\nmat4 getBoneMatrix(const in float i) {\n return cc_matJoint[int(i)];\n}\n#endif\nmat4 skinMatrix() {\n return\n getBoneMatrix(a_joints.x) * a_weights.x +\n getBoneMatrix(a_joints.y) * a_weights.y +\n getBoneMatrix(a_joints.z) * a_weights.z +\n getBoneMatrix(a_joints.w) * a_weights.w;\n}\nvoid skinVertex(inout vec4 a1) {\n mat4 m = skinMatrix();\n a1 = m * a1;\n}\nvoid skinVertex(inout vec4 a1, inout vec4 a2) {\n mat4 m = skinMatrix();\n a1 = m * a1;\n a2 = m * a2;\n}\nvoid skinVertex(inout vec4 a1, inout vec4 a2, inout vec4 a3) {\n mat4 m = skinMatrix();\n a1 = m * a1;\n a2 = m * a2;\n a3 = m * a3;\n}\n#endif\nin vec3 a_position;\nin vec3 a_normal;\nout vec3 v_worldPos;\nout vec3 v_worldNormal;\n#if USE_ALBEDO_MAP || USE_NORMAL_MAP || USE_PBR_MAP || USE_EMISSIVE_MAP\n in vec2 a_texCoord;\n out vec2 v_uv;\n#endif\nvec4 vert () {\n vec4 pos = vec4(a_position, 1.0);\n vec4 normal = vec4(a_normal, 0.0);\n #if CC_USE_SKINNING\n skinVertex(pos, normal);\n #endif\n v_worldPos = (cc_matWorld * pos).xyz;\n v_worldNormal = (cc_matWorldIT * normal).xyz;\n #if USE_ALBEDO_MAP || USE_NORMAL_MAP || USE_PBR_MAP || USE_EMISSIVE_MAP\n v_uv = a_texCoord * tilingOffset.xy + tilingOffset.zw;\n #endif\n return cc_matViewProj * cc_matWorld * pos;\n}\nvoid main() { gl_Position = vert(); }\n`, - "frag": `\nprecision mediump float;\nuniform CCGlobal {\n vec4 cc_time; \n vec4 cc_screenSize; \n vec4 cc_screenScale; \n 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#define MAX_LIGHTS 2\nuniform CCForwardLight {\n vec4 cc_sphereLitPos[2]; \n vec4 cc_sphereLitSizeRange[2]; \n vec4 cc_sphereLitColor[2]; \n vec4 cc_spotLitPosSize[2]; \n vec4 cc_spotLitDirRange[2]; \n vec4 cc_spotLitColor[2]; \n};\n#define PI 3.14159265359\n#define PI2 6.28318530718\n#define EPSILON 1e-6\n#define LOG2 1.442695\n#define saturate(a) clamp( a, 0.0, 1.0 )\n#define FP_MAX = 65504.0;\n#define FP_SCALE (1.0/1024.0);\n#define FP_SCALE_INV 1024.0;\nvec3 SRGBToLinear(vec3 gamma)\n{\n return pow(gamma, vec3(2.2));\n \n}\nvec3 LinearToSRGB(vec3 linear)\n{\n return pow(linear, vec3(0.454545));\n \n}\nfloat SmoothDistAtt(float distSqr, float invSqrAttRadius)\n{\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 GetDistAtt(float distSqr, float invSqrAttRadius)\n{\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{\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{\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{\n return (roughness*0.25 + 0.25) * GGXMobile(roughness, NoH, H, N);\n}\nvec3 BRDFApprox(vec3 specular, float roughness, float NoV)\n{\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}\nuniform Constants {\n vec4 tilingOffset;\n vec4 albedo;\n vec4 albedoScale; \n vec4 pbrParams; \n vec4 pbrScale; \n vec4 emissive;\n vec4 emissiveScale;\n};\nin vec3 v_worldPos;\nin vec3 v_worldNormal;\n#if USE_ALBEDO_MAP || USE_NORMAL_MAP || USE_PBR_MAP || USE_EMISSIVE_MAP\n in vec2 v_uv;\n#endif\n#if USE_ALBEDO_MAP\n uniform sampler2D albedoMap;\n#endif\n#if USE_NORMAL_MAP\n uniform sampler2D normalMap;\n#endif\n#if USE_PBR_MAP\n uniform sampler2D pbrMap;\n#endif\n#if USE_EMISSIVE_MAP\n uniform sampler2D emissiveMap;\n#endif\n#ifdef USE_IBL\n uniform samplerCube envMap;\n#endif\n#if USE_NORMAL_MAP\n vec3 getNormal(vec3 pos, vec3 normal) {\n vec3 q0 = vec3( dFdx( pos.x ), dFdx( pos.y ), dFdx( pos.z ) );\n vec3 q1 = vec3( dFdy( pos.x ), dFdy( pos.y ), dFdy( pos.z ) );\n vec2 st0 = dFdx( v_uv.st );\n vec2 st1 = dFdy( v_uv.st );\n vec3 S = normalize( q0 * st1.t - q1 * st0.t );\n vec3 T = normalize( -q0 * st1.s + q1 * st0.s );\n vec3 N = normal;\n vec3 mapN = texture(normalMap, v_uv).rgb * 2.0 - 1.0;\n mapN.xy = 1.0 * mapN.xy;\n mat3 tsn = mat3( S, T, N );\n return normalize( tsn * mapN );\n }\n#endif\nvec4 frag () {\n #if USE_ALBEDO_MAP\n vec4 baseColor = texture(albedoMap, v_uv);\n #else\n vec4 baseColor = albedo;\n #endif\n baseColor.rgb *= albedoScale.rgb;\n baseColor.rgb = SRGBToLinear(baseColor.rgb);\n #if USE_ALPHA_TEST\n if(baseColor.a < albedoScale.a)\n discard;\n #endif\n vec3 N = normalize(v_worldNormal);\n #if USE_NORMAL_MAP\n N = getNormal(v_worldPos, N);\n #endif\n #if USE_PBR_MAP\n vec4 pbr = texture(pbrMap, v_uv);\n #else\n vec4 pbr = pbrParams;\n #endif\n pbr *= pbrScale;\n float roughness = clamp(pbr.ROUGHNESS_CHANNEL, 0.04, 1.0);\n float metallic = clamp(pbr.METALLIC_CHANNEL, 0.0, 1.0);\n vec3 diffuse = baseColor.rgb * 0.96 * (1.0 - metallic);\n vec3 specular = mix(vec3(0.04), baseColor.rgb, metallic);\n vec3 V = normalize(cc_cameraPos.xyz - v_worldPos);\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, roughness, NV);\n vec3 specularContrib = specular * CalcSpecular(roughness, NH, H, N);\n vec3 diffuseContrib = diffuse / 3.14159265359;\n vec3 finalColor = NL * cc_mainLitColor.rgb * cc_mainLitColor.w * (diffuseContrib + specularContrib);\n for (int i = 0; i < 2; i++) {\n \n vec3 PLU = cc_sphereLitPos[i].xyz - v_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 pDistSqr = dot(PLU, PLU);\n float litRadius = cc_sphereLitSizeRange[i].x;\n float litRadiusSqr = litRadius * litRadius;\n float illum = 3.14159265359 * (litRadiusSqr / max(litRadiusSqr , pDistSqr));\n float pInvSqrAttRadius = 1.0 / max(cc_sphereLitSizeRange[i].y, 0.01);\n pInvSqrAttRadius *= pInvSqrAttRadius;\n float pAtt = SmoothDistAtt(pDistSqr, pInvSqrAttRadius);\n vec3 pSpec = specular * CalcSpecular(roughness, PNH, PH, N);\n finalColor += PNL * cc_sphereLitColor[i].rgb * cc_sphereLitColor[i].w * illum * pAtt * (diffuseContrib + pSpec);\n vec3 SLU = cc_spotLitPosSize[i].xyz - v_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 cosConeAngle = max(dot(-cc_spotLitDirRange[i].xyz, SL), 0.01);\n float sInvSqrAttRadius = 1.0 / max(cc_spotLitDirRange[i].w, 0.01);\n float sDistSqr = dot(SLU, SLU);\n float sAtt = GetDistAtt(sDistSqr, sInvSqrAttRadius);\n sAtt *= cosConeAngle;\n vec3 sSpec = specular * CalcSpecular(roughness, SNH, SH, N);\n finalColor += SNL * cc_spotLitColor[i].rgb * cc_spotLitColor[i].w * sAtt * (diffuseContrib + sSpec);\n }\n float fAmb = dot(N, vec3(0.0, -1.0, 0.0)) * 0.5 + 0.5;\n vec3 ambDiff = mix(cc_ambientSky.rgb, cc_ambientGround.rgb, fAmb) * cc_ambientSky.w;\n finalColor += (ambDiff.rgb * diffuse);\n#if USE_IBL\n vec3 R = normalize(reflect(-V, N));\n vec4 env = texture(envMap, R);\n env.rgb = SRGBToLinear(env.rgb) * cc_ambientSky.w;\n finalColor += (env.rgb * specular);\n#endif\n#if CC_USE_HDR\n finalColor *= (1.0/1024.0);;\n#else\n finalColor *= cc_exposure.x;\n finalColor = LinearToSRGB(finalColor);\n#endif\n return vec4(finalColor, baseColor.a);\n}\nout vec4 cc_FragColor;\nvoid main() { cc_FragColor = frag(); }\n` + "frag": `\nprecision mediump float;\nuniform CCGlobal {\n vec4 cc_time; \n vec4 cc_screenSize; \n vec4 cc_screenScale; \n 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#define MAX_LIGHTS 2\nuniform CCForwardLight {\n vec4 cc_sphereLitPos[2]; \n vec4 cc_sphereLitSizeRange[2]; \n vec4 cc_sphereLitColor[2]; \n vec4 cc_spotLitPosSize[2]; \n vec4 cc_spotLitDirRange[2]; \n vec4 cc_spotLitColor[2]; \n};\n#define PI 3.14159265359\n#define PI2 6.28318530718\n#define EPSILON 1e-6\n#define LOG2 1.442695\n#define saturate(a) clamp( a, 0.0, 1.0 )\n#define FP_MAX = 65504.0;\n#define FP_SCALE (1.0/1024.0);\n#define FP_SCALE_INV 1024.0;\nvec3 SRGBToLinear(vec3 gamma)\n{\n return pow(gamma, vec3(2.2));\n \n}\nvec3 LinearToSRGB(vec3 linear)\n{\n return pow(linear, vec3(0.454545));\n \n}\nfloat SmoothDistAtt(float distSqr, float invSqrAttRadius)\n{\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 GetDistAtt(float distSqr, float invSqrAttRadius)\n{\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{\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{\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{\n return (roughness*0.25 + 0.25) * GGXMobile(roughness, NoH, H, N);\n}\nvec3 BRDFApprox(vec3 specular, float roughness, float NoV)\n{\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}\nuniform Constants {\n vec4 tilingOffset;\n vec4 albedo;\n vec4 albedoScale; \n vec4 pbrParams; \n vec4 pbrScale; \n vec4 emissive;\n vec4 emissiveScale;\n};\nin vec3 v_worldPos;\nin vec3 v_worldNormal;\n#if USE_ALBEDO_MAP || USE_NORMAL_MAP || USE_PBR_MAP || USE_EMISSIVE_MAP\n in vec2 v_uv;\n#endif\n#if USE_ALBEDO_MAP\n uniform sampler2D albedoMap;\n#endif\n#if USE_NORMAL_MAP\n uniform sampler2D normalMap;\n#endif\n#if USE_PBR_MAP\n uniform sampler2D pbrMap;\n#endif\n#if USE_EMISSIVE_MAP\n uniform sampler2D emissiveMap;\n#endif\n#ifdef USE_IBL\n uniform samplerCube envMap;\n#endif\n#if USE_NORMAL_MAP\n vec3 getNormal(vec3 pos, vec3 normal) {\n vec3 q0 = vec3( dFdx( pos.x ), dFdx( pos.y ), dFdx( pos.z ) );\n vec3 q1 = vec3( dFdy( pos.x ), dFdy( pos.y ), dFdy( pos.z ) );\n vec2 st0 = dFdx( v_uv.st );\n vec2 st1 = dFdy( v_uv.st );\n vec3 S = normalize( q0 * st1.t - q1 * st0.t );\n vec3 T = normalize( -q0 * st1.s + q1 * st0.s );\n vec3 N = normal;\n vec3 mapN = texture(normalMap, v_uv).rgb * 2.0 - 1.0;\n mapN.xy = 1.0 * mapN.xy;\n mat3 tsn = mat3( S, T, N );\n return normalize( tsn * mapN );\n }\n#endif\nvec4 frag () {\n #if USE_ALBEDO_MAP\n vec4 baseColor = texture(albedoMap, v_uv);\n #else\n vec4 baseColor = albedo;\n #endif\n baseColor.rgb *= albedoScale.rgb;\n baseColor.rgb = SRGBToLinear(baseColor.rgb);\n #if USE_ALPHA_TEST\n if(baseColor.a < albedoScale.a)\n discard;\n #endif\n vec3 N = normalize(v_worldNormal);\n #if USE_NORMAL_MAP\n N = getNormal(v_worldPos, N);\n #endif\n #if USE_PBR_MAP\n vec4 pbr = texture(pbrMap, v_uv);\n #else\n vec4 pbr = pbrParams;\n #endif\n pbr *= pbrScale;\n float roughness = clamp(pbr.r, 0.04, 1.0);\n float metallic = clamp(pbr.g, 0.0, 1.0);\n vec3 diffuse = baseColor.rgb * 0.96 * (1.0 - metallic);\n vec3 specular = mix(vec3(0.04), baseColor.rgb, metallic);\n vec3 V = normalize(cc_cameraPos.xyz - v_worldPos);\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, roughness, NV);\n vec3 specularContrib = specular * CalcSpecular(roughness, NH, H, N);\n vec3 diffuseContrib = diffuse / 3.14159265359;\n vec3 finalColor = NL * cc_mainLitColor.rgb * cc_mainLitColor.w * (diffuseContrib + specularContrib);\n for (int i = 0; i < 2; i++) {\n \n vec3 PLU = cc_sphereLitPos[i].xyz - v_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 pDistSqr = dot(PLU, PLU);\n float litRadius = cc_sphereLitSizeRange[i].x;\n float litRadiusSqr = litRadius * litRadius;\n float illum = 3.14159265359 * (litRadiusSqr / max(litRadiusSqr , pDistSqr));\n float pInvSqrAttRadius = 1.0 / max(cc_sphereLitSizeRange[i].y, 0.01);\n pInvSqrAttRadius *= pInvSqrAttRadius;\n float pAtt = SmoothDistAtt(pDistSqr, pInvSqrAttRadius);\n vec3 pSpec = specular * CalcSpecular(roughness, PNH, PH, N);\n finalColor += PNL * cc_sphereLitColor[i].rgb * cc_sphereLitColor[i].w * illum * pAtt * (diffuseContrib + pSpec);\n vec3 SLU = cc_spotLitPosSize[i].xyz - v_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 cosConeAngle = max(dot(-cc_spotLitDirRange[i].xyz, SL), 0.01);\n float sInvSqrAttRadius = 1.0 / max(cc_spotLitDirRange[i].w, 0.01);\n float sDistSqr = dot(SLU, SLU);\n float sAtt = GetDistAtt(sDistSqr, sInvSqrAttRadius);\n sAtt *= cosConeAngle;\n vec3 sSpec = specular * CalcSpecular(roughness, SNH, SH, N);\n finalColor += SNL * cc_spotLitColor[i].rgb * cc_spotLitColor[i].w * sAtt * (diffuseContrib + sSpec);\n }\n float fAmb = dot(N, vec3(0.0, -1.0, 0.0)) * 0.5 + 0.5;\n vec3 ambDiff = mix(cc_ambientSky.rgb, cc_ambientGround.rgb, fAmb) * cc_ambientSky.w;\n finalColor += (ambDiff.rgb * diffuse);\n#if USE_IBL\n vec3 R = normalize(reflect(-V, N));\n vec4 env = texture(envMap, R);\n env.rgb = SRGBToLinear(env.rgb) * cc_ambientSky.w;\n finalColor += (env.rgb * specular);\n#endif\n#if CC_USE_HDR\n finalColor *= (1.0/1024.0);;\n#else\n finalColor *= cc_exposure.x;\n finalColor = LinearToSRGB(finalColor);\n#endif\n return vec4(finalColor, baseColor.a);\n}\nout vec4 cc_FragColor;\nvoid main() { cc_FragColor = frag(); }\n` }, "glsl1": { "vert": `\nprecision mediump float;\nuniform vec4 cc_time;\nuniform vec4 cc_screenSize;\nuniform vec4 cc_screenScale;\nuniform mat4 cc_matView;\nuniform mat4 cc_matViewInv;\nuniform mat4 cc_matProj;\nuniform mat4 cc_matProjInv;\nuniform mat4 cc_matViewProj;\nuniform mat4 cc_matViewProjInv;\nuniform vec4 cc_cameraPos;\nuniform vec4 cc_exposure;\nuniform vec4 cc_mainLitDir;\nuniform vec4 cc_mainLitColor;\nuniform vec4 cc_ambientSky;\nuniform vec4 cc_ambientGround;\nuniform mat4 cc_matWorld;\nuniform mat4 cc_matWorldIT;\nuniform vec4 tilingOffset;\nuniform vec4 albedo;\nuniform vec4 albedoScale;\nuniform vec4 pbrParams;\nuniform vec4 pbrScale;\nuniform vec4 emissive;\nuniform vec4 emissiveScale;\n#if CC_USE_SKINNING\nattribute vec4 a_weights;\nattribute vec4 a_joints;\nuniform mat4 cc_matJoint[128];\nuniform vec4 cc_jointsTextureSize;\n#if CC_USE_JOINTS_TEXTURE\nuniform sampler2D cc_jointsTexture;\nmat4 getBoneMatrix(const in float i) {\n float size = cc_jointsTextureSize.x;\n float j = i * 4.0;\n float x = mod(j, size);\n float y = floor(j / size);\n float dx = 1.0 / size;\n float dy = 1.0 / size;\n y = dy * (y + 0.5);\n vec4 v1 = texture2D(cc_jointsTexture, vec2(dx * (x + 0.5), y));\n vec4 v2 = texture2D(cc_jointsTexture, vec2(dx * (x + 1.5), y));\n vec4 v3 = texture2D(cc_jointsTexture, vec2(dx * (x + 2.5), y));\n vec4 v4 = texture2D(cc_jointsTexture, vec2(dx * (x + 3.5), y));\n return mat4(v1, v2, v3, v4);\n}\n#else\nmat4 getBoneMatrix(const in float i) {\n return cc_matJoint[int(i)];\n}\n#endif\nmat4 skinMatrix() {\n return\n getBoneMatrix(a_joints.x) * a_weights.x +\n getBoneMatrix(a_joints.y) * a_weights.y +\n getBoneMatrix(a_joints.z) * a_weights.z +\n getBoneMatrix(a_joints.w) * a_weights.w;\n}\nvoid skinVertex(inout vec4 a1) {\n mat4 m = skinMatrix();\n a1 = m * a1;\n}\nvoid skinVertex(inout vec4 a1, inout vec4 a2) {\n mat4 m = skinMatrix();\n a1 = m * a1;\n a2 = m * a2;\n}\nvoid skinVertex(inout vec4 a1, inout vec4 a2, inout vec4 a3) {\n mat4 m = skinMatrix();\n a1 = m * a1;\n a2 = m * a2;\n a3 = m * a3;\n}\n#endif\nattribute vec3 a_position;\nattribute vec3 a_normal;\nvarying vec3 v_worldPos;\nvarying vec3 v_worldNormal;\n#if USE_ALBEDO_MAP || USE_NORMAL_MAP || USE_PBR_MAP || USE_EMISSIVE_MAP\n attribute vec2 a_texCoord;\n varying vec2 v_uv;\n#endif\nvec4 vert () {\n vec4 pos = vec4(a_position, 1.0);\n vec4 normal = vec4(a_normal, 0.0);\n #if CC_USE_SKINNING\n skinVertex(pos, normal);\n #endif\n v_worldPos = (cc_matWorld * pos).xyz;\n v_worldNormal = (cc_matWorldIT * normal).xyz;\n #if USE_ALBEDO_MAP || USE_NORMAL_MAP || USE_PBR_MAP || USE_EMISSIVE_MAP\n v_uv = a_texCoord * tilingOffset.xy + tilingOffset.zw;\n #endif\n return cc_matViewProj * cc_matWorld * pos;\n}\nvoid main() { gl_Position = vert(); }\n`, - "frag": `\nprecision mediump float;\nuniform vec4 cc_time;\nuniform vec4 cc_screenSize;\nuniform vec4 cc_screenScale;\nuniform mat4 cc_matView;\nuniform mat4 cc_matViewInv;\nuniform mat4 cc_matProj;\nuniform mat4 cc_matProjInv;\nuniform mat4 cc_matViewProj;\nuniform mat4 cc_matViewProjInv;\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#define MAX_LIGHTS 2\nuniform vec4 cc_sphereLitPos[2];\nuniform vec4 cc_sphereLitSizeRange[2];\nuniform vec4 cc_sphereLitColor[2];\nuniform vec4 cc_spotLitPosSize[2];\nuniform vec4 cc_spotLitDirRange[2];\nuniform vec4 cc_spotLitColor[2];\n#define PI 3.14159265359\n#define PI2 6.28318530718\n#define EPSILON 1e-6\n#define LOG2 1.442695\n#define saturate(a) clamp( a, 0.0, 1.0 )\n#define FP_MAX = 65504.0;\n#define FP_SCALE (1.0/1024.0);\n#define FP_SCALE_INV 1024.0;\nvec3 SRGBToLinear(vec3 gamma)\n{\n return pow(gamma, vec3(2.2));\n \n}\nvec3 LinearToSRGB(vec3 linear)\n{\n return pow(linear, vec3(0.454545));\n \n}\nfloat SmoothDistAtt(float distSqr, float invSqrAttRadius)\n{\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 GetDistAtt(float distSqr, float invSqrAttRadius)\n{\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{\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{\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{\n return (roughness*0.25 + 0.25) * GGXMobile(roughness, NoH, H, N);\n}\nvec3 BRDFApprox(vec3 specular, float roughness, float NoV)\n{\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}\nuniform vec4 tilingOffset;\nuniform vec4 albedo;\nuniform vec4 albedoScale;\nuniform vec4 pbrParams;\nuniform vec4 pbrScale;\nuniform vec4 emissive;\nuniform vec4 emissiveScale;\nvarying vec3 v_worldPos;\nvarying vec3 v_worldNormal;\n#if USE_ALBEDO_MAP || USE_NORMAL_MAP || USE_PBR_MAP || USE_EMISSIVE_MAP\n varying vec2 v_uv;\n#endif\n#if USE_ALBEDO_MAP\n uniform sampler2D albedoMap;\n#endif\n#if USE_NORMAL_MAP\n uniform sampler2D normalMap;\n#endif\n#if USE_PBR_MAP\n uniform sampler2D pbrMap;\n#endif\n#if USE_EMISSIVE_MAP\n uniform sampler2D emissiveMap;\n#endif\n#ifdef USE_IBL\n uniform samplerCube envMap;\n#endif\n#if USE_NORMAL_MAP\n vec3 getNormal(vec3 pos, vec3 normal) {\n vec3 q0 = vec3( dFdx( pos.x ), dFdx( pos.y ), dFdx( pos.z ) );\n vec3 q1 = vec3( dFdy( pos.x ), dFdy( pos.y ), dFdy( pos.z ) );\n vec2 st0 = dFdx( v_uv.st );\n vec2 st1 = dFdy( v_uv.st );\n vec3 S = normalize( q0 * st1.t - q1 * st0.t );\n vec3 T = normalize( -q0 * st1.s + q1 * st0.s );\n vec3 N = normal;\n vec3 mapN = texture2D(normalMap, v_uv).rgb * 2.0 - 1.0;\n mapN.xy = 1.0 * mapN.xy;\n mat3 tsn = mat3( S, T, N );\n return normalize( tsn * mapN );\n }\n#endif\nvec4 frag () {\n #if USE_ALBEDO_MAP\n vec4 baseColor = texture2D(albedoMap, v_uv);\n #else\n vec4 baseColor = albedo;\n #endif\n baseColor.rgb *= albedoScale.rgb;\n baseColor.rgb = SRGBToLinear(baseColor.rgb);\n #if USE_ALPHA_TEST\n if(baseColor.a < albedoScale.a)\n discard;\n #endif\n vec3 N = normalize(v_worldNormal);\n #if USE_NORMAL_MAP\n N = getNormal(v_worldPos, N);\n #endif\n #if USE_PBR_MAP\n vec4 pbr = texture2D(pbrMap, v_uv);\n #else\n vec4 pbr = pbrParams;\n #endif\n pbr *= pbrScale;\n float roughness = clamp(pbr.ROUGHNESS_CHANNEL, 0.04, 1.0);\n float metallic = clamp(pbr.METALLIC_CHANNEL, 0.0, 1.0);\n vec3 diffuse = baseColor.rgb * 0.96 * (1.0 - metallic);\n vec3 specular = mix(vec3(0.04), baseColor.rgb, metallic);\n vec3 V = normalize(cc_cameraPos.xyz - v_worldPos);\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, roughness, NV);\n vec3 specularContrib = specular * CalcSpecular(roughness, NH, H, N);\n vec3 diffuseContrib = diffuse / 3.14159265359;\n vec3 finalColor = NL * cc_mainLitColor.rgb * cc_mainLitColor.w * (diffuseContrib + specularContrib);\n for (int i = 0; i < 2; i++) {\n \n vec3 PLU = cc_sphereLitPos[i].xyz - v_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 pDistSqr = dot(PLU, PLU);\n float litRadius = cc_sphereLitSizeRange[i].x;\n float litRadiusSqr = litRadius * litRadius;\n float illum = 3.14159265359 * (litRadiusSqr / max(litRadiusSqr , pDistSqr));\n float pInvSqrAttRadius = 1.0 / max(cc_sphereLitSizeRange[i].y, 0.01);\n pInvSqrAttRadius *= pInvSqrAttRadius;\n float pAtt = SmoothDistAtt(pDistSqr, pInvSqrAttRadius);\n vec3 pSpec = specular * CalcSpecular(roughness, PNH, PH, N);\n finalColor += PNL * cc_sphereLitColor[i].rgb * cc_sphereLitColor[i].w * illum * pAtt * (diffuseContrib + pSpec);\n vec3 SLU = cc_spotLitPosSize[i].xyz - v_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 cosConeAngle = max(dot(-cc_spotLitDirRange[i].xyz, SL), 0.01);\n float sInvSqrAttRadius = 1.0 / max(cc_spotLitDirRange[i].w, 0.01);\n float sDistSqr = dot(SLU, SLU);\n float sAtt = GetDistAtt(sDistSqr, sInvSqrAttRadius);\n sAtt *= cosConeAngle;\n vec3 sSpec = specular * CalcSpecular(roughness, SNH, SH, N);\n finalColor += SNL * cc_spotLitColor[i].rgb * cc_spotLitColor[i].w * sAtt * (diffuseContrib + sSpec);\n }\n float fAmb = dot(N, vec3(0.0, -1.0, 0.0)) * 0.5 + 0.5;\n vec3 ambDiff = mix(cc_ambientSky.rgb, cc_ambientGround.rgb, fAmb) * cc_ambientSky.w;\n finalColor += (ambDiff.rgb * diffuse);\n#if USE_IBL\n vec3 R = normalize(reflect(-V, N));\n vec4 env = textureCube(envMap, R);\n env.rgb = SRGBToLinear(env.rgb) * cc_ambientSky.w;\n finalColor += (env.rgb * specular);\n#endif\n#if CC_USE_HDR\n finalColor *= (1.0/1024.0);;\n#else\n finalColor *= cc_exposure.x;\n finalColor = LinearToSRGB(finalColor);\n#endif\n return vec4(finalColor, baseColor.a);\n}\nvoid main() { gl_FragColor = frag(); }\n` + "frag": `\nprecision mediump float;\nuniform vec4 cc_time;\nuniform vec4 cc_screenSize;\nuniform vec4 cc_screenScale;\nuniform mat4 cc_matView;\nuniform mat4 cc_matViewInv;\nuniform mat4 cc_matProj;\nuniform mat4 cc_matProjInv;\nuniform mat4 cc_matViewProj;\nuniform mat4 cc_matViewProjInv;\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#define MAX_LIGHTS 2\nuniform vec4 cc_sphereLitPos[2];\nuniform vec4 cc_sphereLitSizeRange[2];\nuniform vec4 cc_sphereLitColor[2];\nuniform vec4 cc_spotLitPosSize[2];\nuniform vec4 cc_spotLitDirRange[2];\nuniform vec4 cc_spotLitColor[2];\n#define PI 3.14159265359\n#define PI2 6.28318530718\n#define EPSILON 1e-6\n#define LOG2 1.442695\n#define saturate(a) clamp( a, 0.0, 1.0 )\n#define FP_MAX = 65504.0;\n#define FP_SCALE (1.0/1024.0);\n#define FP_SCALE_INV 1024.0;\nvec3 SRGBToLinear(vec3 gamma)\n{\n return pow(gamma, vec3(2.2));\n \n}\nvec3 LinearToSRGB(vec3 linear)\n{\n return pow(linear, vec3(0.454545));\n \n}\nfloat SmoothDistAtt(float distSqr, float invSqrAttRadius)\n{\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 GetDistAtt(float distSqr, float invSqrAttRadius)\n{\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{\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{\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{\n return (roughness*0.25 + 0.25) * GGXMobile(roughness, NoH, H, N);\n}\nvec3 BRDFApprox(vec3 specular, float roughness, float NoV)\n{\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}\nuniform vec4 tilingOffset;\nuniform vec4 albedo;\nuniform vec4 albedoScale;\nuniform vec4 pbrParams;\nuniform vec4 pbrScale;\nuniform vec4 emissive;\nuniform vec4 emissiveScale;\nvarying vec3 v_worldPos;\nvarying vec3 v_worldNormal;\n#if USE_ALBEDO_MAP || USE_NORMAL_MAP || USE_PBR_MAP || USE_EMISSIVE_MAP\n varying vec2 v_uv;\n#endif\n#if USE_ALBEDO_MAP\n uniform sampler2D albedoMap;\n#endif\n#if USE_NORMAL_MAP\n uniform sampler2D normalMap;\n#endif\n#if USE_PBR_MAP\n uniform sampler2D pbrMap;\n#endif\n#if USE_EMISSIVE_MAP\n uniform sampler2D emissiveMap;\n#endif\n#ifdef USE_IBL\n uniform samplerCube envMap;\n#endif\n#if USE_NORMAL_MAP\n vec3 getNormal(vec3 pos, vec3 normal) {\n vec3 q0 = vec3( dFdx( pos.x ), dFdx( pos.y ), dFdx( pos.z ) );\n vec3 q1 = vec3( dFdy( pos.x ), dFdy( pos.y ), dFdy( pos.z ) );\n vec2 st0 = dFdx( v_uv.st );\n vec2 st1 = dFdy( v_uv.st );\n vec3 S = normalize( q0 * st1.t - q1 * st0.t );\n vec3 T = normalize( -q0 * st1.s + q1 * st0.s );\n vec3 N = normal;\n vec3 mapN = texture2D(normalMap, v_uv).rgb * 2.0 - 1.0;\n mapN.xy = 1.0 * mapN.xy;\n mat3 tsn = mat3( S, T, N );\n return normalize( tsn * mapN );\n }\n#endif\nvec4 frag () {\n #if USE_ALBEDO_MAP\n vec4 baseColor = texture2D(albedoMap, v_uv);\n #else\n vec4 baseColor = albedo;\n #endif\n baseColor.rgb *= albedoScale.rgb;\n baseColor.rgb = SRGBToLinear(baseColor.rgb);\n #if USE_ALPHA_TEST\n if(baseColor.a < albedoScale.a)\n discard;\n #endif\n vec3 N = normalize(v_worldNormal);\n #if USE_NORMAL_MAP\n N = getNormal(v_worldPos, N);\n #endif\n #if USE_PBR_MAP\n vec4 pbr = texture2D(pbrMap, v_uv);\n #else\n vec4 pbr = pbrParams;\n #endif\n pbr *= pbrScale;\n float roughness = clamp(pbr.r, 0.04, 1.0);\n float metallic = clamp(pbr.g, 0.0, 1.0);\n vec3 diffuse = baseColor.rgb * 0.96 * (1.0 - metallic);\n vec3 specular = mix(vec3(0.04), baseColor.rgb, metallic);\n vec3 V = normalize(cc_cameraPos.xyz - v_worldPos);\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, roughness, NV);\n vec3 specularContrib = specular * CalcSpecular(roughness, NH, H, N);\n vec3 diffuseContrib = diffuse / 3.14159265359;\n vec3 finalColor = NL * cc_mainLitColor.rgb * cc_mainLitColor.w * (diffuseContrib + specularContrib);\n for (int i = 0; i < 2; i++) {\n \n vec3 PLU = cc_sphereLitPos[i].xyz - v_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 pDistSqr = dot(PLU, PLU);\n float litRadius = cc_sphereLitSizeRange[i].x;\n float litRadiusSqr = litRadius * litRadius;\n float illum = 3.14159265359 * (litRadiusSqr / max(litRadiusSqr , pDistSqr));\n float pInvSqrAttRadius = 1.0 / max(cc_sphereLitSizeRange[i].y, 0.01);\n pInvSqrAttRadius *= pInvSqrAttRadius;\n float pAtt = SmoothDistAtt(pDistSqr, pInvSqrAttRadius);\n vec3 pSpec = specular * CalcSpecular(roughness, PNH, PH, N);\n finalColor += PNL * cc_sphereLitColor[i].rgb * cc_sphereLitColor[i].w * illum * pAtt * (diffuseContrib + pSpec);\n vec3 SLU = cc_spotLitPosSize[i].xyz - v_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 cosConeAngle = max(dot(-cc_spotLitDirRange[i].xyz, SL), 0.01);\n float sInvSqrAttRadius = 1.0 / max(cc_spotLitDirRange[i].w, 0.01);\n float sDistSqr = dot(SLU, SLU);\n float sAtt = GetDistAtt(sDistSqr, sInvSqrAttRadius);\n sAtt *= cosConeAngle;\n vec3 sSpec = specular * CalcSpecular(roughness, SNH, SH, N);\n finalColor += SNL * cc_spotLitColor[i].rgb * cc_spotLitColor[i].w * sAtt * (diffuseContrib + sSpec);\n }\n float fAmb = dot(N, vec3(0.0, -1.0, 0.0)) * 0.5 + 0.5;\n vec3 ambDiff = mix(cc_ambientSky.rgb, cc_ambientGround.rgb, fAmb) * cc_ambientSky.w;\n finalColor += (ambDiff.rgb * diffuse);\n#if USE_IBL\n vec3 R = normalize(reflect(-V, N));\n vec4 env = textureCube(envMap, R);\n env.rgb = SRGBToLinear(env.rgb) * cc_ambientSky.w;\n finalColor += (env.rgb * specular);\n#endif\n#if CC_USE_HDR\n finalColor *= (1.0/1024.0);;\n#else\n finalColor *= cc_exposure.x;\n finalColor = LinearToSRGB(finalColor);\n#endif\n return vec4(finalColor, baseColor.a);\n}\nvoid main() { gl_FragColor = frag(); }\n` }, "builtins": {"globals":{"blocks":["CCGlobal"], "samplers":[]}, "locals":{"blocks":["CCLocal", "CCSkinning", "CCForwardLight"], "samplers":["cc_jointsTexture"]}}, "defines": [ @@ -121,8 +123,6 @@ export default [ {"name":"USE_PBR_MAP", "type":"boolean", "defines":[]}, {"name":"USE_EMISSIVE_MAP", "type":"boolean", "defines":[]}, {"name":"USE_IBL", "type":"boolean", "defines":[]}, - {"name":"ROUGHNESS_CHANNEL", "type":"string", "options":["r", "g", "b", "a"]}, - {"name":"METALLIC_CHANNEL", "type":"string", "options":["r", "g", "b", "a"]}, {"name":"USE_ALPHA_TEST", "type":"boolean", "defines":[]}, {"name":"CC_USE_HDR", "type":"boolean", "defines":[]} ], @@ -167,7 +167,7 @@ export default [ { "name": "builtin-tonemap", "techniques": [ - {"name":"tonemap", "passes":[{"depthStencilState":{"depthTest":false, "depthWrite":false}, "program":"builtin-tonemap|tonemap-vs:vert|tonemap-fs:frag", "properties":{"u_texSampler":{"type":29}}}]} + {"name":"tonemap", "passes":[{"depthStencilState":{"depthTest":false, "depthWrite":false}, "program":"builtin-tonemap|tonemap-vs:vert|tonemap-fs:frag", "properties":{"u_texSampler":{"type":29, "sampler":{"minFilter":2, "magFilter":2, "mipFilter":0}}}}]} ], "shaders": [ { @@ -202,11 +202,11 @@ export default [ "name": "builtin-unlit|unlit-vs:vert|unlit-fs:frag", "glsl3": { "vert": `\nprecision mediump float;\nuniform CCGlobal {\n vec4 cc_time; \n vec4 cc_screenSize; \n vec4 cc_screenScale; \n 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 mat4 cc_matWorld;\n mat4 cc_matWorldIT;\n};\n#if CC_USE_SKINNING\nin vec4 a_weights;\nin vec4 a_joints;\nuniform CCSkinning {\n mat4 cc_matJoint[128];\n vec4 cc_jointsTextureSize;\n};\n#if CC_USE_JOINTS_TEXTURE\nuniform sampler2D cc_jointsTexture;\nmat4 getBoneMatrix(const in float i) {\n float size = cc_jointsTextureSize.x;\n float j = i * 4.0;\n float x = mod(j, size);\n float y = floor(j / size);\n float dx = 1.0 / size;\n float dy = 1.0 / size;\n y = dy * (y + 0.5);\n vec4 v1 = texture(cc_jointsTexture, vec2(dx * (x + 0.5), y));\n vec4 v2 = texture(cc_jointsTexture, vec2(dx * (x + 1.5), y));\n vec4 v3 = texture(cc_jointsTexture, vec2(dx * (x + 2.5), y));\n vec4 v4 = texture(cc_jointsTexture, vec2(dx * (x + 3.5), y));\n return mat4(v1, v2, v3, v4);\n}\n#else\nmat4 getBoneMatrix(const in float i) {\n return cc_matJoint[int(i)];\n}\n#endif\nmat4 skinMatrix() {\n return\n getBoneMatrix(a_joints.x) * a_weights.x +\n getBoneMatrix(a_joints.y) * a_weights.y +\n getBoneMatrix(a_joints.z) * a_weights.z +\n getBoneMatrix(a_joints.w) * a_weights.w;\n}\nvoid skinVertex(inout vec4 a1) {\n mat4 m = skinMatrix();\n a1 = m * a1;\n}\nvoid skinVertex(inout vec4 a1, inout vec4 a2) {\n mat4 m = skinMatrix();\n a1 = m * a1;\n a2 = m * a2;\n}\nvoid skinVertex(inout vec4 a1, inout vec4 a2, inout vec4 a3) {\n mat4 m = skinMatrix();\n a1 = m * a1;\n a2 = m * a2;\n a3 = m * a3;\n}\n#endif\nin vec3 a_position;\n#if USE_TEXTURE\n in vec2 a_texCoord;\n out vec2 uv0;\n uniform TexCoords {\n vec4 tilingOffset;\n };\n#endif\nvec4 vert () {\n vec4 pos = vec4(a_position, 1);\n #if CC_USE_SKINNING\n skinVertex(pos);\n #endif\n pos = cc_matViewProj * cc_matWorld * pos;\n #if USE_TEXTURE\n uv0 = a_texCoord * tilingOffset.xy + tilingOffset.zw;\n #endif\n return pos;\n}\nvoid main() { gl_Position = vert(); }\n`, - "frag": `\nprecision mediump float;\nuniform CCGlobal {\n vec4 cc_time; \n vec4 cc_screenSize; \n vec4 cc_screenScale; \n 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{\n return pow(gamma, vec3(2.2));\n \n}\nvec3 LinearToSRGB(vec3 linear)\n{\n return pow(linear, vec3(0.454545));\n \n}\nvec4 PostProcess(vec4 color, float scale)\n{\n#if CC_USE_HDR\n color.rgb = SRGBToLinear(color.rgb) * scale;\n#endif\n return color;\n}\n#if USE_TEXTURE\n in vec2 uv0;\n uniform sampler2D mainTexture;\n#endif\n#if USE_COLOR\n uniform Constant {\n vec4 color;\n };\n#endif\nvec4 frag () {\n vec4 o = vec4(1, 1, 1, 1);\n #if USE_TEXTURE\n o *= texture(mainTexture, uv0);\n #endif\n #if USE_COLOR\n o *= color;\n #endif\n return PostProcess(o, cc_exposure.w);\n}\nout vec4 cc_FragColor;\nvoid main() { cc_FragColor = frag(); }\n` + "frag": `\nprecision mediump float;\nuniform CCGlobal {\n vec4 cc_time; \n vec4 cc_screenSize; \n vec4 cc_screenScale; \n 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};\nvec4 PostProcess(vec4 color, float scale, float isHDR)\n{\n#if CC_USE_HDR\n color.rgb = mix(color.rgb, pow(color.rgb, vec3(2.2)) * scale, vec3(isHDR));\n#endif\n return color;\n}\n#if USE_TEXTURE\n in vec2 uv0;\n uniform sampler2D mainTexture;\n#endif\n#if USE_COLOR\n uniform Constant {\n vec4 color;\n };\n#endif\nvec4 frag () {\n vec4 o = vec4(1, 1, 1, 1);\n #if USE_TEXTURE\n o *= texture(mainTexture, uv0);\n #endif\n #if USE_COLOR\n o *= color;\n #endif\n return PostProcess(o, cc_exposure.w, cc_exposure.z);\n}\nout vec4 cc_FragColor;\nvoid main() { cc_FragColor = frag(); }\n` }, "glsl1": { "vert": `\nprecision mediump float;\nuniform vec4 cc_time;\nuniform vec4 cc_screenSize;\nuniform vec4 cc_screenScale;\nuniform mat4 cc_matView;\nuniform mat4 cc_matViewInv;\nuniform mat4 cc_matProj;\nuniform mat4 cc_matProjInv;\nuniform mat4 cc_matViewProj;\nuniform mat4 cc_matViewProjInv;\nuniform vec4 cc_cameraPos;\nuniform vec4 cc_exposure;\nuniform vec4 cc_mainLitDir;\nuniform vec4 cc_mainLitColor;\nuniform vec4 cc_ambientSky;\nuniform vec4 cc_ambientGround;\nuniform mat4 cc_matWorld;\nuniform mat4 cc_matWorldIT;\n#if CC_USE_SKINNING\nattribute vec4 a_weights;\nattribute vec4 a_joints;\nuniform mat4 cc_matJoint[128];\nuniform vec4 cc_jointsTextureSize;\n#if CC_USE_JOINTS_TEXTURE\nuniform sampler2D cc_jointsTexture;\nmat4 getBoneMatrix(const in float i) {\n float size = cc_jointsTextureSize.x;\n float j = i * 4.0;\n float x = mod(j, size);\n float y = floor(j / size);\n float dx = 1.0 / size;\n float dy = 1.0 / size;\n y = dy * (y + 0.5);\n vec4 v1 = texture2D(cc_jointsTexture, vec2(dx * (x + 0.5), y));\n vec4 v2 = texture2D(cc_jointsTexture, vec2(dx * (x + 1.5), y));\n vec4 v3 = texture2D(cc_jointsTexture, vec2(dx * (x + 2.5), y));\n vec4 v4 = texture2D(cc_jointsTexture, vec2(dx * (x + 3.5), y));\n return mat4(v1, v2, v3, v4);\n}\n#else\nmat4 getBoneMatrix(const in float i) {\n return cc_matJoint[int(i)];\n}\n#endif\nmat4 skinMatrix() {\n return\n getBoneMatrix(a_joints.x) * a_weights.x +\n getBoneMatrix(a_joints.y) * a_weights.y +\n getBoneMatrix(a_joints.z) * a_weights.z +\n getBoneMatrix(a_joints.w) * a_weights.w;\n}\nvoid skinVertex(inout vec4 a1) {\n mat4 m = skinMatrix();\n a1 = m * a1;\n}\nvoid skinVertex(inout vec4 a1, inout vec4 a2) {\n mat4 m = skinMatrix();\n a1 = m * a1;\n a2 = m * a2;\n}\nvoid skinVertex(inout vec4 a1, inout vec4 a2, inout vec4 a3) {\n mat4 m = skinMatrix();\n a1 = m * a1;\n a2 = m * a2;\n a3 = m * a3;\n}\n#endif\nattribute vec3 a_position;\n#if USE_TEXTURE\n attribute vec2 a_texCoord;\n varying vec2 uv0;\n uniform vec4 tilingOffset;\n#endif\nvec4 vert () {\n vec4 pos = vec4(a_position, 1);\n #if CC_USE_SKINNING\n skinVertex(pos);\n #endif\n pos = cc_matViewProj * cc_matWorld * pos;\n #if USE_TEXTURE\n uv0 = a_texCoord * tilingOffset.xy + tilingOffset.zw;\n #endif\n return pos;\n}\nvoid main() { gl_Position = vert(); }\n`, - "frag": `\nprecision mediump float;\nuniform vec4 cc_time;\nuniform vec4 cc_screenSize;\nuniform vec4 cc_screenScale;\nuniform mat4 cc_matView;\nuniform mat4 cc_matViewInv;\nuniform mat4 cc_matProj;\nuniform mat4 cc_matProjInv;\nuniform mat4 cc_matViewProj;\nuniform mat4 cc_matViewProjInv;\nuniform vec4 cc_cameraPos;\nuniform vec4 cc_exposure;\nuniform vec4 cc_mainLitDir;\nuniform vec4 cc_mainLitColor;\nuniform vec4 cc_ambientSky;\nuniform vec4 cc_ambientGround;\nvec3 SRGBToLinear(vec3 gamma)\n{\n return pow(gamma, vec3(2.2));\n \n}\nvec3 LinearToSRGB(vec3 linear)\n{\n return pow(linear, vec3(0.454545));\n \n}\nvec4 PostProcess(vec4 color, float scale)\n{\n#if CC_USE_HDR\n color.rgb = SRGBToLinear(color.rgb) * scale;\n#endif\n return color;\n}\n#if USE_TEXTURE\n varying vec2 uv0;\n uniform sampler2D mainTexture;\n#endif\n#if USE_COLOR\n uniform vec4 color;\n#endif\nvec4 frag () {\n vec4 o = vec4(1, 1, 1, 1);\n #if USE_TEXTURE\n o *= texture2D(mainTexture, uv0);\n #endif\n #if USE_COLOR\n o *= color;\n #endif\n return PostProcess(o, cc_exposure.w);\n}\nvoid main() { gl_FragColor = frag(); }\n` + "frag": `\nprecision mediump float;\nuniform vec4 cc_time;\nuniform vec4 cc_screenSize;\nuniform vec4 cc_screenScale;\nuniform mat4 cc_matView;\nuniform mat4 cc_matViewInv;\nuniform mat4 cc_matProj;\nuniform mat4 cc_matProjInv;\nuniform mat4 cc_matViewProj;\nuniform mat4 cc_matViewProjInv;\nuniform vec4 cc_cameraPos;\nuniform vec4 cc_exposure;\nuniform vec4 cc_mainLitDir;\nuniform vec4 cc_mainLitColor;\nuniform vec4 cc_ambientSky;\nuniform vec4 cc_ambientGround;\nvec4 PostProcess(vec4 color, float scale, float isHDR)\n{\n#if CC_USE_HDR\n color.rgb = mix(color.rgb, pow(color.rgb, vec3(2.2)) * scale, vec3(isHDR));\n#endif\n return color;\n}\n#if USE_TEXTURE\n varying vec2 uv0;\n uniform sampler2D mainTexture;\n#endif\n#if USE_COLOR\n uniform vec4 color;\n#endif\nvec4 frag () {\n vec4 o = vec4(1, 1, 1, 1);\n #if USE_TEXTURE\n o *= texture2D(mainTexture, uv0);\n #endif\n #if USE_COLOR\n o *= color;\n #endif\n return PostProcess(o, cc_exposure.w, cc_exposure.z);\n}\nvoid main() { gl_FragColor = frag(); }\n` }, "builtins": {"globals":{"blocks":["CCGlobal"], "samplers":[]}, "locals":{"blocks":["CCLocal", "CCSkinning"], "samplers":["cc_jointsTexture"]}}, "defines": [ diff --git a/cocos/pipeline/render-pipeline.ts b/cocos/pipeline/render-pipeline.ts index 832fd76881..740b4c6dae 100644 --- a/cocos/pipeline/render-pipeline.ts +++ b/cocos/pipeline/render-pipeline.ts @@ -526,7 +526,7 @@ export abstract class RenderPipeline { _vec4Array[0] = camera.exposure; _vec4Array[1] = _vec4Array[0] * this._fpScaleInv; - _vec4Array[2] = 0.0; + _vec4Array[2] = this._isHDR ? 1.0 : 0.0; _vec4Array[3] = 1.0 / _vec4Array[1]; this._defaultUboGlobal!.view.set(_vec4Array, UBOGlobal.EXPOSURE_OFFSET); diff --git a/cocos/pipeline/ui/ui-pipeline.ts b/cocos/pipeline/ui/ui-pipeline.ts index 7d6b730491..d595dcb71a 100644 --- a/cocos/pipeline/ui/ui-pipeline.ts +++ b/cocos/pipeline/ui/ui-pipeline.ts @@ -1,10 +1,11 @@ import { Root } from '../../core/root'; -import { RenderPassStage, UBOGlobal } from '../define'; -import { RenderPipeline, IRenderPipelineInfo } from '../render-pipeline'; +import { mat4 } from '../../core/vmath'; +import { UBOGlobal } from '../define'; +import { IRenderPipelineInfo, RenderPipeline } from '../render-pipeline'; import { RenderView } from '../render-view'; import { UIFlow } from './ui-flow'; -import { mat4 } from '../../core/vmath'; +const _vec4Array = new Float32Array(4); const _mat4Array = new Float32Array(16); export class UIPipeline extends RenderPipeline { @@ -39,6 +40,13 @@ export class UIPipeline extends RenderPipeline { const camera = view.camera; mat4.array(_mat4Array, camera.matViewProj); this._defaultUboGlobal!.view.set(_mat4Array, UBOGlobal.MAT_VIEW_PROJ_OFFSET); + + _vec4Array[0] = camera.exposure; + _vec4Array[1] = _vec4Array[0] * this._fpScaleInv; + _vec4Array[2] = 0.0; + _vec4Array[3] = 1.0 / _vec4Array[1]; + this._defaultUboGlobal!.view.set(_vec4Array, UBOGlobal.EXPOSURE_OFFSET); + // update ubos this._globalBindings.get(UBOGlobal.BLOCK.name)!.buffer!.update(this._defaultUboGlobal!.view.buffer); } From c170469c0738dd56772f606c8f92ce76df1d3986 Mon Sep 17 00:00:00 2001 From: zxg0622 <247274249@qq.com> Date: Thu, 14 Mar 2019 19:44:37 +0800 Subject: [PATCH 4/5] adjust particle property order (#4043) --- .../particle/animator/color-overtime.ts | 5 +- .../particle/animator/force-overtime.ts | 8 ++- .../animator/limit-velocity-overtime.ts | 19 ++++-- .../particle/animator/rotation-overtime.ts | 11 +++- .../particle/animator/size-overtime.ts | 12 +++- .../particle/animator/texture-animation.ts | 28 ++++++-- .../particle/animator/velocity-overtime.ts | 9 ++- .../particle/emitter/shape-module.ts | 66 ++++++++++++++----- .../particle/particle-system-component.ts | 35 ++++++++-- .../renderer/particle-system-renderer.ts | 9 ++- 10 files changed, 161 insertions(+), 41 deletions(-) diff --git a/cocos/3d/framework/particle/animator/color-overtime.ts b/cocos/3d/framework/particle/animator/color-overtime.ts index 082de437cb..261113eef4 100644 --- a/cocos/3d/framework/particle/animator/color-overtime.ts +++ b/cocos/3d/framework/particle/animator/color-overtime.ts @@ -11,11 +11,14 @@ const COLOR_OVERTIME_RAND_OFFSET = 91041; @ccclass('cc.ColorOvertimeModule') export default class ColorOvertimeModule { - @property + @property({ + displayOrder: 0, + }) public enable = false; @property({ type: GradientRange, + displayOrder: 1, }) public color = new GradientRange(); diff --git a/cocos/3d/framework/particle/animator/force-overtime.ts b/cocos/3d/framework/particle/animator/force-overtime.ts index 3c3c35068f..000d68272d 100644 --- a/cocos/3d/framework/particle/animator/force-overtime.ts +++ b/cocos/3d/framework/particle/animator/force-overtime.ts @@ -10,26 +10,32 @@ const FORCE_OVERTIME_RAND_OFFSET = 212165; @ccclass('cc.ForceOvertimeModule') export default class ForceOvertimeModule { - @property + @property({ + displayOrder: 0, + }) public enable = false; @property({ type: CurveRange, + displayOrder: 2, }) public x = new CurveRange(); @property({ type: CurveRange, + displayOrder: 3, }) public y = new CurveRange(); @property({ type: CurveRange, + displayOrder: 4, }) public z = new CurveRange(); @property({ type: Space, + displayOrder: 1, }) public space = Space.Local; diff --git a/cocos/3d/framework/particle/animator/limit-velocity-overtime.ts b/cocos/3d/framework/particle/animator/limit-velocity-overtime.ts index 5c7ad59f4a..633aeb218e 100644 --- a/cocos/3d/framework/particle/animator/limit-velocity-overtime.ts +++ b/cocos/3d/framework/particle/animator/limit-velocity-overtime.ts @@ -11,37 +11,48 @@ const LIMIT_VELOCITY_RAND_OFFSET = 23541; @ccclass('cc.LimitVelocityOvertimeModule') export default class LimitVelocityOvertimeModule { - @property + @property({ + displayOrder: 0, + }) public enable = false; @property({ type: CurveRange, + displayOrder: 4, }) public limitX = new CurveRange(); @property({ type: CurveRange, + displayOrder: 5, }) public limitY = new CurveRange(); @property({ type: CurveRange, + displayOrder: 6, }) public limitZ = new CurveRange(); @property({ type: CurveRange, + displayOrder: 3, }) public limit = new CurveRange(); - @property - public dampen = 0; + @property({ + displayOrder: 7, + }) + public dampen = 3; - @property + @property({ + displayOrder: 2, + }) public separateAxes = false; @property({ type: Space, + displayOrder: 1, }) public space = Space.Local; diff --git a/cocos/3d/framework/particle/animator/rotation-overtime.ts b/cocos/3d/framework/particle/animator/rotation-overtime.ts index 29d1de795a..4ef6bb13f5 100644 --- a/cocos/3d/framework/particle/animator/rotation-overtime.ts +++ b/cocos/3d/framework/particle/animator/rotation-overtime.ts @@ -10,13 +10,17 @@ const ROTATION_OVERTIME_RAND_OFFSET = 125292; @ccclass('cc.RotationOvertimeModule') export default class RotationOvertimeModule { - @property + @property({ + displayOrder: 0, + }) public enable = false; @property private _separateAxes = false; - @property + @property({ + displayOrder: 1, + }) get separateAxes () { return this._separateAxes; } @@ -32,16 +36,19 @@ export default class RotationOvertimeModule { @property({ type: CurveRange, + displayOrder: 2, }) public x = new CurveRange(); @property({ type: CurveRange, + displayOrder: 3, }) public y = new CurveRange(); @property({ type: CurveRange, + displayOrder: 4, }) public z = new CurveRange(); diff --git a/cocos/3d/framework/particle/animator/size-overtime.ts b/cocos/3d/framework/particle/animator/size-overtime.ts index d885bb5521..d7a5730a28 100644 --- a/cocos/3d/framework/particle/animator/size-overtime.ts +++ b/cocos/3d/framework/particle/animator/size-overtime.ts @@ -10,29 +10,37 @@ const SIZE_OVERTIME_RAND_OFFSET = 39825; @ccclass('cc.SizeOvertimeModule') export default class SizeOvertimeModule { - @property + @property({ + displayOrder: 0, + }) public enable = false; - @property + @property({ + displayOrder: 1, + }) public separateAxes = false; @property({ type: CurveRange, + displayOrder: 2, }) public size = new CurveRange(); @property({ type: CurveRange, + displayOrder: 3, }) public x = new CurveRange(); @property({ type: CurveRange, + displayOrder: 4, }) public y = new CurveRange(); @property({ type: CurveRange, + displayOrder: 5, }) public z = new CurveRange(); diff --git a/cocos/3d/framework/particle/animator/texture-animation.ts b/cocos/3d/framework/particle/animator/texture-animation.ts index 9f53738296..5a68e5ff83 100644 --- a/cocos/3d/framework/particle/animator/texture-animation.ts +++ b/cocos/3d/framework/particle/animator/texture-animation.ts @@ -25,7 +25,9 @@ export default class TextureAnimationModule { @property private _enable = false; - @property + @property({ + displayOrder: 0, + }) get enable () { return this._enable; } @@ -42,6 +44,7 @@ export default class TextureAnimationModule { @property({ type: Mode, + displayOrder: 1, }) get mode () { return this._mode; @@ -54,28 +57,37 @@ export default class TextureAnimationModule { } } - @property + @property({ + displayOrder: 2, + }) public numTilesX = 0; - @property + @property({ + displayOrder: 3, + }) public numTilesY = 0; @property({ type: Animation, + displayOrder: 4, }) public animation = Animation.WholeSheet; @property({ type: CurveRange, + displayOrder: 7, }) public frameOverTime = new CurveRange(); @property({ type: CurveRange, + displayOrder: 8, }) public startFrame = new CurveRange(); - @property + @property({ + displayOrder: 9, + }) public cycleCount = 0; @property @@ -111,10 +123,14 @@ export default class TextureAnimationModule { console.error("particle texture animation's uvChannelMask is not supported!"); } - @property + @property({ + displayOrder: 5, + }) public randomRow = false; - @property + @property({ + displayOrder: 6, + }) public rowIndex = 0; private ps: ParticleSystemComponent | null = null; diff --git a/cocos/3d/framework/particle/animator/velocity-overtime.ts b/cocos/3d/framework/particle/animator/velocity-overtime.ts index 90acc40c17..b3f0747af1 100644 --- a/cocos/3d/framework/particle/animator/velocity-overtime.ts +++ b/cocos/3d/framework/particle/animator/velocity-overtime.ts @@ -11,31 +11,38 @@ const VELOCITY_OVERTIME_RAND_OFFSET = 197866; @ccclass('cc.VelocityOvertimeModule') export default class VelocityOvertimeModule { - @property + @property({ + displayOrder: 0, + }) public enable = false; @property({ type: CurveRange, + displayOrder: 2, }) public x = new CurveRange(); @property({ type: CurveRange, + displayOrder: 3, }) public y = new CurveRange(); @property({ type: CurveRange, + displayOrder: 4, }) public z = new CurveRange(); @property({ type: CurveRange, + displayOrder: 5, }) public speedModifier = new CurveRange(); @property({ type: Space, + displayOrder: 1, }) public space = Space.Local; diff --git a/cocos/3d/framework/particle/emitter/shape-module.ts b/cocos/3d/framework/particle/emitter/shape-module.ts index 7da1634f90..82025c3e72 100644 --- a/cocos/3d/framework/particle/emitter/shape-module.ts +++ b/cocos/3d/framework/particle/emitter/shape-module.ts @@ -35,23 +35,29 @@ const ArcMode = Enum({ @ccclass('cc.ShapeModule') export default class ShapeModule { - @property + @property({ + displayOrder: 0, + }) public enable = false; @property({ type: ShapeType, + displayOrder: 1, }) public shapeType = ShapeType.Box; @property({ type: EmitLocation, + displayOrder: 2, }) public emitFrom = EmitLocation.Volume; @property private _position = new Vec3(0, 0, 0); - @property + @property({ + displayOrder: 12, + }) get position () { return this._position; } @@ -63,7 +69,9 @@ export default class ShapeModule { @property private _rotation = new Vec3(0, 0, 0); - @property + @property({ + displayOrder: 13, + }) get rotation () { return this._rotation; } @@ -75,7 +83,9 @@ export default class ShapeModule { @property private _scale = new Vec3(1, 1, 1); - @property + @property({ + displayOrder: 14, + }) get scale () { return this._scale; } @@ -84,28 +94,42 @@ export default class ShapeModule { this.constructMat(); } - @property + @property({ + displayOrder: 15, + }) public alignToDirection = false; - @property + @property({ + displayOrder: 16, + }) public randomDirectionAmount = 0; - @property + @property({ + displayOrder: 17, + }) public sphericalDirectionAmount = 0; - @property + @property({ + displayOrder: 18, + }) public randomPositionAmount = 0; - @property + @property({ + displayOrder: 3, + }) public radius = 1; - @property + @property({ + displayOrder: 4, + }) public radiusThickness = 1; @property private _arc = toRadian(360); - @property + @property({ + displayOrder: 6, + }) get arc () { return toDegree(this._arc); } @@ -116,21 +140,27 @@ export default class ShapeModule { @property({ type: ArcMode, + displayOrder: 7, }) public arcMode = ArcMode.Random; - @property - public arcSpread = 0; + @property({ + displayOrder: 0, + }) + public arcSpread = 8; @property({ type: CurveRange, + displayOrder: 9, }) public arcSpeed = new CurveRange(); @property private _angle = toRadian(25); - @property + @property({ + displayOrder: 5, + }) get angle () { return toDegree(this._angle); } @@ -139,10 +169,14 @@ export default class ShapeModule { this._angle = toRadian(val); } - @property + @property({ + displayOrder: 10, + }) public length = 0; - @property + @property({ + displayOrder: 11, + }) public boxThickness = new Vec3(0, 0, 0); private mat: mat4; diff --git a/cocos/3d/framework/particle/particle-system-component.ts b/cocos/3d/framework/particle/particle-system-component.ts index f945afbc0c..16109f3d64 100644 --- a/cocos/3d/framework/particle/particle-system-component.ts +++ b/cocos/3d/framework/particle/particle-system-component.ts @@ -29,49 +29,63 @@ const _world_mat = mat4.create(); @executeInEditMode export class ParticleSystemComponent extends Component { - @property + @property({ + displayOrder: 1, + }) public capacity = 2000; @property({ type: GradientRange, + displayOrder: 8, }) public startColor = new GradientRange(); @property({ type: CurveRange, + displayOrder: 9, }) public startSize = new CurveRange(); @property({ type: CurveRange, + displayOrder: 10, }) public startSpeed = new CurveRange(); @property({ type: CurveRange, + displayOrder: 11, }) public startRotation = new CurveRange(); @property({ type: CurveRange, + displayOrder: 6, }) public startDelay = new CurveRange(); @property({ type: CurveRange, + displayOrder: 7, }) public startLifetime = new CurveRange(); - @property + @property({ + displayOrder: 0, + }) public duration = 5.0; - @property + @property({ + displayOrder: 2, + }) public loop = true; @property private _prewarm = false; - @property + @property({ + displayOrder: 3, + }) get prewarm () { return this._prewarm; } @@ -88,6 +102,7 @@ export class ParticleSystemComponent extends Component { @property({ type: Space, + displayOrder: 4, }) get simulationSpace () { return this._simulationSpace; @@ -100,30 +115,38 @@ export class ParticleSystemComponent extends Component { } } - @property + @property({ + displayOrder: 5, + }) public simulationSpeed = 1.0; - @property + @property({ + displayOrder: 2, + }) public playOnAwake = true; @property({ type: CurveRange, + displayOrder: 12, }) public gravityModifier = new CurveRange(); // emission module @property({ type: CurveRange, + displayOrder: 13, }) public rateOverTime = new CurveRange(); @property({ type: CurveRange, + displayOrder: 14, }) public rateOverDistance = new CurveRange(); @property({ type: [Burst], + displayOrder: 15, }) public bursts = new Array(); diff --git a/cocos/3d/framework/particle/renderer/particle-system-renderer.ts b/cocos/3d/framework/particle/renderer/particle-system-renderer.ts index 5b202e8263..e3e208f7ee 100644 --- a/cocos/3d/framework/particle/renderer/particle-system-renderer.ts +++ b/cocos/3d/framework/particle/renderer/particle-system-renderer.ts @@ -46,6 +46,7 @@ export default class ParticleSystemRenderer extends RenderableComponent { @property({ type: RenderMode, + displayOrder: 0, }) public get renderMode () { return this._renderMode; @@ -60,7 +61,9 @@ export default class ParticleSystemRenderer extends RenderableComponent { this._updateModel(); } - @property + @property({ + displayOrder: 1, + }) public get velocityScale () { return this._velocityScale; } @@ -71,7 +74,9 @@ export default class ParticleSystemRenderer extends RenderableComponent { // this._updateModel(); } - @property + @property({ + displayOrder: 2, + }) public get lengthScale () { return this._lengthScale; } From 932cada8e62f7fc7f541242899647024c4acf180 Mon Sep 17 00:00:00 2001 From: JoneLau <32630749+JoneLau@users.noreply.github.com> Date: Thu, 14 Mar 2019 19:45:04 +0800 Subject: [PATCH 5/5] fix sprite-atlas serialized (#4044) --- cocos/3d/ui/components/sprite-component.ts | 53 ++++++++++++++-------- cocos/assets/sprite-atlas.ts | 48 ++++++++++++++------ 2 files changed, 66 insertions(+), 35 deletions(-) diff --git a/cocos/3d/ui/components/sprite-component.ts b/cocos/3d/ui/components/sprite-component.ts index 5af61f7098..4cdfe10c52 100644 --- a/cocos/3d/ui/components/sprite-component.ts +++ b/cocos/3d/ui/components/sprite-component.ts @@ -150,6 +150,27 @@ ccenum(SizeMode); @menu('UI/Sprite') export class SpriteComponent extends UIRenderComponent { + /** + * !#en The atlas of the sprite. + * !#zh 精灵的图集 + * @return {SpriteAtlas} + */ + @property({ + type: SpriteAtlas, + }) + get spriteAtlas () { + return this._atlas; + } + + set spriteAtlas (value) { + if (this._atlas === value) { + return; + } + + this._atlas = value; + this.spriteFrame = null; + } + /** * !#en The sprite frame of the sprite. * !#zh 精灵的精灵帧 @@ -162,7 +183,7 @@ export class SpriteComponent extends UIRenderComponent { return this._spriteFrame; } - set spriteFrame (value: SpriteFrame | null) { + set spriteFrame (value) { if (this._spriteFrame === value) { return; } @@ -347,17 +368,6 @@ export class SpriteComponent extends UIRenderComponent { } } - get spriteAtlas() { - return this._atlas; - } - - @property({ - type: cc.SpriteAtlas, - }) - set spriteAtlas(value) { - this._atlas = value; - } - public static FillType = FillType; public static Type = SpriteType; public static SizeMode = SizeMode; @@ -378,7 +388,6 @@ export class SpriteComponent extends UIRenderComponent { @property private _isTrimmedMode = true; // _state = 0; - // TODO: @property private _atlas: SpriteAtlas | null = null; // static State = State; @@ -563,13 +572,17 @@ export class SpriteComponent extends UIRenderComponent { return; } // Set atlas - if (spriteFrame && spriteFrame.atlasUuid) { - const self = this; - cc.AssetLibrary.loadAsset(spriteFrame.atlasUuid, (err, asset) => { - self._atlas = asset; - }); - } else { - this._atlas = null; + if (spriteFrame) { + if (spriteFrame.atlasUuid.length > 0) { + if (!this._atlas || this._atlas._uuid !== spriteFrame.atlasUuid) { + const self = this; + cc.AssetLibrary.loadAsset(spriteFrame.atlasUuid, (err, asset) => { + self._atlas = asset; + }); + } + }else{ + this._atlas = null; + } } } diff --git a/cocos/assets/sprite-atlas.ts b/cocos/assets/sprite-atlas.ts index 2d77ed3ff0..f3c6c82a48 100644 --- a/cocos/assets/sprite-atlas.ts +++ b/cocos/assets/sprite-atlas.ts @@ -28,20 +28,22 @@ import { ccclass, property } from '../core/data/class-decorator'; import { Asset } from './asset'; import { SpriteFrame } from './CCSpriteFrame'; -interface ISpriteAtlas { - [key: string]: SpriteFrame | null; -} - /** * !#en Class for sprite atlas handling. * !#zh 精灵图集资源类。 * @class SpriteAtlas * @extends Asset */ + +interface ISpriteAtlasSerializeData{ + name: string; + spriteFrames: string[]; +} + @ccclass('cc.SpriteAtlas') export class SpriteAtlas extends Asset { @property - public spriteFrames: ISpriteAtlas = {}; + public spriteFrames: Map = new Map(); /** * Returns the texture of the sprite atlas @@ -49,11 +51,10 @@ export class SpriteAtlas extends Asset { * @returns {Texture2D} */ public getTexture () { - const keys = Object.keys(this.spriteFrames); - if (keys.length > 0) { - const spriteFrame = this.spriteFrames[keys[0]]; - // return spriteFrame ? spriteFrame.getTexture() : null; - return spriteFrame; + const values = this.spriteFrames.values; + if (values.length > 0) { + const spriteFrame = values[0]; + return spriteFrame && spriteFrame.image ? spriteFrame.image : null; } else { return null; @@ -84,20 +85,37 @@ export class SpriteAtlas extends Asset { */ public getSpriteFrames () { const frames: Array = []; - const spriteFrames = this.spriteFrames; - - for (const key of Object.keys(spriteFrames)) { - frames.push(this.getSpriteFrame(key)); + for (const spriteFrame of this.spriteFrames) { + frames.push(spriteFrame[1]); } return frames; } public _serialize () { + const frames: string[] = []; + for (const spriteFrame of this.spriteFrames) { + const id = spriteFrame[1] ? spriteFrame[1]._uuid : ''; + frames.push(spriteFrame[0]); + frames.push(id); + } + return { - spriteFrames: this.spriteFrames, + name: this._name, + spriteFrames: frames, }; } + + public _deserialize (serializeData: any, handle: any){ + const data = serializeData as ISpriteAtlasSerializeData; + this._name = data.name; + const frames = data.spriteFrames; + this.spriteFrames.clear(); + for (let i = 0; i < frames.length; i += 2) { + this.spriteFrames.set(frames[i], new SpriteFrame()); + handle.result.push(this.spriteFrames, `${i}`, frames[i + 1]); + } + } } cc.SpriteAtlas = SpriteAtlas;