affine: Bug fix: ColorM.Apply was wrong when alpha is 0

This commit is contained in:
Hajime Hoshi 2018-02-27 12:16:16 +09:00
parent e96d2295bf
commit 3f5fba34da
2 changed files with 23 additions and 14 deletions

View File

@ -169,11 +169,11 @@ func TestColorMConcatSelf(t *testing.T) {
}
}
func absU32(x uint32) uint32 {
if x < 0 {
return -x
func absDiffU32(x, y uint32) uint32 {
if x < y {
return y - x
}
return x
return x - y
}
func TestColorMApply(t *testing.T) {
@ -183,6 +183,9 @@ func TestColorMApply(t *testing.T) {
shiny := ColorM{}
shiny.Translate(1, 1, 1, 0)
shift := ColorM{}
shift.Translate(0.5, 0.5, 0.5, 0.5)
cases := []struct {
ColorM ColorM
In color.Color
@ -213,15 +216,20 @@ func TestColorMApply(t *testing.T) {
Out: color.RGBA{0xb0, 0xb0, 0xb0, 0xb0},
Delta: 1,
},
{
ColorM: shift,
In: color.RGBA{0x00, 0x00, 0x00, 0x00},
Out: color.RGBA{0x40, 0x40, 0x40, 0x80},
Delta: 0x101,
},
}
for _, c := range cases {
out := c.ColorM.Apply(c.In)
r0, g0, b0, a0 := out.RGBA()
r1, g1, b1, a1 := c.Out.RGBA()
if absU32(r0-r1) > c.Delta || absU32(g0-g1) > c.Delta ||
absU32(b0-b1) > c.Delta || absU32(a0-a1) > c.Delta {
println(r0, r1)
t.Errorf("%v.Apply(%v) = %v, want %v", c.ColorM, c.In, out, c.Out)
if absDiffU32(r0, r1) > c.Delta || absDiffU32(g0, g1) > c.Delta ||
absDiffU32(b0, b1) > c.Delta || absDiffU32(a0, a1) > c.Delta {
t.Errorf("%v.Apply(%v) = {%d, %d, %d, %d}, want {%d, %d, %d, %d}", c.ColorM, c.In, r0, g0, b0, a0, r1, g1, b1, a1)
}
}
}

View File

@ -64,13 +64,14 @@ func (c *ColorM) Apply(clr color.Color) color.Color {
return clr
}
r, g, b, a := clr.RGBA()
if a == 0 {
return color.Transparent
rf, gf, bf, af := 0.0, 0.0, 0.0, 0.0
// Unmultiply alpha
if a > 0 {
rf = float64(r) / float64(a)
gf = float64(g) / float64(a)
bf = float64(b) / float64(a)
af = float64(a) / 0xffff
}
rf := float64(r) / float64(a)
gf := float64(g) / float64(a)
bf := float64(b) / float64(a)
af := float64(a) / 0xffff
e := c.elements
rf2 := e[0]*rf + e[1]*gf + e[2]*bf + e[3]*af + e[4]
gf2 := e[5]*rf + e[6]*gf + e[7]*bf + e[8]*af + e[9]