Script.js 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503
  1. import { UIElement, UIPanel, UIText } from './libs/ui.js';
  2. import { SetScriptValueCommand } from './commands/SetScriptValueCommand.js';
  3. import { SetMaterialValueCommand } from './commands/SetMaterialValueCommand.js';
  4. function Script( editor ) {
  5. const signals = editor.signals;
  6. const strings = editor.strings;
  7. const container = new UIPanel();
  8. container.setId( 'script' );
  9. container.setPosition( 'absolute' );
  10. container.setBackgroundColor( '#272822' );
  11. container.setDisplay( 'none' );
  12. const header = new UIPanel();
  13. header.setPadding( '10px' );
  14. container.add( header );
  15. const title = new UIText().setColor( '#fff' );
  16. header.add( title );
  17. const buttonSVG = ( function () {
  18. const svg = document.createElementNS( 'http://www.w3.org/2000/svg', 'svg' );
  19. svg.setAttribute( 'width', 32 );
  20. svg.setAttribute( 'height', 32 );
  21. const path = document.createElementNS( 'http://www.w3.org/2000/svg', 'path' );
  22. path.setAttribute( 'd', 'M 12,12 L 22,22 M 22,12 12,22' );
  23. path.setAttribute( 'stroke', '#fff' );
  24. svg.appendChild( path );
  25. return svg;
  26. } )();
  27. const close = new UIElement( buttonSVG );
  28. close.setPosition( 'absolute' );
  29. close.setTop( '3px' );
  30. close.setRight( '1px' );
  31. close.setCursor( 'pointer' );
  32. close.onClick( function () {
  33. container.setDisplay( 'none' );
  34. } );
  35. header.add( close );
  36. let renderer;
  37. signals.rendererCreated.add( function ( newRenderer ) {
  38. renderer = newRenderer;
  39. } );
  40. let delay;
  41. let currentMode;
  42. let currentScript;
  43. let currentObject;
  44. const codemirror = CodeMirror( container.dom, {
  45. value: '',
  46. lineNumbers: true,
  47. matchBrackets: true,
  48. indentWithTabs: true,
  49. tabSize: 4,
  50. indentUnit: 4,
  51. hintOptions: {
  52. completeSingle: false
  53. }
  54. } );
  55. codemirror.setOption( 'theme', 'monokai' );
  56. codemirror.on( 'change', function () {
  57. if ( codemirror.state.focused === false ) return;
  58. clearTimeout( delay );
  59. delay = setTimeout( function () {
  60. const value = codemirror.getValue();
  61. if ( ! validate( value ) ) return;
  62. if ( typeof ( currentScript ) === 'object' ) {
  63. if ( value !== currentScript.source ) {
  64. editor.execute( new SetScriptValueCommand( editor, currentObject, currentScript, 'source', value ) );
  65. }
  66. return;
  67. }
  68. if ( currentScript !== 'programInfo' ) return;
  69. const json = JSON.parse( value );
  70. if ( JSON.stringify( currentObject.material.defines ) !== JSON.stringify( json.defines ) ) {
  71. const cmd = new SetMaterialValueCommand( editor, currentObject, 'defines', json.defines );
  72. cmd.updatable = false;
  73. editor.execute( cmd );
  74. }
  75. if ( JSON.stringify( currentObject.material.uniforms ) !== JSON.stringify( json.uniforms ) ) {
  76. const cmd = new SetMaterialValueCommand( editor, currentObject, 'uniforms', json.uniforms );
  77. cmd.updatable = false;
  78. editor.execute( cmd );
  79. }
  80. if ( JSON.stringify( currentObject.material.attributes ) !== JSON.stringify( json.attributes ) ) {
  81. const cmd = new SetMaterialValueCommand( editor, currentObject, 'attributes', json.attributes );
  82. cmd.updatable = false;
  83. editor.execute( cmd );
  84. }
  85. }, 300 );
  86. } );
  87. // prevent backspace from deleting objects
  88. const wrapper = codemirror.getWrapperElement();
  89. wrapper.addEventListener( 'keydown', function ( event ) {
  90. event.stopPropagation();
  91. } );
  92. // validate
  93. const errorLines = [];
  94. const widgets = [];
  95. const validate = function ( string ) {
  96. let valid;
  97. let errors = [];
  98. return codemirror.operation( function () {
  99. while ( errorLines.length > 0 ) {
  100. codemirror.removeLineClass( errorLines.shift(), 'background', 'errorLine' );
  101. }
  102. while ( widgets.length > 0 ) {
  103. codemirror.removeLineWidget( widgets.shift() );
  104. }
  105. //
  106. switch ( currentMode ) {
  107. case 'javascript':
  108. try {
  109. const syntax = esprima.parse( string, { tolerant: true } );
  110. errors = syntax.errors;
  111. } catch ( error ) {
  112. errors.push( {
  113. lineNumber: error.lineNumber - 1,
  114. message: error.message
  115. } );
  116. }
  117. for ( let i = 0; i < errors.length; i ++ ) {
  118. const error = errors[ i ];
  119. error.message = error.message.replace( /Line [0-9]+: /, '' );
  120. }
  121. break;
  122. case 'json':
  123. errors = [];
  124. jsonlint.parseError = function ( message, info ) {
  125. message = message.split( '\n' )[ 3 ];
  126. errors.push( {
  127. lineNumber: info.loc.first_line - 1,
  128. message: message
  129. } );
  130. };
  131. try {
  132. jsonlint.parse( string );
  133. } catch ( error ) {
  134. // ignore failed error recovery
  135. }
  136. break;
  137. case 'glsl':
  138. currentObject.material[ currentScript ] = string;
  139. currentObject.material.needsUpdate = true;
  140. signals.materialChanged.dispatch( currentObject, 0 ); // TODO: Add multi-material support
  141. const programs = renderer.info.programs;
  142. valid = true;
  143. const parseMessage = /^(?:ERROR|WARNING): \d+:(\d+): (.*)/g;
  144. for ( let i = 0, n = programs.length; i !== n; ++ i ) {
  145. const diagnostics = programs[ i ].diagnostics;
  146. if ( diagnostics === undefined ||
  147. diagnostics.material !== currentObject.material ) continue;
  148. if ( ! diagnostics.runnable ) valid = false;
  149. const shaderInfo = diagnostics[ currentScript ];
  150. const lineOffset = shaderInfo.prefix.split( /\r\n|\r|\n/ ).length;
  151. while ( true ) {
  152. const parseResult = parseMessage.exec( shaderInfo.log );
  153. if ( parseResult === null ) break;
  154. errors.push( {
  155. lineNumber: parseResult[ 1 ] - lineOffset,
  156. message: parseResult[ 2 ]
  157. } );
  158. } // messages
  159. break;
  160. } // programs
  161. } // mode switch
  162. for ( let i = 0; i < errors.length; i ++ ) {
  163. const error = errors[ i ];
  164. const message = document.createElement( 'div' );
  165. message.className = 'esprima-error';
  166. message.textContent = error.message;
  167. const lineNumber = Math.max( error.lineNumber, 0 );
  168. errorLines.push( lineNumber );
  169. codemirror.addLineClass( lineNumber, 'background', 'errorLine' );
  170. const widget = codemirror.addLineWidget( lineNumber, message );
  171. widgets.push( widget );
  172. }
  173. return valid !== undefined ? valid : errors.length === 0;
  174. } );
  175. };
  176. // tern js autocomplete
  177. const server = new CodeMirror.TernServer( {
  178. caseInsensitive: true,
  179. plugins: { threejs: null }
  180. } );
  181. codemirror.setOption( 'extraKeys', {
  182. 'Ctrl-Space': function ( cm ) {
  183. server.complete( cm );
  184. },
  185. 'Ctrl-I': function ( cm ) {
  186. server.showType( cm );
  187. },
  188. 'Ctrl-O': function ( cm ) {
  189. server.showDocs( cm );
  190. },
  191. 'Alt-.': function ( cm ) {
  192. server.jumpToDef( cm );
  193. },
  194. 'Alt-,': function ( cm ) {
  195. server.jumpBack( cm );
  196. },
  197. 'Ctrl-Q': function ( cm ) {
  198. server.rename( cm );
  199. },
  200. 'Ctrl-.': function ( cm ) {
  201. server.selectName( cm );
  202. }
  203. } );
  204. codemirror.on( 'cursorActivity', function ( cm ) {
  205. if ( currentMode !== 'javascript' ) return;
  206. server.updateArgHints( cm );
  207. } );
  208. codemirror.on( 'keypress', function ( cm, kb ) {
  209. if ( currentMode !== 'javascript' ) return;
  210. if ( /[\w\.]/.exec( kb.key ) ) {
  211. server.complete( cm );
  212. }
  213. } );
  214. //
  215. signals.editorCleared.add( function () {
  216. container.setDisplay( 'none' );
  217. } );
  218. function setTitle( object, script ) {
  219. if ( typeof script === 'object' ) {
  220. title.setValue( object.name + ' / ' + script.name );
  221. } else {
  222. switch ( script ) {
  223. case 'vertexShader':
  224. title.setValue( object.material.name + ' / ' + strings.getKey( 'script/title/vertexShader' ) );
  225. break;
  226. case 'fragmentShader':
  227. title.setValue( object.material.name + ' / ' + strings.getKey( 'script/title/fragmentShader' ) );
  228. break;
  229. case 'programInfo':
  230. title.setValue( object.material.name + ' / ' + strings.getKey( 'script/title/programInfo' ) );
  231. break;
  232. default:
  233. throw new Error( 'setTitle: Unknown script' );
  234. }
  235. }
  236. }
  237. signals.editScript.add( function ( object, script ) {
  238. let mode, source;
  239. if ( typeof ( script ) === 'object' ) {
  240. mode = 'javascript';
  241. source = script.source;
  242. } else {
  243. switch ( script ) {
  244. case 'vertexShader':
  245. mode = 'glsl';
  246. source = object.material.vertexShader || '';
  247. break;
  248. case 'fragmentShader':
  249. mode = 'glsl';
  250. source = object.material.fragmentShader || '';
  251. break;
  252. case 'programInfo':
  253. mode = 'json';
  254. const json = {
  255. defines: object.material.defines,
  256. uniforms: object.material.uniforms,
  257. attributes: object.material.attributes
  258. };
  259. source = JSON.stringify( json, null, '\t' );
  260. break;
  261. default:
  262. throw new Error( 'editScript: Unknown script' );
  263. }
  264. }
  265. setTitle( object, script );
  266. currentMode = mode;
  267. currentScript = script;
  268. currentObject = object;
  269. container.setDisplay( '' );
  270. codemirror.setValue( source );
  271. codemirror.clearHistory();
  272. if ( mode === 'json' ) mode = { name: 'javascript', json: true };
  273. codemirror.setOption( 'mode', mode );
  274. } );
  275. signals.scriptRemoved.add( function ( script ) {
  276. if ( currentScript === script ) {
  277. container.setDisplay( 'none' );
  278. }
  279. } );
  280. signals.objectChanged.add( function ( object ) {
  281. if ( object !== currentObject ) return;
  282. if ( [ 'programInfo', 'vertexShader', 'fragmentShader' ].includes( currentScript ) ) return;
  283. setTitle( currentObject, currentScript );
  284. } );
  285. signals.scriptChanged.add( function ( script ) {
  286. if ( script === currentScript ) {
  287. setTitle( currentObject, currentScript );
  288. }
  289. } );
  290. signals.materialChanged.add( function ( object, slot ) {
  291. if ( object !== currentObject ) return;
  292. // TODO: Adds multi-material support
  293. setTitle( currentObject, currentScript );
  294. } );
  295. return container;
  296. }
  297. export { Script };