r_place/go/util.go

82 lines
2.1 KiB
Go
Raw Normal View History

2022-05-26 12:14:36 +00:00
package main
import (
2022-05-27 14:12:27 +00:00
"fmt"
"sync"
2022-05-26 12:14:36 +00:00
)
2022-05-27 14:12:27 +00:00
type Message struct {
X uint32 `json:"x"`
Y uint32 `json:"y"`
2022-05-26 12:14:36 +00:00
Color uint8 `json:"color"`
2022-05-26 13:01:09 +00:00
Timestamp int64 `json:"timestamp"`
2022-05-26 12:14:36 +00:00
UserID uint64 `json:"userid"`
}
2022-05-27 14:12:27 +00:00
type pixel struct {
Color uint8 `json:"color"`
Timestamp int64 `json:"timestamp"`
UserID uint64 `json:"userid"`
}
type pixelContainer struct {
pixel pixel
Mutex sync.Mutex
2022-05-27 16:00:19 +00:00
}
type image struct {
width uint32
height uint32
pixels []pixelContainer
2022-05-27 16:00:19 +00:00
}
func GetImage(w uint32, h uint32) image {
pixels := make([]pixelContainer, w*h)
2022-05-27 14:12:27 +00:00
for i := 0; i < int(w*h); i++ {
pixels[i] = pixelContainer{pixel: pixel{Color: 0, Timestamp: 0, UserID: 0}, Mutex: sync.Mutex{}}
2022-05-27 14:12:27 +00:00
}
return image{width: w, height: h, pixels: pixels}
}
func (p *pixelContainer) setColor(color uint8, timestamp int64, userid uint64) {
2022-05-27 14:12:27 +00:00
p.Mutex.Lock()
defer p.Mutex.Unlock()
if timestamp > p.pixel.Timestamp {
p.pixel.Color = color
p.pixel.Timestamp = timestamp
p.pixel.UserID = userid
2022-05-27 14:12:27 +00:00
}
}
2022-05-31 14:15:09 +00:00
func (img *image) SetPixel(message Message) int {
2022-05-27 14:12:27 +00:00
if message.X >= img.width || message.Y >= img.height || message.X < 0 || message.Y < 0 {
fmt.Printf("User %d tried accessing out of bounds \n", message.UserID)
2022-05-31 14:15:09 +00:00
return 1
2022-05-27 14:12:27 +00:00
}
2022-05-31 16:29:44 +00:00
if message.Color >= 255 || message.Color < 0 {
2022-05-27 14:12:27 +00:00
fmt.Printf("User %d tried setting non existent color \n", message.UserID)
2022-05-31 14:15:09 +00:00
return 1
2022-05-27 14:12:27 +00:00
}
pos := uint32(message.X)*uint32(img.width) + uint32(message.Y)
img.pixels[pos].setColor(message.Color, message.Timestamp, message.UserID)
2022-05-31 14:15:09 +00:00
return 0
2022-05-26 12:14:36 +00:00
}
2022-05-27 16:00:19 +00:00
func comparePixels(pixel1 *pixelContainer, pixel2 *pixelContainer) bool {
return pixel1.pixel.Color == pixel2.pixel.Color &&
pixel1.pixel.Timestamp == pixel2.pixel.Timestamp &&
pixel1.pixel.UserID == pixel2.pixel.UserID
2022-05-27 16:00:19 +00:00
}
func (img *image) GetDiff(img2 *image) image {
diff := GetImage(img.width, img.height)
2022-05-27 16:00:19 +00:00
for i := 0; i < int(img.width*img.height); i++ {
if !comparePixels(&img.pixels[i], &img2.pixels[i]) {
diff.pixels[i].pixel.Color = img2.pixels[i].pixel.Color
diff.pixels[i].pixel.UserID = img2.pixels[i].pixel.UserID
diff.pixels[i].pixel.Timestamp = img2.pixels[i].pixel.Timestamp
2022-05-27 16:00:19 +00:00
}
}
return diff
}