* Build an output palette of 'maxcol' entries: * - slots 0-15: fixed AMIV UI colors * - slots 16+: tile colors from the BMP * * Returns remap[0..nsrc-1] mapping BMP palette index * to output palette index. */
| 218 | * to output palette index. |
| 219 | */ |
| 220 | static void |
| 221 | build_palette(const RGB *src, int nsrc, |
| 222 | const uint8_t *pix, int npix, |
| 223 | int maxcol, |
| 224 | RGB *out, int *remap) |
| 225 | { |
| 226 | int freq[256] = {0}; |
| 227 | int order[256]; |
| 228 | int i, j, nfree, nuniq; |
| 229 | |
| 230 | /* count pixel frequency per BMP palette entry */ |
| 231 | for (i = 0; i < npix; i++) |
| 232 | freq[pix[i]]++; |
| 233 | |
| 234 | /* sort BMP colors by frequency (descending) */ |
| 235 | for (i = 0; i < nsrc; i++) order[i] = i; |
| 236 | for (i = 1; i < nsrc; i++) { |
| 237 | int k = order[i], kf = freq[k]; |
| 238 | j = i - 1; |
| 239 | while (j >= 0 && freq[order[j]] < kf) { |
| 240 | order[j+1] = order[j]; |
| 241 | j--; |
| 242 | } |
| 243 | order[j+1] = k; |
| 244 | } |
| 245 | |
| 246 | /* count unique colors actually used */ |
| 247 | nuniq = 0; |
| 248 | for (i = 0; i < nsrc; i++) |
| 249 | if (freq[i] > 0) nuniq++; |
| 250 | |
| 251 | /* first 16 slots are AMIV UI */ |
| 252 | for (i = 0; i < 16 && i < maxcol; i++) |
| 253 | out[i] = amiv_pal[i]; |
| 254 | for (i = 16; i < maxcol; i++) |
| 255 | memset(&out[i], 0, sizeof(RGB)); |
| 256 | |
| 257 | nfree = maxcol - 16; |
| 258 | if (nfree < 0) nfree = 0; |
| 259 | |
| 260 | /* |
| 261 | * Case 1: enough free slots for all unique colors. |
| 262 | * Assign each unique BMP color its own pen, exact |
| 263 | * AMIV matches share the UI pen. |
| 264 | */ |
| 265 | if (nuniq <= nfree) { |
| 266 | int next = 16; |
| 267 | for (i = 0; i < nsrc; i++) { |
| 268 | if (freq[i] == 0) { |
| 269 | remap[i] = 0; |
| 270 | continue; |
| 271 | } |
| 272 | /* exact match to an AMIV pen? */ |
| 273 | int best = nearest(&src[i], amiv_pal, 16); |
| 274 | if (coldist(&src[i], &amiv_pal[best]) == 0) { |
| 275 | remap[i] = best; |
| 276 | } else { |
| 277 | remap[i] = next; |