1- import fs from "node:fs" ;
2- import path from "node:path" ;
31import { execFileSync } from "node:child_process" ;
2+ import fs from "node:fs" ;
43import { tmpdir } from "node:os" ;
5- import { createCanvas } from "canvas" ;
6- import { Grid , copyGrid , Color } from "@snk/types/grid" ;
7- import { Snake } from "@snk/types/snake" ;
4+ import path from "node:path" ;
85import {
96 type Options as DrawOptions ,
107 drawLerpWorld ,
118 getCanvasWorldSize ,
129} from "@snk/draw/drawWorld" ;
13- import type { Point } from "@snk/types/point" ;
1410import { step } from "@snk/solver/step" ;
15- import gifsicle from "gifsicle" ;
11+ import { Color , copyGrid , Grid } from "@snk/types/grid" ;
12+ import type { Point } from "@snk/types/point" ;
13+ import { Snake } from "@snk/types/snake" ;
14+ import { createCanvas } from "canvas" ;
1615// @ts -ignore
1716import GIFEncoder from "gif-encoder-2" ;
17+ import gifsicle from "gifsicle" ;
1818
1919export type { Options as DrawOptions } from "@snk/draw/drawWorld" ;
2020
@@ -78,6 +78,38 @@ export const createGif = async (
7878 const outFileName = path . join ( dir , "out.gif" ) ;
7979 const optimizedFileName = path . join ( dir , "out.optimized.gif" ) ;
8080
81+ // generate palette file
82+ const paletteFileName = path . join ( dir , "palette.txt" ) ;
83+ {
84+ const colors = [
85+ drawOptions . colorBackground ,
86+ drawOptions . colorEmpty ,
87+ drawOptions . colorSnake ,
88+ drawOptions . colorDotBorder ,
89+ ...Object . values ( drawOptions . colorDots ) ,
90+ ] . filter ( Boolean ) as string [ ] ;
91+
92+ const canvas = createCanvas ( colors . length , 1 ) ;
93+ const ctx = canvas . getContext ( "2d" ) as any as CanvasRenderingContext2D ;
94+ for ( let i = colors . length ; i -- ; ) {
95+ ctx . fillStyle = colors [ i ] ;
96+ ctx . fillRect ( i , 0 , 1 , 1 ) ;
97+ }
98+
99+ const imgData = ctx . getImageData ( 0 , 0 , colors . length , 1 ) ;
100+
101+ fs . writeFileSync (
102+ paletteFileName ,
103+ Array . from ( { length : colors . length } , ( _ , i ) =>
104+ [
105+ imgData . data [ i * 4 + 0 ] ,
106+ imgData . data [ i * 4 + 1 ] ,
107+ imgData . data [ i * 4 + 2 ] ,
108+ ] . join ( " " ) ,
109+ ) . join ( "\n" ) ,
110+ ) ;
111+ }
112+
81113 encoder . finish ( ) ;
82114 fs . writeFileSync ( outFileName , encoder . out . getData ( ) ) ;
83115
@@ -87,7 +119,8 @@ export const createGif = async (
87119 //
88120 "--optimize=3" ,
89121 "--color-method=diversity" ,
90- "--colors=16" ,
122+ `--use-colormap=${ paletteFileName } ` ,
123+ // "--colors=16",
91124 outFileName ,
92125 [ "--output" , optimizedFileName ] ,
93126 ] . flat ( ) ,
0 commit comments