babylon.renderablePrim2d.ts 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987
  1. module BABYLON {
  2. export class InstanceClassInfo {
  3. constructor(base: InstanceClassInfo) {
  4. this._baseInfo = base;
  5. this._nextOffset = new StringDictionary<number>();
  6. this._attributes = new Array<InstancePropInfo>();
  7. }
  8. mapProperty(propInfo: InstancePropInfo, push: boolean) {
  9. let curOff = this._nextOffset.getOrAdd(InstanceClassInfo._CurCategories, 0);
  10. propInfo.instanceOffset.add(InstanceClassInfo._CurCategories, this._getBaseOffset(InstanceClassInfo._CurCategories) + curOff);
  11. //console.log(`[${InstanceClassInfo._CurCategories}] New PropInfo. Category: ${propInfo.category}, Name: ${propInfo.attributeName}, Offset: ${propInfo.instanceOffset.get(InstanceClassInfo._CurCategories)}, Size: ${propInfo.size / 4}`);
  12. this._nextOffset.set(InstanceClassInfo._CurCategories, curOff + (propInfo.size / 4));
  13. if (push) {
  14. this._attributes.push(propInfo);
  15. }
  16. }
  17. getInstancingAttributeInfos(effect: Effect, categories: string[]): InstancingAttributeInfo[] {
  18. let catInline = ";" + categories.join(";") + ";";
  19. let res = new Array<InstancingAttributeInfo>();
  20. let curInfo: InstanceClassInfo = this;
  21. while (curInfo) {
  22. for (let attrib of curInfo._attributes) {
  23. // Only map if there's no category assigned to the instance data or if there's a category and it's in the given list
  24. if (!attrib.category || categories.indexOf(attrib.category) !== -1) {
  25. let index = effect.getAttributeLocationByName(attrib.attributeName);
  26. let iai = new InstancingAttributeInfo();
  27. iai.index = index;
  28. iai.attributeSize = attrib.size / 4; // attrib.size is in byte and we need to store in "component" (i.e float is 1, vec3 is 3)
  29. iai.offset = attrib.instanceOffset.get(catInline) * 4; // attrib.instanceOffset is in float, iai.offset must be in bytes
  30. iai.attributeName = attrib.attributeName;
  31. res.push(iai);
  32. }
  33. }
  34. curInfo = curInfo._baseInfo;
  35. }
  36. return res;
  37. }
  38. getShaderAttributes(categories: string[]): string[] {
  39. let res = new Array<string>();
  40. let curInfo: InstanceClassInfo = this;
  41. while (curInfo) {
  42. for (let attrib of curInfo._attributes) {
  43. // Only map if there's no category assigned to the instance data or if there's a category and it's in the given list
  44. if (!attrib.category || categories.indexOf(attrib.category) !== -1) {
  45. res.push(attrib.attributeName);
  46. }
  47. }
  48. curInfo = curInfo._baseInfo;
  49. }
  50. return res;
  51. }
  52. private _getBaseOffset(categories: string): number {
  53. let curOffset = 0;
  54. let curBase = this._baseInfo;
  55. while (curBase) {
  56. curOffset += curBase._nextOffset.getOrAdd(categories, 0);
  57. curBase = curBase._baseInfo;
  58. }
  59. return curOffset;
  60. }
  61. static _CurCategories: string;
  62. private _baseInfo: InstanceClassInfo;
  63. private _nextOffset: StringDictionary<number>;
  64. private _attributes: Array<InstancePropInfo>;
  65. }
  66. export class InstancePropInfo {
  67. attributeName: string;
  68. category: string;
  69. size: number;
  70. shaderOffset: number;
  71. instanceOffset: StringDictionary<number>;
  72. dataType: ShaderDataType;
  73. //uniformLocation: WebGLUniformLocation;
  74. delimitedCategory: string;
  75. constructor() {
  76. this.instanceOffset = new StringDictionary<number>();
  77. }
  78. setSize(val) {
  79. if (val instanceof Vector2) {
  80. this.size = 8;
  81. this.dataType = ShaderDataType.Vector2;
  82. return;
  83. }
  84. if (val instanceof Vector3) {
  85. this.size = 12;
  86. this.dataType = ShaderDataType.Vector3;
  87. return;
  88. }
  89. if (val instanceof Vector4) {
  90. this.size = 16;
  91. this.dataType = ShaderDataType.Vector4;
  92. return;
  93. }
  94. if (val instanceof Matrix) {
  95. throw new Error("Matrix type is not supported by WebGL Instance Buffer, you have to use four Vector4 properties instead");
  96. }
  97. if (typeof (val) === "number") {
  98. this.size = 4;
  99. this.dataType = ShaderDataType.float;
  100. return;
  101. }
  102. if (val instanceof Color3) {
  103. this.size = 12;
  104. this.dataType = ShaderDataType.Color3;
  105. return;
  106. }
  107. if (val instanceof Color4) {
  108. this.size = 16;
  109. this.dataType = ShaderDataType.Color4;
  110. return;
  111. }
  112. if (val instanceof Size) {
  113. this.size = 8;
  114. this.dataType = ShaderDataType.Size;
  115. return;
  116. } return;
  117. }
  118. writeData(array: Float32Array, offset: number, val) {
  119. switch (this.dataType) {
  120. case ShaderDataType.Vector2:
  121. {
  122. let v = <Vector2>val;
  123. array[offset + 0] = v.x;
  124. array[offset + 1] = v.y;
  125. break;
  126. }
  127. case ShaderDataType.Vector3:
  128. {
  129. let v = <Vector3>val;
  130. array[offset + 0] = v.x;
  131. array[offset + 1] = v.y;
  132. array[offset + 2] = v.z;
  133. break;
  134. }
  135. case ShaderDataType.Vector4:
  136. {
  137. let v = <Vector4>val;
  138. array[offset + 0] = v.x;
  139. array[offset + 1] = v.y;
  140. array[offset + 2] = v.z;
  141. array[offset + 3] = v.w;
  142. break;
  143. }
  144. case ShaderDataType.Color3:
  145. {
  146. let v = <Color3>val;
  147. array[offset + 0] = v.r;
  148. array[offset + 1] = v.g;
  149. array[offset + 2] = v.b;
  150. break;
  151. }
  152. case ShaderDataType.Color4:
  153. {
  154. let v = <Color4>val;
  155. array[offset + 0] = v.r;
  156. array[offset + 1] = v.g;
  157. array[offset + 2] = v.b;
  158. array[offset + 3] = v.a;
  159. break;
  160. }
  161. case ShaderDataType.float:
  162. {
  163. let v = <number>val;
  164. array[offset] = v;
  165. break;
  166. }
  167. case ShaderDataType.Matrix:
  168. {
  169. let v = <Matrix>val;
  170. for (let i = 0; i < 16; i++) {
  171. array[offset + i] = v.m[i];
  172. }
  173. break;
  174. }
  175. case ShaderDataType.Size:
  176. {
  177. let s = <Size>val;
  178. array[offset + 0] = s.width;
  179. array[offset + 1] = s.height;
  180. break;
  181. }
  182. }
  183. }
  184. }
  185. export function instanceData<T>(category?: string, shaderAttributeName?: string): (target: Object, propName: string | symbol, descriptor: TypedPropertyDescriptor<T>) => void {
  186. return (target: Object, propName: string | symbol, descriptor: TypedPropertyDescriptor<T>) => {
  187. let dic = ClassTreeInfo.getOrRegister<InstanceClassInfo, InstancePropInfo>(target, (base) => new InstanceClassInfo(base));
  188. let node = dic.getLevelOf(target);
  189. let instanceDataName = <string>propName;
  190. shaderAttributeName = shaderAttributeName || instanceDataName;
  191. let info = node.levelContent.get(instanceDataName);
  192. if (info) {
  193. throw new Error(`The ID ${instanceDataName} is already taken by another instance data`);
  194. }
  195. info = new InstancePropInfo();
  196. info.attributeName = shaderAttributeName;
  197. info.category = category || null;
  198. if (info.category) {
  199. info.delimitedCategory = ";" + info.category + ";";
  200. }
  201. node.levelContent.add(instanceDataName, info);
  202. descriptor.get = function () {
  203. return null;
  204. }
  205. descriptor.set = function (val) {
  206. // Check that we're not trying to set a property that belongs to a category that is not allowed (current)
  207. // Quit if it's the case, otherwise we could overwrite data somewhere...
  208. if (info.category && InstanceClassInfo._CurCategories.indexOf(info.delimitedCategory) === -1) {
  209. return;
  210. }
  211. if (!info.size) {
  212. info.setSize(val);
  213. node.classContent.mapProperty(info, true);
  214. } else if (!info.instanceOffset.contains(InstanceClassInfo._CurCategories)) {
  215. node.classContent.mapProperty(info, false);
  216. }
  217. let obj: InstanceDataBase = this;
  218. if (obj.dataBuffer && obj.dataElements) {
  219. let offset = obj.dataElements[obj.curElement].offset + info.instanceOffset.get(InstanceClassInfo._CurCategories);
  220. info.writeData(obj.dataBuffer.buffer, offset, val);
  221. }
  222. }
  223. }
  224. }
  225. export class InstanceDataBase {
  226. constructor(partId: number, dataElementCount: number) {
  227. this.id = partId;
  228. this.curElement = 0;
  229. this._dataElementCount = dataElementCount;
  230. this.renderMode = 0;
  231. this.arrayLengthChanged = false;
  232. }
  233. id: number;
  234. isVisible: boolean;
  235. @instanceData()
  236. get zBias(): Vector2 {
  237. return null;
  238. }
  239. set zBias(value: Vector2) {
  240. }
  241. @instanceData()
  242. get transformX(): Vector4 {
  243. return null;
  244. }
  245. set transformX(value: Vector4) {
  246. }
  247. @instanceData()
  248. get transformY(): Vector4 {
  249. return null;
  250. }
  251. set transformY(value: Vector4) {
  252. }
  253. @instanceData()
  254. get opacity(): number {
  255. return null;
  256. }
  257. set opacity(value: number) {
  258. }
  259. getClassTreeInfo(): ClassTreeInfo<InstanceClassInfo, InstancePropInfo> {
  260. if (!this.typeInfo) {
  261. this.typeInfo = ClassTreeInfo.get<InstanceClassInfo, InstancePropInfo>(Object.getPrototypeOf(this));
  262. }
  263. return this.typeInfo;
  264. }
  265. allocElements() {
  266. if (!this.dataBuffer || this.dataElements) {
  267. return;
  268. }
  269. let res = new Array<DynamicFloatArrayElementInfo>(this.dataElementCount);
  270. for (let i = 0; i < this.dataElementCount; i++) {
  271. res[i] = this.dataBuffer.allocElement();
  272. }
  273. this.dataElements = res;
  274. }
  275. freeElements() {
  276. if (!this.dataElements) {
  277. return;
  278. }
  279. for (let ei of this.dataElements) {
  280. this.dataBuffer.freeElement(ei);
  281. }
  282. this.dataElements = null;
  283. }
  284. get dataElementCount(): number {
  285. return this._dataElementCount;
  286. }
  287. set dataElementCount(value: number) {
  288. if (value === this._dataElementCount) {
  289. return;
  290. }
  291. this.arrayLengthChanged = true;
  292. this.freeElements();
  293. this._dataElementCount = value;
  294. this.allocElements();
  295. }
  296. groupInstanceInfo: GroupInstanceInfo;
  297. arrayLengthChanged: boolean;
  298. curElement: number;
  299. renderMode: number;
  300. dataElements: DynamicFloatArrayElementInfo[];
  301. dataBuffer: DynamicFloatArray;
  302. typeInfo: ClassTreeInfo<InstanceClassInfo, InstancePropInfo>;
  303. private _dataElementCount: number;
  304. }
  305. @className("RenderablePrim2D")
  306. /**
  307. * The abstract class for primitive that render into the Canvas2D
  308. */
  309. export abstract class RenderablePrim2D extends Prim2DBase {
  310. static RENDERABLEPRIM2D_PROPCOUNT: number = Prim2DBase.PRIM2DBASE_PROPCOUNT + 5;
  311. public static isAlphaTestProperty: Prim2DPropInfo;
  312. public static isTransparentProperty: Prim2DPropInfo;
  313. @dynamicLevelProperty(Prim2DBase.PRIM2DBASE_PROPCOUNT + 0, pi => RenderablePrim2D.isAlphaTestProperty = pi)
  314. /**
  315. * Get/set if the Primitive is from the AlphaTest rendering category.
  316. * The AlphaTest category is the rendering pass with alpha blend, depth compare and write activated.
  317. * Primitives that render with an alpha mask should be from this category.
  318. * The setter should be used only by implementers of new primitive type.
  319. */
  320. public get isAlphaTest(): boolean {
  321. return this._useTextureAlpha() || this._isPrimAlphaTest();
  322. }
  323. @dynamicLevelProperty(Prim2DBase.PRIM2DBASE_PROPCOUNT + 1, pi => RenderablePrim2D.isTransparentProperty = pi)
  324. /**
  325. * Get/set if the Primitive is from the Transparent rendering category.
  326. * The setter should be used only by implementers of new primitive type.
  327. */
  328. public get isTransparent(): boolean {
  329. return (this.actualOpacity<1) || this._shouldUseAlphaFromTexture() || this._isPrimTransparent();
  330. }
  331. public get renderMode(): number {
  332. return this._renderMode;
  333. }
  334. constructor(settings?: {
  335. parent ?: Prim2DBase,
  336. id ?: string,
  337. origin ?: Vector2,
  338. isVisible ?: boolean,
  339. }) {
  340. super(settings);
  341. this._transparentPrimitiveInfo = null;
  342. }
  343. /**
  344. * Dispose the primitive and its resources, remove it from its parent
  345. */
  346. public dispose(): boolean {
  347. if (!super.dispose()) {
  348. return false;
  349. }
  350. if (this.renderGroup) {
  351. this.renderGroup._setCacheGroupDirty();
  352. }
  353. if (this._transparentPrimitiveInfo) {
  354. this.renderGroup._renderableData.removeTransparentPrimitiveInfo(this._transparentPrimitiveInfo);
  355. this._transparentPrimitiveInfo = null;
  356. }
  357. if (this._instanceDataParts) {
  358. this._cleanupInstanceDataParts();
  359. }
  360. if (this._modelRenderCache) {
  361. this._modelRenderCache.dispose();
  362. this._modelRenderCache = null;
  363. }
  364. if (this._instanceDataParts) {
  365. this._instanceDataParts.forEach(p => {
  366. p.freeElements();
  367. });
  368. this._instanceDataParts = null;
  369. }
  370. return true;
  371. }
  372. private _cleanupInstanceDataParts() {
  373. let gii: GroupInstanceInfo = null;
  374. for (let part of this._instanceDataParts) {
  375. part.freeElements();
  376. gii = part.groupInstanceInfo;
  377. }
  378. if (gii) {
  379. let usedCount = 0;
  380. if (gii.hasOpaqueData) {
  381. let od = gii.opaqueData[0];
  382. usedCount += od._partData.usedElementCount;
  383. gii.opaqueDirty = true;
  384. }
  385. if (gii.hasAlphaTestData) {
  386. let atd = gii.alphaTestData[0];
  387. usedCount += atd._partData.usedElementCount;
  388. gii.alphaTestDirty = true;
  389. }
  390. if (gii.hasTransparentData) {
  391. let td = gii.transparentData[0];
  392. usedCount += td._partData.usedElementCount;
  393. gii.transparentDirty = true;
  394. }
  395. if (usedCount === 0 && gii.modelRenderCache!=null) {
  396. this.renderGroup._renderableData._renderGroupInstancesInfo.remove(gii.modelRenderCache.modelKey);
  397. gii.dispose();
  398. }
  399. if (this._modelRenderCache) {
  400. this._modelRenderCache.dispose();
  401. this._modelRenderCache = null;
  402. }
  403. }
  404. this._instanceDataParts = null;
  405. }
  406. public _prepareRenderPre(context: PrepareRender2DContext) {
  407. super._prepareRenderPre(context);
  408. // If the model changed and we have already an instance, we must remove this instance from the obsolete model
  409. if (this._isFlagSet(SmartPropertyPrim.flagModelDirty) && this._instanceDataParts) {
  410. this._cleanupInstanceDataParts();
  411. }
  412. // Need to create the model?
  413. let setupModelRenderCache = false;
  414. if (!this._modelRenderCache || this._isFlagSet(SmartPropertyPrim.flagModelDirty)) {
  415. setupModelRenderCache = this._createModelRenderCache();
  416. }
  417. let gii: GroupInstanceInfo = null;
  418. let newInstance = false;
  419. // Need to create the instance data parts?
  420. if (!this._instanceDataParts) {
  421. // Yes, flag it for later, more processing will have to be done
  422. newInstance = true;
  423. gii = this._createModelDataParts();
  424. }
  425. // If the ModelRenderCache is brand new, now is the time to call the implementation's specific setup method to create the rendering resources
  426. if (setupModelRenderCache) {
  427. this.setupModelRenderCache(this._modelRenderCache);
  428. }
  429. // At this stage we have everything correctly initialized, ModelRenderCache is setup, Model Instance data are good too, they have allocated elements in the Instanced DynamicFloatArray.
  430. // The last thing to do is check if the instanced related data must be updated because a InstanceLevel property had changed or the primitive visibility changed.
  431. if (this._areSomeFlagsSet(SmartPropertyPrim.flagVisibilityChanged | SmartPropertyPrim.flagNeedRefresh) || context.forceRefreshPrimitive || newInstance || (this._instanceDirtyFlags !== 0) || (this._globalTransformProcessStep !== this._globalTransformStep) || this._mustUpdateInstance()) {
  432. this._updateInstanceDataParts(gii);
  433. }
  434. }
  435. private _createModelRenderCache(): boolean {
  436. let setupModelRenderCache = false;
  437. if (this._modelRenderCache) {
  438. this._modelRenderCache.dispose();
  439. }
  440. this._modelRenderCache = this.owner._engineData.GetOrAddModelCache(this.modelKey, (key: string) => {
  441. let mrc = this.createModelRenderCache(key);
  442. setupModelRenderCache = true;
  443. return mrc;
  444. });
  445. this._clearFlags(SmartPropertyPrim.flagModelDirty);
  446. // if this is still false it means the MRC already exists, so we add a reference to it
  447. if (!setupModelRenderCache) {
  448. this._modelRenderCache.addRef();
  449. }
  450. return setupModelRenderCache;
  451. }
  452. private _createModelDataParts(): GroupInstanceInfo {
  453. // Create the instance data parts of the primitive and store them
  454. let parts = this.createInstanceDataParts();
  455. this._instanceDataParts = parts;
  456. // Check if the ModelRenderCache for this particular instance is also brand new, initialize it if it's the case
  457. if (!this._modelRenderCache._partData) {
  458. this._setupModelRenderCache(parts);
  459. }
  460. // The Rendering resources (Effect, VB, IB, Textures) are stored in the ModelRenderCache
  461. // But it's the RenderGroup that will store all the Instanced related data to render all the primitive it owns.
  462. // So for a given ModelKey we getOrAdd a GroupInstanceInfo that will store all these data
  463. let gii = this.renderGroup._renderableData._renderGroupInstancesInfo.getOrAddWithFactory(this.modelKey, k => {
  464. let res = new GroupInstanceInfo(this.renderGroup, this._modelRenderCache, this._modelRenderCache._partData.length);
  465. for (let j = 0; j < this._modelRenderCache._partData.length; j++) {
  466. let part = this._instanceDataParts[j];
  467. res.partIndexFromId.add(part.id.toString(), j);
  468. res.usedShaderCategories[j] = ";" + this.getUsedShaderCategories(part).join(";") + ";";
  469. res.strides[j] = this._modelRenderCache._partData[j]._partDataStride;
  470. }
  471. return res;
  472. });
  473. // Get the GroupInfoDataPart corresponding to the render category of the part
  474. let rm = 0;
  475. let gipd: GroupInfoPartData[] = null;
  476. if (this.isTransparent) {
  477. gipd = gii.transparentData;
  478. rm = Render2DContext.RenderModeTransparent;
  479. } else if (this.isAlphaTest) {
  480. gipd = gii.alphaTestData;
  481. rm = Render2DContext.RenderModeAlphaTest;
  482. } else {
  483. gipd = gii.opaqueData;
  484. rm = Render2DContext.RenderModeOpaque;
  485. }
  486. // For each instance data part of the primitive, allocate the instanced element it needs for render
  487. for (let i = 0; i < parts.length; i++) {
  488. let part = parts[i];
  489. part.dataBuffer = gipd[i]._partData;
  490. part.allocElements();
  491. part.renderMode = rm;
  492. part.groupInstanceInfo = gii;
  493. }
  494. return gii;
  495. }
  496. private _setupModelRenderCache(parts: InstanceDataBase[]) {
  497. let ctiArray = new Array<ClassTreeInfo<InstanceClassInfo, InstancePropInfo>>();
  498. this._modelRenderCache._partData = new Array<ModelRenderCachePartData>();
  499. for (let dataPart of parts) {
  500. var pd = new ModelRenderCachePartData();
  501. this._modelRenderCache._partData.push(pd)
  502. var cat = this.getUsedShaderCategories(dataPart);
  503. var cti = dataPart.getClassTreeInfo();
  504. // Make sure the instance is visible other the properties won't be set and their size/offset wont be computed
  505. let curVisible = this.isVisible;
  506. this.isVisible = true;
  507. // We manually trigger refreshInstanceData for the only sake of evaluating each instance property size and offset in the instance data, this can only be made at runtime. Once it's done we have all the information to create the instance data buffer.
  508. //console.log("Build Prop Layout for " + Tools.getClassName(this._instanceDataParts[0]));
  509. var joinCat = ";" + cat.join(";") + ";";
  510. pd._partJoinedUsedCategories = joinCat;
  511. InstanceClassInfo._CurCategories = joinCat;
  512. let obj = this.beforeRefreshForLayoutConstruction(dataPart);
  513. if (!this.refreshInstanceDataPart(dataPart)) {
  514. console.log(`Layout construction for ${Tools.getClassName(this._instanceDataParts[0])} failed because refresh returned false`);
  515. }
  516. this.afterRefreshForLayoutConstruction(dataPart, obj);
  517. this.isVisible = curVisible;
  518. var size = 0;
  519. cti.fullContent.forEach((k, v) => {
  520. if (!v.category || cat.indexOf(v.category) !== -1) {
  521. if (v.attributeName === "zBias") {
  522. pd._zBiasOffset = v.instanceOffset.get(joinCat);
  523. }
  524. if (!v.size) {
  525. console.log(`ERROR: Couldn't detect the size of the Property ${v.attributeName} from type ${Tools.getClassName(cti.type)}. Property is ignored.`);
  526. } else {
  527. size += v.size;
  528. }
  529. }
  530. });
  531. pd._partDataStride = size;
  532. pd._partUsedCategories = cat;
  533. pd._partId = dataPart.id;
  534. ctiArray.push(cti);
  535. }
  536. this._modelRenderCache._partsClassInfo = ctiArray;
  537. }
  538. protected onZOrderChanged() {
  539. if (this.isTransparent && this._transparentPrimitiveInfo) {
  540. this.renderGroup._renderableData.transparentPrimitiveZChanged(this._transparentPrimitiveInfo);
  541. let gii = this.renderGroup._renderableData._renderGroupInstancesInfo.get(this.modelKey);
  542. // Flag the transparentData dirty has will have to sort it again
  543. gii.transparentOrderDirty = true;
  544. }
  545. }
  546. protected _mustUpdateInstance(): boolean {
  547. return false;
  548. }
  549. protected _useTextureAlpha(): boolean {
  550. return false;
  551. }
  552. protected _shouldUseAlphaFromTexture(): boolean {
  553. return false;
  554. }
  555. protected _isPrimAlphaTest(): boolean {
  556. return false;
  557. }
  558. protected _isPrimTransparent(): boolean {
  559. return false;
  560. }
  561. private _updateInstanceDataParts(gii: GroupInstanceInfo) {
  562. // Fetch the GroupInstanceInfo if we don't already have it
  563. let rd = this.renderGroup._renderableData;
  564. if (!gii) {
  565. gii = rd._renderGroupInstancesInfo.get(this.modelKey);
  566. }
  567. let isTransparent = this.isTransparent;
  568. let isAlphaTest = this.isAlphaTest;
  569. let wereTransparent = false;
  570. // Check a render mode change
  571. let rmChanged = false;
  572. if (this._instanceDataParts.length>0) {
  573. let firstPart = this._instanceDataParts[0];
  574. let partRM = firstPart.renderMode;
  575. let curRM = this.renderMode;
  576. if (partRM !== curRM) {
  577. wereTransparent = partRM === Render2DContext.RenderModeTransparent;
  578. rmChanged = true;
  579. let gipd: TransparentGroupInfoPartData[];
  580. switch (curRM) {
  581. case Render2DContext.RenderModeTransparent:
  582. gipd = gii.transparentData;
  583. break;
  584. case Render2DContext.RenderModeAlphaTest:
  585. gipd = gii.alphaTestData;
  586. break;
  587. default:
  588. gipd = gii.opaqueData;
  589. }
  590. for (let i = 0; i < this._instanceDataParts.length; i++) {
  591. let part = this._instanceDataParts[i];
  592. part.freeElements();
  593. part.dataBuffer = gipd[i]._partData;
  594. part.renderMode = curRM;
  595. }
  596. }
  597. }
  598. // Handle changes related to ZOffset
  599. let visChanged = this._isFlagSet(SmartPropertyPrim.flagVisibilityChanged);
  600. if (isTransparent || wereTransparent) {
  601. // Handle visibility change, which is also triggered when the primitive just got created
  602. if (visChanged || rmChanged) {
  603. if (this.isVisible && !wereTransparent) {
  604. if (!this._transparentPrimitiveInfo) {
  605. // Add the primitive to the list of transparent ones in the group that render is
  606. this._transparentPrimitiveInfo = rd.addNewTransparentPrimitiveInfo(this, gii);
  607. }
  608. } else {
  609. if (this._transparentPrimitiveInfo) {
  610. rd.removeTransparentPrimitiveInfo(this._transparentPrimitiveInfo);
  611. this._transparentPrimitiveInfo = null;
  612. }
  613. }
  614. gii.transparentOrderDirty = true;
  615. }
  616. }
  617. let rebuildTrans = false;
  618. // For each Instance Data part, refresh it to update the data in the DynamicFloatArray
  619. for (let part of this._instanceDataParts) {
  620. let justAllocated = false;
  621. // Check if we need to allocate data elements (hidden prim which becomes visible again)
  622. if (!part.dataElements && (visChanged || rmChanged || this.isVisible)) {
  623. part.allocElements();
  624. justAllocated = true;
  625. }
  626. InstanceClassInfo._CurCategories = gii.usedShaderCategories[gii.partIndexFromId.get(part.id.toString())];
  627. // Will return false if the instance should not be rendered (not visible or other any reasons)
  628. part.arrayLengthChanged = false;
  629. if (!this.refreshInstanceDataPart(part)) {
  630. // Free the data element
  631. if (part.dataElements) {
  632. part.freeElements();
  633. }
  634. // The refresh couldn't succeed, push the primitive to be dirty again for the next render
  635. if (this.isVisible) {
  636. rd._primNewDirtyList.push(this);
  637. }
  638. }
  639. rebuildTrans = rebuildTrans || part.arrayLengthChanged || justAllocated;
  640. }
  641. this._instanceDirtyFlags = 0;
  642. // Make the appropriate data dirty
  643. if (isTransparent) {
  644. gii.transparentDirty = true;
  645. if (rebuildTrans) {
  646. rd._transparentListChanged = true;
  647. }
  648. } else if (isAlphaTest) {
  649. gii.alphaTestDirty = true;
  650. } else {
  651. gii.opaqueDirty = true;
  652. }
  653. this._clearFlags(SmartPropertyPrim.flagVisibilityChanged); // Reset the flag as we've handled the case
  654. }
  655. _updateTransparentSegmentIndices(ts: TransparentSegment) {
  656. let minOff = Prim2DBase._bigInt;
  657. let maxOff = 0;
  658. for (let part of this._instanceDataParts) {
  659. if (part && part.dataElements) {
  660. part.dataBuffer.pack();
  661. for (let el of part.dataElements) {
  662. minOff = Math.min(minOff, el.offset);
  663. maxOff = Math.max(maxOff, el.offset);
  664. }
  665. ts.startDataIndex = Math.min(ts.startDataIndex, minOff / part.dataBuffer.stride);
  666. ts.endDataIndex = Math.max(ts.endDataIndex, (maxOff / part.dataBuffer.stride) + 1); // +1 for exclusive
  667. }
  668. }
  669. }
  670. // This internal method is mainly used for transparency processing
  671. public _getNextPrimZOrder(): number {
  672. let length = this._instanceDataParts.length;
  673. for (let i = 0; i < length; i++) {
  674. let part = this._instanceDataParts[i];
  675. if (part) {
  676. let stride = part.dataBuffer.stride;
  677. let lastElementOffset = part.dataElements[part.dataElements.length - 1].offset;
  678. // check if it's the last in the DFA
  679. if (part.dataBuffer.totalElementCount * stride <= lastElementOffset) {
  680. return null;
  681. }
  682. // Return the Z of the next primitive that lies in the DFA
  683. return part.dataBuffer[lastElementOffset + stride + this.modelRenderCache._partData[i]._zBiasOffset];
  684. }
  685. }
  686. return null;
  687. }
  688. // This internal method is mainly used for transparency processing
  689. public _getPrevPrimZOrder(): number {
  690. let length = this._instanceDataParts.length;
  691. for (let i = 0; i < length; i++) {
  692. let part = this._instanceDataParts[i];
  693. if (part) {
  694. let stride = part.dataBuffer.stride;
  695. let firstElementOffset = part.dataElements[0].offset;
  696. // check if it's the first in the DFA
  697. if (firstElementOffset === 0) {
  698. return null;
  699. }
  700. // Return the Z of the previous primitive that lies in the DFA
  701. return part.dataBuffer[firstElementOffset - stride + this.modelRenderCache._partData[i]._zBiasOffset];
  702. }
  703. }
  704. return null;
  705. }
  706. /**
  707. * Transform a given point using the Primitive's origin setting.
  708. * This method requires the Primitive's actualSize to be accurate
  709. * @param p the point to transform
  710. * @param originOffset an offset applied on the current origin before performing the transformation. Depending on which frame of reference your data is expressed you may have to apply a offset. (if you data is expressed from the bottom/left, no offset is required. If it's expressed from the center the a [-0.5;-0.5] offset has to be applied.
  711. * @param res an allocated Vector2 that will receive the transformed content
  712. */
  713. protected transformPointWithOriginByRef(p: Vector2, originOffset:Vector2, res: Vector2) {
  714. let actualSize = this.actualSize;
  715. res.x = p.x - ((this.origin.x + (originOffset ? originOffset.x : 0)) * actualSize.width);
  716. res.y = p.y - ((this.origin.y + (originOffset ? originOffset.y : 0)) * actualSize.height);
  717. }
  718. protected transformPointWithOriginToRef(p: Vector2, originOffset: Vector2, res: Vector2) {
  719. this.transformPointWithOriginByRef(p, originOffset, res);
  720. return res;
  721. }
  722. /**
  723. * Get the info for a given effect based on the dataPart metadata
  724. * @param dataPartId partId in part list to get the info
  725. * @param vertexBufferAttributes vertex buffer attributes to manually add
  726. * @param uniforms uniforms to manually add
  727. * @param useInstanced specified if Instanced Array should be used, if null the engine caps will be used (so true if WebGL supports it, false otherwise), but you have the possibility to override the engine capability. However, if you manually set true but the engine does not support Instanced Array, this method will return null
  728. */
  729. protected getDataPartEffectInfo(dataPartId: number, vertexBufferAttributes: string[], uniforms: string[] = null, useInstanced: boolean = null): { attributes: string[], uniforms: string[], defines: string } {
  730. let dataPart = Tools.first(this._instanceDataParts, i => i.id === dataPartId);
  731. if (!dataPart) {
  732. return null;
  733. }
  734. let instancedArray = this.owner.supportInstancedArray;
  735. if (useInstanced != null) {
  736. // Check if the caller ask for Instanced Array and the engine does not support it, return null if it's the case
  737. if (useInstanced && instancedArray === false) {
  738. return null;
  739. }
  740. // Use the caller's setting
  741. instancedArray = useInstanced;
  742. }
  743. let cti = dataPart.getClassTreeInfo();
  744. let categories = this.getUsedShaderCategories(dataPart);
  745. let att = cti.classContent.getShaderAttributes(categories);
  746. let defines = "";
  747. categories.forEach(c => { defines += `#define ${c}\n` });
  748. if (instancedArray) {
  749. defines += "#define Instanced\n";
  750. }
  751. return {
  752. attributes: instancedArray ? vertexBufferAttributes.concat(att) : vertexBufferAttributes,
  753. uniforms: instancedArray ? (uniforms != null ? uniforms : []) : ((uniforms != null) ? att.concat(uniforms) : (att!=null ? att : [])),
  754. defines: defines
  755. };
  756. }
  757. protected get modelRenderCache(): ModelRenderCache {
  758. return this._modelRenderCache;
  759. }
  760. protected createModelRenderCache(modelKey: string): ModelRenderCache {
  761. return null;
  762. }
  763. protected setupModelRenderCache(modelRenderCache: ModelRenderCache) {
  764. }
  765. protected createInstanceDataParts(): InstanceDataBase[] {
  766. return null;
  767. }
  768. protected getUsedShaderCategories(dataPart: InstanceDataBase): string[] {
  769. return [];
  770. }
  771. protected beforeRefreshForLayoutConstruction(part: InstanceDataBase): any {
  772. }
  773. protected afterRefreshForLayoutConstruction(part: InstanceDataBase, obj: any) {
  774. }
  775. protected applyActualScaleOnTransform(): boolean {
  776. return true;
  777. }
  778. protected refreshInstanceDataPart(part: InstanceDataBase): boolean {
  779. if (!this.isVisible) {
  780. return false;
  781. }
  782. part.isVisible = this.isVisible;
  783. // Which means, if there's only one data element, we're update it from this method, otherwise it is the responsibility of the derived class to call updateInstanceDataPart as many times as needed, properly (look at Text2D's implementation for more information)
  784. if (part.dataElementCount === 1) {
  785. part.curElement = 0;
  786. this.updateInstanceDataPart(part);
  787. }
  788. return true;
  789. }
  790. private static _uV = new Vector2(1, 1);
  791. /**
  792. * Update the instanceDataBase level properties of a part
  793. * @param part the part to update
  794. * @param positionOffset to use in multi part per primitive (e.g. the Text2D has N parts for N letter to display), this give the offset to apply (e.g. the position of the letter from the bottom/left corner of the text).
  795. */
  796. protected updateInstanceDataPart(part: InstanceDataBase, positionOffset: Vector2 = null) {
  797. let t = this._globalTransform.multiply(this.renderGroup.invGlobalTransform); // Compute the transformation into the renderGroup's space
  798. let rgScale = this._areSomeFlagsSet(SmartPropertyPrim.flagDontInheritParentScale) ? RenderablePrim2D._uV : this.renderGroup.actualScale; // We still need to apply the scale of the renderGroup to our rendering, so get it.
  799. let size = (<Size>this.renderGroup.viewportSize);
  800. let zBias = this.actualZOffset;
  801. let offX = 0;
  802. let offY = 0;
  803. // If there's an offset, apply the global transformation matrix on it to get a global offset
  804. if (positionOffset) {
  805. offX = positionOffset.x * t.m[0] + positionOffset.y * t.m[4];
  806. offY = positionOffset.x * t.m[1] + positionOffset.y * t.m[5];
  807. }
  808. // Have to convert the coordinates to clip space which is ranged between [-1;1] on X and Y axis, with 0,0 being the left/bottom corner
  809. // Current coordinates are expressed in renderGroup coordinates ([0, renderGroup.actualSize.width|height]) with 0,0 being at the left/top corner
  810. // So for X:
  811. // - tx.x = value * 2 / width: is to switch from [0, renderGroup.width] to [0, 2]
  812. // - tx.w = (value * 2 / width) - 1: w stores the translation in renderGroup coordinates so (value * 2 / width) to switch to a clip space translation value. - 1 is to offset the overall [0;2] to [-1;1].
  813. // At last we don't forget to apply the actualScale of the Render Group to tx[0] and ty[1] to propagate scaling correctly
  814. let w = size.width;
  815. let h = size.height;
  816. let invZBias = 1 / zBias;
  817. let tx = new Vector4(t.m[0] * rgScale.x * 2 / w, t.m[4] * 2 / w, 0/*t.m[8]*/, ((t.m[12] + offX) * rgScale.x * 2 / w) - 1);
  818. let ty = new Vector4(t.m[1] * 2 / h, t.m[5] * rgScale.y * 2 / h, 0/*t.m[9]*/, ((t.m[13] + offY) * rgScale.y * 2 / h) - 1);
  819. if (!this.applyActualScaleOnTransform()) {
  820. let las = this.actualScale;
  821. tx.x /= las.x;
  822. ty.y /= las.y;
  823. }
  824. part.transformX = tx;
  825. part.transformY = ty;
  826. part.opacity = this.actualOpacity;
  827. // Stores zBias and it's inverse value because that's needed to compute the clip space W coordinate (which is 1/Z, so 1/zBias)
  828. part.zBias = new Vector2(zBias, invZBias);
  829. }
  830. protected _updateRenderMode() {
  831. if (this.isTransparent) {
  832. this._renderMode = Render2DContext.RenderModeTransparent;
  833. } else if (this.isAlphaTest) {
  834. this._renderMode = Render2DContext.RenderModeAlphaTest;
  835. } else {
  836. this._renderMode = Render2DContext.RenderModeOpaque;
  837. }
  838. }
  839. private _modelRenderCache: ModelRenderCache;
  840. private _transparentPrimitiveInfo: TransparentPrimitiveInfo;
  841. protected _instanceDataParts: InstanceDataBase[];
  842. private _renderMode: number;
  843. }
  844. }