mirror of
https://bitbucket.org/s_l_teichmann/mtsatellite
synced 2024-11-08 11:10:27 +01:00
1c530a2ce7
to determine if a color index corresponds to a transparent color.
84 lines
1.7 KiB
Go
84 lines
1.7 KiB
Go
// Copyright 2014 by Sascha L. Teichmann
|
|
// Use of this source code is governed by the MIT license
|
|
// that can be found in the LICENSE file.
|
|
|
|
package common
|
|
|
|
import (
|
|
"bufio"
|
|
"fmt"
|
|
"image/color"
|
|
"os"
|
|
"sort"
|
|
"strings"
|
|
)
|
|
|
|
type Colors struct {
|
|
Colors []color.RGBA
|
|
NameIndex map[string]int32
|
|
Transparent int
|
|
}
|
|
|
|
type namedColor struct {
|
|
name string
|
|
color color.RGBA
|
|
}
|
|
|
|
type sortByAlpha []namedColor
|
|
|
|
func (colors sortByAlpha) Less(i, j int) bool {
|
|
return colors[i].color.A < colors[j].color.A
|
|
}
|
|
|
|
func (colors sortByAlpha) Len() int {
|
|
return len(colors)
|
|
}
|
|
|
|
func (colors sortByAlpha) Swap(i, j int) {
|
|
colors[i], colors[j] = colors[j], colors[i]
|
|
}
|
|
|
|
func ParseColors(filename string) (colors *Colors, err error) {
|
|
|
|
var file *os.File
|
|
if file, err = os.Open(filename); err != nil {
|
|
return
|
|
}
|
|
defer file.Close()
|
|
|
|
cols := make([]namedColor, 0, 2200)
|
|
|
|
scanner := bufio.NewScanner(file)
|
|
for scanner.Scan() {
|
|
line := scanner.Text()
|
|
if strings.HasPrefix(line, "#") {
|
|
continue
|
|
}
|
|
c := color.RGBA{A: 0xff}
|
|
var name string
|
|
if n, _ := fmt.Sscanf(
|
|
line, "%s %d %d %d %d", &name, &c.R, &c.G, &c.B, &c.A); n > 0 {
|
|
cols = append(cols, namedColor{name: name, color: c})
|
|
}
|
|
}
|
|
err = scanner.Err()
|
|
|
|
// Sort transparent colors to front. Makes it easier to figure out
|
|
// if an index corresponds to a transparent color (i < Transparent).
|
|
sort.Sort(sortByAlpha(cols))
|
|
|
|
cs := make([]color.RGBA, len(cols))
|
|
nameIndex := make(map[string]int32, len(cols))
|
|
|
|
transparent := 0
|
|
for i, nc := range cols {
|
|
if nc.color.A < 0xff {
|
|
transparent++
|
|
}
|
|
cs[i] = nc.color
|
|
nameIndex[nc.name] = int32(i)
|
|
}
|
|
colors = &Colors{Colors: cs, NameIndex: nameIndex, Transparent: transparent}
|
|
return
|
|
}
|