TSLGraphLoader.js 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. import { FileLoader, error } from 'three';
  2. import * as THREE from 'three';
  3. import * as TSL from 'three/tsl';
  4. const _library = {
  5. 'three': { ...THREE },
  6. 'three/tsl': { ...TSL }
  7. };
  8. const STORAGE_PREFIX = 'tsl-graph';
  9. const STORAGE_CODE = 'tsl-graph-code';
  10. function _storageKey( graphId ) {
  11. return `${STORAGE_PREFIX}:${graphId}`;
  12. }
  13. class TSLGraphLoaderApplier {
  14. constructor( tslGraphFns ) {
  15. this.tslGraphFns = tslGraphFns;
  16. }
  17. apply( scene ) {
  18. const tslGraphFns = this.tslGraphFns;
  19. scene.traverse( ( object ) => {
  20. if ( object.material && object.material.userData.graphId ) {
  21. if ( tslGraphFns[ object.material.userData.graphId ] ) {
  22. tslGraphFns[ object.material.userData.graphId ]( object.material );
  23. object.material.needsUpdate = true;
  24. }
  25. }
  26. } );
  27. }
  28. }
  29. export class TSLGraphLoader extends FileLoader {
  30. constructor( manager ) {
  31. super( manager );
  32. }
  33. load( url, onLoad, onProgress, onError ) {
  34. super.load( url, ( text ) => {
  35. let json;
  36. try {
  37. json = JSON.parse( text );
  38. } catch ( e ) {
  39. if ( onError ) onError( e );
  40. return;
  41. }
  42. const applier = this.parse( json );
  43. if ( onLoad ) onLoad( applier );
  44. }, onProgress, onError );
  45. }
  46. parseMaterial( json ) {
  47. const baseFn = 'tslGraph';
  48. const imports = {};
  49. const materials = [ this._generateMaterialCode( json, baseFn, imports ) ];
  50. const code = this._generateCode( materials, imports );
  51. const tslFunction = new Function( code )()( THREE, imports );
  52. return tslFunction;
  53. }
  54. parseMaterials( json ) {
  55. const imports = {};
  56. const materials = [];
  57. for ( const [ name, material ] of Object.entries( json ) ) {
  58. materials.push( this._generateMaterialCode( material, name, imports ) );
  59. }
  60. const code = this._generateCode( materials, imports );
  61. const tslFunction = new Function( code )()( THREE, imports );
  62. return tslFunction;
  63. }
  64. parse( json ) {
  65. let result;
  66. if ( json.material && json.material.code ) {
  67. result = this.parseMaterial( json.material );
  68. } else if ( json.materials ) {
  69. result = this.parseMaterials( json.materials );
  70. } else if ( json.codes && json.graphs ) {
  71. result = this.parseMaterials( json.codes.materials );
  72. TSLGraphLoader.setGraphs( json );
  73. }
  74. return new TSLGraphLoaderApplier( result );
  75. }
  76. _generateMaterialCode( json, name = 'tslGraph', imports = {} ) {
  77. const code = json.code.replace( 'function tslGraph', `materials[ '${ name }' ] = function` ).replace( /\n|^/g, '\n\t' );
  78. for ( const importData of json.imports ) {
  79. if ( _library[ importData.from ] ) {
  80. for ( const importName of importData.imports ) {
  81. if ( _library[ importData.from ][ importName ] ) {
  82. imports[ importName ] = _library[ importData.from ][ importName ];
  83. } else {
  84. error( `TSLGraph: Import ${ importName } not found in ${ importData.from }.` );
  85. }
  86. }
  87. } else {
  88. error( `TSLGraph: Library ${ importData.from } not found.` );
  89. }
  90. }
  91. return code;
  92. }
  93. _generateCode( materials, imports ) {
  94. const fnCode = `return ( THREE, { ${ Object.keys( imports ).join( ', ' ) } } ) => {\n\n\tconst materials = {};\n${ materials.join( '\n' ) }\n\n\treturn materials;\n\n}`;
  95. return fnCode;
  96. }
  97. static get hasGraphs() {
  98. return Object.keys( TSLGraphLoader.getCodes().materials ).length > 0;
  99. }
  100. static getCodes() {
  101. const code = window.localStorage.getItem( STORAGE_CODE );
  102. return code ? JSON.parse( code ) : { materials: {} };
  103. }
  104. static setCodes( codes ) {
  105. window.localStorage.setItem( STORAGE_CODE, JSON.stringify( codes ) );
  106. }
  107. static setGraph( graphId, graphData ) {
  108. window.localStorage.setItem( _storageKey( graphId ), JSON.stringify( graphData ) );
  109. }
  110. static getGraph( graphId ) {
  111. const raw = window.localStorage.getItem( _storageKey( graphId ) );
  112. if ( ! raw ) return null;
  113. try {
  114. return JSON.parse( raw );
  115. } catch ( e ) {
  116. error( 'TSLGraph: Invalid graph JSON in localStorage, ignoring.', e );
  117. return null;
  118. }
  119. }
  120. static deleteGraph( graphId ) {
  121. window.localStorage.removeItem( _storageKey( graphId ) );
  122. }
  123. static setGraphs( json ) {
  124. if ( ! json.codes || ! json.graphs ) {
  125. throw new Error( 'TSLGraphLoader: Invalid import file structure.' );
  126. }
  127. TSLGraphLoader.clearGraphs();
  128. // Save imported graph visualizations
  129. for ( const [ id, graphData ] of Object.entries( json.graphs ) ) {
  130. TSLGraphLoader.setGraph( id, graphData );
  131. }
  132. // Fully overwrite codes
  133. TSLGraphLoader.setCodes( json.codes );
  134. return json;
  135. }
  136. static clearGraphs() {
  137. const keysToRemove = [];
  138. for ( let i = 0; i < window.localStorage.length; i ++ ) {
  139. const key = window.localStorage.key( i );
  140. if ( key.startsWith( STORAGE_PREFIX ) ) {
  141. keysToRemove.push( key );
  142. }
  143. }
  144. for ( const key of keysToRemove ) {
  145. window.localStorage.removeItem( key );
  146. }
  147. }
  148. }
粤ICP备19079148号