graphEditor.tsx 31 KB

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