graphEditor.tsx 30 KB

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