合并杂项功能服务器节点到multi服务器节点

This commit is contained in:
flswld committed 2023-10-22 19:46:08 +08:00
1 parent 64699c23d7
commit 6cca998915
42 files changed
+344 -647

No files matched your search

+92
View File
@@ -0,0 +1,92 @@
package app
import (
"context"
_ "net/http/pprof"
"os"
"os/signal"
"syscall"
"time"
"hk4e/common/config"
"hk4e/common/mq"
"hk4e/common/rpc"
"hk4e/gdconf"
"hk4e/multi/handle"
"hk4e/node/api"
"hk4e/pkg/logger"
)
var APPID string
var APPVERSION string
func Run(ctx context.Context, configFile string) error {
config.InitConfig(configFile)
// natsrpc client
discoveryClient, err := rpc.NewDiscoveryClient()
if err != nil {
return err
}
// 注册到节点服务器
rsp, err := discoveryClient.RegisterServer(context.TODO(), &api.RegisterServerReq{
ServerType: api.MULTI,
AppVersion: APPVERSION,
})
if err != nil {
return err
}
APPID = rsp.GetAppId()
go func() {
ticker := time.NewTicker(time.Second * 15)
for {
<-ticker.C
_, err := discoveryClient.KeepaliveServer(context.TODO(), &api.KeepaliveServerReq{
ServerType: api.MULTI,
AppId: APPID,
})
if err != nil {
logger.Error("keepalive error: %v", err)
}
}
}()
defer func() {
_, _ = discoveryClient.CancelServer(context.TODO(), &api.CancelServerReq{
ServerType: api.MULTI,
AppId: APPID,
})
}()
logger.InitLogger("multi_" + APPID)
logger.Warn("multi start, appid: %v", APPID)
defer func() {
logger.CloseLogger()
}()
gdconf.InitGameDataConfig()
messageQueue := mq.NewMessageQueue(api.MULTI, APPID, discoveryClient)
defer messageQueue.Close()
_ = handle.NewHandle(messageQueue)
c := make(chan os.Signal, 1)
signal.Notify(c, syscall.SIGHUP, syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT)
for {
select {
case <-ctx.Done():
return nil
case s := <-c:
logger.Warn("get a signal %s", s.String())
switch s {
case syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT:
logger.Warn("multi exit, appid: %v", APPID)
return nil
case syscall.SIGHUP:
default:
return nil
}
}
}
}
+235
View File
@@ -0,0 +1,235 @@
package handle
import (
"math"
"time"
"hk4e/common/constant"
"hk4e/gdconf"
"hk4e/pkg/logger"
"hk4e/protocol/proto"
pb "google.golang.org/protobuf/proto"
)
const (
MoveVectorCacheNum = 10
MaxMoveSpeed = 100.0
JumpDistance = 500.0
PointDistance = 10.0
AttackCountLimitEntitySec = 10
KickCheatPlayer = false
)
type MoveVector struct {
pos *proto.Vector
time int64
}
type AttackEntity struct {
attackStartTime uint64
attackCount uint32
}
type AnticheatContext struct {
sceneId uint32
moveVectorList []*MoveVector
attackEntityMap map[uint32]*AttackEntity
}
func (a *AnticheatContext) Move(pos *proto.Vector) bool {
now := time.Now().UnixMilli()
if len(a.moveVectorList) > 0 {
lastMoveVector := a.moveVectorList[len(a.moveVectorList)-1]
if now-lastMoveVector.time < 1000 {
return true
}
distance := GetDistance(pos, lastMoveVector.pos)
if distance > JumpDistance {
// 瞬时变化太大 判断是否为传送
scenePointMap := gdconf.GetScenePointMapBySceneId(int32(a.sceneId))
if scenePointMap == nil {
return true
}
isJump := true
for _, pointData := range scenePointMap {
if pointData.TranPos == nil {
continue
}
d := GetDistance(pos, &proto.Vector{
X: float32(pointData.TranPos.X),
Y: float32(pointData.TranPos.Y),
Z: float32(pointData.TranPos.Z),
})
if d < PointDistance {
isJump = false
break
}
}
if isJump {
return false
} else {
a.moveVectorList = make([]*MoveVector, 0)
}
}
}
a.moveVectorList = append(a.moveVectorList, &MoveVector{
pos: pos,
time: now,
})
if len(a.moveVectorList) > MoveVectorCacheNum {
a.moveVectorList = a.moveVectorList[len(a.moveVectorList)-MoveVectorCacheNum:]
}
return true
}
func (a *AnticheatContext) GetMoveSpeed() float32 {
avgMoveSpeed := float32(0.0)
if len(a.moveVectorList) < MoveVectorCacheNum {
return avgMoveSpeed
}
for index := range a.moveVectorList {
if index+1 >= len(a.moveVectorList) {
break
}
nextMoveVector := a.moveVectorList[index+1]
beforeMoveVector := a.moveVectorList[index]
dx := GetDistance(nextMoveVector.pos, beforeMoveVector.pos)
dt := float32(nextMoveVector.time-beforeMoveVector.time) / 1000.0
avgMoveSpeed += dx / dt
}
avgMoveSpeed /= float32(len(a.moveVectorList))
return avgMoveSpeed
}
func (a *AnticheatContext) Attack(defEntityId uint32) bool {
now := uint64(time.Now().UnixMilli())
attackEntity, exist := a.attackEntityMap[defEntityId]
if !exist {
attackEntity = &AttackEntity{
attackStartTime: now,
attackCount: 0,
}
a.attackEntityMap[defEntityId] = attackEntity
}
attackEntity.attackCount++
if attackEntity.attackCount > AttackCountLimitEntitySec {
if now-attackEntity.attackStartTime < 1000 {
return false
} else {
attackEntity.attackStartTime = now
attackEntity.attackCount = 0
}
}
return true
}
func NewAnticheatContext() *AnticheatContext {
r := &AnticheatContext{
sceneId: 0,
moveVectorList: make([]*MoveVector, 0),
attackEntityMap: make(map[uint32]*AttackEntity),
}
return r
}
func (h *Handle) AddPlayerAcCtx(userId uint32) {
h.playerAcCtxMap[userId] = NewAnticheatContext()
}
func (h *Handle) DelPlayerAcCtx(userId uint32) {
delete(h.playerAcCtxMap, userId)
}
func (h *Handle) GetPlayerAcCtx(userId uint32) *AnticheatContext {
return h.playerAcCtxMap[userId]
}
func (h *Handle) CombatInvocationsNotify(userId uint32, gateAppId string, payloadMsg pb.Message) {
req := payloadMsg.(*proto.CombatInvocationsNotify)
ctx := h.GetPlayerAcCtx(userId)
if ctx == nil {
logger.Error("get player anticheat context is nil, uid: %v", userId)
return
}
for _, entry := range req.InvokeList {
switch entry.ArgumentType {
case proto.CombatTypeArgument_ENTITY_MOVE:
entityMoveInfo := new(proto.EntityMoveInfo)
err := pb.Unmarshal(entry.CombatData, entityMoveInfo)
if err != nil {
logger.Error("parse EntityMoveInfo error: %v, uid: %v", err, userId)
continue
}
if GetEntityType(entityMoveInfo.EntityId) != constant.ENTITY_TYPE_AVATAR {
continue
}
if entityMoveInfo.MotionInfo == nil {
continue
}
motionInfo := entityMoveInfo.MotionInfo
if motionInfo.Pos == nil {
continue
}
// 玩家超速移动检测
if ctx.sceneId != 3 {
continue
}
ok := ctx.Move(motionInfo.Pos)
if !ok {
logger.Warn("player move jump, pos: %v, uid: %v", motionInfo.Pos, userId)
h.KickPlayer(userId, gateAppId)
continue
}
moveSpeed := ctx.GetMoveSpeed()
if moveSpeed > MaxMoveSpeed {
logger.Warn("player move overspeed, speed: %v, uid: %v", moveSpeed, userId)
h.KickPlayer(userId, gateAppId)
continue
}
case proto.CombatTypeArgument_COMBAT_EVT_BEING_HIT:
evtBeingHitInfo := new(proto.EvtBeingHitInfo)
err := pb.Unmarshal(entry.CombatData, evtBeingHitInfo)
if err != nil {
logger.Error("parse EvtBeingHitInfo error: %v, uid: %v", err, userId)
continue
}
attackResult := evtBeingHitInfo.AttackResult
if attackResult == nil {
continue
}
if GetEntityType(attackResult.DefenseId) != constant.ENTITY_TYPE_MONSTER {
continue
}
ok := ctx.Attack(attackResult.DefenseId)
if !ok {
logger.Warn("player attack monster feq too high, uid: %v", userId)
h.KickPlayer(userId, gateAppId)
continue
}
}
}
}
func (h *Handle) ToTheMoonEnterSceneReq(userId uint32, gateAppId string, payloadMsg pb.Message) {
req := payloadMsg.(*proto.ToTheMoonEnterSceneReq)
ctx := h.GetPlayerAcCtx(userId)
if ctx == nil {
logger.Error("get player anticheat context is nil, uid: %v", userId)
return
}
ctx.sceneId = req.SceneId
logger.Info("player enter scene: %v, uid: %v", req.SceneId, userId)
}
func GetEntityType(entityId uint32) int {
return int(entityId >> 24)
}
func GetDistance(v1 *proto.Vector, v2 *proto.Vector) float32 {
return float32(math.Sqrt(
float64((v1.X-v2.X)*(v1.X-v2.X)) +
float64((v1.Y-v2.Y)*(v1.Y-v2.Y)) +
float64((v1.Z-v2.Z)*(v1.Z-v2.Z)),
))
}
+102
View File
@@ -0,0 +1,102 @@
package handle
import (
"hk4e/common/mq"
"hk4e/gate/kcp"
"hk4e/node/api"
"hk4e/pkg/logger"
"hk4e/protocol/cmd"
pb "google.golang.org/protobuf/proto"
)
type Handle struct {
messageQueue *mq.MessageQueue
playerAcCtxMap map[uint32]*AnticheatContext
worldStatic *WorldStatic
}
func NewHandle(messageQueue *mq.MessageQueue) (r *Handle) {
r = new(Handle)
r.messageQueue = messageQueue
r.playerAcCtxMap = make(map[uint32]*AnticheatContext)
r.worldStatic = NewWorldStatic()
r.worldStatic.InitTerrain()
go r.run()
return r
}
func (h *Handle) run() {
logger.Info("start handle")
for {
netMsg := <-h.messageQueue.GetNetMsg()
switch netMsg.MsgType {
case mq.MsgTypeGame:
if netMsg.OriginServerType != api.GATE {
continue
}
if netMsg.EventId != mq.NormalMsg {
continue
}
gameMsg := netMsg.GameMsg
switch gameMsg.CmdId {
case cmd.CombatInvocationsNotify:
h.CombatInvocationsNotify(gameMsg.UserId, netMsg.OriginServerAppId, gameMsg.PayloadMessage)
case cmd.ToTheMoonEnterSceneReq:
h.ToTheMoonEnterSceneReq(gameMsg.UserId, netMsg.OriginServerAppId, gameMsg.PayloadMessage)
case cmd.QueryPathReq:
h.QueryPath(gameMsg.UserId, netMsg.OriginServerAppId, gameMsg.PayloadMessage)
case cmd.ObstacleModifyNotify:
h.ObstacleModifyNotify(gameMsg.UserId, netMsg.OriginServerAppId, gameMsg.PayloadMessage)
}
case mq.MsgTypeServer:
serverMsg := netMsg.ServerMsg
switch netMsg.EventId {
case mq.ServerUserOnlineStateChangeNotify:
logger.Info("player online state change, state: %v, uid: %v", serverMsg.IsOnline, serverMsg.UserId)
if serverMsg.IsOnline {
h.AddPlayerAcCtx(serverMsg.UserId)
} else {
h.DelPlayerAcCtx(serverMsg.UserId)
}
}
}
}
}
func (h *Handle) KickPlayer(userId uint32, gateAppId string) {
if !KickCheatPlayer {
return
}
h.messageQueue.SendToGate(gateAppId, &mq.NetMsg{
MsgType: mq.MsgTypeConnCtrl,
EventId: mq.KickPlayerNotify,
ConnCtrlMsg: &mq.ConnCtrlMsg{
KickUserId: userId,
KickReason: kcp.EnetServerKillClient,
},
})
}
// SendMsg 发送消息给客户端
func (h *Handle) SendMsg(cmdId uint16, userId uint32, gateAppId string, payloadMsg pb.Message) {
if payloadMsg == nil {
return
}
gameMsg := new(mq.GameMsg)
gameMsg.UserId = userId
gameMsg.CmdId = cmdId
gameMsg.ClientSeq = 0
// 在这里直接序列化成二进制数据 防止发送的消息内包含各种游戏数据指针 而造成并发读写的问题
payloadMessageData, err := pb.Marshal(payloadMsg)
if err != nil {
logger.Error("parse payload msg to bin error: %v", err)
return
}
gameMsg.PayloadMessageData = payloadMessageData
h.messageQueue.SendToGate(gateAppId, &mq.NetMsg{
MsgType: mq.MsgTypeGame,
EventId: mq.NormalMsg,
GameMsg: gameMsg,
})
}
+162
View File
@@ -0,0 +1,162 @@
package handle
import (
"bytes"
"encoding/gob"
"os"
"hk4e/pkg/alg"
"hk4e/pkg/logger"
"hk4e/protocol/cmd"
"hk4e/protocol/proto"
pb "google.golang.org/protobuf/proto"
)
func (h *Handle) ConvPbVecToMeshVec(pbVec *proto.Vector) alg.MeshVector {
return alg.MeshVector{
X: int16(pbVec.X),
Y: int16(pbVec.Y),
Z: int16(pbVec.Z),
}
}
func (h *Handle) ConvMeshVecToPbVec(meshVec alg.MeshVector) *proto.Vector {
return &proto.Vector{
X: float32(meshVec.X),
Y: float32(meshVec.Y),
Z: float32(meshVec.Z),
}
}
func (h *Handle) ConvPbVecListToMeshVecList(pbVecList []*proto.Vector) []alg.MeshVector {
ret := make([]alg.MeshVector, 0)
for _, pbVec := range pbVecList {
ret = append(ret, h.ConvPbVecToMeshVec(pbVec))
}
return ret
}
func (h *Handle) ConvMeshVecListToPbVecList(meshVecList []alg.MeshVector) []*proto.Vector {
ret := make([]*proto.Vector, 0)
for _, meshVec := range meshVecList {
ret = append(ret, h.ConvMeshVecToPbVec(meshVec))
}
return ret
}
func (h *Handle) QueryPath(userId uint32, gateAppId string, payloadMsg pb.Message) {
req := payloadMsg.(*proto.QueryPathReq)
logger.Debug("query path req: %v, uid: %v, gateAppId: %v", req, userId, gateAppId)
var ok = false
var path []alg.MeshVector = nil
for _, destinationPos := range req.DestinationPos {
ok, path = h.worldStatic.Pathfinding(h.ConvPbVecToMeshVec(req.SourcePos), h.ConvPbVecToMeshVec(destinationPos))
if ok {
break
}
}
if !ok {
queryPathRsp := &proto.QueryPathRsp{
QueryId: req.QueryId,
QueryStatus: proto.QueryPathRsp_STATUS_SUCC,
Corners: []*proto.Vector{req.DestinationPos[0]},
}
h.SendMsg(cmd.QueryPathRsp, userId, gateAppId, queryPathRsp)
return
}
queryPathRsp := &proto.QueryPathRsp{
QueryId: req.QueryId,
QueryStatus: proto.QueryPathRsp_STATUS_SUCC,
Corners: h.ConvMeshVecListToPbVecList(path),
}
h.SendMsg(cmd.QueryPathRsp, userId, gateAppId, queryPathRsp)
}
func (h *Handle) ObstacleModifyNotify(userId uint32, gateAppId string, payloadMsg pb.Message) {
req := payloadMsg.(*proto.ObstacleModifyNotify)
logger.Debug("obstacle modify req: %v, uid: %v, gateAppId: %v", req, userId, gateAppId)
}
type WorldStatic struct {
// x y z -> if terrain exist
terrain map[alg.MeshVector]bool
}
func NewWorldStatic() (r *WorldStatic) {
r = new(WorldStatic)
r.terrain = make(map[alg.MeshVector]bool)
return r
}
func (w *WorldStatic) InitTerrain() bool {
data, err := os.ReadFile("./world_terrain.bin")
if err != nil {
logger.Error("read world terrain file error: %v", err)
return false
}
decoder := gob.NewDecoder(bytes.NewReader(data))
err = decoder.Decode(&w.terrain)
if err != nil {
logger.Error("unmarshal world terrain data error: %v", err)
return false
}
return true
}
func (w *WorldStatic) SaveTerrain() bool {
var buffer bytes.Buffer
encoder := gob.NewEncoder(&buffer)
err := encoder.Encode(w.terrain)
if err != nil {
logger.Error("marshal world terrain data error: %v", err)
return false
}
err = os.WriteFile("./world_terrain.bin", buffer.Bytes(), 0644)
if err != nil {
logger.Error("write world terrain file error: %v", err)
return false
}
return true
}
func (w *WorldStatic) GetTerrain(x int16, y int16, z int16) (exist bool) {
pos := alg.MeshVector{
X: x,
Y: y,
Z: z,
}
exist = w.terrain[pos]
return exist
}
func (w *WorldStatic) SetTerrain(x int16, y int16, z int16) {
pos := alg.MeshVector{
X: x,
Y: y,
Z: z,
}
w.terrain[pos] = true
}
func (w *WorldStatic) Pathfinding(startPos alg.MeshVector, endPos alg.MeshVector) (bool, []alg.MeshVector) {
defer func() {
if err := recover(); err != nil {
logger.Error("pathfinding error, panic, startPos: %v, endPos: %v", startPos, endPos)
}
}()
bfs := alg.NewBFS()
bfs.InitMap(
w.terrain,
startPos,
endPos,
0,
)
pathVectorList := bfs.Pathfinding()
if pathVectorList == nil {
logger.Error("could not find path")
return false, nil
}
logger.Debug("find path success, path: %v", pathVectorList)
return true, pathVectorList
}