graphEditor.tsx 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572
  1. import * as React from "react";
  2. import { GlobalState } from './globalState';
  3. import { NodeMaterialBlock } from 'babylonjs/Materials/Node/nodeMaterialBlock';
  4. import { NodeListComponent } from './components/nodeList/nodeListComponent';
  5. import { PropertyTabComponent } from './components/propertyTab/propertyTabComponent';
  6. import { Portal } from './portal';
  7. import { LogComponent, LogEntry } from './components/log/logComponent';
  8. import { DataStorage } from './dataStorage';
  9. import { NodeMaterialBlockConnectionPointTypes } from 'babylonjs/Materials/Node/Enums/nodeMaterialBlockConnectionPointTypes';
  10. import { InputBlock } from 'babylonjs/Materials/Node/Blocks/Input/inputBlock';
  11. import { Nullable } from 'babylonjs/types';
  12. import { MessageDialogComponent } from './sharedComponents/messageDialog';
  13. import { BlockTools } from './blockTools';
  14. import { PreviewManager } from './components/preview/previewManager';
  15. import { IEditorData } from './nodeLocationInfo';
  16. import { PreviewMeshControlComponent } from './components/preview/previewMeshControlComponent';
  17. import { PreviewAreaComponent } from './components/preview/previewAreaComponent';
  18. import { SerializationTools } from './serializationTools';
  19. import { GraphCanvasComponent } from './diagram/graphCanvas';
  20. import { GraphNode } from './diagram/graphNode';
  21. import { GraphFrame } from './diagram/graphFrame';
  22. require("./main.scss");
  23. interface IGraphEditorProps {
  24. globalState: GlobalState;
  25. }
  26. export class GraphEditor extends React.Component<IGraphEditorProps> {
  27. private readonly NodeWidth = 100;
  28. private _graphCanvas: GraphCanvasComponent;
  29. private _startX: number;
  30. private _moveInProgress: boolean;
  31. private _leftWidth = DataStorage.ReadNumber("LeftWidth", 200);
  32. private _rightWidth = DataStorage.ReadNumber("RightWidth", 300);
  33. private _blocks = new Array<NodeMaterialBlock>();
  34. private _previewManager: PreviewManager;
  35. private _copiedNodes: GraphNode[] = [];
  36. private _copiedFrame: Nullable<GraphFrame> = null;
  37. private _mouseLocationX = 0;
  38. private _mouseLocationY = 0;
  39. private _onWidgetKeyUpPointer: any;
  40. public createNodeFromObject(block: NodeMaterialBlock, recursion = true) {
  41. if (this._blocks.indexOf(block) !== -1) {
  42. return this._graphCanvas.nodes.filter(n => n.block === block)[0];
  43. }
  44. this._blocks.push(block);
  45. if (this.props.globalState.nodeMaterial!.attachedBlocks.indexOf(block) === -1) {
  46. this.props.globalState.nodeMaterial!.attachedBlocks.push(block);
  47. }
  48. if (block.isFinalMerger) {
  49. this.props.globalState.nodeMaterial!.addOutputNode(block);
  50. }
  51. // Connections
  52. if (block.inputs.length) {
  53. for (var input of block.inputs) {
  54. if (input.isConnected && recursion) {
  55. this.createNodeFromObject(input.sourceBlock!);
  56. }
  57. }
  58. }
  59. // Graph
  60. const node = this._graphCanvas.appendBlock(block);
  61. // Links
  62. if (block.inputs.length && recursion) {
  63. for (var input of block.inputs) {
  64. if (input.isConnected) {
  65. this._graphCanvas.connectPorts(input.connectedPoint!, input);
  66. }
  67. }
  68. }
  69. return node;
  70. }
  71. addValueNode(type: string) {
  72. let nodeType: NodeMaterialBlockConnectionPointTypes = BlockTools.GetConnectionNodeTypeFromString(type);
  73. let newInputBlock = new InputBlock(type, undefined, nodeType);
  74. return this.createNodeFromObject(newInputBlock)
  75. }
  76. componentDidMount() {
  77. if (this.props.globalState.hostDocument) {
  78. this._graphCanvas = (this.refs["graphCanvas"] as GraphCanvasComponent);
  79. this._previewManager = new PreviewManager(this.props.globalState.hostDocument.getElementById("preview-canvas") as HTMLCanvasElement, this.props.globalState);
  80. }
  81. if (navigator.userAgent.indexOf("Mobile") !== -1) {
  82. ((this.props.globalState.hostDocument || document).querySelector(".blocker") as HTMLElement).style.visibility = "visible";
  83. }
  84. this.build();
  85. }
  86. componentWillUnmount() {
  87. if (this.props.globalState.hostDocument) {
  88. this.props.globalState.hostDocument!.removeEventListener("keyup", this._onWidgetKeyUpPointer, false);
  89. }
  90. if (this._previewManager) {
  91. this._previewManager.dispose();
  92. }
  93. }
  94. constructor(props: IGraphEditorProps) {
  95. super(props);
  96. this.props.globalState.onRebuildRequiredObservable.add(() => {
  97. if (this.props.globalState.nodeMaterial) {
  98. this.buildMaterial();
  99. }
  100. });
  101. this.props.globalState.onResetRequiredObservable.add(() => {
  102. this.build();
  103. if (this.props.globalState.nodeMaterial) {
  104. this.buildMaterial();
  105. }
  106. });
  107. this.props.globalState.onZoomToFitRequiredObservable.add(() => {
  108. this.zoomToFit();
  109. });
  110. this.props.globalState.onReOrganizedRequiredObservable.add(() => {
  111. this.reOrganize();
  112. });
  113. this.props.globalState.onGetNodeFromBlock = (block) => {
  114. return this._graphCanvas.findNodeFromBlock(block);
  115. }
  116. this.props.globalState.hostDocument!.addEventListener("keydown", evt => {
  117. if (evt.keyCode === 46 && !this.props.globalState.blockKeyboardEvents) { // Delete
  118. let selectedItems = this._graphCanvas.selectedNodes;
  119. for (var selectedItem of selectedItems) {
  120. selectedItem.dispose();
  121. let targetBlock = selectedItem.block;
  122. this.props.globalState.nodeMaterial!.removeBlock(targetBlock);
  123. let blockIndex = this._blocks.indexOf(targetBlock);
  124. if (blockIndex > -1) {
  125. this._blocks.splice(blockIndex, 1);
  126. }
  127. }
  128. if (this._graphCanvas.selectedLink) {
  129. this._graphCanvas.selectedLink.dispose();
  130. }
  131. if (this._graphCanvas.selectedFrame) {
  132. this._graphCanvas.selectedFrame.dispose();
  133. }
  134. this.props.globalState.onSelectionChangedObservable.notifyObservers(null);
  135. this.props.globalState.onRebuildRequiredObservable.notifyObservers();
  136. return;
  137. }
  138. if (!evt.ctrlKey || this.props.globalState.blockKeyboardEvents) {
  139. return;
  140. }
  141. if (evt.key === "c") { // Copy
  142. this._copiedNodes = [];
  143. this._copiedFrame = null;
  144. if (this._graphCanvas.selectedFrame) {
  145. this._copiedFrame = this._graphCanvas.selectedFrame;
  146. return;
  147. }
  148. let selectedItems = this._graphCanvas.selectedNodes;
  149. if (!selectedItems.length) {
  150. return;
  151. }
  152. let selectedItem = selectedItems[0] as GraphNode;
  153. if (!selectedItem.block) {
  154. return;
  155. }
  156. this._copiedNodes = selectedItems.slice(0);
  157. } else if (evt.key === "v") { // Paste
  158. const rootElement = this.props.globalState.hostDocument!.querySelector(".diagram-container") as HTMLDivElement;
  159. const zoomLevel = this._graphCanvas.zoom;
  160. let currentY = (this._mouseLocationY - rootElement.offsetTop - this._graphCanvas.y - 20) / zoomLevel;
  161. if (this._copiedFrame) {
  162. // New frame
  163. let newFrame = new GraphFrame(null, this._graphCanvas, true);
  164. this._graphCanvas.frames.push(newFrame);
  165. newFrame.width = this._copiedFrame.width;
  166. newFrame.height = this._copiedFrame.height;newFrame.width / 2
  167. newFrame.name = this._copiedFrame.name;
  168. newFrame.color = this._copiedFrame.color;
  169. let currentX = (this._mouseLocationX - rootElement.offsetLeft - this._graphCanvas.x) / zoomLevel;
  170. newFrame.x = currentX - newFrame.width / 2;
  171. newFrame.y = currentY;
  172. // Paste nodes
  173. if (this._copiedFrame.nodes.length) {
  174. currentX = newFrame.x + this._copiedFrame.nodes[0].x - this._copiedFrame.x;
  175. currentY = newFrame.y + this._copiedFrame.nodes[0].y - this._copiedFrame.y;
  176. this.pasteSelection(this._copiedFrame.nodes, currentX, currentY);
  177. }
  178. if (this._copiedFrame.isCollapsed) {
  179. newFrame.isCollapsed = true;
  180. }
  181. return;
  182. }
  183. if (!this._copiedNodes.length) {
  184. return;
  185. }
  186. let currentX = (this._mouseLocationX - rootElement.offsetLeft - this._graphCanvas.x - this.NodeWidth) / zoomLevel;
  187. this.pasteSelection(this._copiedNodes, currentX, currentY);
  188. }
  189. }, false);
  190. }
  191. reconnectNewNodes(nodeIndex: number, newNodes:GraphNode[], sourceNodes:GraphNode[], done: boolean[]) {
  192. if (done[nodeIndex]) {
  193. return;
  194. }
  195. const currentNode = newNodes[nodeIndex];
  196. const block = currentNode.block;
  197. const sourceNode = sourceNodes[nodeIndex];
  198. for (var inputIndex = 0; inputIndex < sourceNode.block.inputs.length; inputIndex++) {
  199. let sourceInput = sourceNode.block.inputs[inputIndex];
  200. const currentInput = block.inputs[inputIndex];
  201. if (!sourceInput.isConnected) {
  202. continue;
  203. }
  204. const sourceBlock = sourceInput.connectedPoint!.ownerBlock;
  205. const activeNodes = sourceNodes.filter(s => s.block === sourceBlock);
  206. if (activeNodes.length > 0) {
  207. const activeNode = activeNodes[0];
  208. let indexInList = sourceNodes.indexOf(activeNode);
  209. // First make sure to connect the other one
  210. this.reconnectNewNodes(indexInList, newNodes, sourceNodes, done);
  211. // Then reconnect
  212. const outputIndex = sourceBlock.outputs.indexOf(sourceInput.connectedPoint!);
  213. const newOutput = newNodes[indexInList].block.outputs[outputIndex];
  214. newOutput.connectTo(currentInput);
  215. } else {
  216. // Connect with outside blocks
  217. sourceInput._connectedPoint!.connectTo(currentInput);
  218. }
  219. this._graphCanvas.connectPorts(currentInput.connectedPoint!, currentInput);
  220. }
  221. currentNode.refresh();
  222. done[nodeIndex] = true;
  223. }
  224. pasteSelection(copiedNodes: GraphNode[], currentX: number, currentY: number) {
  225. let originalNode: Nullable<GraphNode> = null;
  226. let newNodes:GraphNode[] = [];
  227. // Create new nodes
  228. for (var node of copiedNodes) {
  229. let block = node.block;
  230. if (!block) {
  231. continue;
  232. }
  233. let clone = block.clone(this.props.globalState.nodeMaterial.getScene());
  234. if (!clone) {
  235. return;
  236. }
  237. let newNode = this.createNodeFromObject(clone, false);
  238. let x = 0;
  239. let y = 0;
  240. if (originalNode) {
  241. x = currentX + node.x - originalNode.x;
  242. y = currentY + node.y - originalNode.y;
  243. } else {
  244. originalNode = node;
  245. x = currentX;
  246. y = currentY;
  247. }
  248. newNode.x = x;
  249. newNode.y = y;
  250. newNode.cleanAccumulation();
  251. newNodes.push(newNode);
  252. }
  253. // Relink
  254. let done = new Array<boolean>(newNodes.length);
  255. for (var index = 0; index < newNodes.length; index++) {
  256. this.reconnectNewNodes(index, newNodes, copiedNodes, done);
  257. }
  258. }
  259. zoomToFit() {
  260. this._graphCanvas.zoomToFit();
  261. }
  262. buildMaterial() {
  263. if (!this.props.globalState.nodeMaterial) {
  264. return;
  265. }
  266. try {
  267. this.props.globalState.nodeMaterial.options.emitComments = true;
  268. this.props.globalState.nodeMaterial.build(true);
  269. this.props.globalState.onLogRequiredObservable.notifyObservers(new LogEntry("Node material build successful", false));
  270. }
  271. catch (err) {
  272. this.props.globalState.onLogRequiredObservable.notifyObservers(new LogEntry(err, true));
  273. }
  274. SerializationTools.UpdateLocations(this.props.globalState.nodeMaterial, this.props.globalState);
  275. }
  276. build() {
  277. let editorData = this.props.globalState.nodeMaterial.editorData;
  278. if (editorData instanceof Array) {
  279. editorData = {
  280. locations: editorData
  281. }
  282. }
  283. // setup the diagram model
  284. this._blocks = [];
  285. this._graphCanvas.reset();
  286. // Load graph of nodes from the material
  287. if (this.props.globalState.nodeMaterial) {
  288. var material = this.props.globalState.nodeMaterial;
  289. material._vertexOutputNodes.forEach((n: any) => {
  290. this.createNodeFromObject(n);
  291. });
  292. material._fragmentOutputNodes.forEach((n: any) => {
  293. this.createNodeFromObject(n);
  294. });
  295. material.attachedBlocks.forEach((n: any) => {
  296. this.createNodeFromObject(n);
  297. });
  298. // Links
  299. material.attachedBlocks.forEach((n: any) => {
  300. if (n.inputs.length) {
  301. for (var input of n.inputs) {
  302. if (input.isConnected) {
  303. this._graphCanvas.connectPorts(input.connectedPoint!, input);
  304. }
  305. }
  306. }
  307. });
  308. }
  309. this.reOrganize(editorData);
  310. }
  311. reOrganize(editorData: Nullable<IEditorData> = null) {
  312. if (!editorData || !editorData.locations) {
  313. this._graphCanvas.distributeGraph();
  314. } else {
  315. // Locations
  316. for (var location of editorData.locations) {
  317. for (var node of this._graphCanvas.nodes) {
  318. if (node.block && node.block.uniqueId === location.blockId) {
  319. node.x = location.x;
  320. node.y = location.y;
  321. node.cleanAccumulation();
  322. break;
  323. }
  324. }
  325. }
  326. this._graphCanvas.processEditorData(editorData);
  327. }
  328. }
  329. onPointerDown(evt: React.PointerEvent<HTMLDivElement>) {
  330. this._startX = evt.clientX;
  331. this._moveInProgress = true;
  332. evt.currentTarget.setPointerCapture(evt.pointerId);
  333. }
  334. onPointerUp(evt: React.PointerEvent<HTMLDivElement>) {
  335. this._moveInProgress = false;
  336. evt.currentTarget.releasePointerCapture(evt.pointerId);
  337. }
  338. resizeColumns(evt: React.PointerEvent<HTMLDivElement>, forLeft = true) {
  339. if (!this._moveInProgress) {
  340. return;
  341. }
  342. const deltaX = evt.clientX - this._startX;
  343. const rootElement = evt.currentTarget.ownerDocument!.getElementById("node-editor-graph-root") as HTMLDivElement;
  344. if (forLeft) {
  345. this._leftWidth += deltaX;
  346. this._leftWidth = Math.max(150, Math.min(400, this._leftWidth));
  347. DataStorage.StoreNumber("LeftWidth", this._leftWidth);
  348. } else {
  349. this._rightWidth -= deltaX;
  350. this._rightWidth = Math.max(250, Math.min(500, this._rightWidth));
  351. DataStorage.StoreNumber("RightWidth", this._rightWidth);
  352. rootElement.ownerDocument!.getElementById("preview")!.style.height = this._rightWidth + "px";
  353. }
  354. rootElement.style.gridTemplateColumns = this.buildColumnLayout();
  355. this._startX = evt.clientX;
  356. }
  357. buildColumnLayout() {
  358. return `${this._leftWidth}px 4px calc(100% - ${this._leftWidth + 8 + this._rightWidth}px) 4px ${this._rightWidth}px`;
  359. }
  360. emitNewBlock(event: React.DragEvent<HTMLDivElement>) {
  361. var data = event.dataTransfer.getData("babylonjs-material-node") as string;
  362. let newNode: GraphNode;
  363. if (data.indexOf("Block") === -1) {
  364. newNode = this.addValueNode(data);
  365. } else {
  366. let block = BlockTools.GetBlockFromString(data, this.props.globalState.nodeMaterial.getScene(), this.props.globalState.nodeMaterial)!;
  367. if (block.isUnique) {
  368. const className = block.getClassName();
  369. for (var other of this._blocks) {
  370. if (other !== block && other.getClassName() === className) {
  371. this.props.globalState.onErrorMessageDialogRequiredObservable.notifyObservers(`You can only have one ${className} per graph`);
  372. return;
  373. }
  374. }
  375. }
  376. block.autoConfigure(this.props.globalState.nodeMaterial);
  377. newNode = this.createNodeFromObject(block);
  378. };
  379. let x = event.clientX - event.currentTarget.offsetLeft - this._graphCanvas.x - this.NodeWidth;
  380. let y = event.clientY - event.currentTarget.offsetTop - this._graphCanvas.y - 20;
  381. newNode.x = x / this._graphCanvas.zoom;
  382. newNode.y = y / this._graphCanvas.zoom;
  383. newNode.cleanAccumulation();
  384. this.props.globalState.onSelectionChangedObservable.notifyObservers(null);
  385. this.props.globalState.onSelectionChangedObservable.notifyObservers(newNode);
  386. let block = newNode.block;
  387. x -= this.NodeWidth + 150;
  388. block.inputs.forEach((connection) => {
  389. if (connection.connectedPoint) {
  390. var existingNodes = this._graphCanvas.nodes.filter((n) => { return n.block === (connection as any).connectedPoint.ownerBlock });
  391. let connectedNode = existingNodes[0];
  392. if (connectedNode.x === 0 && connectedNode.y === 0) {
  393. connectedNode.x = x / this._graphCanvas.zoom;
  394. connectedNode.y = y / this._graphCanvas.zoom;
  395. connectedNode.cleanAccumulation();
  396. y += 80;
  397. }
  398. }
  399. });
  400. this.forceUpdate();
  401. }
  402. render() {
  403. return (
  404. <Portal globalState={this.props.globalState}>
  405. <div id="node-editor-graph-root" style={
  406. {
  407. gridTemplateColumns: this.buildColumnLayout()
  408. }}
  409. onMouseMove={evt => {
  410. this._mouseLocationX = evt.pageX;
  411. this._mouseLocationY = evt.pageY;
  412. }}
  413. onMouseDown={(evt) => {
  414. if ((evt.target as HTMLElement).nodeName === "INPUT") {
  415. return;
  416. }
  417. this.props.globalState.blockKeyboardEvents = false;
  418. }}
  419. >
  420. {/* Node creation menu */}
  421. <NodeListComponent globalState={this.props.globalState} />
  422. <div id="leftGrab"
  423. onPointerDown={evt => this.onPointerDown(evt)}
  424. onPointerUp={evt => this.onPointerUp(evt)}
  425. onPointerMove={evt => this.resizeColumns(evt)}
  426. ></div>
  427. {/* The node graph diagram */}
  428. <div className="diagram-container"
  429. onDrop={event => {
  430. this.emitNewBlock(event);
  431. }}
  432. onDragOver={event => {
  433. event.preventDefault();
  434. }}
  435. >
  436. <GraphCanvasComponent ref={"graphCanvas"} globalState={this.props.globalState}/>
  437. </div>
  438. <div id="rightGrab"
  439. onPointerDown={evt => this.onPointerDown(evt)}
  440. onPointerUp={evt => this.onPointerUp(evt)}
  441. onPointerMove={evt => this.resizeColumns(evt, false)}
  442. ></div>
  443. {/* Property tab */}
  444. <div className="right-panel">
  445. <PropertyTabComponent globalState={this.props.globalState} />
  446. <PreviewMeshControlComponent globalState={this.props.globalState} />
  447. <PreviewAreaComponent globalState={this.props.globalState} width={this._rightWidth}/>
  448. </div>
  449. <LogComponent globalState={this.props.globalState} />
  450. </div>
  451. <MessageDialogComponent globalState={this.props.globalState} />
  452. <div className="blocker">
  453. Node Material Editor runs only on desktop
  454. </div>
  455. </Portal>
  456. );
  457. }
  458. }