From 271a7a0b3a65893b74dfda58b21a2be29c86ecf2 Mon Sep 17 00:00:00 2001 From: Yun Hsiao Wu Date: Wed, 16 Jan 2019 13:50:37 +0800 Subject: [PATCH] material hash --- cocos/3d/assets/effect-asset.ts | 2 +- cocos/3d/assets/material.ts | 23 ++- cocos/3d/assets/mesh.ts | 8 +- cocos/3d/misc/utils.ts | 6 +- cocos/3d/primitive/box.ts | 2 - cocos/3d/primitive/define.ts | 10 +- cocos/3d/primitive/sphere.js | 1 + cocos/core/utils/murmurhash2_gc.js | 50 +++++++ cocos/gfx/shader.ts | 1 + cocos/gfx/webgl/webgl-device.ts | 54 ++++--- cocos/renderer/core/pass.ts | 35 ++++- cocos/renderer/core/program-lib.ts | 7 +- playground/camera.js | 233 +++++++++++++++++++++++++++++ playground/simple.html | 27 ++-- 14 files changed, 401 insertions(+), 58 deletions(-) create mode 100644 cocos/core/utils/murmurhash2_gc.js create mode 100644 playground/camera.js diff --git a/cocos/3d/assets/effect-asset.ts b/cocos/3d/assets/effect-asset.ts index 8b5194fdd2..c7bbbc97d4 100644 --- a/cocos/3d/assets/effect-asset.ts +++ b/cocos/3d/assets/effect-asset.ts @@ -2,7 +2,7 @@ import { Asset } from '../../assets/asset'; import { ccclass, property } from '../../core/data/class-decorator'; import { GFXPrimitiveMode } from '../../gfx/define'; import { GFXBlendState, GFXDepthStencilState, GFXRasterizerState } from '../../gfx/pipeline-state'; -import { RenderPassStage } from '../../pipeline/render-pipeline'; +import { RenderPassStage } from '../../pipeline/define'; export interface IPropertyInfo { type: number; // auto-extracted if not specified diff --git a/cocos/3d/assets/material.ts b/cocos/3d/assets/material.ts index dd82a19612..9747f6d9cf 100644 --- a/cocos/3d/assets/material.ts +++ b/cocos/3d/assets/material.ts @@ -24,6 +24,7 @@ ****************************************************************************/ import { Asset } from '../../assets/asset'; import { ccclass, property } from '../../core/data/class-decorator'; +import { murmurhash2_32_gc } from '../../core/utils/murmurhash2_gc'; import { GFXBindingType } from '../../gfx/define'; import { Effect } from '../../renderer/core/effect'; import { IPassOverrides, Pass } from '../../renderer/core/pass'; @@ -54,6 +55,7 @@ export class Material extends Asset { protected _passes: Pass[] = []; protected _owner: any = null; + protected _hash = 0; @property set effectAsset (val: EffectAsset | null) { @@ -87,6 +89,10 @@ export class Material extends Asset { return this._passes; } + get hash () { + return this._hash; + } + public setDefines (defines: Record) { this._defines = defines; this.update(); @@ -99,6 +105,7 @@ export class Material extends Asset { */ public setProperty (name: string, val: any, passIdx?: number) { if (!val) { console.warn(`illegal property value: ${val}.`); return; } + let success = false; if (passIdx === undefined) { // set property for all applicable passes const passes = this._passes; const len = passes.length; @@ -106,6 +113,7 @@ export class Material extends Asset { const pass = passes[i]; if (this._uploadProperty(pass, name, val)) { this._props[i][name] = val; + success = true; } } } else { @@ -113,14 +121,15 @@ export class Material extends Asset { const pass = this._passes[passIdx]; if (this._uploadProperty(pass, name, val)) { this._props[passIdx][name] = val; - } else { - console.warn(`illegal property name: ${name}.`); return; + success = true; } } + if (!success) { console.warn(`illegal property name: ${name}.`); return; } } public copy (mat: Material) { this._props.length = mat._props.length; + this._props.fill({}); for (let i = 0; i < mat._props.length; i++) { Object.assign(this._props[i], mat._props[i]); } @@ -143,6 +152,7 @@ export class Material extends Asset { } else { this._passes[idx].rebuildWithOverrides(passInfos[idx], overrides); } + this.prepareHash(); } public update (asset: EffectAsset | string | null = this._effectAsset, keepProps: boolean = true) { @@ -177,6 +187,7 @@ export class Material extends Asset { } else { this._props.fill({}); } + this.prepareHash(); } protected _uploadProperty (pass: Pass, name: string, val: any) { @@ -192,6 +203,14 @@ export class Material extends Asset { } return true; } + + protected prepareHash () { + let str = ''; + for (const pass of this._passes) { + str += pass.serializePipelineStates(); + } + this._hash = murmurhash2_32_gc(str, 666); + } } cc.Material = Material; diff --git a/cocos/3d/assets/mesh.ts b/cocos/3d/assets/mesh.ts index 60b4b345f0..809beaeae1 100644 --- a/cocos/3d/assets/mesh.ts +++ b/cocos/3d/assets/mesh.ts @@ -248,8 +248,10 @@ export interface IPrimitive { indexUnit: IndexUnit; }; - // for raycast purpose - geomInfo?: { + /** + * Geometric info for raycast purposes. + */ + geometricInfo?: { doubleSided?: boolean; range: IBufferRange; }; @@ -501,7 +503,7 @@ export class Mesh extends Asset { inputAssemblerInfo.indexBuffer = indexBuffer; } - const geomInfo: any = primitive.geomInfo; + const geomInfo: any = primitive.geometricInfo; if (geomInfo) { geomInfo.indices = ib; geomInfo.positions = new Float32Array(buffer, geomInfo.range.offset, geomInfo.range.length / 4); diff --git a/cocos/3d/misc/utils.ts b/cocos/3d/misc/utils.ts index 46598bc0f6..b327007067 100644 --- a/cocos/3d/misc/utils.ts +++ b/cocos/3d/misc/utils.ts @@ -101,7 +101,7 @@ export function createMesh (geometry: IGeometry) { // Create primitive. const primitive: IPrimitive = { - primitiveMode: geometry.primitiveMode, + primitiveMode: geometry.primitiveMode || GFXPrimitiveMode.TRIANGLE_LIST, vertexBundelIndices: [0], }; if (indexBuffer) { @@ -116,9 +116,9 @@ export function createMesh (geometry: IGeometry) { } // geometric info for raycasting - if (geometry.primitiveMode >= GFXPrimitiveMode.TRIANGLE_LIST) { + if (primitive.primitiveMode >= GFXPrimitiveMode.TRIANGLE_LIST) { const geomInfo = Float32Array.from(geometry.positions); - primitive.geomInfo = { + primitive.geometricInfo = { doubleSided: geometry.doubleSided, range: { offset: bufferBlob.getLength(), length: geomInfo.byteLength }, }; diff --git a/cocos/3d/primitive/box.ts b/cocos/3d/primitive/box.ts index 8b72c51041..e7e17f0d38 100644 --- a/cocos/3d/primitive/box.ts +++ b/cocos/3d/primitive/box.ts @@ -1,6 +1,5 @@ import { Vec3 } from '../../core/value-types'; import { vec3 } from '../../core/vmath'; -import { GFXPrimitiveMode } from '../../gfx/define'; import { IGeometry, IGeometryOptions } from './define'; interface IBoxOptions extends IGeometryOptions { @@ -132,7 +131,6 @@ export default function box (options?: IBoxOptions): IGeometry { _buildPlane(2, ws, ls); // TOP return { - primitiveMode: GFXPrimitiveMode.TRIANGLE_LIST, positions, normals, uvs, diff --git a/cocos/3d/primitive/define.ts b/cocos/3d/primitive/define.ts index 0dd827cdaa..9199a5dc36 100644 --- a/cocos/3d/primitive/define.ts +++ b/cocos/3d/primitive/define.ts @@ -8,11 +8,6 @@ export interface IGeometryOptions { } export interface IGeometry { - /** - * Topology of the geometry vertices. - */ - primitiveMode: GFXPrimitiveMode; - /** * Vertex positions. */ @@ -61,6 +56,11 @@ export interface IGeometry { */ colors?: number[]; + /** + * Topology of the geometry vertices. Default is TRIANGLE_LIST. + */ + primitiveMode?: GFXPrimitiveMode; + /** * whether rays casting from the back face of this geometry could collide with it */ diff --git a/cocos/3d/primitive/sphere.js b/cocos/3d/primitive/sphere.js index f7e1037801..9e22d56bce 100644 --- a/cocos/3d/primitive/sphere.js +++ b/cocos/3d/primitive/sphere.js @@ -1,6 +1,7 @@ 'use strict'; import { vec3 } from '../../core/vmath'; +import { GFXPrimitiveMode } from '../../gfx/define'; /** * @param {Number} radius diff --git a/cocos/core/utils/murmurhash2_gc.js b/cocos/core/utils/murmurhash2_gc.js new file mode 100644 index 0000000000..4e6f89fb42 --- /dev/null +++ b/cocos/core/utils/murmurhash2_gc.js @@ -0,0 +1,50 @@ +/** + * JS Implementation of MurmurHash2 + * + * @author Gary Court + * @see http://github.com/garycourt/murmurhash-js + * @author Austin Appleby + * @see http://sites.google.com/site/murmurhash/ + * + * @param {string} str ASCII only + * @param {number} seed Positive integer only + * @return {number} 32-bit positive integer hash + */ + +export function murmurhash2_32_gc(str, seed) { + var + l = str.length, + h = seed ^ l, + i = 0, + k; + + while (l >= 4) { + k = + ((str.charCodeAt(i) & 0xff)) | + ((str.charCodeAt(++i) & 0xff) << 8) | + ((str.charCodeAt(++i) & 0xff) << 16) | + ((str.charCodeAt(++i) & 0xff) << 24); + + k = (((k & 0xffff) * 0x5bd1e995) + ((((k >>> 16) * 0x5bd1e995) & 0xffff) << 16)); + k ^= k >>> 24; + k = (((k & 0xffff) * 0x5bd1e995) + ((((k >>> 16) * 0x5bd1e995) & 0xffff) << 16)); + + h = (((h & 0xffff) * 0x5bd1e995) + ((((h >>> 16) * 0x5bd1e995) & 0xffff) << 16)) ^ k; + + l -= 4; + ++i; + } + + switch (l) { + case 3: h ^= (str.charCodeAt(i + 2) & 0xff) << 16; + case 2: h ^= (str.charCodeAt(i + 1) & 0xff) << 8; + case 1: h ^= (str.charCodeAt(i) & 0xff); + h = (((h & 0xffff) * 0x5bd1e995) + ((((h >>> 16) * 0x5bd1e995) & 0xffff) << 16)); + } + + h ^= h >>> 13; + h = (((h & 0xffff) * 0x5bd1e995) + ((((h >>> 16) * 0x5bd1e995) & 0xffff) << 16)); + h ^= h >>> 15; + + return h >>> 0; +} diff --git a/cocos/gfx/shader.ts b/cocos/gfx/shader.ts index 4059d228b6..5cae992798 100644 --- a/cocos/gfx/shader.ts +++ b/cocos/gfx/shader.ts @@ -63,4 +63,5 @@ export abstract class GFXShader extends GFXObject { public abstract initialize (info: IGFXShaderInfo): boolean; public abstract destroy (); + public get name () { return this._name; } } diff --git a/cocos/gfx/webgl/webgl-device.ts b/cocos/gfx/webgl/webgl-device.ts index 74114e9b82..dc4d6d2d7b 100644 --- a/cocos/gfx/webgl/webgl-device.ts +++ b/cocos/gfx/webgl/webgl-device.ts @@ -3,7 +3,6 @@ import { GFXBuffer, GFXBufferSource, IGFXBufferInfo } from '../buffer'; import { GFXCommandAllocator, IGFXCommandAllocatorInfo } from '../command-allocator'; import { GFXCommandBuffer, IGFXCommandBufferInfo } from '../command-buffer'; import { - GFXAddress, GFXBindingType, GFXBufferTextureCopy, GFXBufferUsageBit, @@ -11,7 +10,6 @@ import { GFXFormat, GFXFormatInfos, GFXFormatSize, - GFXPrimitiveMode, GFXQueueType, GFXTextureFlagBit, GFXTextureType, @@ -75,29 +73,29 @@ import { WebGLGFXTexture } from './webgl-texture'; import { WebGLGFXTextureView } from './webgl-texture-view'; import { WebGLGFXWindow } from './webgl-window'; -const WebGLPrimitives = new Map([ - [ GFXPrimitiveMode.POINT_LIST, WebGLRenderingContext.POINTS ], - [ GFXPrimitiveMode.LINE_LIST, WebGLRenderingContext.LINES ], - [ GFXPrimitiveMode.LINE_LOOP, WebGLRenderingContext.LINE_LOOP ], - [ GFXPrimitiveMode.LINE_STRIP, WebGLRenderingContext.LINE_STRIP ], - [ GFXPrimitiveMode.TRIANGLE_LIST, WebGLRenderingContext.TRIANGLES ], - [ GFXPrimitiveMode.TRIANGLE_STRIP, WebGLRenderingContext.TRIANGLE_STRIP ], - [ GFXPrimitiveMode.TRIANGLE_FAN, WebGLRenderingContext.TRIANGLE_FAN ], - [ GFXPrimitiveMode.LINE_LIST_ADJACENCY, WebGLRenderingContext.NONE ], - [ GFXPrimitiveMode.LINE_STRIP_ADJACENCY, WebGLRenderingContext.NONE ], - [ GFXPrimitiveMode.ISO_LINE_LIST, WebGLRenderingContext.NONE ], - [ GFXPrimitiveMode.TRIANGLE_LIST_ADJACENCY, WebGLRenderingContext.NONE ], - [ GFXPrimitiveMode.TRIANGLE_STRIP_ADJACENCY, WebGLRenderingContext.NONE ], - [ GFXPrimitiveMode.TRIANGLE_PATCH_ADJACENCY, WebGLRenderingContext.NONE ], - [ GFXPrimitiveMode.QUAD_PATCH_LIST, WebGLRenderingContext.NONE ], -]); +const WebGLPrimitives: GLenum[] = [ + WebGLRenderingContext.POINTS, + WebGLRenderingContext.LINES, + WebGLRenderingContext.LINE_STRIP, + WebGLRenderingContext.LINE_LOOP, + WebGLRenderingContext.NONE, + WebGLRenderingContext.NONE, + WebGLRenderingContext.NONE, + WebGLRenderingContext.TRIANGLES, + WebGLRenderingContext.TRIANGLE_STRIP, + WebGLRenderingContext.TRIANGLE_FAN, + WebGLRenderingContext.NONE, + WebGLRenderingContext.NONE, + WebGLRenderingContext.NONE, + WebGLRenderingContext.NONE, +]; -const WebGLWraps = new Map([ - [ GFXAddress.WRAP, WebGLRenderingContext.REPEAT ], - [ GFXAddress.MIRROR, WebGLRenderingContext.MIRRORED_REPEAT ], - [ GFXAddress.CLAMP, WebGLRenderingContext.CLAMP_TO_EDGE ], - [ GFXAddress.BORDER, WebGLRenderingContext.CLAMP_TO_EDGE ], -]); +const WebGLWraps: GLenum[] = [ + WebGLRenderingContext.REPEAT, + WebGLRenderingContext.MIRRORED_REPEAT, + WebGLRenderingContext.CLAMP_TO_EDGE, + WebGLRenderingContext.CLAMP_TO_EDGE, +]; export class WebGLGFXDevice extends GFXDevice { @@ -793,9 +791,9 @@ export class WebGLGFXDevice extends GFXDevice { glMagFilter = WebGLRenderingContext.NEAREST; } - const glWrapS = (info.addressU !== undefined ? WebGLWraps.get(info.addressU)! : WebGLRenderingContext.REPEAT); - const glWrapT = (info.addressU !== undefined ? WebGLWraps.get(info.addressU)! : WebGLRenderingContext.REPEAT); - const glWrapR = (info.addressU !== undefined ? WebGLWraps.get(info.addressU)! : WebGLRenderingContext.REPEAT); + const glWrapS = (info.addressU !== undefined ? WebGLWraps[info.addressU] : WebGLRenderingContext.REPEAT); + const glWrapT = (info.addressU !== undefined ? WebGLWraps[info.addressU] : WebGLRenderingContext.REPEAT); + const glWrapR = (info.addressU !== undefined ? WebGLWraps[info.addressU] : WebGLRenderingContext.REPEAT); const gpuSampler: WebGLGPUSampler = { objType: WebGLGPUObjectType.SAMPLER, @@ -872,7 +870,7 @@ export class WebGLGFXDevice extends GFXDevice { const gpuPipelineState: WebGLGPUPipelineState = { objType: WebGLGPUObjectType.PIPELINE_STATE, - glPrimitive: WebGLPrimitives.get(info.primitive)!, + glPrimitive: WebGLPrimitives[info.primitive], gpuShader, rs: info.rs, dss: info.dss, diff --git a/cocos/renderer/core/pass.ts b/cocos/renderer/core/pass.ts index 50ba99dc85..550dbc5b84 100644 --- a/cocos/renderer/core/pass.ts +++ b/cocos/renderer/core/pass.ts @@ -211,7 +211,7 @@ export class Pass { if (this._pipelineState) { this._pipelineState.destroy(); } const ors = Object.assign({}, overrides); this._createPipelineState(info, (states) => { - if (overrides.primitive !== undefined) { states.primitive = overrides.primitive; } + if (overrides.primitive !== undefined) { this._primitive = states.primitive = overrides.primitive; } Object.assign(states.rs, ors.rs); Object.assign(states.dss, ors.dss); if (ors.bs) { @@ -246,6 +246,15 @@ export class Pass { (this._bindingLayout as GFXBindingLayout).update(); } + public serializePipelineStates () { + const ps = this._pipelineState as GFXPipelineState; + let res = `${ps.shader.name},${this._stage},${ps.primitive}`; + res += serializeBlendState(ps.blendState); + res += serializeDepthStencilState(ps.depthStencilState); + res += serializeRasterizerState(ps.rasterizerState); + return res; + } + protected _createPipelineState (info: Partial, override?: (states: IGFXPipelineStateInfo) => any) { if (info.primitive) { this._primitive = info.primitive; } if (info.stage) { this._stage = info.stage; } @@ -287,3 +296,27 @@ export class Pass { get bindingLayout () { return this._bindingLayout as GFXBindingLayout; } get primitive (): GFXPrimitiveMode { return this._primitive; } } + +function serializeBlendState (bs: GFXBlendState) { + let res = `,bs,${bs.isA2C},${bs.blendColor}`; + for (const t of bs.targets) { + res += `,bt,${t.blend},${t.blendEq},${t.blendAlphaEq},${t.blendColorMask}`; + res += `,${t.blendSrc},${t.blendDst},${t.blendSrcAlpha},${t.blendDstAlpha}`; + } + return res; +} + +function serializeRasterizerState (rs: GFXRasterizerState) { + const res = `,rs,${rs.cullMode},${rs.depthBias},${rs.depthBiasFactor},${rs.isFrontFaceCCW}`; + return res; +} + +// tslint:disable: max-line-length +function serializeDepthStencilState (dss: GFXDepthStencilState) { + let res = `,dss,${dss.depthTest},${dss.depthWrite},${dss.depthFunc}`; + res += `,${dss.stencilTestFront},${dss.stencilFuncFront},${dss.stencilRefFront},${dss.stencilReadMaskFront}`; + res += `,${dss.stencilFailOpFront},${dss.stencilZFailOpFront},${dss.stencilPassOpFront},${dss.stencilWriteMaskFront}`; + res += `,${dss.stencilTestBack},${dss.stencilFuncBack},${dss.stencilRefBack},${dss.stencilReadMaskBack}`; + res += `,${dss.stencilFailOpBack},${dss.stencilZFailOpBack},${dss.stencilPassOpBack},${dss.stencilWriteMaskBack}`; + return res; +} diff --git a/cocos/renderer/core/program-lib.ts b/cocos/renderer/core/program-lib.ts index d0f80131ca..dbc3bd05a2 100644 --- a/cocos/renderer/core/program-lib.ts +++ b/cocos/renderer/core/program-lib.ts @@ -126,9 +126,9 @@ export class ProgramLib { const vert = customDef + tmpl.vert; const frag = customDef + tmpl.frag; - tmpl.blocks = tmpl.blocks.concat(convertToBlockInfo(UBOGlobal.BLOCK), convertToBlockInfo(UBOLocal.BLOCK)); + tmpl.blocks = tmpl.blocks.concat(globals, locals); - const instanceName = Object.keys(defines).reduce((acc, cur) => `${acc}|${cur}`, name); + const instanceName = Object.keys(defines).reduce((acc, cur) => defines[cur] ? `${acc}|${cur}` : acc, name); program = this._device.createShader({ name: instanceName, blocks: tmpl.blocks, @@ -143,6 +143,9 @@ export class ProgramLib { } } +const globals = convertToBlockInfo(UBOGlobal.BLOCK); +const locals = convertToBlockInfo(UBOLocal.BLOCK); + function convertToUniformInfo (uniform: GFXUniform): IBlockMember { return { name: uniform.name, diff --git a/playground/camera.js b/playground/camera.js new file mode 100644 index 0000000000..ed608e6761 --- /dev/null +++ b/playground/camera.js @@ -0,0 +1,233 @@ +// camera + + "use strict"; + +var _dec, _class; + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +var FirstPersonCamera = (_dec = cc._decorator.ccclass(), _dec(_class = +/*#__PURE__*/ +function (_cc$Component) { + _inherits(FirstPersonCamera, _cc$Component); + + function FirstPersonCamera() { + var _this; + + _classCallCheck(this, FirstPersonCamera); + + _this = _possibleConstructorReturn(this, _getPrototypeOf(FirstPersonCamera).call(this)); + _this._lbtnDown = false; + _this._rbtnDown = false; + _this._keyStates = new Array(128); + + _this._keyStates.fill(false); + + return _this; + } + + _createClass(FirstPersonCamera, [{ + key: "start", + value: function start() { + var _this2 = this; + + var cameraComponent = this.node.getComponent("cc.CameraComponent"); + + if (!cameraComponent) { + console.error("Cannot find cc.CameraComponent on node ".concat(this.node.name)); + } + + cc.eventManager.setEnabled(true); + var mouseListener = cc.EventListener.create({ + event: cc.EventListener.MOUSE, + onMouseDown: function onMouseDown() { + return _this2._mouseDownHandler.apply(_this2, arguments); + }, + onMouseMove: function onMouseMove() { + return _this2._mouseMoveHandler.apply(_this2, arguments); + }, + onMouseUp: function onMouseUp() { + return _this2._mouseUpHandler.apply(_this2, arguments); + }, + onMouseScroll: function onMouseScroll() { + return _this2._mouseWheelHandler.apply(_this2, arguments); + } + }); + cc.eventManager.addListener(mouseListener, 1); + var keyListener = cc.EventListener.create({ + event: cc.EventListener.KEYBOARD, + onKeyPressed: function onKeyPressed() { + return _this2._keyDownHandler.apply(_this2, arguments); + }, + onKeyReleased: function onKeyReleased() { + return _this2._keyUpHandler.apply(_this2, arguments); + } + }); + cc.eventManager.addListener(keyListener, 1); + } + }, { + key: "update", + value: function update(dt) { + var _this3 = this; + + var translationDelta = dt * 10; + + var isKeyPressing = function isKeyPressing(keystr) { + return _this3._keyStates[keystr.charCodeAt(0)]; + }; + + if (isKeyPressing("W")) { + this._translate(this._getForward(), translationDelta); + } + + if (isKeyPressing("S")) { + this._translate(this._getForward(), -translationDelta); + } + + if (isKeyPressing("A")) { + this._translate(this._getRight(), -translationDelta); + } + + if (isKeyPressing("D")) { + this._translate(this._getRight(), translationDelta); + } + + if (isKeyPressing("Q")) { + this._translate(cc.v3(0, 1, 0), -translationDelta); + } + + if (isKeyPressing("E")) { + this._translate(cc.v3(0, 1, 0), translationDelta); + } + } + }, { + key: "_mouseWheelHandler", + value: function _mouseWheelHandler(event) { + var delta = event._scrollY / 120; // forward to screen is positive + + this._translate(this._getForward(), delta); + } + }, { + key: "_mouseDownHandler", + value: function _mouseDownHandler(event) { + if (event._button === 0) { + this._lbtnDown = true; + } else if (event._button === 1) { + this._mbtnDown = true; + } else if (event._button === 2) { + cc.game.canvas.requestPointerLock(); + this._rbtnDown = true; + } + } + }, { + key: "_mouseUpHandler", + value: function _mouseUpHandler(event) { + if (event._button === 0) { + this._lbtnDown = false; + } else if (event._button === 1) { + this._mbtnDown = false; + } else if (event._button === 2) { + document.exitPointerLock(); + this._rbtnDown = false; + } + } + }, { + key: "_mouseMoveHandler", + value: function _mouseMoveHandler(event) { + var dx = event.movementX; + var dy = -event.movementY; + + if (dx !== 0) { + if (this._rbtnDown) { + this._rotateSelfHorizon(dx / 5); + } + } + + if (dy !== 0) { + if (this._rbtnDown) { + this._rotateSelfVertical(dy / 5); + } + } + } + }, { + key: "_keyDownHandler", + value: function _keyDownHandler(keycode) { + if (keycode < this._keyStates.length) { + this._keyStates[keycode] = true; + } + } + }, { + key: "_keyUpHandler", + value: function _keyUpHandler(keycode) { + if (keycode < this._keyStates.length) { + this._keyStates[keycode] = false; + } + } + }, { + key: "_translate", + value: function _translate(direction, delta) { + var position = this.node.getPosition(); + cc.vmath.vec3.scaleAndAdd(position, position, direction, delta); + this.node.setPosition(position); + } + }, { + key: "_rotateSelfHorizon", + value: function _rotateSelfHorizon(delta) { + var rotation = this.node.getRotation(); + var up = cc.v3(0, 1, 0); //const up = this._getUp(); + + cc.vmath.quat.rotateAround(rotation, rotation, up, -delta / 360.0 * 3.14159265); + this.node.setRotation(rotation); + } + }, { + key: "_rotateSelfVertical", + value: function _rotateSelfVertical(delta) { + var rotation = this.node.getRotation(); //const right = cc.v3(1, 0, 0); + + var right = this._getRight(); + + cc.vmath.quat.rotateAround(rotation, rotation, right, delta / 360.0 * 3.14159265); + this.node.setRotation(rotation); + } + }, { + key: "_getForward", + value: function _getForward() { + return this._getDirection(0, 0, -1); + } + }, { + key: "_getRight", + value: function _getRight() { + return this._getDirection(1, 0, 0); + } + }, { + key: "_getUp", + value: function _getUp() { + return this._getDirection(0, 1, 0); + } + }, { + key: "_getDirection", + value: function _getDirection(x, y, z) { + var result = cc.v3(x, y, z); + cc.vmath.vec3.transformQuat(result, result, this.node.getRotation()); + return result; + } + }]); + + return FirstPersonCamera; +}(cc.Component)) || _class); diff --git a/playground/simple.html b/playground/simple.html index 689fefbf9f..a69d94197d 100644 --- a/playground/simple.html +++ b/playground/simple.html @@ -28,6 +28,7 @@ +