graphEditor.tsx 34 KB

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