Linear interpolation for RGBA

Share your advanced PureBasic knowledge/code with the community.
Mistrel
Addict
Addict
Posts: 3415
Joined: Sat Jun 30, 2007 8:04 pm

Linear interpolation for RGBA

Post by Mistrel »

Code: Select all

Procedure linearInterpolateRGBA(color1, color2, t.f)
  Protected aR.f=Red(color1)/255.0
  Protected aG.f=Green(color1)/255.0
  Protected aB.f=Blue(color1)/255.0
  Protected aA.f=Alpha(color1)/255.0
  
  Protected bR.f=Red(color2)/255.0
  Protected bG.f=Green(color2)/255.0
  Protected bB.f=Blue(color2)/255.0
  Protected bA.f=Alpha(color2)/255.0
  
  Protected r.f=aR.f+((bR.f-aR.f)*t.f)
  Protected g.f=aG.f+((bG.f-aG.f)*t.f)
  Protected b.f=aB.f+((bB.f-aB.f)*t.f)
  Protected a.f=aA.f+((bA.f-aA.f)*t.f)
  
	ProcedureReturn RGBA(r.f*255,g.f*255,b.f*255,a.f*255)
EndProcedure
Or more succinctly:

Code: Select all

Procedure linearInterpolateRGBA(color1, color2, t.f)
  Protected a.f, b.f, temp
  
  For i=1 To 4
    temp=color1&$FF
    a.f=temp/255.0
    temp=color2&$FF
    b.f=temp/255.0
    
    color1=(color1&$FFFFFF00)+((a.f+((b.f-a.f)*t.f))*255)
    
    color1=color1<<8|((color1>>24)&$FF)
    color2=color2<<8|((color2>>24)&$FF)
  Next i
  
  ProcedureReturn color1
EndProcedure
There are a lot of ways to do this. I had fun with the second one.

Note that it could be shorted and without the temp variable but we are unable to do this:

Code: Select all

a.f=color1&$FF/255.0
Because of this issue:
viewtopic.php?f=13&t=64515

Example:

Code: Select all

window=OpenWindow(#PB_Any,0,0,320,240,"")
StartDrawing(WindowOutput(window))

r1=RGB(255,0,0)
r2=RGB(0,0,0)
g1=RGB(0,255,0)
g2=RGB(0,0,0)
b1=RGB(0,0,255)
b2=RGB(0,0,0)

steps.f=10
w=WindowWidth(window)/steps.f
h=WindowHeight(window)/3

For i=0 To steps.f-1
  Box(i*w,0,w,h,linearInterpolateRGBA(r1,r2,i/steps.f))
  Box(i*w,h,w,h,linearInterpolateRGBA(g1,g2,i/steps.f))
  Box(i*w,h*2,w,h,linearInterpolateRGBA(b1,b2,i/steps.f))
Next i

StopDrawing()

Repeat
Until WaitWindowEvent()=#PB_Event_CloseWindow
User avatar
Tenaja
Addict
Addict
Posts: 1948
Joined: Tue Nov 09, 2010 10:15 pm

Re: Linear interpolation for RGBA

Post by Tenaja »

but we are unable to do this:
a.f=color1&$FF/255.0
Have you tried this?

a.f=(color1&$FF)/(255.0)
Mistrel
Addict
Addict
Posts: 3415
Joined: Sat Jun 30, 2007 8:04 pm

Re: Linear interpolation for RGBA

Post by Mistrel »

Tenaja wrote:Have you tried this?

a.f=(color1&$FF)/(255.0)
Can't use any of the following operands with floats: <<, >>, &, |, !, %.
You would think that we could do this but we cannot.

It probably has to do with the early type promotion done in PureBasic. I suspect that changing this might induce some bugs if it somehow alters traditional behavior unexpectedly. It would definitely require testing:

Code: Select all

a.f=1/2

Debug 1/2
Debug a.f
Output:

Code: Select all

0
0.5
Post Reply