aboutsummaryrefslogtreecommitdiffstats
path: root/packet/command/damage/damage.go
blob: 93ddb1e71a5f84105cd7716873767a9effae3799 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package damage

import (
	"github.com/osm/quake/common/buffer"
	"github.com/osm/quake/common/context"
	"github.com/osm/quake/protocol"
)

type Command struct {
	CoordSize uint8

	Armor byte
	Blood byte
	Coord [3]float32
}

func (cmd *Command) Bytes() []byte {
	buf := buffer.New()

	writeCoord := buf.PutCoord16
	if cmd.CoordSize == 4 {
		writeCoord = buf.PutCoord32
	}

	buf.PutByte(byte(protocol.SVCDamage))
	buf.PutByte(cmd.Armor)
	buf.PutByte(cmd.Blood)

	for i := 0; i < 3; i++ {
		writeCoord(cmd.Coord[i])
	}

	return buf.Bytes()
}

func Parse(ctx *context.Context, buf *buffer.Buffer) (*Command, error) {
	var err error
	var cmd Command

	cmd.CoordSize = ctx.GetCoordSize()
	readCoord := buf.GetCoord16
	if cmd.CoordSize == 4 {
		readCoord = buf.GetCoord32
	}

	if cmd.Armor, err = buf.ReadByte(); err != nil {
		return nil, err
	}

	if cmd.Blood, err = buf.ReadByte(); err != nil {
		return nil, err
	}

	for i := 0; i < 3; i++ {
		if cmd.Coord[i], err = readCoord(); err != nil {
			return nil, err
		}
	}

	return &cmd, nil
}