forked from icexin/gocraft
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rpc.go
129 lines (116 loc) · 2.53 KB
/
rpc.go
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
package main
import (
"flag"
"log"
"net"
"net/rpc"
"strings"
gocraft "github.com/icexin/gocraft-server/client"
"github.com/icexin/gocraft-server/proto"
)
var (
serverAddr = flag.String("s", "", "server address")
client *gocraft.Client
)
func InitClient() error {
if *serverAddr == "" {
return nil
}
addr := *serverAddr
if strings.Index(addr, ":") == -1 {
addr += ":8421"
}
conn, err := net.Dial("tcp", addr)
if err != nil {
return err
}
client = gocraft.NewClient()
client.RegisterService("Block", &BlockService{})
client.RegisterService("Player", &PlayerService{})
client.Start(conn)
return nil
}
func ClientFetchChunk(id Vec3, f func(bid Vec3, w int)) {
if client == nil {
return
}
req := proto.FetchChunkRequest{
P: id.X,
Q: id.Z,
Version: store.GetChunkVersion(id),
}
rep := new(proto.FetchChunkResponse)
err := client.Call("Block.FetchChunk", req, rep)
if err == rpc.ErrShutdown {
return
}
if err != nil {
log.Panic(err)
}
for _, b := range rep.Blocks {
f(Vec3{b[0], b[1], b[2]}, b[3])
}
if req.Version != rep.Version {
store.UpdateChunkVersion(id, rep.Version)
}
}
func ClientUpdateBlock(id Vec3, w int) {
if client == nil {
return
}
cid := id.Chunkid()
req := &proto.UpdateBlockRequest{
Id: client.ClientId,
P: cid.X,
Q: cid.Z,
X: id.X,
Y: id.Y,
Z: id.Z,
W: w,
}
rep := new(proto.UpdateBlockResponse)
err := client.Call("Block.UpdateBlock", req, rep)
if err == rpc.ErrShutdown {
return
}
if err != nil {
log.Panic(err)
}
store.UpdateChunkVersion(id.Chunkid(), rep.Version)
}
func ClientUpdatePlayerState(state PlayerState) {
if client == nil {
return
}
req := &proto.UpdateStateRequest{
Id: client.ClientId,
}
s := &req.State
s.X, s.Y, s.Z, s.Rx, s.Ry = state.X, state.Y, state.Z, state.Rx, state.Ry
rep := new(proto.UpdateStateResponse)
err := client.Call("Player.UpdateState", req, rep)
if err == rpc.ErrShutdown {
return
}
if err != nil {
log.Panic(err)
}
for id, player := range rep.Players {
game.playerRender.UpdateOrAdd(id, player)
}
}
type BlockService struct {
}
func (s *BlockService) UpdateBlock(req *proto.UpdateBlockRequest, rep *proto.UpdateBlockResponse) error {
log.Printf("rpc::UpdateBlock:%v", *req)
bid := Vec3{req.X, req.Y, req.Z}
game.world.UpdateBlock(bid, req.W)
game.blockRender.DirtyChunk(bid.Chunkid())
return nil
}
type PlayerService struct {
}
func (s *PlayerService) RemovePlayer(req *proto.RemovePlayerRequest, rep *proto.RemovePlayerResponse) error {
game.playerRender.Remove(req.Id)
return nil
}