GcodeViewer.tsx 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  1. import { useEffect, useRef, useState, useCallback, useMemo } from 'react';
  2. import { WebGLPreview } from 'gcode-preview';
  3. import { Loader2, Layers, ChevronLeft, ChevronRight, FileWarning } from 'lucide-react';
  4. interface GcodeViewerProps {
  5. gcodeUrl: string;
  6. buildVolume?: { x: number; y: number; z: number };
  7. filamentColors?: string[];
  8. className?: string;
  9. }
  10. export function GcodeViewer({
  11. gcodeUrl,
  12. buildVolume = { x: 256, y: 256, z: 256 },
  13. filamentColors,
  14. className = ''
  15. }: GcodeViewerProps) {
  16. const canvasRef = useRef<HTMLCanvasElement>(null);
  17. const previewRef = useRef<WebGLPreview | null>(null);
  18. const renderTimeoutRef = useRef<number | null>(null);
  19. const initRef = useRef(false);
  20. const [loading, setLoading] = useState(true);
  21. const [error, setError] = useState<string | null>(null);
  22. const [notSliced, setNotSliced] = useState(false);
  23. const [currentLayer, setCurrentLayer] = useState(0);
  24. const [totalLayers, setTotalLayers] = useState(0);
  25. // Memoize colors to prevent re-renders
  26. const colorsKey = useMemo(() => JSON.stringify(filamentColors), [filamentColors]);
  27. useEffect(() => {
  28. if (!canvasRef.current || initRef.current) return;
  29. initRef.current = true;
  30. const canvas = canvasRef.current;
  31. // Set canvas size before creating preview
  32. const rect = canvas.parentElement?.getBoundingClientRect();
  33. if (rect) {
  34. canvas.width = rect.width;
  35. canvas.height = rect.height;
  36. }
  37. // Use extrusionColor as array for multi-tool support
  38. // Index in array = tool number
  39. const hasMultiColor = filamentColors && filamentColors.length > 1;
  40. const primaryColor = filamentColors?.[0] || '#00ae42';
  41. // Create preview
  42. const preview = new WebGLPreview({
  43. canvas,
  44. buildVolume,
  45. backgroundColor: 0x1a1a1a,
  46. // Pass full color array - library uses index as tool number
  47. extrusionColor: hasMultiColor ? filamentColors : primaryColor,
  48. disableGradient: true,
  49. lineHeight: 0.2,
  50. lineWidth: 2,
  51. renderTravel: false,
  52. renderExtrusion: true,
  53. });
  54. previewRef.current = preview;
  55. // Fetch and process gcode
  56. fetch(gcodeUrl)
  57. .then(async response => {
  58. if (!response.ok) {
  59. if (response.status === 404) {
  60. const data = await response.json().catch(() => ({}));
  61. if (data.detail?.includes('sliced')) {
  62. setNotSliced(true);
  63. throw new Error('not_sliced');
  64. }
  65. }
  66. throw new Error('Failed to load G-code');
  67. }
  68. return response.text();
  69. })
  70. .then(gcode => {
  71. // The gcode-preview library only supports T0-T7
  72. // We need to remap higher tool numbers to fit within this range
  73. // First, find all unique tool numbers used
  74. const toolNumbers = new Set<number>();
  75. const toolRegex = /^(\s*)T(\d+)(\s*;.*)?$/gim;
  76. let match;
  77. while ((match = toolRegex.exec(gcode)) !== null) {
  78. const toolNum = parseInt(match[2], 10);
  79. if (toolNum <= 15) { // Valid tool, not a special command
  80. toolNumbers.add(toolNum);
  81. }
  82. }
  83. // Create a mapping from original tool numbers to 0-7 range
  84. const toolMapping = new Map<number, number>();
  85. const sortedTools = Array.from(toolNumbers).sort((a, b) => a - b);
  86. sortedTools.forEach((tool, index) => {
  87. toolMapping.set(tool, index % 8); // Map to 0-7
  88. });
  89. // Build remapped color array based on the mapping
  90. const remappedColors: string[] = [];
  91. sortedTools.forEach((originalTool, index) => {
  92. const color = filamentColors?.[originalTool] || '#00ae42';
  93. remappedColors[index % 8] = color;
  94. });
  95. // Process gcode: filter special commands and remap tool numbers
  96. const cleanedGcode = gcode
  97. .split('\n')
  98. .map(line => {
  99. const match = line.match(/^(\s*)T(\d+)(\s*;.*)?$/i);
  100. if (match) {
  101. const toolNum = parseInt(match[2], 10);
  102. if (toolNum > 15) {
  103. // Filter out Bambu special commands (T255, T1000, T65535, etc.)
  104. return `; FILTERED: ${line.trim()}`;
  105. }
  106. // Remap tool number to 0-7 range
  107. const mappedTool = toolMapping.get(toolNum) ?? 0;
  108. return `${match[1]}T${mappedTool}${match[3] || ''}`;
  109. }
  110. return line;
  111. })
  112. .join('\n');
  113. // Update colors for the preview using the remapped array
  114. if (remappedColors.length > 0) {
  115. (preview as unknown as { extrusionColor: string[] }).extrusionColor = remappedColors;
  116. }
  117. preview.processGCode(cleanedGcode);
  118. const layers = preview.layers?.length || 0;
  119. setTotalLayers(layers);
  120. setCurrentLayer(layers);
  121. preview.render();
  122. setLoading(false);
  123. })
  124. .catch(err => {
  125. if (err.message !== 'not_sliced') {
  126. setError(err.message);
  127. }
  128. setLoading(false);
  129. });
  130. // Handle resize
  131. const handleResize = () => {
  132. if (canvas.parentElement && previewRef.current) {
  133. const newRect = canvas.parentElement.getBoundingClientRect();
  134. canvas.width = newRect.width;
  135. canvas.height = newRect.height;
  136. previewRef.current.resize();
  137. }
  138. };
  139. window.addEventListener('resize', handleResize);
  140. return () => {
  141. window.removeEventListener('resize', handleResize);
  142. if (renderTimeoutRef.current) {
  143. cancelAnimationFrame(renderTimeoutRef.current);
  144. }
  145. if (previewRef.current) {
  146. previewRef.current.dispose();
  147. previewRef.current = null;
  148. }
  149. initRef.current = false;
  150. };
  151. // eslint-disable-next-line react-hooks/exhaustive-deps
  152. }, [gcodeUrl, colorsKey]); // Intentionally use colorsKey instead of filamentColors, buildVolume rarely changes
  153. const handleLayerChange = useCallback((layer: number) => {
  154. if (!previewRef.current) return;
  155. const newLayer = Math.max(1, Math.min(layer, totalLayers));
  156. setCurrentLayer(newLayer);
  157. if (renderTimeoutRef.current) {
  158. cancelAnimationFrame(renderTimeoutRef.current);
  159. }
  160. renderTimeoutRef.current = requestAnimationFrame(() => {
  161. if (previewRef.current) {
  162. previewRef.current.endLayer = newLayer;
  163. previewRef.current.render();
  164. }
  165. });
  166. }, [totalLayers]);
  167. const handleSliderChange = (e: React.ChangeEvent<HTMLInputElement>) => {
  168. handleLayerChange(parseInt(e.target.value, 10));
  169. };
  170. return (
  171. <div className={`relative flex flex-col h-full ${className}`}>
  172. <div className="flex-1 relative bg-bambu-dark rounded-lg overflow-hidden">
  173. <canvas ref={canvasRef} className="w-full h-full" />
  174. {loading && (
  175. <div className="absolute inset-0 flex items-center justify-center bg-bambu-dark/80">
  176. <div className="text-center">
  177. <Loader2 className="w-8 h-8 animate-spin text-bambu-green mx-auto mb-2" />
  178. <p className="text-bambu-gray text-sm">Loading G-code...</p>
  179. </div>
  180. </div>
  181. )}
  182. {notSliced && (
  183. <div className="absolute inset-0 flex items-center justify-center bg-bambu-dark/80">
  184. <div className="text-center max-w-sm px-4">
  185. <FileWarning className="w-12 h-12 text-bambu-gray mx-auto mb-3" />
  186. <p className="text-white font-medium mb-2">G-code not available</p>
  187. <p className="text-bambu-gray text-sm">
  188. This file hasn't been sliced yet. G-code preview is only available
  189. after slicing in Bambu Studio or Orca Slicer.
  190. </p>
  191. </div>
  192. </div>
  193. )}
  194. {error && !notSliced && (
  195. <div className="absolute inset-0 flex items-center justify-center bg-bambu-dark/80">
  196. <div className="text-center text-red-400">
  197. <p className="text-sm">{error}</p>
  198. </div>
  199. </div>
  200. )}
  201. </div>
  202. {!loading && !error && !notSliced && totalLayers > 0 && (
  203. <div className="mt-4 px-2">
  204. <div className="flex items-center gap-3">
  205. <Layers className="w-4 h-4 text-bambu-gray flex-shrink-0" />
  206. <button
  207. onClick={() => handleLayerChange(currentLayer - 1)}
  208. disabled={currentLayer <= 1}
  209. className="p-1 rounded hover:bg-bambu-dark-tertiary disabled:opacity-30 disabled:cursor-not-allowed"
  210. >
  211. <ChevronLeft className="w-4 h-4" />
  212. </button>
  213. <input
  214. type="range"
  215. min={1}
  216. max={totalLayers}
  217. value={currentLayer}
  218. onChange={handleSliderChange}
  219. className="flex-1 h-2 bg-bambu-dark-tertiary rounded-lg appearance-none cursor-pointer accent-bambu-green"
  220. />
  221. <button
  222. onClick={() => handleLayerChange(currentLayer + 1)}
  223. disabled={currentLayer >= totalLayers}
  224. className="p-1 rounded hover:bg-bambu-dark-tertiary disabled:opacity-30 disabled:cursor-not-allowed"
  225. >
  226. <ChevronRight className="w-4 h-4" />
  227. </button>
  228. <span className="text-sm text-bambu-gray min-w-[80px] text-right">
  229. {currentLayer} / {totalLayers}
  230. </span>
  231. </div>
  232. </div>
  233. )}
  234. </div>
  235. );
  236. }