GCodeLoader.js 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. import {
  2. BufferGeometry,
  3. FileLoader,
  4. Float32BufferAttribute,
  5. Group,
  6. LineBasicMaterial,
  7. LineSegments,
  8. Loader
  9. } from 'three';
  10. /**
  11. * A loader for the GCode format.
  12. *
  13. * GCode files are usually used for 3D printing or CNC applications.
  14. *
  15. * ```js
  16. * const loader = new GCodeLoader();
  17. * const object = await loader.loadAsync( 'models/gcode/benchy.gcode' );
  18. * scene.add( object );
  19. * ```
  20. *
  21. * @augments Loader
  22. * @three_import import { GCodeLoader } from 'three/addons/loaders/GCodeLoader.js';
  23. */
  24. class GCodeLoader extends Loader {
  25. /**
  26. * Constructs a new GCode loader.
  27. *
  28. * @param {LoadingManager} [manager] - The loading manager.
  29. */
  30. constructor( manager ) {
  31. super( manager );
  32. /**
  33. * Whether to split layers or not.
  34. *
  35. * @type {boolean}
  36. * @default false
  37. */
  38. this.splitLayer = false;
  39. }
  40. /**
  41. * Starts loading from the given URL and passes the loaded GCode asset
  42. * to the `onLoad()` callback.
  43. *
  44. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  45. * @param {function(Group)} onLoad - Executed when the loading process has been finished.
  46. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  47. * @param {onErrorCallback} onError - Executed when errors occur.
  48. */
  49. load( url, onLoad, onProgress, onError ) {
  50. const scope = this;
  51. const loader = new FileLoader( scope.manager );
  52. loader.setPath( scope.path );
  53. loader.setRequestHeader( scope.requestHeader );
  54. loader.setWithCredentials( scope.withCredentials );
  55. loader.load( url, function ( text ) {
  56. try {
  57. onLoad( scope.parse( text ) );
  58. } catch ( e ) {
  59. if ( onError ) {
  60. onError( e );
  61. } else {
  62. console.error( e );
  63. }
  64. scope.manager.itemError( url );
  65. }
  66. }, onProgress, onError );
  67. }
  68. /**
  69. * Parses the given GCode data and returns a group with lines.
  70. *
  71. * @param {string} data - The raw Gcode data as a string.
  72. * @return {Group} The parsed GCode asset.
  73. */
  74. parse( data ) {
  75. let state = { x: 0, y: 0, z: 0, e: 0, f: 0, extruding: false, relative: false, extrusionOverride: false, extrusionRelative: false };
  76. const layers = [];
  77. let currentLayer = undefined;
  78. const pathMaterial = new LineBasicMaterial( { color: 0xFF0000 } );
  79. pathMaterial.name = 'path';
  80. const extrudingMaterial = new LineBasicMaterial( { color: 0x00FF00 } );
  81. extrudingMaterial.name = 'extruded';
  82. function newLayer( line ) {
  83. currentLayer = { vertex: [], pathVertex: [], z: line.z };
  84. layers.push( currentLayer );
  85. }
  86. //Create lie segment between p1 and p2
  87. function addSegment( p1, p2 ) {
  88. if ( currentLayer === undefined ) {
  89. newLayer( p1 );
  90. }
  91. if ( state.extruding ) {
  92. currentLayer.vertex.push( p1.x, p1.y, p1.z );
  93. currentLayer.vertex.push( p2.x, p2.y, p2.z );
  94. } else {
  95. currentLayer.pathVertex.push( p1.x, p1.y, p1.z );
  96. currentLayer.pathVertex.push( p2.x, p2.y, p2.z );
  97. }
  98. }
  99. function delta( v1, v2 ) {
  100. return state.relative ? v2 : v2 - v1;
  101. }
  102. function absolute( v1, v2 ) {
  103. return state.relative ? v1 + v2 : v2;
  104. }
  105. function absoluteExtrusion( v1, v2 ) {
  106. const relative = state.extrusionOverride ? state.extrusionRelative : state.relative;
  107. return relative ? v1 + v2 : v2;
  108. }
  109. const lines = data.replace( /;.+/g, '' ).split( '\n' );
  110. for ( let i = 0; i < lines.length; i ++ ) {
  111. const tokens = lines[ i ].split( ' ' );
  112. const cmd = tokens[ 0 ].toUpperCase();
  113. //Arguments
  114. const args = {};
  115. tokens.splice( 1 ).forEach( function ( token ) {
  116. if ( token[ 0 ] !== undefined ) {
  117. const key = token[ 0 ].toLowerCase();
  118. const value = parseFloat( token.substring( 1 ) );
  119. args[ key ] = value;
  120. }
  121. } );
  122. //Process commands
  123. //G0/G1 – Linear Movement
  124. if ( cmd === 'G0' || cmd === 'G1' ) {
  125. const line = Object.assign( {}, state ); // clone state
  126. if ( args.x !== undefined ) line.x = absolute( state.x, args.x );
  127. if ( args.y !== undefined ) line.y = absolute( state.y, args.y );
  128. if ( args.z !== undefined ) line.z = absolute( state.z, args.z );
  129. if ( args.e !== undefined ) line.e = absoluteExtrusion( state.e, args.e );
  130. if ( args.f !== undefined ) line.f = absolute( state.f, args.f );
  131. //Layer change detection is or made by watching Z, it's made by watching when we extrude at a new Z position
  132. if ( delta( state.e, line.e ) > 0 ) {
  133. state.extruding = delta( state.e, line.e ) > 0;
  134. if ( currentLayer == undefined || line.z != currentLayer.z ) {
  135. newLayer( line );
  136. }
  137. }
  138. addSegment( state, line );
  139. state = line;
  140. } else if ( cmd === 'G2' || cmd === 'G3' ) {
  141. //G2/G3 - Arc Movement ( G2 clock wise and G3 counter clock wise )
  142. //console.warn( 'THREE.GCodeLoader: Arc command not supported' );
  143. } else if ( cmd === 'G90' ) {
  144. //G90: Set to Absolute Positioning
  145. state.relative = false;
  146. // reset M82/M83 extrusion override
  147. state.extrusionOverride = false;
  148. } else if ( cmd === 'G91' ) {
  149. //G91: Set to state.relative Positioning
  150. state.relative = true;
  151. // reset M82/M83 extrusion override
  152. state.extrusionOverride = false;
  153. } else if ( cmd === 'M82' ) {
  154. //M82: Override G91 and put the E axis into absolute mode independent of the other axes
  155. state.extrusionOverride = true;
  156. state.extrusionRelative = false;
  157. } else if ( cmd === 'M83' ) {
  158. //M83: Overrides G90 and put the E axis into relative mode independent of the other axes
  159. state.extrusionOverride = true;
  160. state.extrusionRelative = true;
  161. } else if ( cmd === 'G92' ) {
  162. //G92: Set Position
  163. const line = state;
  164. line.x = args.x !== undefined ? args.x : line.x;
  165. line.y = args.y !== undefined ? args.y : line.y;
  166. line.z = args.z !== undefined ? args.z : line.z;
  167. line.e = args.e !== undefined ? args.e : line.e;
  168. } else {
  169. //console.warn( 'THREE.GCodeLoader: Command not supported:' + cmd );
  170. }
  171. }
  172. function addObject( vertex, extruding, i ) {
  173. const geometry = new BufferGeometry();
  174. geometry.setAttribute( 'position', new Float32BufferAttribute( vertex, 3 ) );
  175. const segments = new LineSegments( geometry, extruding ? extrudingMaterial : pathMaterial );
  176. segments.name = 'layer' + i;
  177. object.add( segments );
  178. }
  179. const object = new Group();
  180. object.name = 'gcode';
  181. if ( this.splitLayer ) {
  182. for ( let i = 0; i < layers.length; i ++ ) {
  183. const layer = layers[ i ];
  184. addObject( layer.vertex, true, i );
  185. addObject( layer.pathVertex, false, i );
  186. }
  187. } else {
  188. const vertex = [],
  189. pathVertex = [];
  190. for ( let i = 0; i < layers.length; i ++ ) {
  191. const layer = layers[ i ];
  192. const layerVertex = layer.vertex;
  193. const layerPathVertex = layer.pathVertex;
  194. for ( let j = 0; j < layerVertex.length; j ++ ) {
  195. vertex.push( layerVertex[ j ] );
  196. }
  197. for ( let j = 0; j < layerPathVertex.length; j ++ ) {
  198. pathVertex.push( layerPathVertex[ j ] );
  199. }
  200. }
  201. addObject( vertex, true, layers.length );
  202. addObject( pathVertex, false, layers.length );
  203. }
  204. object.rotation.set( - Math.PI / 2, 0, 0 );
  205. return object;
  206. }
  207. }
  208. export { GCodeLoader };
粤ICP备19079148号