void Connection_Manager::connecting_by_id(const string& data, uint32_t sid) { Server_Node_Map::iterator it = nodes_.find(sid); if(it != nodes_.end()) { CConnection* conn = NULL; if(it->second.conn == NULL) //建立一条新的TCP服务器连接 { conn = CONNECTION_POOL.pop_obj(); conn->set_index(0); conn->set_server_type(it->second.server_type); conn->set_server_id(it->second.server_id); //选取连接地址,目标地址为电信用电信网卡进行连接,依次类推 Inet_Addr src_addr, dst_addr; get_address_pair(it->second, src_addr, dst_addr); src_addr.set_port(0); //随机一个端口作为客户机端口 if(src_addr.get_ip() != INADDR_ANY) { src_addr.set_port(15000 + rand() % 15000); } CORE_INFO("connecting " << dst_addr << ", by local addr = " << src_addr << ", dst sid = " << sid); if(conn->connect(src_addr, dst_addr) != 0) { conn->close(); CONNECTION_POOL.push_obj(conn); CORE_DEBUG("push conn = " << this); CORE_ERROR("connect " << dst_addr << "failed!!"); return ; } it->second.conn = conn; } else { conn = it->second.conn; } if(conn->get_state() != CConnection::CONN_CONNECTED) //处于连接状态,缓冲到LIST中 it->second.strms.push_back(data); else conn->send(data); } else { CORE_ERROR("sid = " << sid << " error!!"); } }
int getCategories (const std::string file_name, std::vector<std::string> &categories) { std::string line; std::ifstream fs; fs.open (file_name.c_str (), std::ios::in); if (!fs.is_open () || fs.fail ()) { CORE_ERROR ("Could not open file '%s'! Error : %s\n", file_name.c_str (), strerror (errno)); fs.close (); return (-1); } while (!fs.eof ()) { getline (fs, line); if (line == "") continue; categories.push_back (line); } fs.close (); return (0); }
Buff::Buff(std::string buffName, float dur, BuffType type, Unit* u, Unit* uu) : duration(dur), name(buffName), timeElapsed(0), remove(false), attachedTo(u) , attacker(uu), buffType(type), movementSpeedPercentModifier(0.0f) { //init(); if(name != ""){ // empty name = no buff icon std::string scriptloc = "../../lua/buffs/" + name + ".lua"; CORE_INFO("Loading %s", scriptloc.c_str()); try{ buffScript = new LuaScript(true);//fix buffScript->loadScript(scriptloc); buffScript->setLoaded(true); CORE_INFO("Loaded buff lua script"); buffScript->lua.set_function("getAttachedUnit", [this]() { return attachedTo; }); buffScript->lua.set_function("dealMagicDamage", [this](Unit* target, float amount) { attacker->dealDamageTo(target,amount,DAMAGE_TYPE_MAGICAL,DAMAGE_SOURCE_SPELL); }); CORE_INFO("added lua buff script functions"); }catch(sol::error e){//lua error? don't crash the whole server buffScript->setLoaded(false); CORE_ERROR("Lua buff load error: %s", e.what()); } attachedTo->getMap()->getGame()->notifyAddBuff(attachedTo, attacker, name); } }
int main(int argc, char ** argv) { printf("Yorick %s\n", SERVER_VERSION); Logger::instance().setLogFile("../../log.html", false, true); CORE_INFO("Loading RAF files in filearchives/."); std::string basePath = RAFManager::getInstance()->findGameBasePath(); if(!RAFManager::getInstance()->init(basePath + "filearchives")) { CORE_ERROR("Couldn't load RAF files. Make sure you have a 'filearchives' directory in the server's root directory. This directory is to be taken from RADS/projects/lol_game_client/"); return EXIT_FAILURE; } ItemManager::getInstance()->init(); CORE_INFO("Game started"); Game g; ENetAddress address; address.host = SERVER_HOST; if (argc > 1) { enet_uint16 port = atoi(argv[1]); address.port = port; } else { address.port = SERVER_PORT_DEFAULT; } if (argc > 2) { if (!g.initialize(&address, argv[2])) { CORE_ERROR("Couldn't listen on port %d, or invalid key", &address); return EXIT_FAILURE; } } else { if (!g.initialize(&address, SERVER_KEY_DEFAULT)) { CORE_ERROR("Couldn't listen on port %d, or invalid key", &address); return EXIT_FAILURE; } } g.netLoop(); PathNode::DestroyTable(); // Cleanup return EXIT_SUCCESS; }
int createEntityWithSize(const char* entityResource, LuaPlus::LuaObject luaPosition, LuaPlus::LuaObject luaSize) { if(!luaPosition.IsTable()) { CORE_LOG("LUA", "Invalid position object passed to create_entity."); return INVALID_ENTITY_ID; } if(!luaSize.IsTable()) { CORE_LOG("LUA", "Invalid size object passed to create_entity."); return INVALID_ENTITY_ID; } sf::Vector2f position = tableToVec2<sf::Vector2f>(luaPosition); sf::Vector2f size = tableToVec2<sf::Vector2f>(luaSize); artemis::Entity& entity = WorldLocator::getObject()->createEntity(); // Create entity if(!EntityFactory::get().loadFromFile(entityResource, entity)) { CORE_ERROR("Failed to load entity from file: " + std::string(entityResource)); return INVALID_ENTITY_ID; } Transform* pTransform = safeGetComponent<Transform>(&entity); if(!pTransform) { entity.addComponent(new Transform(position.x, position.y)); } else { pTransform->position = position; } // Get physics comp DynamicBody* pDynamicBody = safeGetComponent<DynamicBody>(&entity); if(pDynamicBody) { // Set dimensions, will be initialized later pDynamicBody->setDimensions(size.x, size.y); } else { entity.addComponent(new DynamicBody(size.x, size.y)); } // commit entity changes entity.refresh(); CORE_LOG("LUA", "Created entity from: " + std::string(entityResource)); return entity.getId(); }
int32_t CConnection::handle_input(BASE_HANDLER handle) { CCorePacket recv_packet; while(true) { recv_packet.body_ptr_ = NULL; if(rbuffer_.remaining_length() == 0) //扩大TCP接收缓冲区,防止缓冲区太小造成收包异常 { if(rbuffer_.length() < MAX_BUFFER_SIZE) rbuffer_.realloc_buffer(rbuffer_.length() - 1); else { CORE_ERROR("rbuffer_ is full, rbuffer_.size = " << rbuffer_.length()); return -2; } } int32_t rc = rbuffer_.recv(sock_stream_); if(rc > 0) { THROTTLER()->add_tcp_packet(rc, false); bool split_flag = true; while(split_flag) //消息组装 { int32_t split_ret = rbuffer_.split(istrm_); if(split_ret == 0) { split_flag = true; try{ istrm_ >> recv_packet;} catch(...) { CORE_FATAL("parse core packet error!!"); return -2; } if(process(recv_packet, istrm_) != 0) return 0; } else if(split_ret < 0) return -1; else //表示包合法,继续收! { #ifndef WIN32 split_flag = false; #else return 0; #endif } }
int32_t CConnection::send(CCorePacket& packet, bool no_delay) { int32_t ret = -1; GAIN_BINSTREAM(strm); *strm << packet; if(sbuffer_.remaining_length() < strm->data_size() + sizeof(uint32_t)) { if(sbuffer_.length() < MAX_BUFFER_SIZE)//扩大TCP发送缓冲区,防止缓冲区太小造成发送包异常 { sbuffer_.realloc_buffer(strm->data_size() + sizeof(uint32_t)); CORE_WARNING("sbuffer realloc buffer, size = " << sbuffer_.length()); } else //发送报文丢弃 { CORE_ERROR("sbuffer is full, sbuffer.size = " << sbuffer_.length()); RETURN_BINSTREAM(strm); return -1; } } THROTTLER()->add_tcp_packet(strm->data_size(), true); send_flag_ = true; if(sbuffer_.put(*strm)) { if(no_delay) { sbuffer_.send(sock_stream_); } if(sbuffer_.data_length() > 0) { REACTOR_INSTANCE()->register_handler(this, MASK_WRITE); } else { REACTOR_INSTANCE()->remove_handler(this, MASK_WRITE); } ret = 0; } RETURN_BINSTREAM(strm); return ret; }
bool Renderable::load(const tinyxml2::XMLElement *pElement) { pElement->QueryIntAttribute("order", &m_drawOrder); const tinyxml2::XMLElement* childElement = pElement->FirstChildElement("Texture"); if(!childElement) { CORE_WARNING("No Texture element declared in Renderable component."); return false; } // Get file name std::string textureFile = make_string(childElement->GetText()); if(textureFile.empty()) { CORE_WARNING("No texture file defined in Renderable Component"); return false; } // Trim whitespace trim(textureFile); sf::TexturePtr pTexture = TextureLocator::getObject()->get(textureFile); if(!pTexture) { CORE_ERROR("Failed to get texture: " + textureFile); return false; } TextureRegion tmpRegion(pTexture); childElement = pElement->FirstChildElement("Dimensions"); if(childElement) { pElement->QueryFloatAttribute("width", &m_width); pElement->QueryFloatAttribute("height", &m_height); setWidth(m_width != 0 ? m_width / PhysicsLocator::PixelsPerMeter.x : 0); setHeight(m_height != 0 ? m_height / PhysicsLocator::PixelsPerMeter.y : 0); } m_textureRegion = tmpRegion; return true; }
int32_t CCoreTCPListener::open(const Inet_Addr& local_addr) { if(acceptor_.open(local_addr, true) == 0) { REACTOR_INSTANCE()->register_handler(this, MASK_READ); CORE_INFO("open tcp listener, listener addr = " << local_addr); return 0; } else { CORE_ERROR("open tcp listener failed, listener addr = " << local_addr << ",error = " << error_no()); return -1; } }
IEventManager::IEventManager(const char *pName, bool setAsGlobal) { if(setAsGlobal) { // If global, the manager is tasked with its setting the global static // instance to reference itself. if(g_pEventManager != nullptr) { CORE_ERROR("Attempting to create two global event managers. " "The previous instance will be destroyed"); delete g_pEventManager; } g_pEventManager = this; } }
void BaseGameManager::initPhysicsRenderer(sf::RenderTargetPtr pRenderTarget) { CORE_ASSERT(m_pWorld != nullptr); if(!m_pPhysicsWorld) { CORE_ERROR("Attempting to initialize physics renderer without initializing physics"); return; } m_pBox2DRenderer = std::unique_ptr<Box2DRenderer>(new Box2DRenderer(pRenderTarget)); CORE_DEBUG("Initializing physics renderer..."); m_pPhysicsWorld->SetDebugDraw(m_pBox2DRenderer.get()); m_pBox2DRenderer->SetFlags(Box2DRenderer::e_shapeBit); }
FILE *Logger::loadFileStream(FILE *stream, const char *filename) { // overwrite previous logs FILE* newStream = fopen(filename, "w"); if(newStream == NULL) { CORE_ERROR( "Failed to open logger file: " + std::string(filename) + ". Using console output...\n\t" + strerror(errno) ); // Use previous stream return stream; } return newStream; }
int createEntity(const char* entityResource, LuaPlus::LuaObject luaPosition) { if(!luaPosition.IsTable()) { CORE_LOG("LUA", "Invalid position object passed to create_entity function. Must be a table"); return INVALID_ENTITY_ID; } sf::Vector2f position = tableToVec2<sf::Vector2f>(luaPosition); artemis::Entity& entity = WorldLocator::getObject()->createEntity(); // Create entity if(!EntityFactory::get().loadFromFile(entityResource, entity)) { CORE_ERROR("Failed to load entity from file: " + std::string(entityResource)); return INVALID_ENTITY_ID; } Transform* transformComp = safeGetComponent<Transform>(&entity); if(!transformComp) { // Create new transform component if it doesn't exist entity.addComponent(new Transform(position.x, position.y)); } else { CORE_DEBUG("Overriding transform with lua object"); transformComp->position = position; } // Commit entity changes entity.refresh(); CORE_LOG("LUA", "Created entity from: " + std::string(entityResource)); return entity.getId(); }
int32_t CConnection::send(const string& bin_stream) { if(bin_stream.empty()) return -1; uint32_t data_size = bin_stream.size(); if(sbuffer_.remaining_length() < data_size + sizeof(uint32_t)) { if(sbuffer_.length() < MAX_BUFFER_SIZE)//扩大TCP发送缓冲区,防止缓冲区太小造成发送包异常 { sbuffer_.realloc_buffer(data_size + sizeof(uint32_t)); CORE_WARNING("sbuffer realloc buffer, size = " << sbuffer_.length()); } else //发送报文丢弃 { CORE_ERROR("sbuffer is full, sbuffer.size = " << sbuffer_.length()); return -1; } } send_flag_ = true; THROTTLER()->add_tcp_packet(data_size, true); if(sbuffer_.put(bin_stream)) { if(sbuffer_.data_length() > 0) { REACTOR_INSTANCE()->register_handler(this, MASK_WRITE); } else { REACTOR_INSTANCE()->remove_handler(this, MASK_WRITE); } } return 0; }
int getData (const std::string dir_name, std::vector<std::string> &data) { DIR* dp; struct dirent* dirp; if ((dp = opendir (dir_name.c_str ())) == NULL) { CORE_ERROR ("Could not open directory '%s'! Error : %s\n", dir_name.c_str (), strerror (errno)); return (-1); } while ((dirp = readdir (dp)) != NULL) { if ((strcmp (dirp->d_name, ".") == 0) || (strcmp (dirp->d_name, "..") == 0)) continue; data.push_back (dir_name + "/" + dirp->d_name); } closedir(dp); return (0); }
int main (int argc, char** argv) { if (argc < 2) { printHelp (argc, argv); return (-1); } double gamma = static_cast<double> (atof (argv[1])); std::string category_file_list = argv[2]; std::vector<std::string> categories; std::vector<std::string> covariances; std::vector<std::vector<svm_node> > data; std::vector<int> labels; int ret_val, label = 1; if ((ret_val = getCategories (category_file_list, categories)) < 0) return (-1); for (std::vector<std::string>::iterator it = categories.begin (); it != categories.end (); ++it) { if ((ret_val = getData (*it, covariances)) < 0) continue; while (!covariances.empty ()) { std::ifstream fs; svm_node node; std::vector<svm_node> nodes; double value; int index = 1; std::string covariance = covariances.back (); covariances.pop_back (); fs.open (covariance.c_str (), std::ios::in); if (!fs.is_open () || fs.fail ()) { CORE_ERROR ("Could not open file '%s'! Error : %s\n", covariance.c_str (), strerror (errno)); fs.close (); continue; } // Fill the feature vector while (fs >> value) { node.index = index; node.value = value; nodes.push_back (node); ++index; } // Terminate the feature vector node.index = -1; nodes.push_back (node); data.push_back (nodes); labels.push_back (label); fs.close(); } // Update the label when changing category ++label; } svmTrain (gamma, data, labels); return (0); }
int svmTrain (double gamma, std::vector<std::vector<svm_node> > data, std::vector<int> labels) { struct svm_model* model; struct svm_problem prob; struct svm_node* x_space; struct svm_parameter param; // Make sure we have data if (data.empty ()) { CORE_ERROR ("No training data\n"); return (-1); } prob.l = data.size (); prob.y = Malloc (double, prob.l); prob.x = Malloc (struct svm_node* , prob.l); x_space = Malloc (struct svm_node, data.size () * data[0].size ()); int j = 0; for (int i = 0; i < prob.l; ++i) { prob.y[i] = *(labels.begin () + i); prob.x[i] = &x_space[j]; for (std::vector<svm_node>::iterator it = data[i].begin (); it != data[i].end (); ++it) { x_space[j].index = it->index; x_space[j].value = it->value; ++j; } } param.svm_type = C_SVC; param.kernel_type = RBF; param.gamma = gamma; param.degree = 3; param.coef0 = 0; param.nu = 0.5; param.cache_size = 100; param.C = 1; param.eps = 1e-3; param.p = 0.1; param.shrinking = 1; param.probability = 0; param.nr_weight = 0; param.weight_label = NULL; param.weight = NULL; // Check whether the parameters are within a feasible range of the problem const char* error_msg = svm_check_parameter (&prob, ¶m); if (error_msg) { CORE_ERROR ("Error checking SVM parameters: %s\n", error_msg); return (-1); } model = svm_train (&prob, ¶m); if (svm_save_model ("model.txt", model)) { CORE_ERROR ("Save SVM model failed\n"); return (-1); } svm_free_and_destroy_model (&model); svm_destroy_param (¶m); free (prob.y); free (prob.x); free (x_space); return (0); }