12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027 |
- 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 {
- // Consts
- public static _FRONTSIDE: number = 0;
- public static _BACKSIDE: number = 1;
- public static _DOUBLESIDE: number = 2;
- public static _DEFAULTSIDE: number = 0;
- public static _NO_CAP = 0;
- public static _CAP_START = 1;
- public static _CAP_END = 2;
- public static _CAP_ALL = 3;
- public static get FRONTSIDE(): number {
- return Mesh._FRONTSIDE;
- }
- public static get BACKSIDE(): number {
- return Mesh._BACKSIDE;
- }
- public static get DOUBLESIDE(): number {
- return Mesh._DOUBLESIDE;
- }
- public static get DEFAULTSIDE(): number {
- return Mesh._DEFAULTSIDE;
- }
- public static get NO_CAP(): number {
- return Mesh._NO_CAP;
- }
- public static get CAP_START(): number {
- return Mesh._CAP_START;
- }
- public static get CAP_END(): number {
- return Mesh._CAP_END;
- }
- public static get CAP_ALL(): number {
- return Mesh._CAP_ALL;
- }
- // Members
- public delayLoadState = Engine.DELAYLOADSTATE_NONE;
- public instances = new Array<InstancedMesh>();
- public delayLoadingFile: string;
- public _binaryInfo: any;
- private _LODLevels = new Array<Internals.MeshLODLevel>();
- public onLODLevelSelection: (distance: number, mesh: Mesh, selectedLevel: Mesh) => void;
- public onBeforeDraw: () => void;
- // Private
- public _geometry: Geometry;
- private _onBeforeRenderCallbacks = new Array<(mesh: AbstractMesh) => void>();
- private _onAfterRenderCallbacks = new Array<(mesh: AbstractMesh) => void>();
- public _delayInfo; //ANY
- public _delayLoadingFunction: (any: any, mesh: 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 _sideOrientation: number = Mesh._DEFAULTSIDE;
- private _areNormalsFrozen: boolean = false; // Will be used by ribbons mainly
- private _sourcePositions: Float32Array; // Will be used to save original positions when using software skinning
- private _sourceNormals: Float32Array; // Will be used to save original normals when using software skinning
- /**
- * @constructor
- * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
- * @param {Scene} scene - The scene to add this mesh to.
- * @param {Node} parent - The parent of this mesh, if it has one
- * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
- * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
- * When false, achieved by calling a clone(), also passing False.
- * This will make creation of children, recursive.
- */
- constructor(name: string, scene: Scene, parent: Node = null, source?: Mesh, doNotCloneChildren?: boolean) {
- super(name, scene);
- if (source) {
- // Geometry
- if (source._geometry) {
- source._geometry.applyToMesh(this);
- }
- // Deep copy
- Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], ["_poseMatrix"]);
- // Pivot
- this.setPivotMatrix(source.getPivotMatrix());
- this.id = name + "." + source.id;
- // Material
- this.material = source.material;
- var index: number;
- if (!doNotCloneChildren) {
- // Children
- for (index = 0; index < scene.meshes.length; index++) {
- var mesh = scene.meshes[index];
- if (mesh.parent === source) {
- // doNotCloneChildren is always going to be False
- var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
- }
- }
- }
- // Particles
- for (index = 0; index < scene.particleSystems.length; index++) {
- var system = scene.particleSystems[index];
- if (system.emitter === source) {
- system.clone(system.name, this);
- }
- }
- this.computeWorldMatrix(true);
- }
- // Parent
- if (parent !== null) {
- this.parent = parent;
- }
- }
- // Methods
- /**
- * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
- */
- public toString(fullDetails? : boolean) : string {
- var ret = super.toString(fullDetails);
- ret += ", n vertices: " + this.getTotalVertices();
- ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
- if (this.animations){
- for (var i = 0; i < this.animations.length; i++){
- ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
- }
- }
-
- if (fullDetails){
- ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
- }
- return ret;
- }
-
- public get hasLODLevels(): boolean {
- return this._LODLevels.length > 0;
- }
- private _sortLODLevels(): void {
- this._LODLevels.sort((a, b) => {
- if (a.distance < b.distance) {
- return 1;
- }
- if (a.distance > b.distance) {
- return -1;
- }
- return 0;
- });
- }
- /**
- * Add a mesh as LOD level triggered at the given distance.
- * @param {number} distance - the distance from the center of the object to show this level
- * @param {Mesh} mesh - the mesh to be added as LOD level
- * @return {Mesh} this mesh (for chaining)
- */
- public addLODLevel(distance: number, mesh: Mesh): Mesh {
- if (mesh && mesh._masterMesh) {
- Tools.Warn("You cannot use a mesh as LOD level twice");
- return this;
- }
- var level = new Internals.MeshLODLevel(distance, mesh);
- this._LODLevels.push(level);
- if (mesh) {
- mesh._masterMesh = this;
- }
- this._sortLODLevels();
- return this;
- }
- public getLODLevelAtDistance(distance: number): Mesh {
- for (var index = 0; index < this._LODLevels.length; index++) {
- var level = this._LODLevels[index];
- if (level.distance === distance) {
- return level.mesh;
- }
- }
- return null;
- }
- /**
- * Remove a mesh from the LOD array
- * @param {Mesh} mesh - the mesh to be removed.
- * @return {Mesh} this mesh (for chaining)
- */
- public removeLODLevel(mesh: Mesh): Mesh {
- for (var index = 0; index < this._LODLevels.length; index++) {
- if (this._LODLevels[index].mesh === mesh) {
- this._LODLevels.splice(index, 1);
- if (mesh) {
- mesh._masterMesh = null;
- }
- }
- }
- this._sortLODLevels();
- return this;
- }
- public getLOD(camera: Camera, boundingSphere?: BoundingSphere): AbstractMesh {
- if (!this._LODLevels || this._LODLevels.length === 0) {
- return this;
- }
- var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
- if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
- if (this.onLODLevelSelection) {
- this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
- }
- 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._preActivate();
- level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
- }
- if (this.onLODLevelSelection) {
- this.onLODLevelSelection(distanceToCamera, this, level.mesh);
- }
- return level.mesh;
- }
- }
- if (this.onLODLevelSelection) {
- this.onLODLevelSelection(distanceToCamera, this, this);
- }
- 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, copyWhenShared?: boolean): number[] | Float32Array {
- if (!this._geometry) {
- return null;
- }
- return this._geometry.getVerticesData(kind, copyWhenShared);
- }
- 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(copyWhenShared?: boolean): number[] | Int32Array {
- if (!this._geometry) {
- return [];
- }
- return this._geometry.getIndices(copyWhenShared);
- }
- public get isBlocked(): boolean {
- return this._masterMesh !== null && this._masterMesh !== undefined;
- }
- public isReady(): boolean {
- if (this.delayLoadState === Engine.DELAYLOADSTATE_LOADING) {
- return false;
- }
- return super.isReady();
- }
- public isDisposed(): boolean {
- return this._isDisposed;
- }
- public get sideOrientation(): number {
- return this._sideOrientation;
- }
- public set sideOrientation(sideO: number) {
- this._sideOrientation = sideO;
- }
- public get areNormalsFrozen(): boolean {
- return this._areNormalsFrozen;
- }
- /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
- public freezeNormals(): void {
- this._areNormalsFrozen = true;
- }
- /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
- public unfreezeNormals(): void {
- this._areNormalsFrozen = false;
- }
- // Methods
- public _preActivate(): void {
- var sceneRenderId = this.getScene().getRenderId();
- if (this._preActivateId === sceneRenderId) {
- return;
- }
- this._preActivateId = sceneRenderId;
- this._visibleInstances = null;
- }
- public _preActivateForIntermediateRendering(renderId: number): void {
- if (this._visibleInstances) {
- this._visibleInstances.intermediateDefaultRenderId = renderId;
- }
- }
- 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 {
- if (this._boundingInfo.isLocked) {
- return;
- }
- var data = this.getVerticesData(VertexBuffer.PositionKind);
- if (data) {
- var extend = Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
- this._boundingInfo = new 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 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;
- }
- SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
- offset += subdivisionSize;
- }
- this.synchronizeInstances();
- }
- public setVerticesData(kind: string, data: number[] | Float32Array, updatable?: boolean, stride?: number): void {
- if (!this._geometry) {
- var vertexData = new VertexData();
- vertexData.set(data, kind);
- var scene = this.getScene();
- new Geometry(Geometry.RandomId(), scene, vertexData, updatable, this);
- }
- else {
- this._geometry.setVerticesData(kind, data, updatable, stride);
- }
- }
- public updateVerticesData(kind: string, data: number[] | Float32Array, 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, offset?: number, makeItUnique?: boolean): void {
- Tools.Warn("Mesh.updateVerticesDataDirectly deprecated since 2.3.");
- if (!this._geometry) {
- return;
- }
- if (!makeItUnique) {
- this._geometry.updateVerticesDataDirectly(kind, data, offset);
- }
- else {
- this.makeGeometryUnique();
- this.updateVerticesDataDirectly(kind, data, offset, false);
- }
- }
- // Mesh positions update function :
- // updates the mesh positions according to the positionFunction returned values.
- // The positionFunction argument must be a javascript function accepting the mesh "positions" array as parameter.
- // This dedicated positionFunction computes new mesh positions according to the given mesh type.
- public updateMeshPositions(positionFunction, computeNormals: boolean = true): void {
- var positions = this.getVerticesData(VertexBuffer.PositionKind);
- positionFunction(positions);
- this.updateVerticesData(VertexBuffer.PositionKind, positions, false, false);
- if (computeNormals) {
- var indices = this.getIndices();
- var normals = this.getVerticesData(VertexBuffer.NormalKind);
- VertexData.ComputeNormals(positions, indices, normals);
- this.updateVerticesData(VertexBuffer.NormalKind, normals, false, false);
- }
- }
- public makeGeometryUnique() {
- if (!this._geometry) {
- return;
- }
- var geometry = this._geometry.copy(Geometry.RandomId());
- geometry.applyToMesh(this);
- }
- public setIndices(indices: number[] | Int32Array, totalVertices?: number): void {
- if (!this._geometry) {
- var vertexData = new VertexData();
- vertexData.indices = indices;
- var scene = this.getScene();
- new Geometry(Geometry.RandomId(), scene, vertexData, false, this);
- }
- else {
- this._geometry.setIndices(indices, totalVertices);
- }
- }
- public _bind(subMesh: SubMesh, effect: Effect, fillMode: number): void {
- var engine = this.getScene().getEngine();
- // Wireframe
- var indexToBind;
- if (this._unIndexed) {
- indexToBind = null;
- } else {
- switch (fillMode) {
- case Material.PointFillMode:
- indexToBind = null;
- break;
- case Material.WireFrameFillMode:
- indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
- break;
- default:
- case Material.TriangleFillMode:
- indexToBind = this._unIndexed ? null : 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;
- }
- if (this.onBeforeDraw) {
- this.onBeforeDraw();
- }
- var engine = this.getScene().getEngine();
- // Draw order
- switch (fillMode) {
- case Material.PointFillMode:
- engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
- break;
- case Material.WireFrameFillMode:
- if (this._unIndexed) {
- engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
- } else {
- engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
- }
- break;
- default:
- if (this._unIndexed) {
- engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
- } else {
- engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
- }
- }
- }
- public registerBeforeRender(func: (mesh: AbstractMesh) => void): void {
- this._onBeforeRenderCallbacks.push(func);
- }
- public unregisterBeforeRender(func: (mesh: AbstractMesh) => void): void {
- var index = this._onBeforeRenderCallbacks.indexOf(func);
- if (index > -1) {
- this._onBeforeRenderCallbacks.splice(index, 1);
- }
- }
- public registerAfterRender(func: (mesh: AbstractMesh) => void): void {
- this._onAfterRenderCallbacks.push(func);
- }
- public unregisterAfterRender(func: (mesh: AbstractMesh) => 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();
- var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
- this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
- var selfRenderId = this._renderId;
- if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
- this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
- currentRenderId = Math.max(defaultRenderId, currentRenderId);
- selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
- }
- 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 visibleInstances = batch.visibleInstances[subMesh._id];
- var matricesCount = visibleInstances.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++;
- }
- 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 _processRendering(subMesh: SubMesh, effect: Effect, fillMode: number, batch: _InstancesBatch, hardwareInstancedRendering: boolean,
- onBeforeDraw: (isInstance: boolean, world: Matrix) => void) {
- var scene = this.getScene();
- var engine = scene.getEngine();
- if (hardwareInstancedRendering) {
- this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
- } else {
- if (batch.renderSelf[subMesh._id]) {
- // Draw
- if (onBeforeDraw) {
- onBeforeDraw(false, this.getWorldMatrix());
- }
- 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
- var world = instance.getWorldMatrix();
- if (onBeforeDraw) {
- onBeforeDraw(true, world);
- }
- // Draw
- this._draw(subMesh, fillMode);
- }
- }
- }
- }
- public render(subMesh: SubMesh, enableAlphaMode: boolean): 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;
- }
- var callbackIndex: number;
- for (callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
- this._onBeforeRenderCallbacks[callbackIndex](this);
- }
- var engine = scene.getEngine();
- var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
- // 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);
- engine.setDepthWrite(savedDepthWrite);
- }
- effectiveMaterial._preBind();
- var effect = effectiveMaterial.getEffect();
- // Bind
- var fillMode = scene.forcePointsCloud ? Material.PointFillMode : (scene.forceWireframe ? Material.WireFrameFillMode : effectiveMaterial.fillMode);
- this._bind(subMesh, effect, fillMode);
- var world = this.getWorldMatrix();
- effectiveMaterial.bind(world, this);
- // Alpha mode
- if (enableAlphaMode) {
- engine.setAlphaMode(effectiveMaterial.alphaMode);
- }
- // Draw
- this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering,
- (isInstance, world) => {
- if (isInstance) {
- effectiveMaterial.bindOnlyWorldMatrix(world);
- }
- });
- // Unbind
- effectiveMaterial.unbind();
- // Outline - step 2
- if (this.renderOutline && savedDepthWrite) {
- engine.setDepthWrite(true);
- engine.setColorWrite(false);
- scene.getOutlineRenderer().render(subMesh, batch);
- engine.setColorWrite(true);
- }
- // Overlay
- if (this.renderOverlay) {
- var currentMode = engine.getAlphaMode();
- engine.setAlphaMode(Engine.ALPHA_COMBINE);
- scene.getOutlineRenderer().render(subMesh, batch, true);
- engine.setAlphaMode(currentMode);
- }
- for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
- this._onAfterRenderCallbacks[callbackIndex](this);
- }
- }
- 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 _checkDelayState(): void {
- var that = this;
- var scene = this.getScene();
- if (this._geometry) {
- this._geometry.load(scene);
- }
- else if (that.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
- that.delayLoadState = Engine.DELAYLOADSTATE_LOADING;
- scene._addPendingData(that);
- var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
- Tools.LoadFile(this.delayLoadingFile, data => {
- if (data instanceof ArrayBuffer) {
- this._delayLoadingFunction(data, this);
- }
- else {
- this._delayLoadingFunction(JSON.parse(data), this);
- }
- this.delayLoadState = Engine.DELAYLOADSTATE_LOADED;
- scene._removePendingData(this);
- }, () => { }, scene.database, getBinaryData);
- }
- }
- public isInFrustum(frustumPlanes: Plane[]): boolean {
- if (this.delayLoadState === 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;
- var index: number;
- for (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(VertexBuffer.PositionKind)) {
- return;
- }
- this._resetPointsArrayCache();
- var data = this.getVerticesData(VertexBuffer.PositionKind);
- var temp = [];
- var index: number;
- for (index = 0; index < data.length; index += 3) {
- Vector3.TransformCoordinates(Vector3.FromArray(data, index), transform).toArray(temp, index);
- }
- this.setVerticesData(VertexBuffer.PositionKind, temp, this.getVertexBuffer(VertexBuffer.PositionKind).isUpdatable());
- // Normals
- if (!this.isVerticesDataPresent(VertexBuffer.NormalKind)) {
- return;
- }
- data = this.getVerticesData(VertexBuffer.NormalKind);
- temp = [];
- for (index = 0; index < data.length; index += 3) {
- Vector3.TransformNormal(Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
- }
- this.setVerticesData(VertexBuffer.NormalKind, temp, this.getVertexBuffer(VertexBuffer.NormalKind).isUpdatable());
- // flip faces?
- if (transform.m[0] * transform.m[5] * transform.m[10] < 0) { this.flipFaces(); }
- }
- // Will apply current transform to mesh and reset world matrix
- public bakeCurrentTransformIntoVertices(): void {
- this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
- this.scaling.copyFromFloats(1, 1, 1);
- this.position.copyFromFloats(0, 0, 0);
- this.rotation.copyFromFloats(0, 0, 0);
- //only if quaternion is already set
- if (this.rotationQuaternion) {
- this.rotationQuaternion = Quaternion.Identity();
- }
- this._worldMatrix = Matrix.Identity();
- }
- // Cache
- public _resetPointsArrayCache(): void {
- this._positions = null;
- }
- public _generatePointsArray(): boolean {
- if (this._positions)
- return true;
- this._positions = [];
- var data = this.getVerticesData(VertexBuffer.PositionKind);
- if (!data) {
- return false;
- }
- for (var index = 0; index < data.length; index += 3) {
- this._positions.push(Vector3.FromArray(data, index));
- }
- return true;
- }
- // Clone
- public clone(name: string, newParent?: Node, doNotCloneChildren?: boolean): Mesh {
- return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
- }
- // 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, onSuccess?: (mesh: Mesh) => void): 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
- //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
- var buffer = <Uint8Array>(<any>context.getImageData(0, 0, heightMapWidth, heightMapHeight).data);
- this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
- //execute success callback, if set
- if (onSuccess) {
- onSuccess(this);
- }
- };
- 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;
- var kindIndex: number;
- var kind: string;
- for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
- kind = kinds[kindIndex];
- var vertexBuffer = this.getVertexBuffer(kind);
- if (kind === 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
- var index: number;
- 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[VertexBuffer.PositionKind];
- for (index = 0; index < totalIndices; index += 3) {
- indices[index] = index;
- indices[index + 1] = index + 1;
- indices[index + 2] = index + 2;
- var p1 = Vector3.FromArray(positions, index * 3);
- var p2 = Vector3.FromArray(positions, (index + 1) * 3);
- var p3 = Vector3.FromArray(positions, (index + 2) * 3);
- var p1p2 = p1.subtract(p2);
- var p3p2 = p3.subtract(p2);
- var normal = Vector3.Normalize(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(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 SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
- }
- this.synchronizeInstances();
- }
- public convertToUnIndexedMesh(): void {
- /// <summary>Remove indices by unfolding faces into buffers</summary>
- /// <summary>Warning: This implies 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;
- var kindIndex: number;
- var kind: string;
- for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
- kind = kinds[kindIndex];
- var vertexBuffer = this.getVertexBuffer(kind);
- 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
- var index: number;
- 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 indices
- for (index = 0; index < totalIndices; index += 3) {
- indices[index] = index;
- indices[index + 1] = index + 1;
- indices[index + 2] = index + 2;
- }
- this.setIndices(indices);
- // 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 SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
- }
- this._unIndexed = true;
- this.synchronizeInstances();
- }
- // will inverse faces orientations, and invert normals too if specified
- public flipFaces(flipNormals: boolean = false): void {
- var vertex_data = VertexData.ExtractFromMesh(this);
- var i: number;
- if (flipNormals && this.isVerticesDataPresent(VertexBuffer.NormalKind)) {
- for (i = 0; i < vertex_data.normals.length; i++) {
- vertex_data.normals[i] *= -1;
- }
- }
- var temp;
- for (i = 0; i < vertex_data.indices.length; i += 3) {
- // reassign indices
- temp = vertex_data.indices[i + 1];
- vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
- vertex_data.indices[i + 2] = temp;
- }
- vertex_data.applyToMesh(this);
- }
- // 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();
- }
- }
- /**
- * Simplify the mesh according to the given array of settings.
- * Function will return immediately and will simplify async.
- * @param settings a collection of simplification settings.
- * @param parallelProcessing should all levels calculate parallel or one after the other.
- * @param type the type of simplification to run.
- * @param successCallback optional success callback to be called after the simplification finished processing all settings.
- */
- public simplify(settings: Array<ISimplificationSettings>, parallelProcessing: boolean = true, simplificationType: SimplificationType = SimplificationType.QUADRATIC, successCallback?: (mesh?: Mesh, submeshIndex?: number) => void) {
- this.getScene().simplificationQueue.addTask({
- settings: settings,
- parallelProcessing: parallelProcessing,
- mesh: this,
- simplificationType: simplificationType,
- successCallback: successCallback
- });
- }
- /**
- * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
- * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
- * This should be used together with the simplification to avoid disappearing triangles.
- * @param successCallback an optional success callback to be called after the optimization finished.
- */
- public optimizeIndices(successCallback?: (mesh?: Mesh) => void) {
- var indices = this.getIndices();
- var positions = this.getVerticesData(VertexBuffer.PositionKind);
- var vectorPositions = [];
- for (var pos = 0; pos < positions.length; pos = pos + 3) {
- vectorPositions.push(Vector3.FromArray(positions, pos));
- }
- var dupes = [];
- AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, (iteration) => {
- var realPos = vectorPositions.length - 1 - iteration;
- var testedPosition = vectorPositions[realPos];
- for (var j = 0; j < realPos; ++j) {
- var againstPosition = vectorPositions[j];
- if (testedPosition.equals(againstPosition)) {
- dupes[realPos] = j;
- break;
- }
- }
- }, () => {
- for (var i = 0; i < indices.length; ++i) {
- indices[i] = dupes[indices[i]] || indices[i];
- }
- //indices are now reordered
- var originalSubMeshes = this.subMeshes.slice(0);
- this.setIndices(indices);
- this.subMeshes = originalSubMeshes;
- if (successCallback) {
- successCallback(this);
- }
- });
- }
- // Statics
- public static Parse(parsedMesh: any, scene: Scene, rootUrl: string): Mesh {
- var mesh = new Mesh(parsedMesh.name, scene);
- mesh.id = parsedMesh.id;
- Tags.AddTagsTo(mesh, parsedMesh.tags);
- mesh.position = Vector3.FromArray(parsedMesh.position);
- if (parsedMesh.rotationQuaternion) {
- mesh.rotationQuaternion = Quaternion.FromArray(parsedMesh.rotationQuaternion);
- } else if (parsedMesh.rotation) {
- mesh.rotation = Vector3.FromArray(parsedMesh.rotation);
- }
- mesh.scaling = Vector3.FromArray(parsedMesh.scaling);
- if (parsedMesh.localMatrix) {
- mesh.setPivotMatrix(Matrix.FromArray(parsedMesh.localMatrix));
- } else if (parsedMesh.pivotMatrix) {
- mesh.setPivotMatrix(Matrix.FromArray(parsedMesh.pivotMatrix));
- }
- mesh.setEnabled(parsedMesh.isEnabled);
- mesh.isVisible = parsedMesh.isVisible;
- mesh.infiniteDistance = parsedMesh.infiniteDistance;
- mesh.showBoundingBox = parsedMesh.showBoundingBox;
- mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
- if (parsedMesh.applyFog !== undefined) {
- mesh.applyFog = parsedMesh.applyFog;
- }
- if (parsedMesh.pickable !== undefined) {
- mesh.isPickable = parsedMesh.pickable;
- }
- if (parsedMesh.alphaIndex !== undefined) {
- mesh.alphaIndex = parsedMesh.alphaIndex;
- }
- mesh.receiveShadows = parsedMesh.receiveShadows;
- mesh.billboardMode = parsedMesh.billboardMode;
- if (parsedMesh.visibility !== undefined) {
- mesh.visibility = parsedMesh.visibility;
- }
- mesh.checkCollisions = parsedMesh.checkCollisions;
- mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
- // freezeWorldMatrix
- if (parsedMesh.freezeWorldMatrix) {
- mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
- }
- // Parent
- if (parsedMesh.parentId) {
- mesh._waitingParentId = parsedMesh.parentId;
- }
- // Actions
- if (parsedMesh.actions !== undefined) {
- mesh._waitingActions = parsedMesh.actions;
- }
- // Geometry
- mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
- if (parsedMesh.delayLoadingFile) {
- mesh.delayLoadState = Engine.DELAYLOADSTATE_NOTLOADED;
- mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
- mesh._boundingInfo = new BoundingInfo(Vector3.FromArray(parsedMesh.boundingBoxMinimum), Vector3.FromArray(parsedMesh.boundingBoxMaximum));
- if (parsedMesh._binaryInfo) {
- mesh._binaryInfo = parsedMesh._binaryInfo;
- }
- mesh._delayInfo = [];
- if (parsedMesh.hasUVs) {
- mesh._delayInfo.push(VertexBuffer.UVKind);
- }
- if (parsedMesh.hasUVs2) {
- mesh._delayInfo.push(VertexBuffer.UV2Kind);
- }
- if (parsedMesh.hasUVs3) {
- mesh._delayInfo.push(VertexBuffer.UV3Kind);
- }
- if (parsedMesh.hasUVs4) {
- mesh._delayInfo.push(VertexBuffer.UV4Kind);
- }
- if (parsedMesh.hasUVs5) {
- mesh._delayInfo.push(VertexBuffer.UV5Kind);
- }
- if (parsedMesh.hasUVs6) {
- mesh._delayInfo.push(VertexBuffer.UV6Kind);
- }
- if (parsedMesh.hasColors) {
- mesh._delayInfo.push(VertexBuffer.ColorKind);
- }
- if (parsedMesh.hasMatricesIndices) {
- mesh._delayInfo.push(VertexBuffer.MatricesIndicesKind);
- }
- if (parsedMesh.hasMatricesWeights) {
- mesh._delayInfo.push(VertexBuffer.MatricesWeightsKind);
- }
- mesh._delayLoadingFunction = Geometry.ImportGeometry;
- if (SceneLoader.ForceFullSceneLoadingForIncremental) {
- mesh._checkDelayState();
- }
- } else {
- Geometry.ImportGeometry(parsedMesh, mesh);
- }
- // Material
- if (parsedMesh.materialId) {
- mesh.setMaterialByID(parsedMesh.materialId);
- } else {
- mesh.material = null;
- }
- // Skeleton
- if (parsedMesh.skeletonId > -1) {
- mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
- if (parsedMesh.numBoneInfluencers) {
- mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
- }
- }
- // Animations
- if (parsedMesh.animations) {
- for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
- var parsedAnimation = parsedMesh.animations[animationIndex];
- mesh.animations.push(Animation.Parse(parsedAnimation));
- }
- Node.ParseAnimationRanges(mesh, parsedMesh, scene);
- }
- if (parsedMesh.autoAnimate) {
- scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
- }
- // Layer Mask
- if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
- mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
- } else {
- mesh.layerMask = 0x0FFFFFFF;
- }
- // Instances
- if (parsedMesh.instances) {
- for (var index = 0; index < parsedMesh.instances.length; index++) {
- var parsedInstance = parsedMesh.instances[index];
- var instance = mesh.createInstance(parsedInstance.name);
- Tags.AddTagsTo(instance, parsedInstance.tags);
- instance.position = Vector3.FromArray(parsedInstance.position);
- if (parsedInstance.rotationQuaternion) {
- instance.rotationQuaternion = Quaternion.FromArray(parsedInstance.rotationQuaternion);
- } else if (parsedInstance.rotation) {
- instance.rotation = Vector3.FromArray(parsedInstance.rotation);
- }
- instance.scaling = Vector3.FromArray(parsedInstance.scaling);
- instance.checkCollisions = mesh.checkCollisions;
- if (parsedMesh.animations) {
- for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
- parsedAnimation = parsedMesh.animations[animationIndex];
- instance.animations.push(Animation.Parse(parsedAnimation));
- }
- Node.ParseAnimationRanges(instance, parsedMesh, scene);
- }
- }
- }
- return mesh;
- }
- public static CreateRibbon(name: string, pathArray: Vector3[][], closeArray: boolean, closePath: boolean, offset: number, scene: Scene, updatable?: boolean, sideOrientation?: number, instance?: Mesh): Mesh {
- return MeshBuilder.CreateRibbon(name, {
- pathArray: pathArray,
- closeArray: closeArray,
- closePath: closePath,
- offset: offset,
- updatable: updatable,
- sideOrientation: sideOrientation,
- instance: instance
- }, scene);
- }
- public static CreateDisc(name: string, radius: number, tessellation: number, scene: Scene, updatable?: boolean, sideOrientation?: number): Mesh {
- var options = {
- radius: radius,
- tessellation: tessellation,
- sideOrientation: sideOrientation,
- updatable: updatable
- }
- return MeshBuilder.CreateDisc(name, options, scene);
- }
- public static CreateBox(name: string, size: number, scene: Scene, updatable?: boolean, sideOrientation?: number): Mesh {
- var options = {
- size: size,
- sideOrientation: sideOrientation,
- updatable: updatable
- };
- return MeshBuilder.CreateBox(name, options, scene);
- }
- public static CreateSphere(name: string, segments: number, diameter: number, scene?: Scene, updatable?: boolean, sideOrientation?: number): Mesh {
- var options = {
- segments: segments,
- diameterX: diameter,
- diameterY: diameter,
- diameterZ: diameter,
- sideOrientation: sideOrientation,
- updatable: updatable
- }
- return MeshBuilder.CreateSphere(name, options, scene);
- }
- // Cylinder and cone
- public static CreateCylinder(name: string, height: number, diameterTop: number, diameterBottom: number, tessellation: number, subdivisions: any, scene: Scene, updatable?: any, sideOrientation?: number): Mesh {
- if (scene === undefined || !(scene instanceof Scene)) {
- if (scene !== undefined) {
- sideOrientation = updatable || Mesh.DEFAULTSIDE;
- updatable = scene;
- }
- scene = <Scene>subdivisions;
- subdivisions = 1;
- }
- var options = {
- height: height,
- diameterTop: diameterTop,
- diameterBottom: diameterBottom,
- tessellation: tessellation,
- subdivisions: subdivisions,
- sideOrientation: sideOrientation,
- updatable: updatable
- }
- return MeshBuilder.CreateCylinder(name, options, scene);
- }
- // Torus (Code from SharpDX.org)
- public static CreateTorus(name: string, diameter: number, thickness: number, tessellation: number, scene: Scene, updatable?: boolean, sideOrientation?: number): Mesh {
- var options = {
- diameter: diameter,
- thickness: thickness,
- tessellation: tessellation,
- sideOrientation: sideOrientation,
- updatable: updatable
- }
- return MeshBuilder.CreateTorus(name, options, scene);
- }
- public static CreateTorusKnot(name: string, radius: number, tube: number, radialSegments: number, tubularSegments: number, p: number, q: number, scene: Scene, updatable?: boolean, sideOrientation?: number): Mesh {
- var options = {
- radius: radius,
- tube: tube,
- radialSegments: radialSegments,
- tubularSegments: tubularSegments,
- p: p,
- q: q,
- sideOrientation: sideOrientation,
- updatable: updatable
- }
- return MeshBuilder.CreateTorusKnot(name, options, scene);
- }
- // Lines
- public static CreateLines(name: string, points: Vector3[], scene: Scene, updatable?: boolean, instance?: LinesMesh): LinesMesh {
- var options = {
- points: points,
- updatable: updatable,
- instance: instance
- }
- return MeshBuilder.CreateLines(name, options, scene);
- }
- // Dashed Lines
- public static CreateDashedLines(name: string, points: Vector3[], dashSize: number, gapSize: number, dashNb: number, scene: Scene, updatable?: boolean, instance?: LinesMesh): LinesMesh {
- var options = {
- points: points,
- dashSize: dashSize,
- gapSize: gapSize,
- dashNb: dashNb,
- updatable: updatable
- }
- return MeshBuilder.CreateDashedLines(name, options, scene);
- }
- // Extrusion
- public static ExtrudeShape(name: string, shape: Vector3[], path: Vector3[], scale: number, rotation: number, cap: number, scene: Scene, updatable?: boolean, sideOrientation?: number, instance?: Mesh): Mesh {
- var options = {
- shape: shape,
- path: path,
- scale: scale,
- rotation: rotation,
- cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
- sideOrientation: sideOrientation,
- instance: instance,
- updatable: updatable
- }
- return MeshBuilder.ExtrudeShape(name, options, scene);
- }
- public static ExtrudeShapeCustom(name: string, shape: Vector3[], path: Vector3[], scaleFunction, rotationFunction, ribbonCloseArray: boolean, ribbonClosePath: boolean, cap: number, scene: Scene, updatable?: boolean, sideOrientation?: number, instance?: Mesh): Mesh {
- var options = {
- shape: shape,
- path: path,
- scaleFunction: scaleFunction,
- rotationFunction: rotationFunction,
- ribbonCloseArray: ribbonCloseArray,
- ribbonClosePath: ribbonClosePath,
- cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
- sideOrientation: sideOrientation,
- instance: instance,
- updatable: updatable
- }
- return MeshBuilder.ExtrudeShapeCustom(name, options, scene);
- }
- // Lathe
- public static CreateLathe(name: string, shape: Vector3[], radius: number, tessellation: number, scene: Scene, updatable?: boolean, sideOrientation?: number): Mesh {
- var options = {
- shape: shape,
- radius: radius,
- tessellation: tessellation,
- sideOrientation: sideOrientation,
- updatable: updatable
- };
- return MeshBuilder.CreateLathe(name, options, scene);
- }
- // Plane & ground
- public static CreatePlane(name: string, size: number, scene: Scene, updatable?: boolean, sideOrientation?: number): Mesh {
- var options = {
- size: size,
- width: size,
- height: size,
- sideOrientation: sideOrientation,
- updatable: updatable
- }
- return MeshBuilder.CreatePlane(name, options, scene);
- }
- public static CreateGround(name: string, width: number, height: number, subdivisions: number, scene: Scene, updatable?: boolean): Mesh {
- var options = {
- width: width,
- height: height,
- subdivisions: subdivisions,
- updatable: updatable
- }
- return MeshBuilder.CreateGround(name, options, scene);
- }
- 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 options = {
- xmin: xmin,
- zmin: zmin,
- xmax: xmax,
- zmax: zmax,
- subdivisions: subdivisions,
- precision: precision,
- updatable: updatable
- }
- return MeshBuilder.CreateTiledGround(name, options, scene);
- }
- public static CreateGroundFromHeightMap(name: string, url: string, width: number, height: number, subdivisions: number, minHeight: number, maxHeight: number, scene: Scene, updatable?: boolean, onReady?: (mesh: GroundMesh) => void): GroundMesh {
- var options = {
- width: width,
- height: height,
- subdivisions: subdivisions,
- minHeight: minHeight,
- maxHeight: maxHeight,
- updatable: updatable,
- onReady: onReady
- };
- return MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
- }
- public static CreateTube(name: string, path: Vector3[], radius: number, tessellation: number, radiusFunction: { (i: number, distance: number): number; }, cap: number, scene: Scene, updatable?: boolean, sideOrientation?: number, instance?: Mesh): Mesh {
- var options = {
- path: path,
- radius: radius,
- tessellation: tessellation,
- radiusFunction: radiusFunction,
- arc: 1,
- cap: cap,
- updatable: updatable,
- sideOrientation: sideOrientation,
- instance: instance
- }
- return MeshBuilder.CreateTube(name, options, scene);
- }
- public static CreatePolyhedron(name: string, options: { type?: number, size?: number, sizeX?: number, sizeY?: number, sizeZ?: number, custom?: any, faceUV?: Vector4[], faceColors?: Color4[], updatable?: boolean, sideOrientation?: number }, scene: Scene): Mesh {
- return MeshBuilder.CreatePolyhedron(name, options, scene);
- }
- public static CreateIcoSphere(name: string, options: { radius?: number, flat?: boolean, subdivisions?: number, sideOrientation?: number, updatable?: boolean }, scene: Scene): Mesh {
- return MeshBuilder.CreateIcoSphere(name, options, scene);
- }
- // Decals
- public static CreateDecal(name: string, sourceMesh: AbstractMesh, position: Vector3, normal: Vector3, size: Vector3, angle: number): Mesh {
- var options = {
- position: position,
- normal: normal,
- size: size,
- angle: angle
- }
- return MeshBuilder.CreateDecal(name, sourceMesh, options);
- }
- // Skeletons
- /**
- * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
- */
- public setPositionsForCPUSkinning(): Float32Array {
- var source: number[] | Float32Array;
- if (!this._sourcePositions) {
- source = this.getVerticesData(VertexBuffer.PositionKind);
- this._sourcePositions = new Float32Array(<any>source);
- if (!this.getVertexBuffer(VertexBuffer.PositionKind).isUpdatable()) {
- this.setVerticesData(VertexBuffer.PositionKind, source, true);
- }
- }
- return this._sourcePositions;
- }
- /**
- * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
- */
- public setNormalsForCPUSkinning(): Float32Array {
- var source: number[] | Float32Array;
- if (!this._sourceNormals) {
- source = this.getVerticesData(VertexBuffer.NormalKind);
- this._sourceNormals = new Float32Array(<any>source);
- if (!this.getVertexBuffer(VertexBuffer.NormalKind).isUpdatable()) {
- this.setVerticesData(VertexBuffer.NormalKind, source, true);
- }
- }
- return this._sourceNormals;
- }
- /**
- * Update the vertex buffers by applying transformation from the bones
- * @param {skeleton} skeleton to apply
- */
- public applySkeleton(skeleton: Skeleton): Mesh {
- if (!this.geometry) {
- return;
- }
- if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
- return;
- }
- this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
- if (!this.isVerticesDataPresent(VertexBuffer.PositionKind)) {
- return this;
- }
- if (!this.isVerticesDataPresent(VertexBuffer.NormalKind)) {
- return this;
- }
- if (!this.isVerticesDataPresent(VertexBuffer.MatricesIndicesKind)) {
- return this;
- }
- if (!this.isVerticesDataPresent(VertexBuffer.MatricesWeightsKind)) {
- return this;
- }
- if (!this._sourcePositions) {
- this.setPositionsForCPUSkinning();
- }
- if (!this._sourceNormals) {
- this.setNormalsForCPUSkinning();
- }
- // positionsData checks for not being Float32Array will only pass at most once
- var positionsData = this.getVerticesData(VertexBuffer.PositionKind);
- if (!(positionsData instanceof Float32Array)) {
- positionsData = new Float32Array(positionsData);
- }
- // normalsData checks for not being Float32Array will only pass at most once
- var normalsData = this.getVerticesData(VertexBuffer.NormalKind);
- if (!(normalsData instanceof Float32Array)) {
- normalsData = new Float32Array(normalsData);
- }
- var matricesIndicesData = this.getVerticesData(VertexBuffer.MatricesIndicesKind);
- var matricesWeightsData = this.getVerticesData(VertexBuffer.MatricesWeightsKind);
- var needExtras = this.numBoneInfluencers > 4;
- var matricesIndicesExtraData = needExtras ? this.getVerticesData(VertexBuffer.MatricesIndicesExtraKind) : null;
- var matricesWeightsExtraData = needExtras ? this.getVerticesData(VertexBuffer.MatricesWeightsExtraKind) : null;
- var skeletonMatrices = skeleton.getTransformMatrices(this);
- var tempVector3 = Vector3.Zero();
- var finalMatrix = new Matrix();
- var tempMatrix = new Matrix();
- var matWeightIdx = 0;
- var inf: number;
- for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
- var weight: number;
- for (inf = 0; inf < 4; inf++) {
- weight = matricesWeightsData[matWeightIdx + inf];
- if (weight > 0) {
- Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
- finalMatrix.addToSelf(tempMatrix);
- } else break;
- }
- if (needExtras) {
- for (inf = 0; inf < 4; inf++) {
- weight = matricesWeightsExtraData[matWeightIdx + inf];
- if (weight > 0) {
- Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
- finalMatrix.addToSelf(tempMatrix);
- } else break;
- }
- }
- Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
- tempVector3.toArray(positionsData, index);
- Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
- tempVector3.toArray(normalsData, index);
- finalMatrix.reset();
- }
- this.updateVerticesData(VertexBuffer.PositionKind, positionsData);
- this.updateVerticesData(VertexBuffer.NormalKind, normalsData);
- return this;
- }
- // Tools
- public static MinMax(meshes: AbstractMesh[]): { min: Vector3; max: Vector3 } {
- var minVector: Vector3 = null;
- var maxVector: Vector3 = 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 : Mesh.MinMax(meshesOrMinMaxVector);
- return Vector3.Center(minMaxVector.min, minMaxVector.max);
- }
- /**
- * Merge the array of meshes into a single mesh for performance reasons.
- * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
- * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
- * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
- * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
- */
- public static MergeMeshes(meshes: Array<Mesh>, disposeSource = true, allow32BitsIndices?: boolean, meshSubclass?: Mesh): Mesh {
- var index: number;
- if (!allow32BitsIndices) {
- var totalVertices = 0;
- // Counting vertices
- for (index = 0; index < meshes.length; index++) {
- if (meshes[index]) {
- totalVertices += meshes[index].getTotalVertices();
- if (totalVertices > 65536) {
- Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
- return null;
- }
- }
- }
- }
- // Merge
- var vertexData: VertexData;
- var otherVertexData: VertexData;
- var source: Mesh;
- for (index = 0; index < meshes.length; index++) {
- if (meshes[index]) {
- meshes[index].computeWorldMatrix(true);
- otherVertexData = VertexData.ExtractFromMesh(meshes[index], true);
- otherVertexData.transform(meshes[index].getWorldMatrix());
- if (vertexData) {
- vertexData.merge(otherVertexData);
- } else {
- vertexData = otherVertexData;
- source = meshes[index];
- }
- }
- }
- if (!meshSubclass) {
- meshSubclass = new Mesh(source.name + "_merged", source.getScene());
- }
- vertexData.applyToMesh(meshSubclass);
- // Setting properties
- meshSubclass.material = source.material;
- meshSubclass.checkCollisions = source.checkCollisions;
- // Cleaning
- if (disposeSource) {
- for (index = 0; index < meshes.length; index++) {
- if (meshes[index]) {
- meshes[index].dispose();
- }
- }
- }
- return meshSubclass;
- }
- }
- }
|