ok, then I'm either blind, or too fubar as a result of twice working until 04:00 on a row :p
Exqueeze me for the bmax, I intended the topic to be only math-related, which is why I placed it in general. Tho, this code is quite generic.., could be readable by all.
SuperStrict
Local window:TGadget=CreateWindow("colorconverter",0,0,800,600)
Local canvas:TGadget=CreateCanvas(0,0,16*16,16*16,window)
Local canvas2:TGadget=CreateCanvas(300,0,16*16,16*16,window)
Local im:Int[16,16] ' <- original image, contains rgb data
Local im2:Int[16,16] ' <- destination image, will contain palette indexes
Local paletteR:Int[8]
Local paletteG:Int[8]
Local paletteB:Int[8]
' black red green blue yellow lightblue purple white
paletteR[1]=255
paletteG[2]=255
paletteB[3]=255
paletteR[4]=255
paletteG[5]=255
paletteB[6]=255
paletteG[4]=255
paletteB[5]=255
paletteR[6]=255
paletteR[7]=255
paletteG[7]=255
paletteB[7]=255
Local r:Int,g:Int,b:Int
Local t:Int
Local x:Int
Local y:Int
' create some pic
For y=0 To 15
For x=0 To 15
im[x,y]=(Limit(x*24,0,255))+256*Limit(y*24,0,255)+65536*Limit(128+Sin(y*70)*140,0,255)
Next
Next
Local varbest:Int
Local indexbest:Int=10000
Local varr:Int,varg:Int,varb:Int,varmax:Int
For y=0 To 15
For x=0 To 15
' a pixel
r=(im[x,y] Shr 16) & $ff
g=(im[x,y] Shr 8) & $ff
b=(im[x,y] ) & $ff
varbest=0
indexbest=10000
For t=0 To 7
' a palette color
varr=Abs(r-paletteR[t])
varg=Abs(g-paletteG[t])
varb=Abs(b-paletteB[t])
varmax=Max(varr,Max(varg,varb))
If varmax<varbest
indexbest=t
varbest=varmax
EndIf
Next
' DebugLog indexbest
indexbest=Min(indexbest,7)
im2[x,y]=indexbest
Next
Next
' update
SetCanvas canvas ' original image
For y=0 To 15
For x=0 To 15
r=(im[x,y] Shr 16) & $ff
g=(im[x,y] Shr 8) & $ff
b=(im[x,y] ) & $ff
SetColor r,g,b
DrawRect x*16,y*16,16,16
Next
Next
Flip
SetCanvas canvas2 ' newly built image
For y=0 To 15
For x=0 To 15
r=paletteR[ im2[x,y] ]
g=paletteG[ im2[x,y] ]
b=paletteB[ im2[x,y] ]
SetColor r,g,b
DrawRect x*16,y*16,16,16
Next
Next
Flip
Repeat
WaitEvent()
If EventID()=EVENT_WINDOWCLOSE End
Forever
Function Limit:Int(v:Int,lo:Int,hi:Int)
If v<lo Return lo
If v>hi Return hi
Return v
End Function
Function SetCanvas(c:TGadget)
SetGraphics CanvasGraphics(c)
End Function
Don't mind the sloppyness of the structure, it's purely intended as quick hack to test it. If you must fix things: don't just replace whole chunks with own routiness, I wish to see thing fixed in my code.. :)