123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143 |
- module BABYLON {
- export class _InstancesBatch {
- public mustReturn = false;
- public visibleInstances = new Array<Array<InstancedMesh>>();
- public renderSelf = new Array<boolean>();
- }
- export class Mesh extends AbstractMesh implements IGetSetVerticesData {
- // Members
- public delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
- public instances = new Array<InstancedMesh>();
- public delayLoadingFile: string;
- public _binaryInfo: any;
- private _LODLevels = new Array<BABYLON.Internals.MeshLODLevel>();
- // Private
- public _geometry: Geometry;
- private _onBeforeRenderCallbacks = new Array<() => void>();
- private _onAfterRenderCallbacks = new Array<() => void>();
- public _delayInfo; //ANY
- public _delayLoadingFunction: (any, Mesh) => void;
- public _visibleInstances: any = {};
- private _renderIdForInstances = new Array<number>();
- private _batchCache = new _InstancesBatch();
- private _worldMatricesInstancesBuffer: WebGLBuffer;
- private _worldMatricesInstancesArray: Float32Array;
- private _instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
- public _shouldGenerateFlatShading: boolean;
- private _preActivateId: number;
- private _attachedLODLevel: BABYLON.Internals.MeshLODLevel;
- constructor(name: string, scene: Scene) {
- super(name, scene);
- }
- // Methods
- private _sortLODLevels(): void {
- this._LODLevels.sort((a, b) => {
- if (a.distance < b.distance) {
- return 1;
- }
- if (a.distance > b.distance) {
- return -1;
- }
- return 0;
- });
- }
- public addLODLevel(distance: number, mesh: Mesh): Mesh {
- var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
- this._LODLevels.push(level);
- if (mesh) {
- mesh._attachedLODLevel = level;
- }
- this._sortLODLevels();
- return this;
- }
- public removeLODLevel(mesh: Mesh): Mesh {
- if (mesh && !mesh._attachedLODLevel) {
- return this;
- }
- var index;
- if (mesh) {
- index = this._LODLevels.indexOf(mesh._attachedLODLevel);
- mesh._attachedLODLevel = null;
- this._LODLevels.splice(index, 1);
- this._sortLODLevels();
- } else {
- for (index = 0; index < this._LODLevels.length; index++) {
- if (this._LODLevels[index].mesh === null) {
- this._LODLevels.splice(index, 1);
- break;
- }
- }
- }
- return this;
- }
- public getLOD(camera: Camera): AbstractMesh {
- if (!this._LODLevels || this._LODLevels.length === 0) {
- return this;
- }
- var distanceToCamera = this.getBoundingInfo().boundingSphere.centerWorld.subtract(camera.position).length();
- if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
- return this;
- }
- for (var index = 0; index < this._LODLevels.length; index++) {
- var level = this._LODLevels[index];
- if (level.distance < distanceToCamera) {
- if (level.mesh) {
- level.mesh._worldMatrix = this._worldMatrix;
- }
- return level.mesh;
- }
- }
- return this;
- }
- public get geometry(): Geometry {
- return this._geometry;
- }
- public getTotalVertices(): number {
- if (!this._geometry) {
- return 0;
- }
- return this._geometry.getTotalVertices();
- }
- public getVerticesData(kind: string): number[] {
- if (!this._geometry) {
- return null;
- }
- return this._geometry.getVerticesData(kind);
- }
- public getVertexBuffer(kind): VertexBuffer {
- if (!this._geometry) {
- return undefined;
- }
- return this._geometry.getVertexBuffer(kind);
- }
- public isVerticesDataPresent(kind: string): boolean {
- if (!this._geometry) {
- if (this._delayInfo) {
- return this._delayInfo.indexOf(kind) !== -1;
- }
- return false;
- }
- return this._geometry.isVerticesDataPresent(kind);
- }
- public getVerticesDataKinds(): string[] {
- if (!this._geometry) {
- var result = [];
- if (this._delayInfo) {
- for (var kind in this._delayInfo) {
- result.push(kind);
- }
- }
- return result;
- }
- return this._geometry.getVerticesDataKinds();
- }
- public getTotalIndices(): number {
- if (!this._geometry) {
- return 0;
- }
- return this._geometry.getTotalIndices();
- }
- public getIndices(): number[] {
- if (!this._geometry) {
- return [];
- }
- return this._geometry.getIndices();
- }
- public get isBlocked(): boolean {
- return this._attachedLODLevel !== null && this._attachedLODLevel !== undefined;
- }
- public isReady(): boolean {
- if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
- return false;
- }
- return super.isReady();
- }
- public isDisposed(): boolean {
- return this._isDisposed;
- }
- // Methods
- public _preActivate(): void {
- var sceneRenderId = this.getScene().getRenderId();
- if (this._preActivateId == sceneRenderId) {
- return;
- }
- this._preActivateId = sceneRenderId;
- this._visibleInstances = null;
- }
- public _registerInstanceForRenderId(instance: InstancedMesh, renderId: number) {
- if (!this._visibleInstances) {
- this._visibleInstances = {};
- this._visibleInstances.defaultRenderId = renderId;
- this._visibleInstances.selfDefaultRenderId = this._renderId;
- }
- if (!this._visibleInstances[renderId]) {
- this._visibleInstances[renderId] = new Array<InstancedMesh>();
- }
- this._visibleInstances[renderId].push(instance);
- }
- public refreshBoundingInfo(): void {
- var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
- if (data) {
- var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
- this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
- }
- if (this.subMeshes) {
- for (var index = 0; index < this.subMeshes.length; index++) {
- this.subMeshes[index].refreshBoundingInfo();
- }
- }
- this._updateBoundingInfo();
- }
- public _createGlobalSubMesh(): SubMesh {
- var totalVertices = this.getTotalVertices();
- if (!totalVertices || !this.getIndices()) {
- return null;
- }
- this.releaseSubMeshes();
- return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
- }
- public subdivide(count: number): void {
- if (count < 1) {
- return;
- }
- var totalIndices = this.getTotalIndices();
- var subdivisionSize = (totalIndices / count) | 0;
- var offset = 0;
- // Ensure that subdivisionSize is a multiple of 3
- while (subdivisionSize % 3 != 0) {
- subdivisionSize++;
- }
- this.releaseSubMeshes();
- for (var index = 0; index < count; index++) {
- if (offset >= totalIndices) {
- break;
- }
- BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
- offset += subdivisionSize;
- }
- this.synchronizeInstances();
- }
- public setVerticesData(kind: any, data: any, updatable?: boolean): void {
- if (kind instanceof Array) {
- var temp = data;
- data = kind;
- kind = temp;
- Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
- }
- if (!this._geometry) {
- var vertexData = new BABYLON.VertexData();
- vertexData.set(data, kind);
- var scene = this.getScene();
- new BABYLON.Geometry(Geometry.RandomId(), scene, vertexData, updatable, this);
- }
- else {
- this._geometry.setVerticesData(kind, data, updatable);
- }
- }
- public updateVerticesData(kind: string, data: number[], updateExtends?: boolean, makeItUnique?: boolean): void {
- if (!this._geometry) {
- return;
- }
- if (!makeItUnique) {
- this._geometry.updateVerticesData(kind, data, updateExtends);
- }
- else {
- this.makeGeometryUnique();
- this.updateVerticesData(kind, data, updateExtends, false);
- }
- }
- public updateVerticesDataDirectly(kind: string, data: Float32Array, makeItUnique?: boolean): void {
- if (!this._geometry) {
- return;
- }
- if (!makeItUnique) {
- this._geometry.updateVerticesDataDirectly(kind, data);
- }
- else {
- this.makeGeometryUnique();
- this.updateVerticesDataDirectly(kind, data, false);
- }
- }
- public makeGeometryUnique() {
- if (!this._geometry) {
- return;
- }
- var geometry = this._geometry.copy(Geometry.RandomId());
- geometry.applyToMesh(this);
- }
- public setIndices(indices: number[]): void {
- if (!this._geometry) {
- var vertexData = new BABYLON.VertexData();
- vertexData.indices = indices;
- var scene = this.getScene();
- new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
- }
- else {
- this._geometry.setIndices(indices);
- }
- }
- public _bind(subMesh: SubMesh, effect: Effect, fillMode: number): void {
- var engine = this.getScene().getEngine();
- // Wireframe
- var indexToBind;
- switch (fillMode) {
- case Material.PointFillMode:
- indexToBind = null;
- break;
- case Material.WireFrameFillMode:
- indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
- break;
- default:
- case Material.TriangleFillMode:
- indexToBind = this._geometry.getIndexBuffer();
- break;
- }
- // VBOs
- engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
- }
- public _draw(subMesh: SubMesh, fillMode: number, instancesCount?: number): void {
- if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
- return;
- }
- var engine = this.getScene().getEngine();
- // Draw order
- switch (fillMode) {
- case Material.PointFillMode:
- engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
- break;
- case Material.WireFrameFillMode:
- engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
- break;
- default:
- engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
- }
- }
- public registerBeforeRender(func: () => void): void {
- this._onBeforeRenderCallbacks.push(func);
- }
- public unregisterBeforeRender(func: () => void): void {
- var index = this._onBeforeRenderCallbacks.indexOf(func);
- if (index > -1) {
- this._onBeforeRenderCallbacks.splice(index, 1);
- }
- }
- public registerAfterRender(func: () => void): void {
- this._onAfterRenderCallbacks.push(func);
- }
- public unregisterAfterRender(func: () => void): void {
- var index = this._onAfterRenderCallbacks.indexOf(func);
- if (index > -1) {
- this._onAfterRenderCallbacks.splice(index, 1);
- }
- }
- public _getInstancesRenderList(subMeshId: number): _InstancesBatch {
- var scene = this.getScene();
- this._batchCache.mustReturn = false;
- this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
- this._batchCache.visibleInstances[subMeshId] = null;
- if (this._visibleInstances) {
- var currentRenderId = scene.getRenderId();
- this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
- var selfRenderId = this._renderId;
- if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
- this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
- currentRenderId = this._visibleInstances.defaultRenderId;
- selfRenderId = this._visibleInstances.selfDefaultRenderId;
- }
- if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
- if (this._renderIdForInstances[subMeshId] === currentRenderId) {
- this._batchCache.mustReturn = true;
- return this._batchCache;
- }
- if (currentRenderId !== selfRenderId) {
- this._batchCache.renderSelf[subMeshId] = false;
- }
- }
- this._renderIdForInstances[subMeshId] = currentRenderId;
- }
- return this._batchCache;
- }
- public _renderWithInstances(subMesh: SubMesh, fillMode: number, batch: _InstancesBatch, effect: Effect, engine: Engine): void {
- var matricesCount = this.instances.length + 1;
- var bufferSize = matricesCount * 16 * 4;
- while (this._instancesBufferSize < bufferSize) {
- this._instancesBufferSize *= 2;
- }
- if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
- if (this._worldMatricesInstancesBuffer) {
- engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
- }
- this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
- this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
- }
- var offset = 0;
- var instancesCount = 0;
- var world = this.getWorldMatrix();
- if (batch.renderSelf[subMesh._id]) {
- world.copyToArray(this._worldMatricesInstancesArray, offset);
- offset += 16;
- instancesCount++;
- }
- var visibleInstances = batch.visibleInstances[subMesh._id];
- if (visibleInstances) {
- for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
- var instance = visibleInstances[instanceIndex];
- instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
- offset += 16;
- instancesCount++;
- }
- }
- var offsetLocation0 = effect.getAttributeLocationByName("world0");
- var offsetLocation1 = effect.getAttributeLocationByName("world1");
- var offsetLocation2 = effect.getAttributeLocationByName("world2");
- var offsetLocation3 = effect.getAttributeLocationByName("world3");
- var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
- engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
- this._draw(subMesh, fillMode, instancesCount);
- engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
- }
- public render(subMesh: SubMesh): void {
- var scene = this.getScene();
- // Managing instances
- var batch = this._getInstancesRenderList(subMesh._id);
- if (batch.mustReturn) {
- return;
- }
- // Checking geometry state
- if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
- return;
- }
- for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
- this._onBeforeRenderCallbacks[callbackIndex]();
- }
- var engine = scene.getEngine();
- var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
- // Material
- var effectiveMaterial = subMesh.getMaterial();
- if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
- return;
- }
- // Outline - step 1
- var savedDepthWrite = engine.getDepthWrite();
- if (this.renderOutline) {
- engine.setDepthWrite(false);
- scene.getOutlineRenderer().render(subMesh, batch);
- }
- effectiveMaterial._preBind();
- var effect = effectiveMaterial.getEffect();
- // Bind
- var fillMode = engine.forceWireframe ? Material.WireFrameFillMode : effectiveMaterial.fillMode;
- this._bind(subMesh, effect, fillMode);
- var world = this.getWorldMatrix();
- effectiveMaterial.bind(world, this);
- // Instances rendering
- if (hardwareInstancedRendering) {
- this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
- } else {
- if (batch.renderSelf[subMesh._id]) {
- // Draw
- this._draw(subMesh, fillMode);
- }
- if (batch.visibleInstances[subMesh._id]) {
- for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
- var instance = batch.visibleInstances[subMesh._id][instanceIndex];
- // World
- world = instance.getWorldMatrix();
- effectiveMaterial.bindOnlyWorldMatrix(world);
- // Draw
- this._draw(subMesh, fillMode);
- }
- }
- }
- // Unbind
- effectiveMaterial.unbind();
- // Outline - step 2
- if (this.renderOutline && savedDepthWrite) {
- engine.setDepthWrite(true);
- engine.setColorWrite(false);
- scene.getOutlineRenderer().render(subMesh, batch);
- engine.setColorWrite(true);
- }
- for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
- this._onAfterRenderCallbacks[callbackIndex]();
- }
- }
- public getEmittedParticleSystems(): ParticleSystem[] {
- var results = new Array<ParticleSystem>();
- for (var index = 0; index < this.getScene().particleSystems.length; index++) {
- var particleSystem = this.getScene().particleSystems[index];
- if (particleSystem.emitter === this) {
- results.push(particleSystem);
- }
- }
- return results;
- }
- public getHierarchyEmittedParticleSystems(): ParticleSystem[] {
- var results = new Array<ParticleSystem>();
- var descendants = this.getDescendants();
- descendants.push(this);
- for (var index = 0; index < this.getScene().particleSystems.length; index++) {
- var particleSystem = this.getScene().particleSystems[index];
- if (descendants.indexOf(particleSystem.emitter) !== -1) {
- results.push(particleSystem);
- }
- }
- return results;
- }
- public getChildren(): Node[] {
- var results = [];
- for (var index = 0; index < this.getScene().meshes.length; index++) {
- var mesh = this.getScene().meshes[index];
- if (mesh.parent == this) {
- results.push(mesh);
- }
- }
- return results;
- }
- public _checkDelayState(): void {
- var that = this;
- var scene = this.getScene();
- if (this._geometry) {
- this._geometry.load(scene);
- }
- else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
- that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
- scene._addPendingData(that);
- var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1) ? true : false;
- BABYLON.Tools.LoadFile(this.delayLoadingFile, data => {
- if (data instanceof ArrayBuffer) {
- this._delayLoadingFunction(data, this);
- }
- else {
- this._delayLoadingFunction(JSON.parse(data), this);
- }
- this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
- scene._removePendingData(this);
- }, () => { }, scene.database, getBinaryData);
- }
- }
- public isInFrustum(frustumPlanes: Plane[]): boolean {
- if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
- return false;
- }
- if (!super.isInFrustum(frustumPlanes)) {
- return false;
- }
- this._checkDelayState();
- return true;
- }
- public setMaterialByID(id: string): void {
- var materials = this.getScene().materials;
- for (var index = 0; index < materials.length; index++) {
- if (materials[index].id == id) {
- this.material = materials[index];
- return;
- }
- }
- // Multi
- var multiMaterials = this.getScene().multiMaterials;
- for (index = 0; index < multiMaterials.length; index++) {
- if (multiMaterials[index].id == id) {
- this.material = multiMaterials[index];
- return;
- }
- }
- }
- public getAnimatables(): IAnimatable[] {
- var results = [];
- if (this.material) {
- results.push(this.material);
- }
- if (this.skeleton) {
- results.push(this.skeleton);
- }
- return results;
- }
- // Geometry
- public bakeTransformIntoVertices(transform: Matrix): void {
- // Position
- if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
- return;
- }
- this._resetPointsArrayCache();
- var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
- var temp = [];
- for (var index = 0; index < data.length; index += 3) {
- BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
- }
- this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
- // Normals
- if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
- return;
- }
- data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
- for (index = 0; index < data.length; index += 3) {
- BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
- }
- this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
- }
- // Cache
- public _resetPointsArrayCache(): void {
- this._positions = null;
- }
- public _generatePointsArray(): boolean {
- if (this._positions)
- return true;
- this._positions = [];
- var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
- if (!data) {
- return false;
- }
- for (var index = 0; index < data.length; index += 3) {
- this._positions.push(BABYLON.Vector3.FromArray(data, index));
- }
- return true;
- }
- // Clone
- public clone(name: string, newParent: Node, doNotCloneChildren?: boolean): Mesh {
- var result = new BABYLON.Mesh(name, this.getScene());
- // Geometry
- this._geometry.applyToMesh(result);
- // Deep copy
- BABYLON.Tools.DeepCopy(this, result, ["name", "material", "skeleton"], []);
- // Material
- result.material = this.material;
- // Parent
- if (newParent) {
- result.parent = newParent;
- }
- if (!doNotCloneChildren) {
- // Children
- for (var index = 0; index < this.getScene().meshes.length; index++) {
- var mesh = this.getScene().meshes[index];
- if (mesh.parent == this) {
- mesh.clone(mesh.name, result);
- }
- }
- }
- // Particles
- for (index = 0; index < this.getScene().particleSystems.length; index++) {
- var system = this.getScene().particleSystems[index];
- if (system.emitter == this) {
- system.clone(system.name, result);
- }
- }
- result.computeWorldMatrix(true);
- return result;
- }
- // Dispose
- public dispose(doNotRecurse?: boolean): void {
- if (this._geometry) {
- this._geometry.releaseForMesh(this, true);
- }
- // Instances
- if (this._worldMatricesInstancesBuffer) {
- this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
- this._worldMatricesInstancesBuffer = null;
- }
- while (this.instances.length) {
- this.instances[0].dispose();
- }
- super.dispose(doNotRecurse);
- }
- // Geometric tools
- public applyDisplacementMap(url: string, minHeight: number, maxHeight: number): void {
- var scene = this.getScene();
- var onload = img => {
- // Getting height map data
- var canvas = document.createElement("canvas");
- var context = canvas.getContext("2d");
- var heightMapWidth = img.width;
- var heightMapHeight = img.height;
- canvas.width = heightMapWidth;
- canvas.height = heightMapHeight;
- context.drawImage(img, 0, 0);
- // Create VertexData from map data
- var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
- this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
- };
- Tools.LoadImage(url, onload, () => { }, scene.database);
- }
- public applyDisplacementMapFromBuffer(buffer: Uint8Array, heightMapWidth: number, heightMapHeight: number, minHeight: number, maxHeight: number): void {
- if (!this.isVerticesDataPresent(VertexBuffer.PositionKind)
- || !this.isVerticesDataPresent(VertexBuffer.NormalKind)
- || !this.isVerticesDataPresent(VertexBuffer.UVKind)) {
- Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
- return;
- }
- var positions = this.getVerticesData(VertexBuffer.PositionKind);
- var normals = this.getVerticesData(VertexBuffer.NormalKind);
- var uvs = this.getVerticesData(VertexBuffer.UVKind);
- var position = Vector3.Zero();
- var normal = Vector3.Zero();
- var uv = Vector2.Zero();
- for (var index = 0; index < positions.length; index += 3) {
- Vector3.FromArrayToRef(positions, index, position);
- Vector3.FromArrayToRef(normals, index, normal);
- Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
- // Compute height
- var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
- var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
- var pos = (u + v * heightMapWidth) * 4;
- var r = buffer[pos] / 255.0;
- var g = buffer[pos + 1] / 255.0;
- var b = buffer[pos + 2] / 255.0;
- var gradient = r * 0.3 + g * 0.59 + b * 0.11;
- normal.normalize();
- normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
- position = position.add(normal);
- position.toArray(positions, index);
- }
- VertexData.ComputeNormals(positions, this.getIndices(), normals);
- this.updateVerticesData(VertexBuffer.PositionKind, positions);
- this.updateVerticesData(VertexBuffer.NormalKind, normals);
- }
- public convertToFlatShadedMesh(): void {
- /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
- /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
- var kinds = this.getVerticesDataKinds();
- var vbs = [];
- var data = [];
- var newdata = [];
- var updatableNormals = false;
- for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
- var kind = kinds[kindIndex];
- var vertexBuffer = this.getVertexBuffer(kind);
- if (kind === BABYLON.VertexBuffer.NormalKind) {
- updatableNormals = vertexBuffer.isUpdatable();
- kinds.splice(kindIndex, 1);
- kindIndex--;
- continue;
- }
- vbs[kind] = vertexBuffer;
- data[kind] = vbs[kind].getData();
- newdata[kind] = [];
- }
- // Save previous submeshes
- var previousSubmeshes = this.subMeshes.slice(0);
- var indices = this.getIndices();
- var totalIndices = this.getTotalIndices();
- // Generating unique vertices per face
- for (index = 0; index < totalIndices; index++) {
- var vertexIndex = indices[index];
- for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
- kind = kinds[kindIndex];
- var stride = vbs[kind].getStrideSize();
- for (var offset = 0; offset < stride; offset++) {
- newdata[kind].push(data[kind][vertexIndex * stride + offset]);
- }
- }
- }
- // Updating faces & normal
- var normals = [];
- var positions = newdata[BABYLON.VertexBuffer.PositionKind];
- for (var index = 0; index < totalIndices; index += 3) {
- indices[index] = index;
- indices[index + 1] = index + 1;
- indices[index + 2] = index + 2;
- var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
- var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
- var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
- var p1p2 = p1.subtract(p2);
- var p3p2 = p3.subtract(p2);
- var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
- // Store same normals for every vertex
- for (var localIndex = 0; localIndex < 3; localIndex++) {
- normals.push(normal.x);
- normals.push(normal.y);
- normals.push(normal.z);
- }
- }
- this.setIndices(indices);
- this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
- // Updating vertex buffers
- for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
- kind = kinds[kindIndex];
- this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
- }
- // Updating submeshes
- this.releaseSubMeshes();
- for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
- var previousOne = previousSubmeshes[submeshIndex];
- var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
- }
- this.synchronizeInstances();
- }
- // Instances
- public createInstance(name: string): InstancedMesh {
- return new InstancedMesh(name, this);
- }
- public synchronizeInstances(): void {
- for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
- var instance = this.instances[instanceIndex];
- instance._syncSubMeshes();
- }
- }
- // Statics
- public static CreateBox(name: string, size: number, scene: Scene, updatable?: boolean): Mesh {
- var box = new BABYLON.Mesh(name, scene);
- var vertexData = BABYLON.VertexData.CreateBox(size);
- vertexData.applyToMesh(box, updatable);
- return box;
- }
- public static CreateSphere(name: string, segments: number, diameter: number, scene: Scene, updatable?: boolean): Mesh {
- var sphere = new BABYLON.Mesh(name, scene);
- var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter);
- vertexData.applyToMesh(sphere, updatable);
- return sphere;
- }
- // Cylinder and cone (Code inspired by SharpDX.org)
- public static CreateCylinder(name: string, height: number, diameterTop: number, diameterBottom: number, tessellation: number, subdivisions: any, scene: Scene, updatable?: any): Mesh {
- // subdivisions is a new parameter, we need to support old signature
- if (scene === undefined || !(scene instanceof Scene)) {
- if (scene !== undefined) {
- updatable = scene;
- }
- scene = <Scene>subdivisions;
- subdivisions = 1;
- }
- var cylinder = new BABYLON.Mesh(name, scene);
- var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions);
- vertexData.applyToMesh(cylinder, updatable);
- return cylinder;
- }
- // Torus (Code from SharpDX.org)
- public static CreateTorus(name: string, diameter: number, thickness: number, tessellation: number, scene: Scene, updatable?: boolean): Mesh {
- var torus = new BABYLON.Mesh(name, scene);
- var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation);
- vertexData.applyToMesh(torus, updatable);
- return torus;
- }
- public static CreateTorusKnot(name: string, radius: number, tube: number, radialSegments: number, tubularSegments: number, p: number, q: number, scene: Scene, updatable?: boolean): Mesh {
- var torusKnot = new BABYLON.Mesh(name, scene);
- var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q);
- vertexData.applyToMesh(torusKnot, updatable);
- return torusKnot;
- }
- // Lines
- public static CreateLines(name: string, points: Vector3[], scene: Scene, updatable?: boolean): LinesMesh {
- var lines = new LinesMesh(name, scene, updatable);
- var vertexData = BABYLON.VertexData.CreateLines(points);
- vertexData.applyToMesh(lines, updatable);
- return lines;
- }
- // Plane & ground
- public static CreatePlane(name: string, size: number, scene: Scene, updatable?: boolean): Mesh {
- var plane = new BABYLON.Mesh(name, scene);
- var vertexData = BABYLON.VertexData.CreatePlane(size);
- vertexData.applyToMesh(plane, updatable);
- return plane;
- }
- public static CreateGround(name: string, width: number, height: number, subdivisions: number, scene: Scene, updatable?: boolean): Mesh {
- var ground = new BABYLON.GroundMesh(name, scene);
- ground._setReady(false);
- ground._subdivisions = subdivisions;
- var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
- vertexData.applyToMesh(ground, updatable);
- ground._setReady(true);
- return ground;
- }
- public static CreateTiledGround(name: string, xmin: number, zmin: number, xmax: number, zmax: number, subdivisions: { w: number; h: number; }, precision: { w: number; h: number; }, scene: Scene, updatable?: boolean): Mesh {
- var tiledGround = new BABYLON.Mesh(name, scene);
- var vertexData = BABYLON.VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
- vertexData.applyToMesh(tiledGround, updatable);
- return tiledGround;
- }
- public static CreateGroundFromHeightMap(name: string, url: string, width: number, height: number, subdivisions: number, minHeight: number, maxHeight: number, scene: Scene, updatable?: boolean): GroundMesh {
- var ground = new BABYLON.GroundMesh(name, scene);
- ground._subdivisions = subdivisions;
- ground._setReady(false);
- var onload = img => {
- // Getting height map data
- var canvas = document.createElement("canvas");
- var context = canvas.getContext("2d");
- var heightMapWidth = img.width;
- var heightMapHeight = img.height;
- canvas.width = heightMapWidth;
- canvas.height = heightMapHeight;
- context.drawImage(img, 0, 0);
- // Create VertexData from map data
- var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
- var vertexData = VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
- vertexData.applyToMesh(ground, updatable);
- ground._setReady(true);
- };
- Tools.LoadImage(url, onload, () => { }, scene.database);
- return ground;
- }
- // Tools
- public static MinMax(meshes: AbstractMesh[]): { min: Vector3; max: Vector3 } {
- var minVector = null;
- var maxVector = null;
- for (var i in meshes) {
- var mesh = meshes[i];
- var boundingBox = mesh.getBoundingInfo().boundingBox;
- if (!minVector) {
- minVector = boundingBox.minimumWorld;
- maxVector = boundingBox.maximumWorld;
- continue;
- }
- minVector.MinimizeInPlace(boundingBox.minimumWorld);
- maxVector.MaximizeInPlace(boundingBox.maximumWorld);
- }
- return {
- min: minVector,
- max: maxVector
- };
- }
- public static Center(meshesOrMinMaxVector): Vector3 {
- var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
- return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
- }
- }
- }
|