添加f8命名空间

This commit is contained in:
aozhiwei 2018-11-26 21:09:20 +08:00
parent 51f7f26e4f
commit 83cf86548e
14 changed files with 1256 additions and 1212 deletions

View File

@ -1,41 +1,45 @@
#include "framework/cpp/dynmodule.h" #include "framework/cpp/dynmodule.h"
DynModule::DynModule() namespace f8
{ {
} DynModule::DynModule()
{
}
DynModule::~DynModule() DynModule::~DynModule()
{ {
}
bool DynModule::IsDataMsg(int msgid)
{
return false;
}
bool DynModule::IsPending()
{
return module_state_.pending;
}
bool DynModule::DataIsValid()
{
return module_state_.data_is_valid;
}
void DynModule::MarkDataValid()
{
module_state_.data_is_valid = true;
}
void DynModule::MarkPending()
{
module_state_.pending = true;
}
void DynModule::CancelPending()
{
module_state_.pending = false;
}
} }
bool DynModule::IsDataMsg(int msgid)
{
return false;
}
bool DynModule::IsPending()
{
return module_state_.pending;
}
bool DynModule::DataIsValid()
{
return module_state_.data_is_valid;
}
void DynModule::MarkDataValid()
{
module_state_.data_is_valid = true;
}
void DynModule::MarkPending()
{
module_state_.pending = true;
}
void DynModule::CancelPending()
{
module_state_.pending = false;
}

View File

@ -1,24 +1,28 @@
#pragma once #pragma once
struct DynModuleState namespace f8
{ {
bool pending = false; struct DynModuleState
bool data_is_valid = false;; {
}; bool pending = false;
bool data_is_valid = false;;
};
class DynModule class DynModule
{ {
public: public:
DynModule(); DynModule();
~DynModule(); ~DynModule();
virtual bool IsDataMsg(int msgid); virtual bool IsDataMsg(int msgid);
bool IsPending(); bool IsPending();
bool DataIsValid(); bool DataIsValid();
void MarkDataValid(); void MarkDataValid();
void MarkPending(); void MarkPending();
void CancelPending(); void CancelPending();
private: private:
DynModuleState module_state_; DynModuleState module_state_;
}; };
}

View File

@ -6,8 +6,11 @@
#include "framework/cpp/protoutils.h" #include "framework/cpp/protoutils.h"
#include "framework/cpp/netmsghandler.h" #include "framework/cpp/netmsghandler.h"
NetMsgHandler* GetNetMsgHandler(NetMsgHandlerObject* handlers, namespace f8
unsigned short msgid)
{ {
return msgid < MAX_MSG_ID ? handlers->handlers[msgid] : nullptr; NetMsgHandler* GetNetMsgHandler(NetMsgHandlerObject* handlers,
unsigned short msgid)
{
return msgid < MAX_MSG_ID ? handlers->handlers[msgid] : nullptr;
}
} }

View File

@ -7,83 +7,85 @@
#include <google/protobuf/extension_set.h> #include <google/protobuf/extension_set.h>
#include <google/protobuf/unknown_field_set.h> #include <google/protobuf/unknown_field_set.h>
const unsigned short MAX_MSG_ID = 2000; namespace f8
struct MsgHdr;
struct NetMsgHandler
{ {
int handlerid; const unsigned short MAX_MSG_ID = 2000;
const ::google::protobuf::Message* prototype = nullptr;
};
struct NetMsgHandlerObject struct MsgHdr;
{
NetMsgHandler* handlers[MAX_MSG_ID] = { nullptr };
};
template<typename InstanceType, typename MsgType> struct NetMsgHandler
static void NetMsgHandlerWrapper(InstanceType* instance, MsgHdr& hdr, NetMsgHandler* handler) {
{ int handlerid;
MsgType msg; const ::google::protobuf::Message* prototype = nullptr;
bool ok = msg.ParseFromArray(hdr.buf + hdr.offset, hdr.buflen - hdr.offset); };
assert(ok);
if (ok) { struct NetMsgHandlerObject
{
NetMsgHandler* handlers[MAX_MSG_ID] = { nullptr };
};
template<typename InstanceType, typename MsgType>
static void NetMsgHandlerWrapper(InstanceType* instance, MsgHdr& hdr, NetMsgHandler* handler)
{
MsgType msg;
bool ok = msg.ParseFromArray(hdr.buf + hdr.offset, hdr.buflen - hdr.offset);
assert(ok);
if (ok) {
struct Invoker: public NetMsgHandler
{
void (*wrapper)(InstanceType*, MsgHdr&, NetMsgHandler*);
void (InstanceType::*func)(MsgHdr&, const MsgType&);
};
Invoker* invoker = (Invoker*)handler;
auto ptr = invoker->func;
(instance->*ptr)(hdr, msg);
}
}
template<typename InstanceType, typename MsgType>
static void RegisterNetMsgHandler(NetMsgHandlerObject* msghandler,
void (InstanceType::*ptr)(MsgHdr&, const MsgType&)
)
{
MsgType dumy_msg;
static int msgid = f8::Net_GetMessageId(dumy_msg);
assert(msgid >= 0 || msgid < MAX_MSG_ID);
if (msgid < 0 || msgid >= MAX_MSG_ID) {
abort();
}
struct Invoker: public NetMsgHandler struct Invoker: public NetMsgHandler
{ {
void (*wrapper)(InstanceType*, MsgHdr&, NetMsgHandler*); void (*wrapper)(InstanceType*, MsgHdr&, NetMsgHandler*);
void (InstanceType::*func)(MsgHdr&, const MsgType&); void (InstanceType::*func)(MsgHdr&, const MsgType&);
}; };
Invoker* invoker = (Invoker*)handler; Invoker *p = new Invoker();
auto ptr = invoker->func; p->wrapper = &NetMsgHandlerWrapper<InstanceType, MsgType>;
(instance->*ptr)(hdr, msg); p->func = ptr;
p->handlerid = InstanceType::HID;
p->prototype = ::google::protobuf::MessageFactory::generated_factory()->GetPrototype(MsgType::descriptor());
msghandler->handlers[msgid] = p;
} }
}
template<typename InstanceType, typename MsgType> template<typename InstanceType>
static void RegisterNetMsgHandler(NetMsgHandlerObject* msghandler, static bool ProcessNetMsg(NetMsgHandler* handler,
void (InstanceType::*ptr)(MsgHdr&, const MsgType&) InstanceType* instance,
) MsgHdr& hdr)
{
MsgType dumy_msg;
static int msgid = ::Net_GetMessageId(dumy_msg);
assert(msgid >= 0 || msgid < MAX_MSG_ID);
if (msgid < 0 || msgid >= MAX_MSG_ID) {
abort();
}
struct Invoker: public NetMsgHandler
{ {
void (*wrapper)(InstanceType*, MsgHdr&, NetMsgHandler*); if(handler){
void (InstanceType::*func)(MsgHdr&, const MsgType&); struct Invoker: public NetMsgHandler
}; {
Invoker *p = new Invoker(); void (*wrapper)(InstanceType*, MsgHdr&, NetMsgHandler*);
p->wrapper = &NetMsgHandlerWrapper<InstanceType, MsgType>; void* func;
p->func = ptr; };
p->handlerid = InstanceType::HID; Invoker *p = (Invoker*)handler;
p->prototype = ::google::protobuf::MessageFactory::generated_factory()->GetPrototype(MsgType::descriptor()); p->wrapper(instance, hdr, p);
msghandler->handlers[msgid] = p; return true;
} }else{
return false;
template<typename InstanceType> }
static bool ProcessNetMsg(NetMsgHandler* handler,
InstanceType* instance,
MsgHdr& hdr)
{
if(handler){
struct Invoker: public NetMsgHandler
{
void (*wrapper)(InstanceType*, MsgHdr&, NetMsgHandler*);
void* func;
};
Invoker *p = (Invoker*)handler;
p->wrapper(instance, hdr, p);
return true;
}else{
return false;
} }
NetMsgHandler* GetNetMsgHandler(NetMsgHandlerObject* handlers,
unsigned short msgid);
} }
NetMsgHandler* GetNetMsgHandler(NetMsgHandlerObject* handlers,
unsigned short msgid);
#endif #endif

View File

@ -8,168 +8,171 @@
#include <google/protobuf/message.h> #include <google/protobuf/message.h>
#include <google/protobuf/descriptor.h> #include <google/protobuf/descriptor.h>
int Net_GetMessageId(::google::protobuf::Message& msg) namespace f8
{ {
std::string msgname; int Net_GetMessageId(::google::protobuf::Message& msg)
{ {
std::string full_msgname = msg.GetTypeName(); std::string msgname;
std::vector<std::string> strings; {
a8::Split(full_msgname, strings, '.'); std::string full_msgname = msg.GetTypeName();
msgname = strings[strings.size() - 1]; std::vector<std::string> strings;
} a8::Split(full_msgname, strings, '.');
assert(msgname.size() > 2); msgname = strings[strings.size() - 1];
if (msgname.size() < 2) { }
abort(); assert(msgname.size() > 2);
return 0; if (msgname.size() < 2) {
} abort();
std::string msgid_enum_name; return 0;
if (msgname[0] == 'C' && msgname[1] == 'M') { }
msgid_enum_name = "cs.CMMessageId_e"; std::string msgid_enum_name;
} else if (msgname[0] == 'S' && msgname[1] == 'M') { if (msgname[0] == 'C' && msgname[1] == 'M') {
msgid_enum_name = "cs.SMMessageId_e"; msgid_enum_name = "cs.CMMessageId_e";
} else if (msgname[0] == 'S' && msgname[1] == 'S') { } else if (msgname[0] == 'S' && msgname[1] == 'M') {
msgid_enum_name = "ss.SSMessageId_e"; msgid_enum_name = "cs.SMMessageId_e";
} else { } else if (msgname[0] == 'S' && msgname[1] == 'S') {
assert(false); msgid_enum_name = "ss.SSMessageId_e";
abort(); } else {
return 0; assert(false);
abort();
return 0;
}
auto msgid_enum = ::google::protobuf::DescriptorPool::generated_pool()->FindEnumTypeByName(msgid_enum_name);
assert(msgid_enum);
if (!msgid_enum) {
abort();
return 0;
}
auto msgid_value = msgid_enum->FindValueByName("_" + msgname);
assert(msgid_value);
if (!msgid_value) {
abort();
return 0;
}
return msgid_value->number();
} }
auto msgid_enum = ::google::protobuf::DescriptorPool::generated_pool()->FindEnumTypeByName(msgid_enum_name); void Net_PackMsg(unsigned short msgid, ::google::protobuf::Message& msg, std::string& out)
assert(msgid_enum); {
if (!msgid_enum) { int packlen = msg.ByteSize();
abort();
return 0; out.resize(sizeof(PackHead) + packlen);
char* buff = (char*)out.data();
PackHead* head = (PackHead*)buff;
head->packlen = packlen;
head->msgid = msgid;
head->magic_code = MAGIC_CODE;
msg.SerializeToArray(buff + sizeof(PackHead), packlen);
} }
auto msgid_value = msgid_enum->FindValueByName("_" + msgname);
assert(msgid_value); int Net_SendMsg(a8::TcpClient* tcp_client, unsigned seqid, unsigned short msgid, ::google::protobuf::Message& msg)
if (!msgid_value) { {
abort(); int packlen = msg.ByteSize();
return 0; assert(packlen < 1024 * 60);
char* buff = (char*)malloc(sizeof(PackHead) + packlen);
PackHead* head = (PackHead*)buff;
head->packlen = packlen;
head->msgid = msgid;
head->seqid = seqid;
head->magic_code = MAGIC_CODE;
head->rpc_error_code = 0;
msg.SerializeToArray(buff + sizeof(PackHead), packlen);
tcp_client->SendBuff(buff, sizeof(PackHead) + packlen);
free(buff);
return sizeof(PackHead) + packlen;
}
int Net_SendMsg(a8::TcpListener* tcp_listener, unsigned short socket_handle, unsigned int seqid,
unsigned short msgid, ::google::protobuf::Message& msg)
{
int packlen = msg.ByteSize();
assert(packlen < 1024 * 60);
char* buff = (char*)malloc(sizeof(PackHead) + packlen);
PackHead* head = (PackHead*)buff;
head->packlen = packlen;
head->msgid = msgid;
head->seqid = seqid;
head->magic_code = MAGIC_CODE;
head->rpc_error_code = 0;
msg.SerializeToArray(buff + sizeof(PackHead), packlen);
tcp_listener->SendClientMsg(socket_handle, buff, sizeof(PackHead) + packlen);
free(buff);
return sizeof(PackHead) + packlen;
}
int Net_BroadcastMsg(a8::TcpListener* tcp_listener, unsigned int seqid,
unsigned short msgid, ::google::protobuf::Message& msg)
{
int packlen = msg.ByteSize();
assert(packlen < 1024 * 60);
char* buff = (char*)malloc(sizeof(PackHead) + packlen);
PackHead* head = (PackHead*)buff;
head->packlen = packlen;
head->msgid = msgid;
head->seqid = seqid;
head->magic_code = MAGIC_CODE;
head->rpc_error_code = 0;
msg.SerializeToArray(buff + sizeof(PackHead), packlen);
tcp_listener->BroadcastMsg(buff, sizeof(PackHead) + packlen);
free(buff);
return sizeof(PackHead) + packlen;
}
int Net_SendProxyCMsg(a8::TcpClient* tcp_client, unsigned short msgid, ::google::protobuf::Message& msg)
{
int packlen = msg.ByteSize();
assert(packlen < 1024 * 60);
char* buff = (char*)malloc(sizeof(WSProxyPackHead_S) + packlen);
WSProxyPackHead_C* head = (WSProxyPackHead_C*)buff;
head->packlen = packlen;
head->msgid = msgid;
#if 1
head->seqid = 0;
#else
head->seqid = seqid;
#endif
head->magic_code = MAGIC_CODE;
#if 0
head->rpc_error_code = error_code;
#endif
#if 1
head->socket_handle = 0;
#else
head->socket_handle = child_socket_handle;
#endif
msg.SerializeToArray(buff + sizeof(WSProxyPackHead_C), packlen);
tcp_client->SendBuff(buff, sizeof(WSProxyPackHead_C) + packlen);
free(buff);
return sizeof(WSProxyPackHead_C) + packlen;
}
int Net_SendProxyMsg(a8::TcpListener* tcp_listener, int socket_handle, unsigned int seqid, unsigned short error_code,
unsigned short msgid, ::google::protobuf::Message& msg)
{
unsigned short parent_socket_handle = (socket_handle >> 16) & 0xFFFF;
unsigned short child_socket_handle = socket_handle & 0xFFFF;
int packlen = msg.ByteSize();
assert(packlen < 1024 * 60);
char* buff = (char*)malloc(sizeof(WSProxyPackHead_S) + packlen);
WSProxyPackHead_S* head = (WSProxyPackHead_S*)buff;
head->packlen = packlen;
head->msgid = msgid;
head->seqid = seqid;
head->magic_code = MAGIC_CODE;
head->rpc_error_code = error_code;
head->socket_handle = child_socket_handle;
head->reserved = 0;
msg.SerializeToArray(buff + sizeof(WSProxyPackHead_S), packlen);
tcp_listener->SendClientMsg(parent_socket_handle, buff, sizeof(WSProxyPackHead_S) + packlen);
free(buff);
return sizeof(WSProxyPackHead_S) + packlen;
} }
return msgid_value->number();
}
void Net_PackMsg(unsigned short msgid, ::google::protobuf::Message& msg, std::string& out)
{
int packlen = msg.ByteSize();
out.resize(sizeof(PackHead) + packlen);
char* buff = (char*)out.data();
PackHead* head = (PackHead*)buff;
head->packlen = packlen;
head->msgid = msgid;
head->magic_code = MAGIC_CODE;
msg.SerializeToArray(buff + sizeof(PackHead), packlen);
}
int Net_SendMsg(a8::TcpClient* tcp_client, unsigned seqid, unsigned short msgid, ::google::protobuf::Message& msg)
{
int packlen = msg.ByteSize();
assert(packlen < 1024 * 60);
char* buff = (char*)malloc(sizeof(PackHead) + packlen);
PackHead* head = (PackHead*)buff;
head->packlen = packlen;
head->msgid = msgid;
head->seqid = seqid;
head->magic_code = MAGIC_CODE;
head->rpc_error_code = 0;
msg.SerializeToArray(buff + sizeof(PackHead), packlen);
tcp_client->SendBuff(buff, sizeof(PackHead) + packlen);
free(buff);
return sizeof(PackHead) + packlen;
}
int Net_SendMsg(a8::TcpListener* tcp_listener, unsigned short socket_handle, unsigned int seqid,
unsigned short msgid, ::google::protobuf::Message& msg)
{
int packlen = msg.ByteSize();
assert(packlen < 1024 * 60);
char* buff = (char*)malloc(sizeof(PackHead) + packlen);
PackHead* head = (PackHead*)buff;
head->packlen = packlen;
head->msgid = msgid;
head->seqid = seqid;
head->magic_code = MAGIC_CODE;
head->rpc_error_code = 0;
msg.SerializeToArray(buff + sizeof(PackHead), packlen);
tcp_listener->SendClientMsg(socket_handle, buff, sizeof(PackHead) + packlen);
free(buff);
return sizeof(PackHead) + packlen;
}
int Net_BroadcastMsg(a8::TcpListener* tcp_listener, unsigned int seqid,
unsigned short msgid, ::google::protobuf::Message& msg)
{
int packlen = msg.ByteSize();
assert(packlen < 1024 * 60);
char* buff = (char*)malloc(sizeof(PackHead) + packlen);
PackHead* head = (PackHead*)buff;
head->packlen = packlen;
head->msgid = msgid;
head->seqid = seqid;
head->magic_code = MAGIC_CODE;
head->rpc_error_code = 0;
msg.SerializeToArray(buff + sizeof(PackHead), packlen);
tcp_listener->BroadcastMsg(buff, sizeof(PackHead) + packlen);
free(buff);
return sizeof(PackHead) + packlen;
}
int Net_SendProxyCMsg(a8::TcpClient* tcp_client, unsigned short msgid, ::google::protobuf::Message& msg)
{
int packlen = msg.ByteSize();
assert(packlen < 1024 * 60);
char* buff = (char*)malloc(sizeof(WSProxyPackHead_S) + packlen);
WSProxyPackHead_C* head = (WSProxyPackHead_C*)buff;
head->packlen = packlen;
head->msgid = msgid;
#if 1
head->seqid = 0;
#else
head->seqid = seqid;
#endif
head->magic_code = MAGIC_CODE;
#if 0
head->rpc_error_code = error_code;
#endif
#if 1
head->socket_handle = 0;
#else
head->socket_handle = child_socket_handle;
#endif
msg.SerializeToArray(buff + sizeof(WSProxyPackHead_C), packlen);
tcp_client->SendBuff(buff, sizeof(WSProxyPackHead_C) + packlen);
free(buff);
return sizeof(WSProxyPackHead_C) + packlen;
}
int Net_SendProxyMsg(a8::TcpListener* tcp_listener, int socket_handle, unsigned int seqid, unsigned short error_code,
unsigned short msgid, ::google::protobuf::Message& msg)
{
unsigned short parent_socket_handle = (socket_handle >> 16) & 0xFFFF;
unsigned short child_socket_handle = socket_handle & 0xFFFF;
int packlen = msg.ByteSize();
assert(packlen < 1024 * 60);
char* buff = (char*)malloc(sizeof(WSProxyPackHead_S) + packlen);
WSProxyPackHead_S* head = (WSProxyPackHead_S*)buff;
head->packlen = packlen;
head->msgid = msgid;
head->seqid = seqid;
head->magic_code = MAGIC_CODE;
head->rpc_error_code = error_code;
head->socket_handle = child_socket_handle;
head->reserved = 0;
msg.SerializeToArray(buff + sizeof(WSProxyPackHead_S), packlen);
tcp_listener->SendClientMsg(parent_socket_handle, buff, sizeof(WSProxyPackHead_S) + packlen);
free(buff);
return sizeof(WSProxyPackHead_S) + packlen;
} }

View File

@ -1,66 +1,6 @@
#pragma once #pragma once
//普通消息头部
struct PackHead
{
unsigned short packlen;
unsigned short msgid;
unsigned int seqid;
unsigned short magic_code;
unsigned short rpc_error_code;
};
//转发类消息头部
struct ForwardPackHead
{
unsigned short packlen;
unsigned short sockethandle;
unsigned short msgid;
unsigned short src_msgid;
unsigned int src_seqid;
unsigned long ip_saddr;
unsigned int sign;
};
struct WSProxyPackHead_C
{
unsigned short packlen;
unsigned short msgid;
unsigned int seqid;
unsigned short magic_code;
unsigned short socket_handle;
unsigned long ip_saddr;
};
struct WSProxyPackHead_S
{
unsigned short packlen;
unsigned short msgid;
unsigned int seqid;
unsigned short magic_code;
unsigned short rpc_error_code;
unsigned short socket_handle;
unsigned short reserved;
};
class Player; class Player;
struct MsgHdr
{
unsigned int seqid;
unsigned short msgid;
int socket_handle;
unsigned long ip_saddr;
const char* buf;
int buflen;
int offset;
Player *hum = nullptr;
const void* user_data = nullptr;
};
const unsigned short MAGIC_CODE = (((unsigned short)'S') << 8) | ((unsigned short)'K');
namespace google namespace google
{ {
namespace protobuf namespace protobuf
@ -75,19 +15,82 @@ namespace a8
class TcpListener; class TcpListener;
} }
int Net_GetMessageId(::google::protobuf::Message& msg); namespace f8
{
//普通消息头部
struct PackHead
{
unsigned short packlen;
unsigned short msgid;
unsigned int seqid;
unsigned short magic_code;
unsigned short rpc_error_code;
};
void Net_PackMsg(unsigned short msgid, ::google::protobuf::Message& msg, std::string& out); //转发类消息头部
int Net_SendMsg(a8::TcpClient* tcp_client, unsigned int seqid, struct ForwardPackHead
unsigned short msgid, ::google::protobuf::Message& msg); {
int Net_SendMsg(a8::TcpClient* tcp_client, unsigned int seqid, unsigned short msgid, unsigned short packlen;
const char* msgbody, int msgbody_len); unsigned short sockethandle;
int Net_SendMsg(a8::TcpListener* tcp_tlistener, unsigned short socket_handle, unsigned int seqid, unsigned short msgid;
unsigned short msgid, ::google::protobuf::Message& msg); unsigned short src_msgid;
int Net_BroadcastMsg(a8::TcpListener* tcp_tlistener, unsigned int seqid, unsigned int src_seqid;
unsigned short msgid, ::google::protobuf::Message& msg); unsigned long ip_saddr;
unsigned int sign;
};
int Net_SendProxyCMsg(a8::TcpClient* tcp_client, unsigned short msgid, ::google::protobuf::Message& msg); struct WSProxyPackHead_C
{
unsigned short packlen;
unsigned short msgid;
unsigned int seqid;
unsigned short magic_code;
int Net_SendProxyMsg(a8::TcpListener* tcp_tlistener, int socket_handle, unsigned int seqid, unsigned short error_code, unsigned short socket_handle;
unsigned short msgid, ::google::protobuf::Message& msg); unsigned long ip_saddr;
};
struct WSProxyPackHead_S
{
unsigned short packlen;
unsigned short msgid;
unsigned int seqid;
unsigned short magic_code;
unsigned short rpc_error_code;
unsigned short socket_handle;
unsigned short reserved;
};
struct MsgHdr
{
unsigned int seqid;
unsigned short msgid;
int socket_handle;
unsigned long ip_saddr;
const char* buf;
int buflen;
int offset;
Player *hum = nullptr;
const void* user_data = nullptr;
};
const unsigned short MAGIC_CODE = (((unsigned short)'S') << 8) | ((unsigned short)'K');
int Net_GetMessageId(::google::protobuf::Message& msg);
void Net_PackMsg(unsigned short msgid, ::google::protobuf::Message& msg, std::string& out);
int Net_SendMsg(a8::TcpClient* tcp_client, unsigned int seqid,
unsigned short msgid, ::google::protobuf::Message& msg);
int Net_SendMsg(a8::TcpClient* tcp_client, unsigned int seqid, unsigned short msgid,
const char* msgbody, int msgbody_len);
int Net_SendMsg(a8::TcpListener* tcp_tlistener, unsigned short socket_handle, unsigned int seqid,
unsigned short msgid, ::google::protobuf::Message& msg);
int Net_BroadcastMsg(a8::TcpListener* tcp_tlistener, unsigned int seqid,
unsigned short msgid, ::google::protobuf::Message& msg);
int Net_SendProxyCMsg(a8::TcpClient* tcp_client, unsigned short msgid, ::google::protobuf::Message& msg);
int Net_SendProxyMsg(a8::TcpListener* tcp_tlistener, int socket_handle, unsigned int seqid, unsigned short error_code,
unsigned short msgid, ::google::protobuf::Message& msg);
}

View File

@ -4,85 +4,88 @@
#include "scriptengine.h" #include "scriptengine.h"
void ScriptEngine::Init() namespace f8
{ {
engine_ = new a8::PyEngine(); void ScriptEngine::Init()
if (getenv("is_dev_env")) { {
engine_->work_path = "/var/data/conf_test/game1008/res/pyscripts/"; engine_ = new a8::PyEngine();
} else { if (getenv("is_dev_env")) {
engine_->work_path = "../config/res/pyscripts/"; engine_->work_path = "/var/data/conf_test/game1008/res/pyscripts/";
} else {
engine_->work_path = "../config/res/pyscripts/";
}
engine_->Init();
if (!engine_->IsInitialized()) {
abort();
}
} }
engine_->Init();
if (!engine_->IsInitialized()) { void ScriptEngine::UnInit()
abort(); {
engine_->UnInit();
delete engine_;
engine_ = nullptr;
}
void ScriptEngine::Update()
{
}
bool ScriptEngine::LoadModule(const std::string& module_name)
{
bool ret = engine_->LoadModule(module_name.c_str());
if (!ret) {
a8::UdpLog::Instance()->Warning("load python module %s error %s\n",
{
module_name,
engine_->GetLastError()
});
assert(false);
}
return ret;
}
bool ScriptEngine::LoadString(const std::string& str)
{
bool ret = engine_->ExecString(str.c_str());
if (!ret) {
a8::UdpLog::Instance()->Warning("load python string %s error %s",
{
str,
engine_->GetLastError()
});
assert(false);
}
return ret;
}
std::tuple<bool, a8::XValue> ScriptEngine::CallGlobalFunc(const char* func_name,
std::initializer_list<a8::XValue> args)
{
auto ret = engine_->CallGlobalFunc(func_name, args);
if (!std::get<0>(ret)) {
a8::UdpLog::Instance()->Warning("call global function %s error %s",
{
func_name,
engine_->GetLastError()
});
}
return ret;
}
std::tuple<bool, a8::XValue> ScriptEngine::CallModuleFunc(const char* module_name,
const char* func_name,
std::initializer_list<a8::XValue> args)
{
auto ret = engine_->CallModuleFunc(module_name, func_name, args);
if (!std::get<0>(ret)) {
a8::UdpLog::Instance()->Warning("call module function [%s] %s error %s",
{
module_name,
func_name,
engine_->GetLastError()
});
}
return ret;
} }
} }
void ScriptEngine::UnInit()
{
engine_->UnInit();
delete engine_;
engine_ = nullptr;
}
void ScriptEngine::Update()
{
}
bool ScriptEngine::LoadModule(const std::string& module_name)
{
bool ret = engine_->LoadModule(module_name.c_str());
if (!ret) {
a8::UdpLog::Instance()->Warning("load python module %s error %s\n",
{
module_name,
engine_->GetLastError()
});
assert(false);
}
return ret;
}
bool ScriptEngine::LoadString(const std::string& str)
{
bool ret = engine_->ExecString(str.c_str());
if (!ret) {
a8::UdpLog::Instance()->Warning("load python string %s error %s",
{
str,
engine_->GetLastError()
});
assert(false);
}
return ret;
}
std::tuple<bool, a8::XValue> ScriptEngine::CallGlobalFunc(const char* func_name,
std::initializer_list<a8::XValue> args)
{
auto ret = engine_->CallGlobalFunc(func_name, args);
if (!std::get<0>(ret)) {
a8::UdpLog::Instance()->Warning("call global function %s error %s",
{
func_name,
engine_->GetLastError()
});
}
return ret;
}
std::tuple<bool, a8::XValue> ScriptEngine::CallModuleFunc(const char* module_name,
const char* func_name,
std::initializer_list<a8::XValue> args)
{
auto ret = engine_->CallModuleFunc(module_name, func_name, args);
if (!std::get<0>(ret)) {
a8::UdpLog::Instance()->Warning("call module function [%s] %s error %s",
{
module_name,
func_name,
engine_->GetLastError()
});
}
return ret;
}

View File

@ -5,26 +5,30 @@ namespace a8
class PyEngine; class PyEngine;
}; };
class ScriptEngine : public a8::Singleton<ScriptEngine> namespace f8
{ {
private: class ScriptEngine : public a8::Singleton<ScriptEngine>
ScriptEngine() {}; {
friend class a8::Singleton<ScriptEngine>; private:
ScriptEngine() {};
friend class a8::Singleton<ScriptEngine>;
public: public:
void Init(); void Init();
void UnInit(); void UnInit();
void Update(); void Update();
bool LoadModule(const std::string& module_name); bool LoadModule(const std::string& module_name);
bool LoadString(const std::string& str); bool LoadString(const std::string& str);
std::tuple<bool, a8::XValue> CallGlobalFunc(const char* func_name, std::tuple<bool, a8::XValue> CallGlobalFunc(const char* func_name,
std::initializer_list<a8::XValue> args); std::initializer_list<a8::XValue> args);
std::tuple<bool, a8::XValue> CallModuleFunc(const char* module_name, std::tuple<bool, a8::XValue> CallModuleFunc(const char* module_name,
const char* func_name, const char* func_name,
std::initializer_list<a8::XValue> args); std::initializer_list<a8::XValue> args);
public: public:
a8::PyEngine *engine_ = nullptr; a8::PyEngine *engine_ = nullptr;
}; };
}

View File

@ -7,189 +7,192 @@
#include <a8/mutable_xobject.h> #include <a8/mutable_xobject.h>
#include "tglog.h" #include "tglog.h"
static const char* const TGLOG_ROOT = "/data/logs/%s/upload/"; namespace f8
static const char* const POLY_TGLOG_ROOT = "/data/logs/%s/%s/upload/";
static const char* const TGLOG_FILENAME = "log_$pid_%Y%m%d%H.log";
struct TGLogMsgNode
{ {
int game_id = 0; static const char* const TGLOG_ROOT = "/data/logs/%s/upload/";
std::string jsonstr; static const char* const POLY_TGLOG_ROOT = "/data/logs/%s/%s/upload/";
TGLogMsgNode* next = nullptr; static const char* const TGLOG_FILENAME = "log_$pid_%Y%m%d%H.log";
};
struct TGLogImpl struct TGLogMsgNode
{
std::string filename_fmt;
std::string project_name;
bool is_poly_log = false;
std::thread* save_thread = nullptr;
bool save_thread_shutdown = false;
std::mutex msg_mutex;
TGLogMsgNode* top_node = nullptr;
TGLogMsgNode* bot_node = nullptr;
TGLogMsgNode* work_node = nullptr;
std::mutex *save_cond_mutex = nullptr;
std::condition_variable *save_cond = nullptr;
TGLogImpl()
{ {
save_cond_mutex = new std::mutex(); int game_id = 0;
save_cond = new std::condition_variable(); std::string jsonstr;
} TGLogMsgNode* next = nullptr;
};
virtual ~TGLogImpl() struct TGLogImpl
{ {
delete save_cond_mutex; std::string filename_fmt;
save_cond_mutex = nullptr; std::string project_name;
delete save_cond; bool is_poly_log = false;
save_cond = nullptr;
}
std::string GetCurrentFileName() std::thread* save_thread = nullptr;
{ bool save_thread_shutdown = false;
time_t nowtime = time(nullptr);
struct tm tm_nowtime = {0};
localtime_r(&nowtime, &tm_nowtime);
char szfilename[256]; std::mutex msg_mutex;
szfilename[0] = '\0'; TGLogMsgNode* top_node = nullptr;
strftime(szfilename, a8::ArraySize(szfilename), filename_fmt.c_str(), &tm_nowtime); TGLogMsgNode* bot_node = nullptr;
std::string filename((char*)szfilename); TGLogMsgNode* work_node = nullptr;
return filename; std::mutex *save_cond_mutex = nullptr;
} std::condition_variable *save_cond = nullptr;
};
void TGLog::Init() TGLogImpl()
{
impl_ = new TGLogImpl();
impl_->filename_fmt = TGLOG_FILENAME;
a8::ReplaceString(impl_->filename_fmt, "$pid", a8::XValue(getpid()));
impl_->project_name = project_name_;
impl_->is_poly_log = is_poly_log_;
impl_->save_thread_shutdown = false;
impl_->save_thread = new std::thread(&TGLog::SaveToFileThreadProc, this);
}
void TGLog::UnInit()
{
delete impl_;
impl_ = nullptr;
}
void TGLog::SetProjectInfo(const std::string& project_name, bool is_poly_log)
{
project_name_ = project_name;
is_poly_log_ = is_poly_log;
}
void TGLog::AddTrackLog(int game_id, const std::string& accountid, unsigned long ip_saddr,
int logclass1, int logclass2, a8::XObject* prop)
{
std::string logtime_str;
{
time_t nowtime = time(nullptr);
struct tm tm_time = {0};
localtime_r(&nowtime, &tm_time);
char buff[256];
strftime(buff, a8::ArraySize(buff), "%F %T", &tm_time);
logtime_str.append((char*)buff);
}
a8::MutableXObject* xobj = a8::MutableXObject::NewObject();
xobj->SetVal("#account_id", accountid);
xobj->SetVal("#type", "track");
xobj->SetVal("#time", logtime_str);
xobj->SetVal("#ip", a8::GetIpAddress(ip_saddr));
xobj->SetVal("#event_name", a8::Format("event_%d_%d", {logclass1, logclass2}));
xobj->SetVal("properties", *prop);
{
TGLogMsgNode *p = new TGLogMsgNode();
p->game_id = game_id;
xobj->ToJsonStr(p->jsonstr);
impl_->msg_mutex.lock();
if (impl_->bot_node) {
impl_->bot_node->next = p;
impl_->bot_node = p;
} else {
impl_->top_node = p;
impl_->bot_node = p;
}
impl_->msg_mutex.unlock();
{ {
std::unique_lock<std::mutex> lk(*impl_->save_cond_mutex); save_cond_mutex = new std::mutex();
impl_->save_cond->notify_all(); save_cond = new std::condition_variable();
} }
virtual ~TGLogImpl()
{
delete save_cond_mutex;
save_cond_mutex = nullptr;
delete save_cond;
save_cond = nullptr;
}
std::string GetCurrentFileName()
{
time_t nowtime = time(nullptr);
struct tm tm_nowtime = {0};
localtime_r(&nowtime, &tm_nowtime);
char szfilename[256];
szfilename[0] = '\0';
strftime(szfilename, a8::ArraySize(szfilename), filename_fmt.c_str(), &tm_nowtime);
std::string filename((char*)szfilename);
return filename;
}
};
void TGLog::Init()
{
impl_ = new TGLogImpl();
impl_->filename_fmt = TGLOG_FILENAME;
a8::ReplaceString(impl_->filename_fmt, "$pid", a8::XValue(getpid()));
impl_->project_name = project_name_;
impl_->is_poly_log = is_poly_log_;
impl_->save_thread_shutdown = false;
impl_->save_thread = new std::thread(&TGLog::SaveToFileThreadProc, this);
} }
}
void TGLog::SaveToFileThreadProc() void TGLog::UnInit()
{ {
auto GetLogFile = [this] (std::map<int, FILE*>& opened_log_files_hash, int game_id, const std::string& filename) -> FILE* delete impl_;
{ impl_ = nullptr;
auto itr = opened_log_files_hash.find(game_id); }
if (itr == opened_log_files_hash.end()) {
std::string log_dir;
if (impl_->is_poly_log) {
log_dir = a8::Format(POLY_TGLOG_ROOT, {impl_->project_name, impl_->work_node->game_id});
} else {
log_dir = a8::Format(TGLOG_ROOT, {impl_->project_name});
}
a8::ForceCreateDir(log_dir);
FILE* logfile = fopen((log_dir + filename).c_str(), "a+");
if (logfile) {
opened_log_files_hash[game_id] = logfile;
}
return logfile;
} else {
return itr->second;
}
};
while (!impl_->save_thread_shutdown) { void TGLog::SetProjectInfo(const std::string& project_name, bool is_poly_log)
if (!impl_->work_node && impl_->top_node) { {
project_name_ = project_name;
is_poly_log_ = is_poly_log;
}
void TGLog::AddTrackLog(int game_id, const std::string& accountid, unsigned long ip_saddr,
int logclass1, int logclass2, a8::XObject* prop)
{
std::string logtime_str;
{
time_t nowtime = time(nullptr);
struct tm tm_time = {0};
localtime_r(&nowtime, &tm_time);
char buff[256];
strftime(buff, a8::ArraySize(buff), "%F %T", &tm_time);
logtime_str.append((char*)buff);
}
a8::MutableXObject* xobj = a8::MutableXObject::NewObject();
xobj->SetVal("#account_id", accountid);
xobj->SetVal("#type", "track");
xobj->SetVal("#time", logtime_str);
xobj->SetVal("#ip", a8::GetIpAddress(ip_saddr));
xobj->SetVal("#event_name", a8::Format("event_%d_%d", {logclass1, logclass2}));
xobj->SetVal("properties", *prop);
{
TGLogMsgNode *p = new TGLogMsgNode();
p->game_id = game_id;
xobj->ToJsonStr(p->jsonstr);
impl_->msg_mutex.lock(); impl_->msg_mutex.lock();
impl_->work_node = impl_->top_node; if (impl_->bot_node) {
impl_->top_node = nullptr; impl_->bot_node->next = p;
impl_->bot_node = nullptr; impl_->bot_node = p;
} else {
impl_->top_node = p;
impl_->bot_node = p;
}
impl_->msg_mutex.unlock(); impl_->msg_mutex.unlock();
} {
std::unique_lock<std::mutex> lk(*impl_->save_cond_mutex);
if (impl_->work_node) { impl_->save_cond->notify_all();
std::string filename = impl_->GetCurrentFileName();
std::map<int, FILE*> opened_log_files_hash;
while (impl_->work_node) {
TGLogMsgNode* nextnode = impl_->work_node->next;
TGLogMsgNode* work_node = impl_->work_node;
FILE* logfile = GetLogFile(opened_log_files_hash, work_node->game_id, filename);
if (logfile) {
work_node->jsonstr.push_back('\n');
fwrite(work_node->jsonstr.c_str(), 1, work_node->jsonstr.size(), logfile);
}
delete work_node;
impl_->work_node = nextnode;
} }
for (auto& pair : opened_log_files_hash) {
if (pair.second) {
fclose(pair.second);
}
}
}
{
std::unique_lock<std::mutex> lk(*impl_->save_cond_mutex);
impl_->save_cond->wait_for(lk, std::chrono::seconds(10));
} }
} }
void TGLog::SaveToFileThreadProc()
{
auto GetLogFile = [this] (std::map<int, FILE*>& opened_log_files_hash, int game_id, const std::string& filename) -> FILE*
{
auto itr = opened_log_files_hash.find(game_id);
if (itr == opened_log_files_hash.end()) {
std::string log_dir;
if (impl_->is_poly_log) {
log_dir = a8::Format(POLY_TGLOG_ROOT, {impl_->project_name, impl_->work_node->game_id});
} else {
log_dir = a8::Format(TGLOG_ROOT, {impl_->project_name});
}
a8::ForceCreateDir(log_dir);
FILE* logfile = fopen((log_dir + filename).c_str(), "a+");
if (logfile) {
opened_log_files_hash[game_id] = logfile;
}
return logfile;
} else {
return itr->second;
}
};
while (!impl_->save_thread_shutdown) {
if (!impl_->work_node && impl_->top_node) {
impl_->msg_mutex.lock();
impl_->work_node = impl_->top_node;
impl_->top_node = nullptr;
impl_->bot_node = nullptr;
impl_->msg_mutex.unlock();
}
if (impl_->work_node) {
std::string filename = impl_->GetCurrentFileName();
std::map<int, FILE*> opened_log_files_hash;
while (impl_->work_node) {
TGLogMsgNode* nextnode = impl_->work_node->next;
TGLogMsgNode* work_node = impl_->work_node;
FILE* logfile = GetLogFile(opened_log_files_hash, work_node->game_id, filename);
if (logfile) {
work_node->jsonstr.push_back('\n');
fwrite(work_node->jsonstr.c_str(), 1, work_node->jsonstr.size(), logfile);
}
delete work_node;
impl_->work_node = nextnode;
}
for (auto& pair : opened_log_files_hash) {
if (pair.second) {
fclose(pair.second);
}
}
}
{
std::unique_lock<std::mutex> lk(*impl_->save_cond_mutex);
impl_->save_cond->wait_for(lk, std::chrono::seconds(10));
}
}
}
} }

View File

@ -1,25 +1,28 @@
#pragma once #pragma once
struct TGLogImpl; namespace f8
class TGLog : public a8::Singleton<TGLog>
{ {
private: struct TGLogImpl;
TGLog() {}; class TGLog : public a8::Singleton<TGLog>
friend class a8::Singleton<TGLog>; {
private:
TGLog() {};
friend class a8::Singleton<TGLog>;
public: public:
void Init(); void Init();
void UnInit(); void UnInit();
void SetProjectInfo(const std::string& project_name, bool is_poly_log); void SetProjectInfo(const std::string& project_name, bool is_poly_log);
void AddTrackLog(int game_id, const std::string& accountid, unsigned long ip_saddr, void AddTrackLog(int game_id, const std::string& accountid, unsigned long ip_saddr,
int logclass1, int logclass2, a8::XObject* prop); int logclass1, int logclass2, a8::XObject* prop);
private: private:
void SaveToFileThreadProc(); void SaveToFileThreadProc();
private: private:
std::string project_name_; std::string project_name_;
bool is_poly_log_ = false; bool is_poly_log_ = false;
TGLogImpl* impl_ = nullptr; TGLogImpl* impl_ = nullptr;
}; };
}

View File

@ -3,355 +3,357 @@
#include <a8/stringlist.h> #include <a8/stringlist.h>
#include "framework/cpp/tiledmap.h" #include "framework/cpp/tiledmap.h"
a8::XValue TiledObject::GetProperty(const std::string& prop_name) namespace f8
{ {
auto itr = prop_hash.find(prop_name); a8::XValue TiledObject::GetProperty(const std::string& prop_name)
return itr != prop_hash.end() ? itr->second : a8::XValue(); {
} auto itr = prop_hash.find(prop_name);
return itr != prop_hash.end() ? itr->second : a8::XValue();
bool TiledObject::HasProperty(const std::string& prop_name)
{
auto itr = prop_hash.find(prop_name);
return itr != prop_hash.end();
}
a8::XValue TiledLayer::GetProperty(const std::string& prop_name)
{
auto itr = prop_hash.find(prop_name);
return itr != prop_hash.end() ? itr->second : a8::XValue();
}
bool TiledLayer::HasProperty(const std::string& prop_name)
{
auto itr = prop_hash.find(prop_name);
return itr != prop_hash.end();
}
bool TiledMap::LoadTmxFile(const std::string& filename)
{
a8::XObject xobj;
if (!xobj.ReadFromXmlFile(filename)) {
return false;
} }
std::shared_ptr<a8::XObject> tileset_node = xobj.At("child_node.tileset")->At(0); bool TiledObject::HasProperty(const std::string& prop_name)
tile_width = tileset_node->At("attrs.tilewidth")->AsXValue(); {
tile_height = tileset_node->At("attrs.tileheight")->AsXValue(); auto itr = prop_hash.find(prop_name);
#if 0 return itr != prop_hash.end();
tile_count = tileset_node->At("attrs.tilecount")->AsXValue();
tile_columns = tileset_node->At("attrs.columns")->AsXValue();
tile_rows = tile_count/tile_columns + 1;
tile_columns += 1;
tile_count = tile_rows * tile_columns;
#endif
for (int i = 0; i < xobj.At("child_node.layer")->Size(); ++i) {
std::shared_ptr<a8::XObject> layer_node = xobj.At("child_node.layer")->At(i);
TiledLayer layer;
{
for (int ii = 0; ii < layer_node->At("attr_names")->Size(); ++ii) {
std::string attr_name = layer_node->At("attr_names")->At(ii)->AsXValue();
layer.prop_hash[attr_name] = layer_node->At("attrs." + attr_name)->AsXValue();
}
std::shared_ptr<a8::XObject> prop_nodes = layer_node->At("child_node.properties")->At(0)->At("child_node.property");
for (int j = 0; j < prop_nodes->Size(); ++j) {
std::shared_ptr<a8::XObject> prop_node = prop_nodes->At(j);
layer.prop_hash[prop_node->At("attrs.name")->AsXValue()] = prop_node->At("attrs.value")->AsXValue();
}
std::shared_ptr<a8::XObject> data_node = layer_node->At("child_node.data")->At(0);
layer.data = data_node->At("node_value")->AsXValue();
}
std::string layer_name = layer_node->At("attrs.name")->AsXValue();
if (layer_name.compare("ground") == 0) {
tile_columns = layer_node->At("attrs.width")->AsXValue();
tile_rows = layer_node->At("attrs.height")->AsXValue();
tile_count = tile_rows * tile_columns;
}
auto itr = layer_hash.find(layer_name);
if (itr != layer_hash.end()) {
itr->second.push_back(layer);
} else {
layer_hash[layer_name] = std::list<TiledLayer>({layer});
}
} }
a8::XValue TiledLayer::GetProperty(const std::string& prop_name)
{
auto itr = prop_hash.find(prop_name);
return itr != prop_hash.end() ? itr->second : a8::XValue();
}
bool TiledLayer::HasProperty(const std::string& prop_name)
{
auto itr = prop_hash.find(prop_name);
return itr != prop_hash.end();
}
bool TiledMap::LoadTmxFile(const std::string& filename)
{
a8::XObject xobj;
if (!xobj.ReadFromXmlFile(filename)) {
return false;
}
std::shared_ptr<a8::XObject> tileset_node = xobj.At("child_node.tileset")->At(0);
tile_width = tileset_node->At("attrs.tilewidth")->AsXValue();
tile_height = tileset_node->At("attrs.tileheight")->AsXValue();
#if 0
tile_count = tileset_node->At("attrs.tilecount")->AsXValue();
tile_columns = tileset_node->At("attrs.columns")->AsXValue();
tile_rows = tile_count/tile_columns + 1;
tile_columns += 1;
tile_count = tile_rows * tile_columns;
#endif
for (int i = 0; i < xobj.At("child_node.layer")->Size(); ++i) {
std::shared_ptr<a8::XObject> layer_node = xobj.At("child_node.layer")->At(i);
TiledLayer layer;
{
for (int ii = 0; ii < layer_node->At("attr_names")->Size(); ++ii) {
std::string attr_name = layer_node->At("attr_names")->At(ii)->AsXValue();
layer.prop_hash[attr_name] = layer_node->At("attrs." + attr_name)->AsXValue();
}
std::shared_ptr<a8::XObject> prop_nodes = layer_node->At("child_node.properties")->At(0)->At("child_node.property");
for (int j = 0; j < prop_nodes->Size(); ++j) {
std::shared_ptr<a8::XObject> prop_node = prop_nodes->At(j);
layer.prop_hash[prop_node->At("attrs.name")->AsXValue()] = prop_node->At("attrs.value")->AsXValue();
}
std::shared_ptr<a8::XObject> data_node = layer_node->At("child_node.data")->At(0);
layer.data = data_node->At("node_value")->AsXValue();
}
std::string layer_name = layer_node->At("attrs.name")->AsXValue();
if (layer_name.compare("ground") == 0) {
tile_columns = layer_node->At("attrs.width")->AsXValue();
tile_rows = layer_node->At("attrs.height")->AsXValue();
tile_count = tile_rows * tile_columns;
}
auto itr = layer_hash.find(layer_name);
if (itr != layer_hash.end()) {
itr->second.push_back(layer);
} else {
layer_hash[layer_name] = std::list<TiledLayer>({layer});
}
}
std::shared_ptr<a8::XObject> objgroup_node = xobj.At("child_node.objectgroup")->At(0); std::shared_ptr<a8::XObject> objgroup_node = xobj.At("child_node.objectgroup")->At(0);
for (int i = 0; i < objgroup_node->At("child_node.object")->Size(); i++) { for (int i = 0; i < objgroup_node->At("child_node.object")->Size(); i++) {
std::shared_ptr<a8::XObject> object_node = objgroup_node->At("child_node.object")->At(i); std::shared_ptr<a8::XObject> object_node = objgroup_node->At("child_node.object")->At(i);
TiledObject object; TiledObject object;
{ {
for (int ii = 0; ii < object_node->At("attr_names")->Size(); ii++) { for (int ii = 0; ii < object_node->At("attr_names")->Size(); ii++) {
std::string attr_name = object_node->At("attr_names")->At(ii)->AsXValue(); std::string attr_name = object_node->At("attr_names")->At(ii)->AsXValue();
object.prop_hash[attr_name] = object_node->At("attrs." + attr_name)->AsXValue(); object.prop_hash[attr_name] = object_node->At("attrs." + attr_name)->AsXValue();
} }
std::shared_ptr<a8::XObject> prop_nodes = object_node->At("child_node.properties")->At(0)->At("child_node.property"); std::shared_ptr<a8::XObject> prop_nodes = object_node->At("child_node.properties")->At(0)->At("child_node.property");
for (int j = 0; j < prop_nodes->Size(); j++) { for (int j = 0; j < prop_nodes->Size(); j++) {
std::shared_ptr<a8::XObject> prop_node = prop_nodes->At(j); std::shared_ptr<a8::XObject> prop_node = prop_nodes->At(j);
object.prop_hash[prop_node->At("attrs.name")->AsXValue()] = prop_node->At("attrs.value")->AsXValue(); object.prop_hash[prop_node->At("attrs.name")->AsXValue()] = prop_node->At("attrs.value")->AsXValue();
} }
} }
std::string object_name = object_node->At("attrs.name")->AsXValue(); std::string object_name = object_node->At("attrs.name")->AsXValue();
auto itr = object_group_hash.find(object_name); auto itr = object_group_hash.find(object_name);
if (itr != object_group_hash.end()) { if (itr != object_group_hash.end()) {
itr->second.push_back(object); itr->second.push_back(object);
} }
else else
{ {
object_group_hash[object_name] = std::list<TiledObject>({ object }); object_group_hash[object_name] = std::list<TiledObject>({ object });
} }
} }
return true; return true;
} }
std::list<TiledObject>* TiledMap::GetObjectGroup(const std::string& object_class_name) std::list<TiledObject>* TiledMap::GetObjectGroup(const std::string& object_class_name)
{ {
auto itr = object_group_hash.find(object_class_name); auto itr = object_group_hash.find(object_class_name);
return itr != object_group_hash.end() ? &itr->second : nullptr; return itr != object_group_hash.end() ? &itr->second : nullptr;
} }
StagePoint* TiledMap::GetStageObject(int point) StagePoint* TiledMap::GetStageObject(int point)
{ {
auto itr = stage_object_hash.find(point); auto itr = stage_object_hash.find(point);
return itr != stage_object_hash.end() ? &itr->second : nullptr; return itr != stage_object_hash.end() ? &itr->second : nullptr;
} }
bool TiledMap::HasStageObject(int point) bool TiledMap::HasStageObject(int point)
{ {
auto itr = stage_object_hash.find(point); auto itr = stage_object_hash.find(point);
return itr != stage_object_hash.end(); return itr != stage_object_hash.end();
} }
std::vector<GridCell*>* TiledMap::GetStagePath(const std::string& path_name) std::vector<GridCell*>* TiledMap::GetStagePath(const std::string& path_name)
{ {
auto itr = stage_path_hash.find(path_name); auto itr = stage_path_hash.find(path_name);
return itr != stage_path_hash.end() ? &itr->second : nullptr; return itr != stage_path_hash.end() ? &itr->second : nullptr;
} }
bool TiledMap::HasStagePath(const std::string& path_name) bool TiledMap::HasStagePath(const std::string& path_name)
{ {
auto itr = stage_path_hash.find(path_name); auto itr = stage_path_hash.find(path_name);
return itr != stage_path_hash.end(); return itr != stage_path_hash.end();
} }
void TiledMap::Init() void TiledMap::Init()
{ {
grid_cell_list.reserve(tile_count); grid_cell_list.reserve(tile_count);
grid_cell_list.assign(tile_count,GridCell{}); grid_cell_list.assign(tile_count,GridCell{});
for (auto& pair : layer_hash) { for (auto& pair : layer_hash) {
for (auto& layer : pair.second) { for (auto& layer : pair.second) {
std::string name = layer.GetProperty("name").GetString(); std::string name = layer.GetProperty("name").GetString();
bool has_speed = layer.HasProperty("area_id"); bool has_speed = layer.HasProperty("area_id");
int speed = layer.GetProperty("area_id"); int speed = layer.GetProperty("area_id");
bool has_trigger = layer.HasProperty("isTrigger"); bool has_trigger = layer.HasProperty("isTrigger");
bool istrigger = layer.GetProperty("isTrigger");; bool istrigger = layer.GetProperty("isTrigger");;
int trigger_point = layer.GetProperty("objName"); int trigger_point = layer.GetProperty("objName");
bool has_num = layer.HasProperty("num"); bool has_num = layer.HasProperty("num");
//int num = layer.GetProperty("num"); //int num = layer.GetProperty("num");
std::vector<GridCell*> grid_cell_path_list; std::vector<GridCell*> grid_cell_path_list;
a8::StringList str_list; a8::StringList str_list;
str_list.SetText(layer.data.GetString().c_str()); str_list.SetText(layer.data.GetString().c_str());
for (int i = 1; i < str_list.Count(); ++i) { for (int i = 1; i < str_list.Count(); ++i) {
std::string str_line = str_list.String(i); std::string str_line = str_list.String(i);
std::vector<std::string> split_list; std::vector<std::string> split_list;
a8::Split(str_line, split_list); a8::Split(str_line, split_list);
int split_count = split_list.size(); int split_count = split_list.size();
for(int j = 0; j < split_count; ++j){ for(int j = 0; j < split_count; ++j){
int value = a8::XValue(split_list[j]); int value = a8::XValue(split_list[j]);
if(value > 0){ if(value > 0){
int index = (i-1)*tile_columns + j; int index = (i-1)*tile_columns + j;
if (has_speed) { if (has_speed) {
grid_cell_list[index].x = j; grid_cell_list[index].x = j;
grid_cell_list[index].y = i-1; grid_cell_list[index].y = i-1;
grid_cell_list[index].speed = speed; grid_cell_list[index].speed = speed;
grid_cell_list[index].value = value; grid_cell_list[index].value = value;
} }
if (has_trigger) { if (has_trigger) {
TriggerPoint tp; TriggerPoint tp;
{ {
tp.x = j; tp.x = j;
tp.y = i-1; tp.y = i-1;
tp.point = trigger_point; tp.point = trigger_point;
tp.istrigger = istrigger; tp.istrigger = istrigger;
trigger_list.push_back(tp); trigger_list.push_back(tp);
}
}
if (has_num) {
grid_cell_path_list.push_back(&grid_cell_list[index]);
} }
}
if (has_num) {
grid_cell_path_list.push_back(&grid_cell_list[index]);
} }
} }
} }
}
if (grid_cell_path_list.size() > 0) { if (grid_cell_path_list.size() > 0) {
stage_path_hash[name] = grid_cell_path_list; stage_path_hash[name] = grid_cell_path_list;
}
}
}
for (auto& pair : object_group_hash) {
for (auto& object : pair.second) {
StagePoint sp;
sp.x = object.GetProperty("tile_x");
sp.y = object.GetProperty("tile_y");
sp.point = object.GetProperty("name");
std::string str_relation = object.GetProperty("relation").GetString();
std::vector<std::string> split_list;
a8::Split(str_relation, split_list, ',');
for (auto& point : split_list) {
sp.relation_list.push_back(a8::XValue(point));
}
int point = object.GetProperty("name");
stage_object_hash[point] = sp;
}
}
}
void TiledMap::Dump()
{
Init();
#if 0
for (auto& pair : stage_path_hash) {
a8::XPrintf("stage$:%s\n", {pair.first});
for (auto& gc : pair.second) {
a8::XPrintf("path$x:%d,y:%d,speed:%d,value:%d\n", {gc->x, gc->y, gc->speed, gc->value});
}
}
#endif
#if 0
for (auto& tp : trigger_list) {
a8::XPrintf("x:%d,y:%d,point:%d,istrigger:%d\n", {tp.x, tp.y, tp.point, a8::XValue(tp.istrigger)});
}
#endif
#if 0
int len = grid_cell_list.size();
a8::XPrintf("grid_cell_size:%s\n", {len});
for (int i= 0; i < len; ++i) {
auto gc = grid_cell_list[i];
a8::XPrintf("i:%d, x:%d,y:%d,speed:%d,value:%d\n", {i, gc.x, gc.y, gc.speed, gc.value});
}
#endif
#if 0
for (auto& pair : stage_object_hash) {
a8::XPrintf("object$:%s\n", {pair.first});
a8::XPrintf("value$x:%d,y:%d,p:%s,relation:", {pair.second.x, pair.second.y, pair.second.point});
for (auto& relation : pair.second.relation_list) {
a8::XPrintf("%s,", {relation});
}
a8::XPrintf("\n",{});
}
#endif
return;
a8::XPrintf("map$tile_count:%d\n", {tile_count});
a8::XPrintf("map$tile_width:%d\n", { tile_width });
a8::XPrintf("map$tile_height:%d\n", { tile_height });
a8::XPrintf("layer$layer_hash.size:%d\n", {layer_hash.size()});
for (auto& pair : layer_hash) {
a8::XPrintf(" layer$layer_type:%s\n", {pair.first});
for (auto& layer : pair.second) {
a8::XPrintf("data$data:%s\n",{layer.data});
for (auto& pair2 : layer.prop_hash) {
a8::XPrintf(" layer$%s:%s\n", {pair2.first, pair2.second});
}
}
}
a8::XPrintf("object$object_group_hash.size:%d\n", {object_group_hash.size()});
for (auto& pair : object_group_hash) {
a8::XPrintf(" object$layer_type:%s\n", {pair.first});
for (auto& layer : pair.second) {
for (auto& pair2 : layer.prop_hash) {
a8::XPrintf(" object$%s:%s\n", {pair2.first, pair2.second});
}
}
}
}
bool TiledMap::CalcCurrPos(std::vector<int>& path_points, int old_pos_x, int old_pos_y, int time_ms, int& curr_pos_x, int& curr_pos_y)
{
if (path_points.size() < 2) {
return false;
}
StagePoint* sp_terminal = GetStageObject(path_points[path_points.size()-1]);
if (sp_terminal) {
if (old_pos_x == sp_terminal->x && old_pos_y == sp_terminal->y) {
curr_pos_x = old_pos_x;
curr_pos_y = old_pos_y;
return true;
}
//报错放终点
curr_pos_x = sp_terminal->x;
curr_pos_y = sp_terminal->y;
}
std::vector<std::string> stage_path_list;
{
std::string path_point;
bool path_start = true;
for (auto& point : path_points) {
if (path_start) {
path_point = a8::XValue(point).GetString();
path_start = !path_start;
} else {
std::string point_str = a8::XValue(point).GetString();
path_point += "-" + point_str;
stage_path_list.push_back(path_point);
path_point = point_str;
}
}
}
std::vector<GridCell*> grid_all_list;
{
bool exc_once = true;
for (auto& stage_path : stage_path_list) {
std::vector<GridCell*>* grid_list = nullptr;
std::string stage_path_reverse;
std::vector<std::string> split_list;
a8::Split(stage_path,split_list,'-');
if (split_list.size() != 2) {
return false;
}
StagePoint* sp = GetStageObject(a8::XValue(split_list.at(0)));
if (sp == nullptr) {
return false;
}
grid_list = GetStagePath(stage_path);
if (grid_list == nullptr) {
stage_path_reverse = split_list[1] + "-" + split_list[0];
grid_list = GetStagePath(stage_path_reverse);
if (grid_list == nullptr) {
return false;
} }
} }
}
std::vector<GridCell*> grid_sort_list = SortGridList(grid_list,sp); for (auto& pair : object_group_hash) {
if (grid_sort_list.size() < 2) { for (auto& object : pair.second) {
return false; StagePoint sp;
} sp.x = object.GetProperty("tile_x");
if (exc_once) { sp.y = object.GetProperty("tile_y");
grid_all_list.insert(grid_all_list.end(),grid_sort_list.begin(),grid_sort_list.end()); sp.point = object.GetProperty("name");
exc_once = false; std::string str_relation = object.GetProperty("relation").GetString();
} else { std::vector<std::string> split_list;
grid_all_list.insert(grid_all_list.end(),grid_sort_list.begin()+1,grid_sort_list.end()); a8::Split(str_relation, split_list, ',');
for (auto& point : split_list) {
sp.relation_list.push_back(a8::XValue(point));
}
int point = object.GetProperty("name");
stage_object_hash[point] = sp;
} }
} }
} }
void TiledMap::Dump()
{
Init();
#if 0
for (auto& pair : stage_path_hash) {
a8::XPrintf("stage$:%s\n", {pair.first});
for (auto& gc : pair.second) {
a8::XPrintf("path$x:%d,y:%d,speed:%d,value:%d\n", {gc->x, gc->y, gc->speed, gc->value});
}
}
#endif
#if 0
for (auto& tp : trigger_list) {
a8::XPrintf("x:%d,y:%d,point:%d,istrigger:%d\n", {tp.x, tp.y, tp.point, a8::XValue(tp.istrigger)});
}
#endif
#if 0
int len = grid_cell_list.size();
a8::XPrintf("grid_cell_size:%s\n", {len});
for (int i= 0; i < len; ++i) {
auto gc = grid_cell_list[i];
a8::XPrintf("i:%d, x:%d,y:%d,speed:%d,value:%d\n", {i, gc.x, gc.y, gc.speed, gc.value});
}
#endif
#if 0
for (auto& pair : stage_object_hash) {
a8::XPrintf("object$:%s\n", {pair.first});
a8::XPrintf("value$x:%d,y:%d,p:%s,relation:", {pair.second.x, pair.second.y, pair.second.point});
for (auto& relation : pair.second.relation_list) {
a8::XPrintf("%s,", {relation});
}
a8::XPrintf("\n",{});
}
#endif
return;
a8::XPrintf("map$tile_count:%d\n", {tile_count});
a8::XPrintf("map$tile_width:%d\n", { tile_width });
a8::XPrintf("map$tile_height:%d\n", { tile_height });
a8::XPrintf("layer$layer_hash.size:%d\n", {layer_hash.size()});
for (auto& pair : layer_hash) {
a8::XPrintf(" layer$layer_type:%s\n", {pair.first});
for (auto& layer : pair.second) {
a8::XPrintf("data$data:%s\n",{layer.data});
for (auto& pair2 : layer.prop_hash) {
a8::XPrintf(" layer$%s:%s\n", {pair2.first, pair2.second});
}
}
}
a8::XPrintf("object$object_group_hash.size:%d\n", {object_group_hash.size()});
for (auto& pair : object_group_hash) {
a8::XPrintf(" object$layer_type:%s\n", {pair.first});
for (auto& layer : pair.second) {
for (auto& pair2 : layer.prop_hash) {
a8::XPrintf(" object$%s:%s\n", {pair2.first, pair2.second});
}
}
}
}
bool TiledMap::CalcCurrPos(std::vector<int>& path_points, int old_pos_x, int old_pos_y, int time_ms, int& curr_pos_x, int& curr_pos_y)
{
if (path_points.size() < 2) {
return false;
}
StagePoint* sp_terminal = GetStageObject(path_points[path_points.size()-1]);
if (sp_terminal) {
if (old_pos_x == sp_terminal->x && old_pos_y == sp_terminal->y) {
curr_pos_x = old_pos_x;
curr_pos_y = old_pos_y;
return true;
}
//报错放终点
curr_pos_x = sp_terminal->x;
curr_pos_y = sp_terminal->y;
}
std::vector<std::string> stage_path_list;
{
std::string path_point;
bool path_start = true;
for (auto& point : path_points) {
if (path_start) {
path_point = a8::XValue(point).GetString();
path_start = !path_start;
} else {
std::string point_str = a8::XValue(point).GetString();
path_point += "-" + point_str;
stage_path_list.push_back(path_point);
path_point = point_str;
}
}
}
std::vector<GridCell*> grid_all_list;
{
bool exc_once = true;
for (auto& stage_path : stage_path_list) {
std::vector<GridCell*>* grid_list = nullptr;
std::string stage_path_reverse;
std::vector<std::string> split_list;
a8::Split(stage_path,split_list,'-');
if (split_list.size() != 2) {
return false;
}
StagePoint* sp = GetStageObject(a8::XValue(split_list.at(0)));
if (sp == nullptr) {
return false;
}
grid_list = GetStagePath(stage_path);
if (grid_list == nullptr) {
stage_path_reverse = split_list[1] + "-" + split_list[0];
grid_list = GetStagePath(stage_path_reverse);
if (grid_list == nullptr) {
return false;
}
}
std::vector<GridCell*> grid_sort_list = SortGridList(grid_list,sp);
if (grid_sort_list.size() < 2) {
return false;
}
if (exc_once) {
grid_all_list.insert(grid_all_list.end(),grid_sort_list.begin(),grid_sort_list.end());
exc_once = false;
} else {
grid_all_list.insert(grid_all_list.end(),grid_sort_list.begin()+1,grid_sort_list.end());
}
}
}
if (grid_all_list.empty()) { if (grid_all_list.empty()) {
return false; return false;
} }
@ -458,3 +460,4 @@ void TiledMap::SetGridCellSpeedByAreaId(std::map<int,int>& area_speed_hash)
} }
} }
} }
}

View File

@ -1,87 +1,90 @@
#pragma once #pragma once
class TiledObject namespace f8
{ {
public: class TiledObject
a8::XValue GetProperty(const std::string& prop_name); {
bool HasProperty(const std::string& prop_name); public:
a8::XValue GetProperty(const std::string& prop_name);
bool HasProperty(const std::string& prop_name);
public: public:
std::map<std::string, a8::XValue> prop_hash; std::map<std::string, a8::XValue> prop_hash;
}; };
class TiledLayer class TiledLayer
{ {
public: public:
a8::XValue GetProperty(const std::string& prop_name); a8::XValue GetProperty(const std::string& prop_name);
bool HasProperty(const std::string& prop_name); bool HasProperty(const std::string& prop_name);
public: public:
std::map<std::string, a8::XValue> prop_hash; std::map<std::string, a8::XValue> prop_hash;
a8::XValue data; a8::XValue data;
}; };
//格子对象 //格子对象
struct GridCell struct GridCell
{ {
int x = 0; int x = 0;
int y = 0; int y = 0;
int speed = 0; int speed = 0;
int value = 0; int value = 0;
}; };
struct StagePoint struct StagePoint
{ {
int x = 0; int x = 0;
int y = 0; int y = 0;
int point = 0; int point = 0;
std::vector<int> relation_list; std::vector<int> relation_list;
}; };
struct TriggerPoint struct TriggerPoint
{ {
int x = 0; int x = 0;
int y = 0; int y = 0;
int point = 0; int point = 0;
bool istrigger = false; bool istrigger = false;
}; };
class TiledMap class TiledMap
{ {
public: public:
TiledLayer* ground_layer = nullptr; TiledLayer* ground_layer = nullptr;
std::list<TiledLayer> speed_layers; std::list<TiledLayer> speed_layers;
int tile_count = 0; //瓦片地图的尺寸。(以瓦片数量为单位) int tile_count = 0; //瓦片地图的尺寸。(以瓦片数量为单位)
int tile_width = 0; //瓦片的宽。(以像素点为单位) int tile_width = 0; //瓦片的宽。(以像素点为单位)
int tile_height = 0; //瓦片的高。(以像素点为单位) int tile_height = 0; //瓦片的高。(以像素点为单位)
int tile_rows = 0; //行 int tile_rows = 0; //行
int tile_columns = 0; //列 int tile_columns = 0; //列
bool LoadTmxFile(const std::string& filename); bool LoadTmxFile(const std::string& filename);
std::list<TiledObject>* GetObjectGroup(const std::string& object_class_name); std::list<TiledObject>* GetObjectGroup(const std::string& object_class_name);
void Dump(); void Dump();
void Init(); void Init();
StagePoint* GetStageObject(int point); StagePoint* GetStageObject(int point);
bool HasStageObject(int point); bool HasStageObject(int point);
std::vector<GridCell*>* GetStagePath(const std::string& path_name); std::vector<GridCell*>* GetStagePath(const std::string& path_name);
bool HasStagePath(const std::string& path_name); bool HasStagePath(const std::string& path_name);
std::vector<GridCell*> SortGridList(std::vector<GridCell*>* grid_list, StagePoint* sp); std::vector<GridCell*> SortGridList(std::vector<GridCell*>* grid_list, StagePoint* sp);
bool CalcCurrPos(std::vector<int>& path_points, int old_pos_x, int old_pos_y, int time_ms, int& curr_pos_x, int& curr_pos_y); bool CalcCurrPos(std::vector<int>& path_points, int old_pos_x, int old_pos_y, int time_ms, int& curr_pos_x, int& curr_pos_y);
//速度设置 //速度设置
void SetGridCellSpeedByAreaId(std::map<int,int>& area_speed_hash);//key:area_id value:speed void SetGridCellSpeedByAreaId(std::map<int,int>& area_speed_hash);//key:area_id value:speed
private: private:
std::map<std::string, std::list<TiledLayer>> layer_hash; std::map<std::string, std::list<TiledLayer>> layer_hash;
std::map<std::string, std::list<TiledObject>> object_group_hash; std::map<std::string, std::list<TiledObject>> object_group_hash;
std::map<int, StagePoint> stage_object_hash; //key point std::map<int, StagePoint> stage_object_hash; //key point
std::vector<TriggerPoint> trigger_list; std::vector<TriggerPoint> trigger_list;
std::map<std::string, std::vector<GridCell*>> stage_path_hash; //key 11|2 std::map<std::string, std::vector<GridCell*>> stage_path_hash; //key 11|2
std::vector<GridCell> grid_cell_list; //所有的格子数组 size = x * y std::vector<GridCell> grid_cell_list; //所有的格子数组 size = x * y
std::map<std::string, std::vector<GridCell>> grid_cell_hash; //key 11|2 坐标 std::map<std::string, std::vector<GridCell>> grid_cell_hash; //key 11|2 坐标
}; };
}

View File

@ -9,169 +9,172 @@
#include "framework/cpp/utils.h" #include "framework/cpp/utils.h"
bool ReadCsvMetaFile(const std::string& filename, namespace f8
google::protobuf::Message* prototype,
std::function<void (google::protobuf::Message*)> push_back_func)
{ {
const google::protobuf::Descriptor* descriptor = prototype->GetDescriptor(); bool ReadCsvMetaFile(const std::string& filename,
const google::protobuf::Reflection* reflection = prototype->GetReflection(); google::protobuf::Message* prototype,
std::function<void (google::protobuf::Message*)> push_back_func)
{
const google::protobuf::Descriptor* descriptor = prototype->GetDescriptor();
const google::protobuf::Reflection* reflection = prototype->GetReflection();
a8::CsvReader reader; a8::CsvReader reader;
reader.Load(filename); reader.Load(filename);
while (reader.NextLine()) { while (reader.NextLine()) {
google::protobuf::Message* msg = prototype->New(); google::protobuf::Message* msg = prototype->New();
for (int i = 0; i < descriptor->field_count(); ++i) { for (int i = 0; i < descriptor->field_count(); ++i) {
const google::protobuf::FieldDescriptor* field_desc = descriptor->field(i); const google::protobuf::FieldDescriptor* field_desc = descriptor->field(i);
const std::string& field_name = field_desc->name(); const std::string& field_name = field_desc->name();
if (field_name.empty() || field_name[0] == '_') { if (field_name.empty() || field_name[0] == '_') {
continue; continue;
} }
switch (field_desc->cpp_type()) { switch (field_desc->cpp_type()) {
case google::protobuf::FieldDescriptor::CPPTYPE_STRING: case google::protobuf::FieldDescriptor::CPPTYPE_STRING:
{ {
reflection->SetString(msg, field_desc, reader.GetValue(field_name)); reflection->SetString(msg, field_desc, reader.GetValue(field_name));
} }
break; break;
case google::protobuf::FieldDescriptor::CPPTYPE_INT32: case google::protobuf::FieldDescriptor::CPPTYPE_INT32:
{ {
reflection->SetInt32(msg, field_desc, reader.GetValue(field_name)); reflection->SetInt32(msg, field_desc, reader.GetValue(field_name));
} }
break; break;
case google::protobuf::FieldDescriptor::CPPTYPE_UINT32: case google::protobuf::FieldDescriptor::CPPTYPE_UINT32:
{ {
reflection->SetUInt32(msg, field_desc, reader.GetValue(field_name)); reflection->SetUInt32(msg, field_desc, reader.GetValue(field_name));
} }
break; break;
case google::protobuf::FieldDescriptor::CPPTYPE_INT64: case google::protobuf::FieldDescriptor::CPPTYPE_INT64:
{ {
reflection->SetInt64(msg, field_desc, reader.GetValue(field_name)); reflection->SetInt64(msg, field_desc, reader.GetValue(field_name));
} }
break; break;
case google::protobuf::FieldDescriptor::CPPTYPE_UINT64: case google::protobuf::FieldDescriptor::CPPTYPE_UINT64:
{ {
reflection->SetUInt64(msg, field_desc, reader.GetValue(field_name)); reflection->SetUInt64(msg, field_desc, reader.GetValue(field_name));
} }
break; break;
case google::protobuf::FieldDescriptor::CPPTYPE_FLOAT: case google::protobuf::FieldDescriptor::CPPTYPE_FLOAT:
{ {
reflection->SetFloat(msg, field_desc, (double)reader.GetValue(field_name)); reflection->SetFloat(msg, field_desc, (double)reader.GetValue(field_name));
} }
break; break;
case google::protobuf::FieldDescriptor::CPPTYPE_DOUBLE: case google::protobuf::FieldDescriptor::CPPTYPE_DOUBLE:
{ {
reflection->SetDouble(msg, field_desc, reader.GetValue(field_name)); reflection->SetDouble(msg, field_desc, reader.GetValue(field_name));
} }
break; break;
default: default:
{ {
abort(); abort();
} }
break; break;
}//end switch }//end switch
}//end for }//end for
push_back_func(msg); push_back_func(msg);
delete msg; delete msg;
}
return true;
} }
return true; void InitMysqlConnection(a8::mysql::Query* query)
} {
a8::UdpLog::Instance()->Info("show variables like 'character%';", {});
void InitMysqlConnection(a8::mysql::Query* query) a8::UdpLog::Instance()->Info("Variable_name\tValue", {});
{
a8::UdpLog::Instance()->Info("show variables like 'character%';", {});
a8::UdpLog::Instance()->Info("Variable_name\tValue", {});
#if 1 #if 1
query->ExecScript("SET character_set_server=utf8;", {}); query->ExecScript("SET character_set_server=utf8;", {});
query->ExecScript("SET NAMES utf8;", {}); query->ExecScript("SET NAMES utf8;", {});
#endif #endif
query->ExecQuery("show variables like 'character%';", {}); query->ExecQuery("show variables like 'character%';", {});
while (!query->Eof()) { while (!query->Eof()) {
std::string line; std::string line;
line = query->GetValue(0).GetString() + "\t" + query->GetValue(1).GetString(); line = query->GetValue(0).GetString() + "\t" + query->GetValue(1).GetString();
a8::UdpLog::Instance()->Info(line.c_str(), {}); a8::UdpLog::Instance()->Info(line.c_str(), {});
assert(!(query->GetValue(0).GetString() == "character_set_client" && assert(!(query->GetValue(0).GetString() == "character_set_client" &&
query->GetValue(1).GetString() != "utf8")); query->GetValue(1).GetString() != "utf8"));
assert(!(query->GetValue(0).GetString() == "character_set_connection" && assert(!(query->GetValue(0).GetString() == "character_set_connection" &&
query->GetValue(1).GetString() != "utf8")); query->GetValue(1).GetString() != "utf8"));
assert(!(query->GetValue(0).GetString() == "character_set_database" && assert(!(query->GetValue(0).GetString() == "character_set_database" &&
query->GetValue(1).GetString() != "utf8")); query->GetValue(1).GetString() != "utf8"));
assert(!(query->GetValue(0).GetString() == "character_set_results" && assert(!(query->GetValue(0).GetString() == "character_set_results" &&
query->GetValue(1).GetString() != "utf8")); query->GetValue(1).GetString() != "utf8"));
assert(!(query->GetValue(0).GetString() == "character_set_server" && assert(!(query->GetValue(0).GetString() == "character_set_server" &&
query->GetValue(1).GetString() != "utf8")); query->GetValue(1).GetString() != "utf8"));
assert(!(query->GetValue(0).GetString() == "character_set_system" && assert(!(query->GetValue(0).GetString() == "character_set_system" &&
query->GetValue(1).GetString() != "utf8")); query->GetValue(1).GetString() != "utf8"));
query->Next(); query->Next();
}
a8::UdpLog::Instance()->Info("show variables like '%collation%';", {});
a8::UdpLog::Instance()->Info("Variable_name\tValue", {});
query->ExecQuery("show variables like '%collation%';", {});
while (!query->Eof()) {
std::string line;
line = query->GetValue(0).GetString() + "\t" + query->GetValue(1).GetString();
a8::UdpLog::Instance()->Info(line.c_str(), {});
assert(query->GetValue(1).GetString() == "utf8_general_ci");
query->Next();
}
} }
a8::UdpLog::Instance()->Info("show variables like '%collation%';", {}); bool CheckRegisterTimeInSessionId(const std::string& accountid, const std::string& sessionid)
a8::UdpLog::Instance()->Info("Variable_name\tValue", {}); {
query->ExecQuery("show variables like '%collation%';", {}); std::vector<std::string> strings;
while (!query->Eof()) { a8::Split(sessionid, strings, '_');
std::string line; if (strings.size() < 4) {
line = query->GetValue(0).GetString() + "\t" + query->GetValue(1).GetString(); return false;
a8::UdpLog::Instance()->Info(line.c_str(), {}); }
assert(query->GetValue(1).GetString() == "utf8_general_ci"); return true;
query->Next();
} }
}
bool CheckRegisterTimeInSessionId(const std::string& accountid, const std::string& sessionid) time_t ExtractRegisterTimeFromSessionId(const std::string& sessionid)
{ {
std::vector<std::string> strings; std::vector<std::string> strings;
a8::Split(sessionid, strings, '_'); a8::Split(sessionid, strings, '_');
if (strings.size() < 4) { if (strings.size() < 4) {
return false; return false;
}
std::string session_createtime = strings[0];
std::string account_registertime = strings[1];
std::string md51 = strings[2];
std::string md52 = strings[3];
return a8::XValue(account_registertime);
} }
return true;
}
time_t ExtractRegisterTimeFromSessionId(const std::string& sessionid) bool IsValidSessionId(const std::string& accountid, const std::string& sessionid)
{ {
std::vector<std::string> strings; std::vector<std::string> strings;
a8::Split(sessionid, strings, '_'); a8::Split(sessionid, strings, '_');
if (strings.size() < 4) { if (strings.size() < 4) {
return false; return false;
}
return true;
} }
std::string session_createtime = strings[0];
std::string account_registertime = strings[1];
std::string md51 = strings[2];
std::string md52 = strings[3];
return a8::XValue(account_registertime);
}
bool IsValidSessionId(const std::string& accountid, const std::string& sessionid) int ExtractGameIdFromAccountId(const std::string& accountid)
{ {
std::vector<std::string> strings; std::vector<std::string> strings;
a8::Split(sessionid, strings, '_'); a8::Split(accountid, strings, '_');
if (strings.size() < 4) { if (strings.size() < 2) {
return false; return false;
}
std::string channelid = strings[0];
std::string gameid = strings[1];
return a8::XValue(gameid);
} }
return true;
}
int ExtractGameIdFromAccountId(const std::string& accountid) int ExtractChannelIdFromAccountId(const std::string& accountid)
{ {
std::vector<std::string> strings; std::vector<std::string> strings;
a8::Split(accountid, strings, '_'); a8::Split(accountid, strings, '_');
if (strings.size() < 2) { if (strings.size() < 2) {
return false; return false;
}
std::string channelid = strings[0];
std::string gameid = strings[1];
return a8::XValue(channelid);
} }
std::string channelid = strings[0];
std::string gameid = strings[1];
return a8::XValue(gameid);
}
int ExtractChannelIdFromAccountId(const std::string& accountid)
{
std::vector<std::string> strings;
a8::Split(accountid, strings, '_');
if (strings.size() < 2) {
return false;
}
std::string channelid = strings[0];
std::string gameid = strings[1];
return a8::XValue(channelid);
} }

View File

@ -17,68 +17,71 @@ namespace a8
} }
} }
bool ReadCsvMetaFile(const std::string& filename, namespace f8
google::protobuf::Message* prototype,
std::function<void (google::protobuf::Message*)> push_back_func);
template <typename T>
bool ReadCsvMetaFile(const std::string& filename, std::list<T>& meta_list)
{ {
T dummy; bool ReadCsvMetaFile(const std::string& filename,
return ReadCsvMetaFile(filename, google::protobuf::Message* prototype,
&dummy, std::function<void (google::protobuf::Message*)> push_back_func);
[&meta_list] (google::protobuf::Message* msg)
{
T t;
t.CopyFrom(*msg);
meta_list.emplace_back(t);
});
}
template <typename T1, template <typename T>
typename T2> bool ReadCsvMetaFile(const std::string& filename, std::list<T>& meta_list)
static void RepeatedFieldToVector(const T1& t1, T2& t2) {
{ T dummy;
t2.clear(); return ReadCsvMetaFile(filename,
for (auto& val : t1) { &dummy,
t2.push_back(val); [&meta_list] (google::protobuf::Message* msg)
{
T t;
t.CopyFrom(*msg);
meta_list.emplace_back(t);
});
} }
}
template <typename T1, template <typename T1,
typename T2> typename T2>
static void RepeatedFieldToSet(const T1& t1, T2& t2) static void RepeatedFieldToVector(const T1& t1, T2& t2)
{ {
t2.clear(); t2.clear();
for (auto& val : t1) { for (auto& val : t1) {
t2.insert(val); t2.push_back(val);
}
} }
}
template <typename T1, template <typename T1,
typename T2> typename T2>
static void VectorToRepeatedField(const T1& t1, T2& t2) static void RepeatedFieldToSet(const T1& t1, T2& t2)
{ {
t2.Clear(); t2.clear();
for (auto& val : t1) { for (auto& val : t1) {
*t2.Add() = val; t2.insert(val);
}
} }
}
template <typename T1, template <typename T1,
typename T2> typename T2>
static void SetToRepeatedField(const T1& t1, T2& t2) static void VectorToRepeatedField(const T1& t1, T2& t2)
{ {
t2.Clear(); t2.Clear();
for (auto& val : t1) { for (auto& val : t1) {
*t2.Add() = val; *t2.Add() = val;
}
} }
template <typename T1,
typename T2>
static void SetToRepeatedField(const T1& t1, T2& t2)
{
t2.Clear();
for (auto& val : t1) {
*t2.Add() = val;
}
}
void InitMysqlConnection(a8::mysql::Query* query);
bool CheckRegisterTimeInSessionId(const std::string& accountid, const std::string& sessionid);
time_t ExtractRegisterTimeFromSessionId(const std::string& sessionid);
bool IsValidSessionId(const std::string& accountid, const std::string& sessionid);
int ExtractGameIdFromAccountId(const std::string& accountid);
int ExtractChannelIdFromAccountId(const std::string& accountid);
} }
void InitMysqlConnection(a8::mysql::Query* query);
bool CheckRegisterTimeInSessionId(const std::string& accountid, const std::string& sessionid);
time_t ExtractRegisterTimeFromSessionId(const std::string& sessionid);
bool IsValidSessionId(const std::string& accountid, const std::string& sessionid);
int ExtractGameIdFromAccountId(const std::string& accountid);
int ExtractChannelIdFromAccountId(const std::string& accountid);