nodeGeometry.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557
  1. import { __decorate } from "../../tslib.es6.js";
  2. import { Observable } from "../../Misc/observable.js";
  3. import { Mesh } from "../mesh.js";
  4. import { GeometryOutputBlock } from "./Blocks/geometryOutputBlock.js";
  5. import { NodeGeometryBuildState } from "./nodeGeometryBuildState.js";
  6. import { GetClass } from "../../Misc/typeStore.js";
  7. import { serialize } from "../../Misc/decorators.js";
  8. import { SerializationHelper } from "../../Misc/decorators.serialization.js";
  9. import { WebRequest } from "../../Misc/webRequest.js";
  10. import { BoxBlock } from "./Blocks/Sources/boxBlock.js";
  11. import { PrecisionDate } from "../../Misc/precisionDate.js";
  12. import { Tools } from "../../Misc/tools.js";
  13. import { Engine } from "../../Engines/engine.js";
  14. /**
  15. * Defines a node based geometry
  16. * @see demo at https://playground.babylonjs.com#PYY6XE#69
  17. */
  18. export class NodeGeometry {
  19. /** @returns the inspector from bundle or global */
  20. _getGlobalNodeGeometryEditor() {
  21. // UMD Global name detection from Webpack Bundle UMD Name.
  22. if (typeof NODEGEOMETRYEDITOR !== "undefined") {
  23. return NODEGEOMETRYEDITOR;
  24. }
  25. // In case of module let's check the global emitted from the editor entry point.
  26. if (typeof BABYLON !== "undefined" && typeof BABYLON.NodeGeometryEditor !== "undefined") {
  27. return BABYLON;
  28. }
  29. return undefined;
  30. }
  31. /**
  32. * Gets the time spent to build this block (in ms)
  33. */
  34. get buildExecutionTime() {
  35. return this._buildExecutionTime;
  36. }
  37. /**
  38. * Creates a new geometry
  39. * @param name defines the name of the geometry
  40. */
  41. constructor(name) {
  42. this._buildId = NodeGeometry._BuildIdGenerator++;
  43. this._buildWasSuccessful = false;
  44. this._vertexData = null;
  45. this._buildExecutionTime = 0;
  46. // eslint-disable-next-line @typescript-eslint/naming-convention
  47. this.BJSNODEGEOMETRYEDITOR = this._getGlobalNodeGeometryEditor();
  48. /**
  49. * Gets or sets data used by visual editor
  50. * @see https://nge.babylonjs.com
  51. */
  52. this.editorData = null;
  53. /**
  54. * Gets an array of blocks that needs to be serialized even if they are not yet connected
  55. */
  56. this.attachedBlocks = [];
  57. /**
  58. * Observable raised when the geometry is built
  59. */
  60. this.onBuildObservable = new Observable();
  61. /** Gets or sets the GeometryOutputBlock used to gather the final geometry data */
  62. this.outputBlock = null;
  63. this.name = name;
  64. }
  65. /**
  66. * Gets the current class name of the geometry e.g. "NodeGeometry"
  67. * @returns the class name
  68. */
  69. getClassName() {
  70. return "NodeGeometry";
  71. }
  72. /**
  73. * Get a block by its name
  74. * @param name defines the name of the block to retrieve
  75. * @returns the required block or null if not found
  76. */
  77. getBlockByName(name) {
  78. let result = null;
  79. for (const block of this.attachedBlocks) {
  80. if (block.name === name) {
  81. if (!result) {
  82. result = block;
  83. }
  84. else {
  85. Tools.Warn("More than one block was found with the name `" + name + "`");
  86. return result;
  87. }
  88. }
  89. }
  90. return result;
  91. }
  92. /**
  93. * Get a block using a predicate
  94. * @param predicate defines the predicate used to find the good candidate
  95. * @returns the required block or null if not found
  96. */
  97. getBlockByPredicate(predicate) {
  98. for (const block of this.attachedBlocks) {
  99. if (predicate(block)) {
  100. return block;
  101. }
  102. }
  103. return null;
  104. }
  105. /**
  106. * Gets the list of input blocks attached to this material
  107. * @returns an array of InputBlocks
  108. */
  109. getInputBlocks() {
  110. const blocks = [];
  111. for (const block of this.attachedBlocks) {
  112. if (block.isInput) {
  113. blocks.push(block);
  114. }
  115. }
  116. return blocks;
  117. }
  118. /**
  119. * Launch the node geometry editor
  120. * @param config Define the configuration of the editor
  121. * @returns a promise fulfilled when the node editor is visible
  122. */
  123. edit(config) {
  124. return new Promise((resolve) => {
  125. this.BJSNODEGEOMETRYEDITOR = this.BJSNODEGEOMETRYEDITOR || this._getGlobalNodeGeometryEditor();
  126. if (typeof this.BJSNODEGEOMETRYEDITOR == "undefined") {
  127. const editorUrl = config && config.editorURL ? config.editorURL : NodeGeometry.EditorURL;
  128. // Load editor and add it to the DOM
  129. Tools.LoadBabylonScript(editorUrl, () => {
  130. this.BJSNODEGEOMETRYEDITOR = this.BJSNODEGEOMETRYEDITOR || this._getGlobalNodeGeometryEditor();
  131. this._createNodeEditor(config?.nodeGeometryEditorConfig);
  132. resolve();
  133. });
  134. }
  135. else {
  136. // Otherwise creates the editor
  137. this._createNodeEditor(config?.nodeGeometryEditorConfig);
  138. resolve();
  139. }
  140. });
  141. }
  142. /**
  143. * Creates the node editor window.
  144. * @param additionalConfig Additional configuration for the NGE
  145. */
  146. _createNodeEditor(additionalConfig) {
  147. const nodeEditorConfig = {
  148. nodeGeometry: this,
  149. ...additionalConfig,
  150. };
  151. this.BJSNODEGEOMETRYEDITOR.NodeGeometryEditor.Show(nodeEditorConfig);
  152. }
  153. /**
  154. * Build the final geometry
  155. * @param verbose defines if the build should log activity
  156. * @param updateBuildId defines if the internal build Id should be updated (default is true)
  157. * @param autoConfigure defines if the autoConfigure method should be called when initializing blocks (default is false)
  158. */
  159. build(verbose = false, updateBuildId = true, autoConfigure = false) {
  160. this._buildWasSuccessful = false;
  161. if (!this.outputBlock) {
  162. // eslint-disable-next-line no-throw-literal
  163. throw "You must define the outputBlock property before building the geometry";
  164. }
  165. const now = PrecisionDate.Now;
  166. // Initialize blocks
  167. this._initializeBlock(this.outputBlock, autoConfigure);
  168. // Build
  169. const state = new NodeGeometryBuildState();
  170. state.buildId = this._buildId;
  171. state.verbose = verbose;
  172. this.outputBlock.build(state);
  173. if (updateBuildId) {
  174. this._buildId = NodeGeometry._BuildIdGenerator++;
  175. }
  176. this._buildExecutionTime = PrecisionDate.Now - now;
  177. // Errors
  178. state.emitErrors();
  179. this._buildWasSuccessful = true;
  180. this._vertexData = state.vertexData;
  181. this.onBuildObservable.notifyObservers(this);
  182. }
  183. /**
  184. * Creates a mesh from the geometry blocks
  185. * @param name defines the name of the mesh
  186. * @param scene The scene the mesh is scoped to
  187. * @returns The new mesh
  188. */
  189. createMesh(name, scene = null) {
  190. if (!this._buildWasSuccessful) {
  191. this.build();
  192. }
  193. if (!this._vertexData) {
  194. return null;
  195. }
  196. const mesh = new Mesh(name, scene);
  197. this._vertexData.applyToMesh(mesh);
  198. mesh._internalMetadata = mesh._internalMetadata || {};
  199. mesh._internalMetadata.nodeGeometry = this;
  200. return mesh;
  201. }
  202. /**
  203. * Creates a mesh from the geometry blocks
  204. * @param mesh the mesh to update
  205. * @returns True if successfully updated
  206. */
  207. updateMesh(mesh) {
  208. if (!this._buildWasSuccessful) {
  209. this.build();
  210. }
  211. if (!this._vertexData) {
  212. return false;
  213. }
  214. this._vertexData.applyToMesh(mesh);
  215. mesh._internalMetadata = mesh._internalMetadata || {};
  216. mesh._internalMetadata.nodeGeometry = this;
  217. return mesh;
  218. }
  219. _initializeBlock(node, autoConfigure = true) {
  220. node.initialize();
  221. if (autoConfigure) {
  222. node.autoConfigure();
  223. }
  224. node._preparationId = this._buildId;
  225. if (this.attachedBlocks.indexOf(node) === -1) {
  226. this.attachedBlocks.push(node);
  227. }
  228. for (const input of node.inputs) {
  229. const connectedPoint = input.connectedPoint;
  230. if (connectedPoint) {
  231. const block = connectedPoint.ownerBlock;
  232. if (block !== node) {
  233. this._initializeBlock(block, autoConfigure);
  234. }
  235. }
  236. }
  237. }
  238. /**
  239. * Clear the current geometry
  240. */
  241. clear() {
  242. this.outputBlock = null;
  243. this.attachedBlocks.length = 0;
  244. }
  245. /**
  246. * Remove a block from the current geometry
  247. * @param block defines the block to remove
  248. */
  249. removeBlock(block) {
  250. const attachedBlockIndex = this.attachedBlocks.indexOf(block);
  251. if (attachedBlockIndex > -1) {
  252. this.attachedBlocks.splice(attachedBlockIndex, 1);
  253. }
  254. if (block === this.outputBlock) {
  255. this.outputBlock = null;
  256. }
  257. }
  258. /**
  259. * Clear the current graph and load a new one from a serialization object
  260. * @param source defines the JSON representation of the geometry
  261. * @param merge defines whether or not the source must be merged or replace the current content
  262. */
  263. parseSerializedObject(source, merge = false) {
  264. if (!merge) {
  265. this.clear();
  266. }
  267. const map = {};
  268. // Create blocks
  269. for (const parsedBlock of source.blocks) {
  270. const blockType = GetClass(parsedBlock.customType);
  271. if (blockType) {
  272. const block = new blockType();
  273. block._deserialize(parsedBlock);
  274. map[parsedBlock.id] = block;
  275. this.attachedBlocks.push(block);
  276. }
  277. }
  278. // Reconnect teleportation
  279. for (const block of this.attachedBlocks) {
  280. if (block.isTeleportOut) {
  281. const teleportOut = block;
  282. const id = teleportOut._tempEntryPointUniqueId;
  283. if (id) {
  284. const source = map[id];
  285. if (source) {
  286. source.attachToEndpoint(teleportOut);
  287. }
  288. }
  289. }
  290. }
  291. // Connections - Starts with input blocks only (except if in "merge" mode where we scan all blocks)
  292. for (let blockIndex = 0; blockIndex < source.blocks.length; blockIndex++) {
  293. const parsedBlock = source.blocks[blockIndex];
  294. const block = map[parsedBlock.id];
  295. if (!block) {
  296. continue;
  297. }
  298. if (block.inputs.length && parsedBlock.inputs.some((i) => i.targetConnectionName) && !merge) {
  299. continue;
  300. }
  301. this._restoreConnections(block, source, map);
  302. }
  303. // Outputs
  304. if (source.outputNodeId) {
  305. this.outputBlock = map[source.outputNodeId];
  306. }
  307. // UI related info
  308. if (source.locations || (source.editorData && source.editorData.locations)) {
  309. const locations = source.locations || source.editorData.locations;
  310. for (const location of locations) {
  311. if (map[location.blockId]) {
  312. location.blockId = map[location.blockId].uniqueId;
  313. }
  314. }
  315. if (merge && this.editorData && this.editorData.locations) {
  316. locations.concat(this.editorData.locations);
  317. }
  318. if (source.locations) {
  319. this.editorData = {
  320. locations: locations,
  321. };
  322. }
  323. else {
  324. this.editorData = source.editorData;
  325. this.editorData.locations = locations;
  326. }
  327. const blockMap = [];
  328. for (const key in map) {
  329. blockMap[key] = map[key].uniqueId;
  330. }
  331. this.editorData.map = blockMap;
  332. }
  333. this.comment = source.comment;
  334. }
  335. _restoreConnections(block, source, map) {
  336. for (const outputPoint of block.outputs) {
  337. for (const candidate of source.blocks) {
  338. const target = map[candidate.id];
  339. if (!target) {
  340. continue;
  341. }
  342. for (const input of candidate.inputs) {
  343. if (map[input.targetBlockId] === block && input.targetConnectionName === outputPoint.name) {
  344. const inputPoint = target.getInputByName(input.inputName);
  345. if (!inputPoint || inputPoint.isConnected) {
  346. continue;
  347. }
  348. outputPoint.connectTo(inputPoint, true);
  349. this._restoreConnections(target, source, map);
  350. continue;
  351. }
  352. }
  353. }
  354. }
  355. }
  356. /**
  357. * Generate a string containing the code declaration required to create an equivalent of this geometry
  358. * @returns a string
  359. */
  360. generateCode() {
  361. let alreadyDumped = [];
  362. const blocks = [];
  363. const uniqueNames = ["const", "var", "let"];
  364. // Gets active blocks
  365. if (this.outputBlock) {
  366. this._gatherBlocks(this.outputBlock, blocks);
  367. }
  368. // Generate
  369. let codeString = `let nodeGeometry = new BABYLON.NodeGeometry("${this.name || "node geometry"}");\n`;
  370. for (const node of blocks) {
  371. if (node.isInput && alreadyDumped.indexOf(node) === -1) {
  372. codeString += node._dumpCode(uniqueNames, alreadyDumped);
  373. }
  374. }
  375. if (this.outputBlock) {
  376. // Connections
  377. alreadyDumped = [];
  378. codeString += "// Connections\n";
  379. codeString += this.outputBlock._dumpCodeForOutputConnections(alreadyDumped);
  380. // Output nodes
  381. codeString += "// Output nodes\n";
  382. codeString += `nodeGeometry.outputBlock = ${this.outputBlock._codeVariableName};\n`;
  383. codeString += `nodeGeometry.build();\n`;
  384. }
  385. return codeString;
  386. }
  387. _gatherBlocks(rootNode, list) {
  388. if (list.indexOf(rootNode) !== -1) {
  389. return;
  390. }
  391. list.push(rootNode);
  392. for (const input of rootNode.inputs) {
  393. const connectedPoint = input.connectedPoint;
  394. if (connectedPoint) {
  395. const block = connectedPoint.ownerBlock;
  396. if (block !== rootNode) {
  397. this._gatherBlocks(block, list);
  398. }
  399. }
  400. }
  401. // Teleportation
  402. if (rootNode.isTeleportOut) {
  403. const block = rootNode;
  404. if (block.entryPoint) {
  405. this._gatherBlocks(block.entryPoint, list);
  406. }
  407. }
  408. }
  409. /**
  410. * Clear the current geometry and set it to a default state
  411. */
  412. setToDefault() {
  413. this.clear();
  414. this.editorData = null;
  415. // Source
  416. const dataBlock = new BoxBlock("Box");
  417. dataBlock.autoConfigure();
  418. // Final output
  419. const output = new GeometryOutputBlock("Geometry Output");
  420. dataBlock.geometry.connectTo(output.geometry);
  421. this.outputBlock = output;
  422. }
  423. /**
  424. * Makes a duplicate of the current geometry.
  425. * @param name defines the name to use for the new geometry
  426. * @returns the new geometry
  427. */
  428. clone(name) {
  429. const serializationObject = this.serialize();
  430. const clone = SerializationHelper.Clone(() => new NodeGeometry(name), this);
  431. clone.name = name;
  432. clone.parseSerializedObject(serializationObject);
  433. clone._buildId = this._buildId;
  434. clone.build(false);
  435. return clone;
  436. }
  437. /**
  438. * Serializes this geometry in a JSON representation
  439. * @param selectedBlocks defines the list of blocks to save (if null the whole geometry will be saved)
  440. * @returns the serialized geometry object
  441. */
  442. serialize(selectedBlocks) {
  443. const serializationObject = selectedBlocks ? {} : SerializationHelper.Serialize(this);
  444. serializationObject.editorData = JSON.parse(JSON.stringify(this.editorData)); // Copy
  445. let blocks = [];
  446. if (selectedBlocks) {
  447. blocks = selectedBlocks;
  448. }
  449. else {
  450. serializationObject.customType = "BABYLON.NodeGeometry";
  451. if (this.outputBlock) {
  452. serializationObject.outputNodeId = this.outputBlock.uniqueId;
  453. }
  454. }
  455. // Blocks
  456. serializationObject.blocks = [];
  457. for (const block of blocks) {
  458. serializationObject.blocks.push(block.serialize());
  459. }
  460. if (!selectedBlocks) {
  461. for (const block of this.attachedBlocks) {
  462. if (blocks.indexOf(block) !== -1) {
  463. continue;
  464. }
  465. serializationObject.blocks.push(block.serialize());
  466. }
  467. }
  468. return serializationObject;
  469. }
  470. /**
  471. * Disposes the ressources
  472. */
  473. dispose() {
  474. for (const block of this.attachedBlocks) {
  475. block.dispose();
  476. }
  477. this.attachedBlocks.length = 0;
  478. this.onBuildObservable.clear();
  479. }
  480. /**
  481. * Creates a new node geometry set to default basic configuration
  482. * @param name defines the name of the geometry
  483. * @returns a new NodeGeometry
  484. */
  485. static CreateDefault(name) {
  486. const nodeGeometry = new NodeGeometry(name);
  487. nodeGeometry.setToDefault();
  488. nodeGeometry.build();
  489. return nodeGeometry;
  490. }
  491. /**
  492. * Creates a node geometry from parsed geometry data
  493. * @param source defines the JSON representation of the geometry
  494. * @returns a new node geometry
  495. */
  496. static Parse(source) {
  497. const nodeGeometry = SerializationHelper.Parse(() => new NodeGeometry(source.name), source, null);
  498. nodeGeometry.parseSerializedObject(source);
  499. nodeGeometry.build();
  500. return nodeGeometry;
  501. }
  502. /**
  503. * Creates a node geometry from a snippet saved by the node geometry editor
  504. * @param snippetId defines the snippet to load
  505. * @param nodeGeometry defines a node geometry to update (instead of creating a new one)
  506. * @param skipBuild defines whether to build the node geometry
  507. * @returns a promise that will resolve to the new node geometry
  508. */
  509. static ParseFromSnippetAsync(snippetId, nodeGeometry, skipBuild = false) {
  510. if (snippetId === "_BLANK") {
  511. return Promise.resolve(NodeGeometry.CreateDefault("blank"));
  512. }
  513. return new Promise((resolve, reject) => {
  514. const request = new WebRequest();
  515. request.addEventListener("readystatechange", () => {
  516. if (request.readyState == 4) {
  517. if (request.status == 200) {
  518. const snippet = JSON.parse(JSON.parse(request.responseText).jsonPayload);
  519. const serializationObject = JSON.parse(snippet.nodeGeometry);
  520. if (!nodeGeometry) {
  521. nodeGeometry = SerializationHelper.Parse(() => new NodeGeometry(snippetId), serializationObject, null);
  522. }
  523. nodeGeometry.parseSerializedObject(serializationObject);
  524. nodeGeometry.snippetId = snippetId;
  525. try {
  526. if (!skipBuild) {
  527. nodeGeometry.build();
  528. }
  529. resolve(nodeGeometry);
  530. }
  531. catch (err) {
  532. reject(err);
  533. }
  534. }
  535. else {
  536. reject("Unable to load the snippet " + snippetId);
  537. }
  538. }
  539. });
  540. request.open("GET", this.SnippetUrl + "/" + snippetId.replace(/#/g, "/"));
  541. request.send();
  542. });
  543. }
  544. }
  545. NodeGeometry._BuildIdGenerator = 0;
  546. /** Define the Url to load node editor script */
  547. NodeGeometry.EditorURL = `${Tools._DefaultCdnUrl}/v${Engine.Version}/nodeGeometryEditor/babylon.nodeGeometryEditor.js`;
  548. /** Define the Url to load snippets */
  549. NodeGeometry.SnippetUrl = `https://snippet.babylonjs.com`;
  550. __decorate([
  551. serialize()
  552. ], NodeGeometry.prototype, "name", void 0);
  553. __decorate([
  554. serialize("comment")
  555. ], NodeGeometry.prototype, "comment", void 0);
  556. //# sourceMappingURL=nodeGeometry.js.map