Optimize the case that nothing has changes concerning the players. This should not lead to broadcasting of notifications.

This commit is contained in:
Sascha L. Teichmann 2015-03-10 12:08:14 +01:00
parent 6e9585ed67
commit 09e24cda65

View File

@ -6,8 +6,10 @@ import (
"encoding/json"
"html/template"
"log"
"math"
"net/http"
"os"
"sort"
"sync"
"time"
)
@ -51,6 +53,27 @@ func (p *player) MarshalJSON() ([]byte, error) {
return buf.Bytes(), nil
}
func (p *player) same(o *player) bool {
return p.Name == o.Name &&
math.Abs(p.X-o.X) < 0.000001 &&
math.Abs(p.Y-o.Y) < 0.000001 &&
math.Abs(p.Z-o.Z) < 0.000001
}
type sortPlayersByName []*player
func (pls sortPlayersByName) Len() int {
return len(pls)
}
func (pls sortPlayersByName) Less(i, j int) bool {
return pls[i].Name < pls[j].Name
}
func (pls sortPlayersByName) Swap(i, j int) {
pls[i], pls[j] = pls[j], pls[i]
}
func (ps *players) readFromFIFO() ([]*player, error) {
file, err := os.Open(ps.fifo)
if err != nil {
@ -67,6 +90,18 @@ func (ps *players) readFromFIFO() ([]*player, error) {
return pls, nil
}
func differentPlayers(a, b []*player) bool {
if len(a) == len(b) {
return true
}
for i, p := range a {
if !p.same(b[i]) {
return true
}
}
return false
}
func (ps *players) run() {
for {
pls, err := ps.readFromFIFO()
@ -74,10 +109,17 @@ func (ps *players) run() {
time.Sleep(sleepInterval)
continue
}
if pls == nil {
continue
}
sort.Sort(sortPlayersByName(pls))
var change bool
ps.mu.Lock()
if change = differentPlayers(pls, ps.pls); change {
ps.pls = pls
}
ps.mu.Unlock()
if ps.wsf != nil {
if change && ps.wsf != nil {
// TODO: Throttle this!
ps.wsf.BroadcastPlayers(pls)
}