graphEditor.tsx 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855
  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 'babylonjs/Misc/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. import * as ReactDOM from 'react-dom';
  23. import { IInspectorOptions } from "babylonjs/Debug/debugLayer";
  24. import { _TypeStore } from 'babylonjs/Misc/typeStore';
  25. require("./main.scss");
  26. interface IGraphEditorProps {
  27. globalState: GlobalState;
  28. }
  29. interface IGraphEditorState {
  30. showPreviewPopUp: boolean;
  31. };
  32. interface IInternalPreviewAreaOptions extends IInspectorOptions {
  33. popup: boolean;
  34. original: boolean;
  35. explorerWidth?: string;
  36. inspectorWidth?: string;
  37. embedHostWidth?: string;
  38. }
  39. export class GraphEditor extends React.Component<IGraphEditorProps, IGraphEditorState> {
  40. private readonly NodeWidth = 100;
  41. private _graphCanvas: GraphCanvasComponent;
  42. private _startX: number;
  43. private _moveInProgress: boolean;
  44. private _leftWidth = DataStorage.ReadNumber("LeftWidth", 200);
  45. private _rightWidth = DataStorage.ReadNumber("RightWidth", 300);
  46. private _blocks = new Array<NodeMaterialBlock>();
  47. private _previewManager: PreviewManager;
  48. private _copiedNodes: GraphNode[] = [];
  49. private _copiedFrame: Nullable<GraphFrame> = null;
  50. private _mouseLocationX = 0;
  51. private _mouseLocationY = 0;
  52. private _onWidgetKeyUpPointer: any;
  53. private _previewHost: Nullable<HTMLElement>;
  54. private _popUpWindow: Window;
  55. /**
  56. * Creates a node and recursivly creates its parent nodes from it's input
  57. * @param nodeMaterialBlock
  58. */
  59. public createNodeFromObject(block: NodeMaterialBlock, recursion = true) {
  60. if (this._blocks.indexOf(block) !== -1) {
  61. return this._graphCanvas.nodes.filter(n => n.block === block)[0];
  62. }
  63. this._blocks.push(block);
  64. if (this.props.globalState.nodeMaterial!.attachedBlocks.indexOf(block) === -1) {
  65. this.props.globalState.nodeMaterial!.attachedBlocks.push(block);
  66. }
  67. if (block.isFinalMerger) {
  68. this.props.globalState.nodeMaterial!.addOutputNode(block);
  69. }
  70. // Connections
  71. if (block.inputs.length) {
  72. for (var input of block.inputs) {
  73. if (input.isConnected && recursion) {
  74. this.createNodeFromObject(input.sourceBlock!);
  75. }
  76. }
  77. }
  78. // Graph
  79. const node = this._graphCanvas.appendBlock(block);
  80. // Links
  81. if (block.inputs.length && recursion) {
  82. for (var input of block.inputs) {
  83. if (input.isConnected) {
  84. this._graphCanvas.connectPorts(input.connectedPoint!, input);
  85. }
  86. }
  87. }
  88. return node;
  89. }
  90. addValueNode(type: string) {
  91. let nodeType: NodeMaterialBlockConnectionPointTypes = BlockTools.GetConnectionNodeTypeFromString(type);
  92. let newInputBlock = new InputBlock(type, undefined, nodeType);
  93. return this.createNodeFromObject(newInputBlock);
  94. }
  95. componentDidMount() {
  96. if (this.props.globalState.hostDocument) {
  97. this._graphCanvas = (this.refs["graphCanvas"] as GraphCanvasComponent);
  98. this._previewManager = new PreviewManager(this.props.globalState.hostDocument.getElementById("preview-canvas") as HTMLCanvasElement, this.props.globalState);
  99. }
  100. if (navigator.userAgent.indexOf("Mobile") !== -1) {
  101. ((this.props.globalState.hostDocument || document).querySelector(".blocker") as HTMLElement).style.visibility = "visible";
  102. }
  103. this.build();
  104. }
  105. componentWillUnmount() {
  106. if (this.props.globalState.hostDocument) {
  107. this.props.globalState.hostDocument!.removeEventListener("keyup", this._onWidgetKeyUpPointer, false);
  108. }
  109. if (this._previewManager) {
  110. this._previewManager.dispose();
  111. }
  112. }
  113. constructor(props: IGraphEditorProps) {
  114. super(props);
  115. this.state = {
  116. showPreviewPopUp: false
  117. };
  118. this.props.globalState.onRebuildRequiredObservable.add(() => {
  119. if (this.props.globalState.nodeMaterial) {
  120. this.buildMaterial();
  121. }
  122. });
  123. this.props.globalState.onResetRequiredObservable.add(() => {
  124. this.build();
  125. if (this.props.globalState.nodeMaterial) {
  126. this.buildMaterial();
  127. }
  128. });
  129. this.props.globalState.onImportFrameObservable.add((source: any) => {
  130. const frameData = source.editorData.frames[0];
  131. // create new graph nodes for only blocks from frame (last blocks added)
  132. this.props.globalState.nodeMaterial.attachedBlocks.slice(-(frameData.blocks.length)).forEach((block: NodeMaterialBlock) => {
  133. this.createNodeFromObject(block);
  134. });
  135. this._graphCanvas.addFrame(frameData);
  136. this.reOrganize(this.props.globalState.nodeMaterial.editorData, true);
  137. })
  138. this.props.globalState.onZoomToFitRequiredObservable.add(() => {
  139. this.zoomToFit();
  140. });
  141. this.props.globalState.onReOrganizedRequiredObservable.add(() => {
  142. this.reOrganize();
  143. });
  144. this.props.globalState.onGetNodeFromBlock = (block) => {
  145. return this._graphCanvas.findNodeFromBlock(block);
  146. }
  147. this.props.globalState.hostDocument!.addEventListener("keydown", evt => {
  148. if ((evt.keyCode === 46 || evt.keyCode === 8) && !this.props.globalState.blockKeyboardEvents) { // Delete
  149. let selectedItems = this._graphCanvas.selectedNodes;
  150. for (var selectedItem of selectedItems) {
  151. selectedItem.dispose();
  152. let targetBlock = selectedItem.block;
  153. this.props.globalState.nodeMaterial!.removeBlock(targetBlock);
  154. let blockIndex = this._blocks.indexOf(targetBlock);
  155. if (blockIndex > -1) {
  156. this._blocks.splice(blockIndex, 1);
  157. }
  158. }
  159. if (this._graphCanvas.selectedLink) {
  160. this._graphCanvas.selectedLink.dispose();
  161. }
  162. if (this._graphCanvas.selectedFrame) {
  163. this._graphCanvas.selectedFrame.dispose();
  164. }
  165. this.props.globalState.onSelectionChangedObservable.notifyObservers(null);
  166. this.props.globalState.onRebuildRequiredObservable.notifyObservers();
  167. return;
  168. }
  169. if (!evt.ctrlKey || this.props.globalState.blockKeyboardEvents) {
  170. return;
  171. }
  172. if (evt.key === "c") { // Copy
  173. this._copiedNodes = [];
  174. this._copiedFrame = null;
  175. if (this._graphCanvas.selectedFrame) {
  176. this._copiedFrame = this._graphCanvas.selectedFrame;
  177. return;
  178. }
  179. let selectedItems = this._graphCanvas.selectedNodes;
  180. if (!selectedItems.length) {
  181. return;
  182. }
  183. let selectedItem = selectedItems[0] as GraphNode;
  184. if (!selectedItem.block) {
  185. return;
  186. }
  187. this._copiedNodes = selectedItems.slice(0);
  188. } else if (evt.key === "v") { // Paste
  189. const rootElement = this.props.globalState.hostDocument!.querySelector(".diagram-container") as HTMLDivElement;
  190. const zoomLevel = this._graphCanvas.zoom;
  191. let currentY = (this._mouseLocationY - rootElement.offsetTop - this._graphCanvas.y - 20) / zoomLevel;
  192. if (this._copiedFrame) {
  193. // New frame
  194. let newFrame = new GraphFrame(null, this._graphCanvas, true);
  195. this._graphCanvas.frames.push(newFrame);
  196. newFrame.width = this._copiedFrame.width;
  197. newFrame.height = this._copiedFrame.height;newFrame.width / 2
  198. newFrame.name = this._copiedFrame.name;
  199. newFrame.color = this._copiedFrame.color;
  200. let currentX = (this._mouseLocationX - rootElement.offsetLeft - this._graphCanvas.x) / zoomLevel;
  201. newFrame.x = currentX - newFrame.width / 2;
  202. newFrame.y = currentY;
  203. // Paste nodes
  204. if (this._copiedFrame.nodes.length) {
  205. currentX = newFrame.x + this._copiedFrame.nodes[0].x - this._copiedFrame.x;
  206. currentY = newFrame.y + this._copiedFrame.nodes[0].y - this._copiedFrame.y;
  207. this._graphCanvas._frameIsMoving = true;
  208. let newNodes = this.pasteSelection(this._copiedFrame.nodes, currentX, currentY);
  209. if (newNodes) {
  210. for (var node of newNodes) {
  211. newFrame.syncNode(node);
  212. }
  213. }
  214. this._graphCanvas._frameIsMoving = false;
  215. }
  216. if (this._copiedFrame.isCollapsed) {
  217. newFrame.isCollapsed = true;
  218. }
  219. // Select
  220. this.props.globalState.onSelectionChangedObservable.notifyObservers(newFrame);
  221. return;
  222. }
  223. if (!this._copiedNodes.length) {
  224. return;
  225. }
  226. let currentX = (this._mouseLocationX - rootElement.offsetLeft - this._graphCanvas.x - this.NodeWidth) / zoomLevel;
  227. this.pasteSelection(this._copiedNodes, currentX, currentY, true);
  228. }
  229. }, false);
  230. }
  231. reconnectNewNodes(nodeIndex: number, newNodes:GraphNode[], sourceNodes:GraphNode[], done: boolean[]) {
  232. if (done[nodeIndex]) {
  233. return;
  234. }
  235. const currentNode = newNodes[nodeIndex];
  236. const block = currentNode.block;
  237. const sourceNode = sourceNodes[nodeIndex];
  238. for (var inputIndex = 0; inputIndex < sourceNode.block.inputs.length; inputIndex++) {
  239. let sourceInput = sourceNode.block.inputs[inputIndex];
  240. const currentInput = block.inputs[inputIndex];
  241. if (!sourceInput.isConnected) {
  242. continue;
  243. }
  244. const sourceBlock = sourceInput.connectedPoint!.ownerBlock;
  245. const activeNodes = sourceNodes.filter(s => s.block === sourceBlock);
  246. if (activeNodes.length > 0) {
  247. const activeNode = activeNodes[0];
  248. let indexInList = sourceNodes.indexOf(activeNode);
  249. // First make sure to connect the other one
  250. this.reconnectNewNodes(indexInList, newNodes, sourceNodes, done);
  251. // Then reconnect
  252. const outputIndex = sourceBlock.outputs.indexOf(sourceInput.connectedPoint!);
  253. const newOutput = newNodes[indexInList].block.outputs[outputIndex];
  254. newOutput.connectTo(currentInput);
  255. } else {
  256. // Connect with outside blocks
  257. sourceInput._connectedPoint!.connectTo(currentInput);
  258. }
  259. this._graphCanvas.connectPorts(currentInput.connectedPoint!, currentInput);
  260. }
  261. currentNode.refresh();
  262. done[nodeIndex] = true;
  263. }
  264. pasteSelection(copiedNodes: GraphNode[], currentX: number, currentY: number, selectNew = false) {
  265. let originalNode: Nullable<GraphNode> = null;
  266. let newNodes:GraphNode[] = [];
  267. // Copy to prevent recursive side effects while creating nodes.
  268. copiedNodes = copiedNodes.slice();
  269. // Cancel selection
  270. this.props.globalState.onSelectionChangedObservable.notifyObservers(null);
  271. // Create new nodes
  272. for (var node of copiedNodes) {
  273. let block = node.block;
  274. if (!block) {
  275. continue;
  276. }
  277. let clone = block.clone(this.props.globalState.nodeMaterial.getScene());
  278. if (!clone) {
  279. return;
  280. }
  281. let newNode = this.createNodeFromObject(clone, false);
  282. let x = 0;
  283. let y = 0;
  284. if (originalNode) {
  285. x = currentX + node.x - originalNode.x;
  286. y = currentY + node.y - originalNode.y;
  287. } else {
  288. originalNode = node;
  289. x = currentX;
  290. y = currentY;
  291. }
  292. newNode.x = x;
  293. newNode.y = y;
  294. newNode.cleanAccumulation();
  295. newNodes.push(newNode);
  296. if (selectNew) {
  297. this.props.globalState.onSelectionChangedObservable.notifyObservers(newNode);
  298. }
  299. }
  300. // Relink
  301. let done = new Array<boolean>(newNodes.length);
  302. for (var index = 0; index < newNodes.length; index++) {
  303. this.reconnectNewNodes(index, newNodes, copiedNodes, done);
  304. }
  305. return newNodes;
  306. }
  307. zoomToFit() {
  308. this._graphCanvas.zoomToFit();
  309. }
  310. buildMaterial() {
  311. if (!this.props.globalState.nodeMaterial) {
  312. return;
  313. }
  314. try {
  315. this.props.globalState.nodeMaterial.options.emitComments = true;
  316. this.props.globalState.nodeMaterial.build(true);
  317. this.props.globalState.onLogRequiredObservable.notifyObservers(new LogEntry("Node material build successful", false));
  318. }
  319. catch (err) {
  320. this.props.globalState.onLogRequiredObservable.notifyObservers(new LogEntry(err, true));
  321. }
  322. SerializationTools.UpdateLocations(this.props.globalState.nodeMaterial, this.props.globalState);
  323. this.props.globalState.onBuiltObservable.notifyObservers();
  324. }
  325. build() {
  326. let editorData = this.props.globalState.nodeMaterial.editorData;
  327. this._graphCanvas._isLoading = true; // Will help loading large graphes
  328. if (editorData instanceof Array) {
  329. editorData = {
  330. locations: editorData
  331. }
  332. }
  333. // setup the diagram model
  334. this._blocks = [];
  335. this._graphCanvas.reset();
  336. // Load graph of nodes from the material
  337. if (this.props.globalState.nodeMaterial) {
  338. this.loadGraph()
  339. }
  340. this.reOrganize(editorData);
  341. }
  342. loadGraph() {
  343. var material = this.props.globalState.nodeMaterial;
  344. material._vertexOutputNodes.forEach((n: any) => {
  345. this.createNodeFromObject(n, true);
  346. });
  347. material._fragmentOutputNodes.forEach((n: any) => {
  348. this.createNodeFromObject(n, true);
  349. });
  350. material.attachedBlocks.forEach((n: any) => {
  351. this.createNodeFromObject(n, true);
  352. });
  353. // Links
  354. material.attachedBlocks.forEach((n: any) => {
  355. if (n.inputs.length) {
  356. for (var input of n.inputs) {
  357. if (input.isConnected) {
  358. this._graphCanvas.connectPorts(input.connectedPoint!, input);
  359. }
  360. }
  361. }
  362. });
  363. }
  364. showWaitScreen() {
  365. this.props.globalState.hostDocument.querySelector(".wait-screen")?.classList.remove("hidden");
  366. }
  367. hideWaitScreen() {
  368. this.props.globalState.hostDocument.querySelector(".wait-screen")?.classList.add("hidden");
  369. }
  370. reOrganize(editorData: Nullable<IEditorData> = null, isImportingAFrame = false) {
  371. this.showWaitScreen();
  372. this._graphCanvas._isLoading = true; // Will help loading large graphes
  373. setTimeout(() => {
  374. if (!editorData || !editorData.locations) {
  375. this._graphCanvas.distributeGraph();
  376. } else {
  377. // Locations
  378. for (var location of editorData.locations) {
  379. for (var node of this._graphCanvas.nodes) {
  380. if (node.block && node.block.uniqueId === location.blockId) {
  381. node.x = location.x;
  382. node.y = location.y;
  383. node.cleanAccumulation();
  384. break;
  385. }
  386. }
  387. }
  388. if (!isImportingAFrame){
  389. this._graphCanvas.processEditorData(editorData);
  390. }
  391. }
  392. this._graphCanvas._isLoading = false;
  393. for (var node of this._graphCanvas.nodes) {
  394. node._refreshLinks();
  395. }
  396. this.hideWaitScreen();
  397. });
  398. }
  399. onPointerDown(evt: React.PointerEvent<HTMLDivElement>) {
  400. this._startX = evt.clientX;
  401. this._moveInProgress = true;
  402. evt.currentTarget.setPointerCapture(evt.pointerId);
  403. }
  404. onPointerUp(evt: React.PointerEvent<HTMLDivElement>) {
  405. this._moveInProgress = false;
  406. evt.currentTarget.releasePointerCapture(evt.pointerId);
  407. }
  408. resizeColumns(evt: React.PointerEvent<HTMLDivElement>, forLeft = true) {
  409. if (!this._moveInProgress) {
  410. return;
  411. }
  412. const deltaX = evt.clientX - this._startX;
  413. const rootElement = evt.currentTarget.ownerDocument!.getElementById("node-editor-graph-root") as HTMLDivElement;
  414. if (forLeft) {
  415. this._leftWidth += deltaX;
  416. this._leftWidth = Math.max(150, Math.min(400, this._leftWidth));
  417. DataStorage.WriteNumber("LeftWidth", this._leftWidth);
  418. } else {
  419. this._rightWidth -= deltaX;
  420. this._rightWidth = Math.max(250, Math.min(500, this._rightWidth));
  421. DataStorage.WriteNumber("RightWidth", this._rightWidth);
  422. rootElement.ownerDocument!.getElementById("preview")!.style.height = this._rightWidth + "px";
  423. }
  424. rootElement.style.gridTemplateColumns = this.buildColumnLayout();
  425. this._startX = evt.clientX;
  426. }
  427. buildColumnLayout() {
  428. return `${this._leftWidth}px 4px calc(100% - ${this._leftWidth + 8 + this._rightWidth}px) 4px ${this._rightWidth}px`;
  429. }
  430. emitNewBlock(event: React.DragEvent<HTMLDivElement>) {
  431. var data = event.dataTransfer.getData("babylonjs-material-node") as string;
  432. let newNode: GraphNode;
  433. if (data.indexOf("Block") === -1) {
  434. newNode = this.addValueNode(data);
  435. } else {
  436. let block = BlockTools.GetBlockFromString(data, this.props.globalState.nodeMaterial.getScene(), this.props.globalState.nodeMaterial)!;
  437. if (block.isUnique) {
  438. const className = block.getClassName();
  439. for (var other of this._blocks) {
  440. if (other !== block && other.getClassName() === className) {
  441. this.props.globalState.onErrorMessageDialogRequiredObservable.notifyObservers(`You can only have one ${className} per graph`);
  442. return;
  443. }
  444. }
  445. }
  446. block.autoConfigure(this.props.globalState.nodeMaterial);
  447. newNode = this.createNodeFromObject(block);
  448. };
  449. let x = event.clientX - event.currentTarget.offsetLeft - this._graphCanvas.x - this.NodeWidth;
  450. let y = event.clientY - event.currentTarget.offsetTop - this._graphCanvas.y - 20;
  451. newNode.x = x / this._graphCanvas.zoom;
  452. newNode.y = y / this._graphCanvas.zoom;
  453. newNode.cleanAccumulation();
  454. this.props.globalState.onSelectionChangedObservable.notifyObservers(null);
  455. this.props.globalState.onSelectionChangedObservable.notifyObservers(newNode);
  456. let block = newNode.block;
  457. x -= this.NodeWidth + 150;
  458. block.inputs.forEach((connection) => {
  459. if (connection.connectedPoint) {
  460. var existingNodes = this._graphCanvas.nodes.filter((n) => { return n.block === (connection as any).connectedPoint.ownerBlock });
  461. let connectedNode = existingNodes[0];
  462. if (connectedNode.x === 0 && connectedNode.y === 0) {
  463. connectedNode.x = x / this._graphCanvas.zoom;
  464. connectedNode.y = y / this._graphCanvas.zoom;
  465. connectedNode.cleanAccumulation();
  466. y += 80;
  467. }
  468. }
  469. });
  470. this.forceUpdate();
  471. }
  472. handlePopUp = () => {
  473. this.setState({
  474. showPreviewPopUp : true
  475. });
  476. this.createPopUp();
  477. this.props.globalState.hostWindow.addEventListener('beforeunload', this.handleClosingPopUp);
  478. }
  479. handleClosingPopUp = () => {
  480. this._previewManager.dispose();
  481. this._popUpWindow.close();
  482. this.setState({
  483. showPreviewPopUp: false
  484. }, () => this.initiatePreviewArea()
  485. );
  486. }
  487. initiatePreviewArea = (canvas: HTMLCanvasElement = this.props.globalState.hostDocument.getElementById("preview-canvas") as HTMLCanvasElement) => {
  488. this._previewManager = new PreviewManager(canvas, this.props.globalState);
  489. }
  490. createPopUp = () => {
  491. const userOptions = {
  492. original: true,
  493. popup: true,
  494. overlay: false,
  495. embedMode: false,
  496. enableClose: true,
  497. handleResize: true,
  498. enablePopup: true,
  499. };
  500. const options = {
  501. embedHostWidth: "100%",
  502. ...userOptions
  503. };
  504. const popUpWindow = this.createPopupWindow("PREVIEW AREA", "_PreviewHostWindow");
  505. if (popUpWindow) {
  506. popUpWindow.addEventListener('beforeunload', this.handleClosingPopUp);
  507. const parentControl = popUpWindow.document.getElementById('node-editor-graph-root');
  508. this.createPreviewMeshControlHost(options, parentControl);
  509. this.createPreviewHost(options, parentControl);
  510. if (parentControl) {
  511. this.fixPopUpStyles(parentControl.ownerDocument!);
  512. this.initiatePreviewArea(parentControl.ownerDocument!.getElementById("preview-canvas") as HTMLCanvasElement);
  513. }
  514. }
  515. }
  516. createPopupWindow = (title: string, windowVariableName: string, width = 500, height = 500): Window | null => {
  517. const windowCreationOptionsList = {
  518. width: width,
  519. height: height,
  520. top: (this.props.globalState.hostWindow.innerHeight - width) / 2 + window.screenY,
  521. left: (this.props.globalState.hostWindow.innerWidth - height) / 2 + window.screenX
  522. };
  523. var windowCreationOptions = Object.keys(windowCreationOptionsList)
  524. .map(
  525. (key) => key + '=' + (windowCreationOptionsList as any)[key]
  526. )
  527. .join(',');
  528. const popupWindow = this.props.globalState.hostWindow.open("", title, windowCreationOptions);
  529. if (!popupWindow) {
  530. return null;
  531. }
  532. const parentDocument = popupWindow.document;
  533. parentDocument.title = title;
  534. parentDocument.body.style.width = "100%";
  535. parentDocument.body.style.height = "100%";
  536. parentDocument.body.style.margin = "0";
  537. parentDocument.body.style.padding = "0";
  538. let parentControl = parentDocument.createElement("div");
  539. parentControl.style.width = "100%";
  540. parentControl.style.height = "100%";
  541. parentControl.style.margin = "0";
  542. parentControl.style.padding = "0";
  543. parentControl.style.display = "grid";
  544. parentControl.style.gridTemplateRows = "40px auto";
  545. parentControl.id = 'node-editor-graph-root';
  546. parentControl.className = 'right-panel';
  547. popupWindow.document.body.appendChild(parentControl);
  548. this.copyStyles(this.props.globalState.hostWindow.document, parentDocument);
  549. (this as any)[windowVariableName] = popupWindow;
  550. this._popUpWindow = popupWindow;
  551. return popupWindow;
  552. }
  553. copyStyles = (sourceDoc: HTMLDocument, targetDoc: HTMLDocument) => {
  554. const styleContainer = [];
  555. for (var index = 0; index < sourceDoc.styleSheets.length; index++) {
  556. var styleSheet: any = sourceDoc.styleSheets[index];
  557. try {
  558. if (styleSheet.href) { // for <link> elements loading CSS from a URL
  559. const newLinkEl = sourceDoc.createElement('link');
  560. newLinkEl.rel = 'stylesheet';
  561. newLinkEl.href = styleSheet.href;
  562. targetDoc.head!.appendChild(newLinkEl);
  563. styleContainer.push(newLinkEl);
  564. }
  565. else if (styleSheet.cssRules) { // for <style> elements
  566. const newStyleEl = sourceDoc.createElement('style');
  567. for (var cssRule of styleSheet.cssRules) {
  568. newStyleEl.appendChild(sourceDoc.createTextNode(cssRule.cssText));
  569. }
  570. targetDoc.head!.appendChild(newStyleEl);
  571. styleContainer.push(newStyleEl);
  572. }
  573. } catch (e) {
  574. console.log(e);
  575. }
  576. }
  577. }
  578. createPreviewMeshControlHost = (options: IInternalPreviewAreaOptions, parentControl: Nullable<HTMLElement>) => {
  579. // Prepare the preview control host
  580. if (parentControl) {
  581. const host = parentControl.ownerDocument!.createElement("div");
  582. host.id = "PreviewMeshControl-host";
  583. host.style.width = options.embedHostWidth || "auto";
  584. parentControl.appendChild(host);
  585. const PreviewMeshControlComponentHost = React.createElement(PreviewMeshControlComponent, {
  586. globalState: this.props.globalState,
  587. togglePreviewAreaComponent: this.handlePopUp
  588. });
  589. ReactDOM.render(PreviewMeshControlComponentHost, host);
  590. }
  591. }
  592. createPreviewHost = (options: IInternalPreviewAreaOptions, parentControl: Nullable<HTMLElement>) => {
  593. // Prepare the preview host
  594. if (parentControl) {
  595. const host = parentControl.ownerDocument!.createElement("div");
  596. host.id = "PreviewAreaComponent-host";
  597. host.style.width = options.embedHostWidth || "auto";
  598. host.style.display = "grid";
  599. host.style.gridRow = '2';
  600. host.style.gridTemplateRows = "auto 40px";
  601. parentControl.appendChild(host);
  602. this._previewHost = host;
  603. if (!options.overlay) {
  604. this._previewHost.style.position = "relative";
  605. }
  606. }
  607. if (this._previewHost) {
  608. const PreviewAreaComponentHost = React.createElement(PreviewAreaComponent, {
  609. globalState: this.props.globalState,
  610. width: 200
  611. });
  612. ReactDOM.render(PreviewAreaComponentHost, this._previewHost);
  613. }
  614. }
  615. fixPopUpStyles = (document: Document) => {
  616. const previewContainer = document.getElementById("preview");
  617. if (previewContainer) {
  618. previewContainer.style.height = "auto";
  619. previewContainer.style.gridRow = "1";
  620. }
  621. const previewConfigBar = document.getElementById("preview-config-bar");
  622. if (previewConfigBar) {
  623. previewConfigBar.style.gridRow = "2";
  624. }
  625. const newWindowButton = document.getElementById('preview-new-window');
  626. if (newWindowButton) {
  627. newWindowButton.style.display = 'none';
  628. }
  629. const previewMeshBar = document.getElementById('preview-mesh-bar');
  630. if (previewMeshBar) {
  631. previewMeshBar.style.gridTemplateColumns = "auto 1fr 40px 40px";
  632. }
  633. }
  634. render() {
  635. return (
  636. <Portal globalState={this.props.globalState}>
  637. <div id="node-editor-graph-root" style={
  638. {
  639. gridTemplateColumns: this.buildColumnLayout()
  640. }}
  641. onMouseMove={evt => {
  642. this._mouseLocationX = evt.pageX;
  643. this._mouseLocationY = evt.pageY;
  644. }}
  645. onMouseDown={(evt) => {
  646. if ((evt.target as HTMLElement).nodeName === "INPUT") {
  647. return;
  648. }
  649. this.props.globalState.blockKeyboardEvents = false;
  650. }}
  651. >
  652. {/* Node creation menu */}
  653. <NodeListComponent globalState={this.props.globalState} />
  654. <div id="leftGrab"
  655. onPointerDown={evt => this.onPointerDown(evt)}
  656. onPointerUp={evt => this.onPointerUp(evt)}
  657. onPointerMove={evt => this.resizeColumns(evt)}
  658. ></div>
  659. {/* The node graph diagram */}
  660. <div className="diagram-container"
  661. onDrop={event => {
  662. this.emitNewBlock(event);
  663. }}
  664. onDragOver={event => {
  665. event.preventDefault();
  666. }}
  667. >
  668. <GraphCanvasComponent ref={"graphCanvas"} globalState={this.props.globalState}/>
  669. </div>
  670. <div id="rightGrab"
  671. onPointerDown={evt => this.onPointerDown(evt)}
  672. onPointerUp={evt => this.onPointerUp(evt)}
  673. onPointerMove={evt => this.resizeColumns(evt, false)}
  674. ></div>
  675. {/* Property tab */}
  676. <div className="right-panel">
  677. <PropertyTabComponent globalState={this.props.globalState} />
  678. {!this.state.showPreviewPopUp ? <PreviewMeshControlComponent globalState={this.props.globalState} togglePreviewAreaComponent={this.handlePopUp} /> : null }
  679. {!this.state.showPreviewPopUp ? <PreviewAreaComponent globalState={this.props.globalState} width={this._rightWidth} /> : null}
  680. </div>
  681. <LogComponent globalState={this.props.globalState} />
  682. </div>
  683. <MessageDialogComponent globalState={this.props.globalState} />
  684. <div className="blocker">
  685. Node Material Editor runs only on desktop
  686. </div>
  687. <div className="wait-screen hidden">
  688. Processing...please wait
  689. </div>
  690. </Portal>
  691. );
  692. }
  693. }