graphEditor.tsx 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694
  1. import {
  2. DiagramEngine,
  3. DiagramModel,
  4. DiagramWidget,
  5. LinkModel
  6. } from "storm-react-diagrams";
  7. import * as React from "react";
  8. import { GlobalState } from './globalState';
  9. import { GenericNodeFactory } from './components/diagram/generic/genericNodeFactory';
  10. import { GenericNodeModel } from './components/diagram/generic/genericNodeModel';
  11. import { NodeMaterialBlock } from 'babylonjs/Materials/Node/nodeMaterialBlock';
  12. import { NodeMaterialConnectionPoint } from 'babylonjs/Materials/Node/nodeMaterialBlockConnectionPoint';
  13. import { NodeListComponent } from './components/nodeList/nodeListComponent';
  14. import { PropertyTabComponent } from './components/propertyTab/propertyTabComponent';
  15. import { Portal } from './portal';
  16. import { TextureNodeFactory } from './components/diagram/texture/textureNodeFactory';
  17. import { DefaultNodeModel } from './components/diagram/defaultNodeModel';
  18. import { TextureNodeModel } from './components/diagram/texture/textureNodeModel';
  19. import { DefaultPortModel } from './components/diagram/port/defaultPortModel';
  20. import { InputNodeFactory } from './components/diagram/input/inputNodeFactory';
  21. import { InputNodeModel } from './components/diagram/input/inputNodeModel';
  22. import { TextureBlock } from 'babylonjs/Materials/Node/Blocks/Dual/textureBlock';
  23. import { LogComponent, LogEntry } from './components/log/logComponent';
  24. import { LightBlock } from 'babylonjs/Materials/Node/Blocks/Dual/lightBlock';
  25. import { LightNodeModel } from './components/diagram/light/lightNodeModel';
  26. import { LightNodeFactory } from './components/diagram/light/lightNodeFactory';
  27. import { DataStorage } from './dataStorage';
  28. import { NodeMaterialBlockConnectionPointTypes } from 'babylonjs/Materials/Node/nodeMaterialBlockConnectionPointTypes';
  29. import { InputBlock } from 'babylonjs/Materials/Node/Blocks/Input/inputBlock';
  30. import { Nullable } from 'babylonjs/types';
  31. import { MessageDialogComponent } from './sharedComponents/messageDialog';
  32. import { BlockTools } from './blockTools';
  33. import { AdvancedLinkFactory } from './components/diagram/link/advancedLinkFactory';
  34. import { RemapNodeFactory } from './components/diagram/remap/remapNodeFactory';
  35. import { RemapNodeModel } from './components/diagram/remap/remapNodeModel';
  36. import { RemapBlock } from 'babylonjs/Materials/Node/Blocks/remapBlock';
  37. import { GraphHelper } from './graphHelper';
  38. import { PreviewManager } from './components/preview/previewManager';
  39. import { INodeLocationInfo } from './nodeLocationInfo';
  40. import { PreviewMeshControlComponent } from './components/preview/previewMeshControlComponent';
  41. import { TrigonometryNodeFactory } from './components/diagram/trigonometry/trigonometryNodeFactory';
  42. import { TrigonometryBlock } from 'babylonjs/Materials/Node/Blocks/trigonometryBlock';
  43. import { TrigonometryNodeModel } from './components/diagram/trigonometry/trigonometryNodeModel';
  44. import { AdvancedLinkModel } from './components/diagram/link/advancedLinkModel';
  45. import { ClampNodeFactory } from './components/diagram/clamp/clampNodeFactory';
  46. import { ClampNodeModel } from './components/diagram/clamp/clampNodeModel';
  47. import { ClampBlock } from 'babylonjs/Materials/Node/Blocks/clampBlock';
  48. import { LightInformationNodeFactory } from './components/diagram/lightInformation/lightInformationNodeFactory';
  49. import { LightInformationNodeModel } from './components/diagram/lightInformation/lightInformationNodeModel';
  50. import { LightInformationBlock } from 'babylonjs/Materials/Node/Blocks/Vertex/lightInformationBlock';
  51. import { PreviewAreaComponent } from './components/preview/previewAreaComponent';
  52. require("storm-react-diagrams/dist/style.min.css");
  53. require("./main.scss");
  54. require("./components/diagram/diagram.scss");
  55. interface IGraphEditorProps {
  56. globalState: GlobalState;
  57. }
  58. export class NodeCreationOptions {
  59. nodeMaterialBlock: NodeMaterialBlock;
  60. type?: string;
  61. connection?: NodeMaterialConnectionPoint;
  62. }
  63. export class GraphEditor extends React.Component<IGraphEditorProps> {
  64. private readonly NodeWidth = 100;
  65. private _engine: DiagramEngine;
  66. private _model: DiagramModel;
  67. private _startX: number;
  68. private _moveInProgress: boolean;
  69. private _leftWidth = DataStorage.ReadNumber("LeftWidth", 200);
  70. private _rightWidth = DataStorage.ReadNumber("RightWidth", 300);
  71. private _nodes = new Array<DefaultNodeModel>();
  72. private _blocks = new Array<NodeMaterialBlock>();
  73. private _previewManager: PreviewManager;
  74. private _copiedNodes: DefaultNodeModel[] = [];
  75. private _mouseLocationX = 0;
  76. private _mouseLocationY = 0;
  77. private _onWidgetKeyUpPointer: any;
  78. /** @hidden */
  79. public _toAdd: LinkModel[] | null = [];
  80. /**
  81. * Creates a node and recursivly creates its parent nodes from it's input
  82. * @param nodeMaterialBlock
  83. */
  84. public createNodeFromObject(options: NodeCreationOptions) {
  85. if (this._blocks.indexOf(options.nodeMaterialBlock) !== -1) {
  86. return this._nodes.filter(n => n.block === options.nodeMaterialBlock)[0];
  87. }
  88. this._blocks.push(options.nodeMaterialBlock);
  89. if (this.props.globalState.nodeMaterial!.attachedBlocks.indexOf(options.nodeMaterialBlock) === -1) {
  90. this.props.globalState.nodeMaterial!.attachedBlocks.push(options.nodeMaterialBlock);
  91. }
  92. // Create new node in the graph
  93. var newNode: DefaultNodeModel;
  94. if (options.nodeMaterialBlock instanceof TextureBlock) {
  95. newNode = new TextureNodeModel();
  96. } else if (options.nodeMaterialBlock instanceof LightBlock) {
  97. newNode = new LightNodeModel();
  98. } else if (options.nodeMaterialBlock instanceof InputBlock) {
  99. newNode = new InputNodeModel();
  100. } else if (options.nodeMaterialBlock instanceof TrigonometryBlock) {
  101. newNode = new TrigonometryNodeModel();
  102. } else if (options.nodeMaterialBlock instanceof RemapBlock) {
  103. newNode = new RemapNodeModel();
  104. } else if (options.nodeMaterialBlock instanceof ClampBlock) {
  105. newNode = new ClampNodeModel();
  106. } else if (options.nodeMaterialBlock instanceof LightInformationBlock) {
  107. newNode = new LightInformationNodeModel();
  108. } else {
  109. newNode = new GenericNodeModel();
  110. }
  111. if (options.nodeMaterialBlock.isFinalMerger) {
  112. this.props.globalState.nodeMaterial!.addOutputNode(options.nodeMaterialBlock);
  113. }
  114. this._nodes.push(newNode);
  115. this._model.addAll(newNode);
  116. if (options.nodeMaterialBlock) {
  117. newNode.prepare(options, this._nodes, this._model, this);
  118. }
  119. return newNode;
  120. }
  121. addValueNode(type: string) {
  122. let nodeType: NodeMaterialBlockConnectionPointTypes = BlockTools.GetConnectionNodeTypeFromString(type);
  123. let newInputBlock = new InputBlock(type, undefined, nodeType);
  124. var localNode = this.createNodeFromObject({ type: type, nodeMaterialBlock: newInputBlock })
  125. return localNode;
  126. }
  127. onWidgetKeyUp(evt: any) {
  128. var widget = (this.refs["test"] as DiagramWidget);
  129. if (!widget || this.props.globalState.blockKeyboardEvents) {
  130. return;
  131. }
  132. widget.onKeyUp(evt)
  133. }
  134. componentDidMount() {
  135. if (this.props.globalState.hostDocument) {
  136. var widget = (this.refs["test"] as DiagramWidget);
  137. widget.setState({ document: this.props.globalState.hostDocument })
  138. this._onWidgetKeyUpPointer = this.onWidgetKeyUp.bind(this)
  139. this.props.globalState.hostDocument!.addEventListener("keyup", this._onWidgetKeyUpPointer, false);
  140. this._previewManager = new PreviewManager(this.props.globalState.hostDocument.getElementById("preview-canvas") as HTMLCanvasElement, this.props.globalState);
  141. }
  142. }
  143. componentWillUnmount() {
  144. if (this.props.globalState.hostDocument) {
  145. this.props.globalState.hostDocument!.removeEventListener("keyup", this._onWidgetKeyUpPointer, false);
  146. }
  147. if (this._previewManager) {
  148. this._previewManager.dispose();
  149. }
  150. }
  151. constructor(props: IGraphEditorProps) {
  152. super(props);
  153. // setup the diagram engine
  154. this._engine = new DiagramEngine();
  155. this._engine.installDefaultFactories()
  156. this._engine.registerNodeFactory(new GenericNodeFactory(this.props.globalState));
  157. this._engine.registerNodeFactory(new TextureNodeFactory(this.props.globalState));
  158. this._engine.registerNodeFactory(new LightNodeFactory(this.props.globalState));
  159. this._engine.registerNodeFactory(new InputNodeFactory(this.props.globalState));
  160. this._engine.registerNodeFactory(new RemapNodeFactory(this.props.globalState));
  161. this._engine.registerNodeFactory(new TrigonometryNodeFactory(this.props.globalState));
  162. this._engine.registerNodeFactory(new ClampNodeFactory(this.props.globalState));
  163. this._engine.registerNodeFactory(new LightInformationNodeFactory(this.props.globalState));
  164. this._engine.registerLinkFactory(new AdvancedLinkFactory());
  165. this.props.globalState.onRebuildRequiredObservable.add(() => {
  166. if (this.props.globalState.nodeMaterial) {
  167. this.buildMaterial();
  168. }
  169. this.forceUpdate();
  170. });
  171. this.props.globalState.onResetRequiredObservable.add((locations) => {
  172. this.build(false, locations);
  173. if (this.props.globalState.nodeMaterial) {
  174. this.buildMaterial();
  175. }
  176. });
  177. this.props.globalState.onUpdateRequiredObservable.add(() => {
  178. this.forceUpdate();
  179. });
  180. this.props.globalState.onZoomToFitRequiredObservable.add(() => {
  181. this.zoomToFit();
  182. });
  183. this.props.globalState.onReOrganizedRequiredObservable.add(() => {
  184. this.reOrganize();
  185. });
  186. this.props.globalState.onGetNodeFromBlock = (block) => {
  187. return this._nodes.filter(n => n.block === block)[0];
  188. }
  189. this.props.globalState.hostDocument!.addEventListener("keydown", evt => {
  190. if (!evt.ctrlKey) {
  191. return;
  192. }
  193. if (evt.key === "c") {
  194. let selectedItems = this._engine.diagramModel.getSelectedItems();
  195. if (!selectedItems.length) {
  196. return;
  197. }
  198. let selectedItem = selectedItems[0] as DefaultNodeModel;
  199. if (!selectedItem.block) {
  200. return;
  201. }
  202. this._copiedNodes = selectedItems.map(i => (i as DefaultNodeModel)!);
  203. } else if (evt.key === "v") {
  204. if (!this._copiedNodes.length) {
  205. return;
  206. }
  207. const rootElement = this.props.globalState.hostDocument!.querySelector(".diagram-container") as HTMLDivElement;
  208. const zoomLevel = this._engine.diagramModel.getZoomLevel() / 100.0;
  209. let currentX = (this._mouseLocationX - rootElement.offsetLeft - this._engine.diagramModel.getOffsetX() - this.NodeWidth) / zoomLevel;
  210. let currentY = (this._mouseLocationY - rootElement.offsetTop - this._engine.diagramModel.getOffsetY() - 20) / zoomLevel;
  211. let originalNode: Nullable<DefaultNodeModel> = null;
  212. for (var node of this._copiedNodes) {
  213. let block = node.block;
  214. if (!block) {
  215. continue;
  216. }
  217. let clone = block.clone(this.props.globalState.nodeMaterial.getScene());
  218. if (!clone) {
  219. return;
  220. }
  221. let newNode = this.createNodeFromObject({ nodeMaterialBlock: clone });
  222. let x = 0;
  223. let y = 0;
  224. if (originalNode) {
  225. x = currentX + node.x - originalNode.x;
  226. y = currentY + node.y - originalNode.y;
  227. } else {
  228. originalNode = node;
  229. x = currentX;
  230. y = currentY;
  231. }
  232. newNode.setPosition(x, y);
  233. }
  234. this._engine.repaintCanvas();
  235. }
  236. }, false);
  237. this.build(true);
  238. }
  239. zoomToFit(retry = 0) {
  240. const xFactor = this._engine.canvas.clientWidth / this._engine.canvas.scrollWidth;
  241. const yFactor = this._engine.canvas.clientHeight / this._engine.canvas.scrollHeight;
  242. const zoomFactor = xFactor < yFactor ? xFactor : yFactor;
  243. if (zoomFactor === 1) {
  244. return;
  245. }
  246. this._engine.diagramModel.setZoomLevel(this._engine.diagramModel.getZoomLevel() * zoomFactor);
  247. this._engine.diagramModel.setOffset(0, 0);
  248. this._engine.repaintCanvas();
  249. retry++;
  250. if (retry < 4) {
  251. setTimeout(() => this.zoomToFit(retry), 1);
  252. }
  253. }
  254. buildMaterial() {
  255. if (!this.props.globalState.nodeMaterial) {
  256. return;
  257. }
  258. try {
  259. this.props.globalState.nodeMaterial.build(true);
  260. this.props.globalState.onLogRequiredObservable.notifyObservers(new LogEntry("Node material build successful", false));
  261. }
  262. catch (err) {
  263. this.props.globalState.onLogRequiredObservable.notifyObservers(new LogEntry(err, true));
  264. }
  265. }
  266. applyFragmentOutputConstraints(rootInput: DefaultPortModel) {
  267. var model = rootInput.parent as GenericNodeModel;
  268. for (var inputKey in model.getPorts()) {
  269. let input = model.getPorts()[inputKey];
  270. if (rootInput.name === "rgba" && (inputKey === "a" || inputKey === "rgb")
  271. ||
  272. (rootInput.name === "a" || rootInput.name === "rgb") && inputKey === "rgba") {
  273. for (var key in input.links) {
  274. let other = input.links[key];
  275. other.remove();
  276. }
  277. continue;
  278. }
  279. }
  280. }
  281. build(needToWait = false, locations: Nullable<INodeLocationInfo[]> = null) {
  282. // setup the diagram model
  283. this._model = new DiagramModel();
  284. this._nodes = [];
  285. this._blocks = [];
  286. // Listen to events
  287. this._model.addListener({
  288. nodesUpdated: (e) => {
  289. if (!e.isCreated) {
  290. // Block is deleted
  291. let targetBlock = (e.node as GenericNodeModel).block;
  292. if (targetBlock) {
  293. let attachedBlockIndex = this.props.globalState.nodeMaterial!.attachedBlocks.indexOf(targetBlock);
  294. if (attachedBlockIndex > -1) {
  295. this.props.globalState.nodeMaterial!.attachedBlocks.splice(attachedBlockIndex, 1);
  296. }
  297. if (targetBlock.isFinalMerger) {
  298. this.props.globalState.nodeMaterial!.removeOutputNode(targetBlock);
  299. }
  300. let blockIndex = this._blocks.indexOf(targetBlock);
  301. if (blockIndex > -1) {
  302. this._blocks.splice(blockIndex, 1);
  303. }
  304. }
  305. this.props.globalState.onSelectionChangedObservable.notifyObservers(null);
  306. } else {
  307. }
  308. },
  309. linksUpdated: (e) => {
  310. if (!e.isCreated) {
  311. // Link is deleted
  312. this.props.globalState.onSelectionChangedObservable.notifyObservers(null);
  313. let sourcePort = e.link.sourcePort as DefaultPortModel;
  314. var link = DefaultPortModel.SortInputOutput(sourcePort, e.link.targetPort as DefaultPortModel);
  315. if (link) {
  316. if (link.input.connection && link.output.connection) {
  317. if (link.input.connection.connectedPoint) {
  318. // Disconnect standard nodes
  319. link.output.connection.disconnectFrom(link.input.connection);
  320. link.input.syncWithNodeMaterialConnectionPoint(link.input.connection);
  321. link.output.syncWithNodeMaterialConnectionPoint(link.output.connection);
  322. this.props.globalState.onRebuildRequiredObservable.notifyObservers();
  323. }
  324. }
  325. } else {
  326. if (!e.link.targetPort && e.link.sourcePort && (e.link.sourcePort as DefaultPortModel).position === "input") {
  327. // Drag from input port, we are going to build an input for it
  328. let input = e.link.sourcePort as DefaultPortModel;
  329. if (input.connection!.type == NodeMaterialBlockConnectionPointTypes.AutoDetect) {
  330. return;
  331. }
  332. let nodeModel = this.addValueNode(BlockTools.GetStringFromConnectionNodeType(input.connection!.type));
  333. let link = nodeModel.ports.output.link(input);
  334. nodeModel.x = e.link.points[1].x - this.NodeWidth;
  335. nodeModel.y = e.link.points[1].y;
  336. setTimeout(() => {
  337. this._model.addLink(link);
  338. input.syncWithNodeMaterialConnectionPoint(input.connection!);
  339. nodeModel.ports.output.syncWithNodeMaterialConnectionPoint(nodeModel.ports.output.connection!);
  340. let isFragmentOutput = (input.parent as DefaultNodeModel).block!.getClassName() === "FragmentOutputBlock";
  341. if (isFragmentOutput) {
  342. this.applyFragmentOutputConstraints(input);
  343. }
  344. this.forceUpdate();
  345. }, 1);
  346. nodeModel.ports.output.connection!.connectTo(input.connection!);
  347. this.props.globalState.onRebuildRequiredObservable.notifyObservers();
  348. }
  349. }
  350. this.forceUpdate();
  351. return;
  352. } else {
  353. e.link.addListener({
  354. sourcePortChanged: () => {
  355. },
  356. targetPortChanged: (evt) => {
  357. // Link is created with a target port
  358. var link = DefaultPortModel.SortInputOutput(e.link.sourcePort as DefaultPortModel, e.link.targetPort as DefaultPortModel);
  359. if (link) {
  360. if (link.output.connection && link.input.connection) {
  361. let currentBlock = link.input.connection.ownerBlock;
  362. let isFragmentOutput = currentBlock.getClassName() === "FragmentOutputBlock";
  363. // Disconnect previous connection
  364. for (var key in link.input.links) {
  365. let other = link.input.links[key];
  366. let sourcePortConnection = (other.getSourcePort() as DefaultPortModel).connection;
  367. let targetPortConnection = (other.getTargetPort() as DefaultPortModel).connection;
  368. if (
  369. sourcePortConnection !== (link.output as DefaultPortModel).connection &&
  370. targetPortConnection !== (link.output as DefaultPortModel).connection
  371. ) {
  372. other.remove();
  373. }
  374. }
  375. if (link.output.connection.canConnectTo(link.input.connection)) {
  376. if (isFragmentOutput) {
  377. this.applyFragmentOutputConstraints(link.input);
  378. }
  379. link.output.connection.connectTo(link.input.connection);
  380. } else {
  381. (evt.entity as AdvancedLinkModel).remove();
  382. this.props.globalState.onErrorMessageDialogRequiredObservable.notifyObservers("Cannot connect two different connection types");
  383. }
  384. this.forceUpdate();
  385. }
  386. if (this.props.globalState.nodeMaterial) {
  387. this.buildMaterial();
  388. }
  389. }
  390. }
  391. });
  392. }
  393. }
  394. });
  395. // Load graph of nodes from the material
  396. if (this.props.globalState.nodeMaterial) {
  397. var material = this.props.globalState.nodeMaterial;
  398. material._vertexOutputNodes.forEach((n: any) => {
  399. this.createNodeFromObject({ nodeMaterialBlock: n });
  400. });
  401. material._fragmentOutputNodes.forEach((n: any) => {
  402. this.createNodeFromObject({ nodeMaterialBlock: n });
  403. });
  404. material.attachedBlocks.forEach((n: any) => {
  405. this.createNodeFromObject({ nodeMaterialBlock: n });
  406. });
  407. }
  408. // load model into engine
  409. setTimeout(() => {
  410. if (this._toAdd) {
  411. this._model.addAll(...this._toAdd);
  412. }
  413. this._toAdd = null;
  414. this._engine.setDiagramModel(this._model);
  415. this.forceUpdate();
  416. this.reOrganize(locations);
  417. }, needToWait ? 500 : 1);
  418. }
  419. reOrganize(locations: Nullable<INodeLocationInfo[]> = null) {
  420. if (!locations) {
  421. let nodes = GraphHelper.DistributeGraph(this._model);
  422. nodes.forEach(node => {
  423. for (var nodeName in this._model.nodes) {
  424. let modelNode = this._model.nodes[nodeName];
  425. if (modelNode.id === node.id) {
  426. modelNode.setPosition(node.x - node.width / 2, node.y - node.height / 2);
  427. return;
  428. }
  429. }
  430. });
  431. } else {
  432. for (var location of locations) {
  433. for (var node of this._nodes) {
  434. if (node.block && node.block.uniqueId === location.blockId) {
  435. node.setPosition(location.x, location.y);
  436. break;
  437. }
  438. }
  439. }
  440. }
  441. this._engine.repaintCanvas();
  442. }
  443. onPointerDown(evt: React.PointerEvent<HTMLDivElement>) {
  444. this._startX = evt.clientX;
  445. this._moveInProgress = true;
  446. evt.currentTarget.setPointerCapture(evt.pointerId);
  447. }
  448. onPointerUp(evt: React.PointerEvent<HTMLDivElement>) {
  449. this._moveInProgress = false;
  450. evt.currentTarget.releasePointerCapture(evt.pointerId);
  451. }
  452. resizeColumns(evt: React.PointerEvent<HTMLDivElement>, forLeft = true) {
  453. if (!this._moveInProgress) {
  454. return;
  455. }
  456. const deltaX = evt.clientX - this._startX;
  457. const rootElement = evt.currentTarget.ownerDocument!.getElementById("node-editor-graph-root") as HTMLDivElement;
  458. if (forLeft) {
  459. this._leftWidth += deltaX;
  460. this._leftWidth = Math.max(150, Math.min(400, this._leftWidth));
  461. DataStorage.StoreNumber("LeftWidth", this._leftWidth);
  462. } else {
  463. this._rightWidth -= deltaX;
  464. this._rightWidth = Math.max(250, Math.min(500, this._rightWidth));
  465. DataStorage.StoreNumber("RightWidth", this._rightWidth);
  466. rootElement.ownerDocument!.getElementById("preview")!.style.height = this._rightWidth + "px";
  467. }
  468. rootElement.style.gridTemplateColumns = this.buildColumnLayout();
  469. this._startX = evt.clientX;
  470. }
  471. buildColumnLayout() {
  472. return `${this._leftWidth}px 4px calc(100% - ${this._leftWidth + 8 + this._rightWidth}px) 4px ${this._rightWidth}px`;
  473. }
  474. emitNewBlock(event: React.DragEvent<HTMLDivElement>) {
  475. var data = event.dataTransfer.getData("babylonjs-material-node") as string;
  476. let nodeModel: Nullable<DefaultNodeModel> = null;
  477. if (data.indexOf("Block") === -1) {
  478. nodeModel = this.addValueNode(data);
  479. } else {
  480. let block = BlockTools.GetBlockFromString(data);
  481. if (block) {
  482. this._toAdd = [];
  483. block.autoConfigure(this.props.globalState.nodeMaterial);
  484. nodeModel = this.createNodeFromObject({ nodeMaterialBlock: block });
  485. }
  486. };
  487. if (nodeModel) {
  488. const zoomLevel = this._engine.diagramModel.getZoomLevel() / 100.0;
  489. let x = (event.clientX - event.currentTarget.offsetLeft - this._engine.diagramModel.getOffsetX() - this.NodeWidth) / zoomLevel;
  490. let y = (event.clientY - event.currentTarget.offsetTop - this._engine.diagramModel.getOffsetY() - 20) / zoomLevel;
  491. nodeModel.setPosition(x, y);
  492. let block = nodeModel!.block;
  493. x -= this.NodeWidth + 150;
  494. block!._inputs.forEach((connection) => {
  495. if (connection.connectedPoint) {
  496. var existingNodes = this._nodes.filter((n) => { return n.block === (connection as any)._connectedPoint._ownerBlock });
  497. let connectedNode = existingNodes[0];
  498. if (connectedNode.x === 0 && connectedNode.y === 0) {
  499. connectedNode.setPosition(x, y);
  500. y += 80;
  501. }
  502. }
  503. });
  504. this._engine.repaintCanvas();
  505. setTimeout(() => {
  506. this._model.addAll(...this._toAdd!);
  507. this._toAdd = null;
  508. this._model.clearSelection();
  509. nodeModel!.setSelected(true);
  510. this._engine.repaintCanvas();
  511. }, 150);
  512. }
  513. this.forceUpdate();
  514. }
  515. render() {
  516. return (
  517. <Portal globalState={this.props.globalState}>
  518. <div id="node-editor-graph-root" style={
  519. {
  520. gridTemplateColumns: this.buildColumnLayout()
  521. }}
  522. onMouseMove={evt => {
  523. this._mouseLocationX = evt.pageX;
  524. this._mouseLocationY = evt.pageY;
  525. }}
  526. onMouseDown={(evt) => {
  527. if ((evt.target as HTMLElement).nodeName === "INPUT") {
  528. return;
  529. }
  530. this.props.globalState.blockKeyboardEvents = false;
  531. }}
  532. >
  533. {/* Node creation menu */}
  534. <NodeListComponent globalState={this.props.globalState} />
  535. <div id="leftGrab"
  536. onPointerDown={evt => this.onPointerDown(evt)}
  537. onPointerUp={evt => this.onPointerUp(evt)}
  538. onPointerMove={evt => this.resizeColumns(evt)}
  539. ></div>
  540. {/* The node graph diagram */}
  541. <div className="diagram-container"
  542. onDrop={event => {
  543. this.emitNewBlock(event);
  544. }}
  545. onDragOver={event => {
  546. event.preventDefault();
  547. }}
  548. >
  549. <DiagramWidget className="diagram" deleteKeys={[46]} ref={"test"}
  550. allowLooseLinks={false}
  551. inverseZoom={true}
  552. diagramEngine={this._engine}
  553. maxNumberPointsPerLink={0} />
  554. </div>
  555. <div id="rightGrab"
  556. onPointerDown={evt => this.onPointerDown(evt)}
  557. onPointerUp={evt => this.onPointerUp(evt)}
  558. onPointerMove={evt => this.resizeColumns(evt, false)}
  559. ></div>
  560. {/* Property tab */}
  561. <div className="right-panel">
  562. <PropertyTabComponent globalState={this.props.globalState} />
  563. <PreviewMeshControlComponent globalState={this.props.globalState} />
  564. <PreviewAreaComponent globalState={this.props.globalState} width={this._rightWidth}/>
  565. </div>
  566. <LogComponent globalState={this.props.globalState} />
  567. </div>
  568. <MessageDialogComponent globalState={this.props.globalState} />
  569. <div className="blocker">
  570. Node Material Editor requires a screen with a minimal resolution of 1000px
  571. </div>
  572. </Portal>
  573. );
  574. }
  575. }