RequestProcessorResponseStatus RequestProcessor::ProcessSubscribeKeepalive(Envelope &request, vector<Envelope> &output) { OBTAIN_MESSAGE(protocol::request::SubscribeKeepaliveV1, m, request, 0); { ::zippylog::request_processor::ForwardSubscribeKeepalive log; /// @todo support multiple ids log.set_subscription(m->id(0)); LOG_MESSAGE(log, this->logger_sock); } /// @todo validation LOG_END: RequestProcessorHandlerResult result = this->impl->HandleSubscribeKeepalive(request, output); if (result.deferred) return DEFERRED; return AUTHORITATIVE; }
void SaveGameManager::parseScript(Ogre::DataStreamPtr &stream, const Ogre::String &groupName) { Ogre::String name = stream->getName(); name = name.substr(0, name.length()-5); //delete ".save" at the and of the name int pointpos = name.find_last_of("."); name = name.substr(0, pointpos); if(Ogre::StringConverter::isNumber(name)) { mHighestSaveGameNumber = std::max(mHighestSaveGameNumber, Ogre::StringConverter::parseInt(name)); SaveGameFile* file = new SaveGameFile("", Ogre::StringConverter::parseInt(name)); LOG_MESSAGE(Logger::RULES, "Parsing header of save game: " + name + ".save"); SaveGameFileReader reader; reader.parseSaveGameFileHeader(stream, groupName, file); if(file->getProperty(SaveGameFile::PROPERTY_MODULEID) != "") // broken save game mSaveGames[Ogre::StringConverter::parseInt(name)] = file; } }
// "trace unset" console command. void cmd_trace_unset(void) { int i, argc; const char *arg; const char *api; TRACE_RESULT ret; argc=CMD_ARGC(); if(argc < 3) { LOG_CONSOLE(PLID, "usage: trace unset <routine>"); return; } for(i=1; i < argc; i++) { arg=CMD_ARGV(i); ret=trace_setflag(&arg, mFALSE, &api); if(ret==TR_SUCCESS) LOG_MESSAGE(PLID, "Un-Tracing %s routine '%s'", api, arg); else if(ret==TR_ALREADY) LOG_CONSOLE(PLID, "Already not tracing %s routine '%s'", api, arg); else LOG_CONSOLE(PLID, "Unrecognized API routine '%s'", arg); } }
void Connection::internalSend(OutputMessage_ptr msg) { TRACK_MESSAGE(msg); try{ ++m_pendingWrite; m_writeTimer.expires_from_now(boost::posix_time::seconds(Connection::write_timeout)); m_writeTimer.async_wait( boost::bind(&Connection::handleWriteTimeout, boost::weak_ptr<Connection>(shared_from_this()), boost::asio::placeholders::error)); boost::asio::async_write(getHandle(), boost::asio::buffer(msg->getOutputBuffer(), msg->getMessageLength()), boost::bind(&Connection::onWriteOperation, shared_from_this(), msg, boost::asio::placeholders::error)); } catch(boost::system::system_error& e){ if(m_logError){ LOG_MESSAGE("NETWORK", LOGTYPE_ERROR, 1, e.what()); m_logError = false; } } }
void Connection::parseHeader(const boost::system::error_code& error) { m_connectionLock.lock(); m_readTimer.cancel(); int32_t size = m_msg.decodeHeader(); if (error || size <= 0 || size >= NETWORKMESSAGE_MAXSIZE - 16) { handleReadError(error); } if (m_connectionState != CONNECTION_STATE_OPEN || m_readError) { closeConnection(); m_connectionLock.unlock(); return; } --m_pendingRead; try { ++m_pendingRead; m_readTimer.expires_from_now(boost::posix_time::seconds(Connection::read_timeout)); m_readTimer.async_wait( boost::bind(&Connection::handleReadTimeout, boost::weak_ptr<Connection>(shared_from_this()), boost::asio::placeholders::error)); // Read packet content m_msg.setMessageLength(size + NetworkMessage::header_length); boost::asio::async_read(getHandle(), boost::asio::buffer(m_msg.getBodyBuffer(), size), boost::bind(&Connection::parsePacket, shared_from_this(), boost::asio::placeholders::error)); } catch (boost::system::system_error& e) { if (m_logError) { LOG_MESSAGE("NETWORK", LOGTYPE_ERROR, 1, e.what()); m_logError = false; } closeConnection(); } m_connectionLock.unlock(); }
PhysicsRagDoll::PhysicsRagDoll(const Ogre::String& ragdollResource, Actor* actor) : mRootBone(NULL), mNode(NULL), mWorld(NULL), mMesh(NULL), mSkeleton(NULL) { mRootBone = NULL; mNode = actor->_getSceneNode(); mWorld = PhysicsManager::getSingleton()._getNewtonWorld(); if (!actor->getControlledObject()->isMeshObject()) Throw(IllegalArgumentException, "PhysicsRagDoll::PhysicsRagDoll needs a Mesh-Actor as argument!"); MeshObject* meshObj = static_cast<MeshObject*>(actor->getControlledObject()); // stop all animations meshObj->stopAllAnimations(); // get the skeleton. mSkeleton = meshObj->getEntity()->getSkeleton(); // get the mesh. mMesh = meshObj->getEntity()->getMesh(); LOG_MESSAGE(Logger::CORE, "Loading ragdoll '" + ragdollResource + "'"); TiXmlDocument* doc = loadDocument(ragdollResource); if (!doc) { LOG_ERROR(Logger::CORE, "Ragdoll resource '" + ragdollResource + "' not found"); } else { TiXmlElement* dataDocumentContent = doc->RootElement(); mRootBone =_addAllBones(NULL, getChildNamed(dataDocumentContent, "Bone"), actor); } }
/* ModMusic::loadFromMemory * Loads mod data for playback *******************************************************************/ bool ModMusic::loadFromMemory(const uint8_t* data, const uint32_t size) { // Init DUMB if needed if (!init_done) initDumb(); // Close current module if any close(); // Load module file dumb_module = dumb_read_any(dumbfile_open_memory((const char*)data, size), 0, 0); if (dumb_module != NULL) { initialize(2, 44100); return true; } else { LOG_MESSAGE(1, "Failed to load module music data"); return false; } }
CMaterialPtr CMaterialManager::CreateMaterial(nstring & name, nstring & group, nova::CColorRGB AmbientColor, nova::CColorRGB DiffuseColor, nova::CColorRGB SpecularColor, nReal Shininess, nReal Transparency, nstring TexMap, nstring MultiTexMap, nstring SpecMap, nstring BumpMap, nstring ReflectionMap, CResource::TAttach state) { CMaterialPtr mat = CResourceManager::AddNewResource(name, group, state); if(mat.IsNull()) throw NOVA_EXP("CMaterialManager::CreateMaterial - resource factory return \ Null pointer...", MEM_ERROR); mat->SetAmbientColor(AmbientColor); mat->SetDiffuseColor(DiffuseColor); mat->SetSpecularColor(SpecularColor); mat->SetShininess(Shininess); mat->SetTransparency(Transparency); mat->SetTexMap(TexMap); mat->SetMultiTexMap(MultiTexMap); mat->SetSpecMap(SpecMap); mat->SetBumpMap(BumpMap); mat->SetReflectionMap(ReflectionMap); mat->PrepareResource(); mat->BuildResource(); nova::nstringstream str; str << "Material Factory: material name: " << name << " group: " << group << " created.."; LOG_MESSAGE(str.str()); return mat; }
/* ModMusic::openFromFile * Loads a mod file for playback *******************************************************************/ bool ModMusic::openFromFile(const std::string& filename) { // Init DUMB if needed if (!init_done) initDumb(); // Close current module if any close(); // Load module file dumb_module = dumb_load_any(filename.c_str(), 0, 0); if (dumb_module != NULL) { initialize(2, 44100); return true; } else { LOG_MESSAGE(1, "Failed to load module music file \"%s\"", filename.c_str()); return false; } }
void Connection::closeSocket() { m_connectionLock.lock(); if (m_socket->is_open()) { m_pendingRead = 0; m_pendingWrite = 0; try { boost::system::error_code error; m_socket->shutdown(boost::asio::ip::tcp::socket::shutdown_both, error); m_socket->close(error); } catch (boost::system::system_error& e) { if (m_logError) { LOG_MESSAGE("NETWORK", LOGTYPE_ERROR, 1, e.what()); m_logError = false; } } } m_connectionLock.unlock(); }
void CTKRepeat::TestKeyboardRepeatRateL(const TTimeIntervalMicroSeconds32 &aInitialTime, const TTimeIntervalMicroSeconds32 &aTime) { do { #if defined(LOGGING) const TInt KOneSec=1000000; const TInt KOneHundrethSec=KOneSec/100; TLogMessageText logMessageText; _LIT(KRepeatRate,"Repeat Rate Initial=%d.%02dsecs, Subsequent=%d.%02dsecs"); logMessageText.Format(KRepeatRate,aInitialTime.Int()/KOneSec,(aInitialTime.Int()%KOneSec)/KOneHundrethSec ,aTime.Int()/KOneSec,(aTime.Int()%KOneSec)/KOneHundrethSec); LOG_MESSAGE(logMessageText); #endif TheClient->iWs.SetKeyboardRepeatRate(aInitialTime, aTime); iWin->SetKeyboardRepeatRate(aInitialTime, aTime); CActiveScheduler::Start(); if (iAbort) { iTest->AbortL(); } } while(CheckReportL()); }
/* MapSpecials::processZDoomLineSpecial * Process ZDoom line special *******************************************************************/ void MapSpecials::processZDoomLineSpecial(MapLine* line) { // Get special int special = line->getSpecial(); if (special == 0) return; // Get parent map SLADEMap* map = line->getParentMap(); // Get args int args[5]; for (unsigned arg = 0; arg < 5; arg++) args[arg] = line->intProperty(S_FMT("arg%d", arg)); // --- TranslucentLine --- if (special == 208) { // Get tagged lines vector<MapLine*> tagged; if (args[0] > 0) map->getLinesById(args[0], tagged); else tagged.push_back(line); // Get args double alpha = (double)args[1] / 255.0; string type = (args[2] == 0) ? "translucent" : "add"; // Set transparency for (unsigned l = 0; l < tagged.size(); l++) { tagged[l]->setFloatProperty("alpha", alpha); tagged[l]->setStringProperty("renderstyle", type); LOG_MESSAGE(3, S_FMT("Line %d translucent: (%d) %1.2f, %s", tagged[l]->getIndex(), args[1], alpha, CHR(type))); } } }
void ServicePort::open(IPAddressList ips, uint16_t port) { m_pendingStart = false; m_serverPort = port; bool error = false; IPAddressList pendingIps; for(IPAddressList::iterator it = ips.begin(); it != ips.end(); ++it) { try { Acceptor_ptr tmp(new boost::asio::ip::tcp::acceptor(m_io_service, boost::asio::ip::tcp::endpoint(*it, m_serverPort))); tmp->set_option(boost::asio::ip::tcp::acceptor::reuse_address(true)); tmp->set_option(boost::asio::ip::tcp::no_delay(true)); accept(tmp); m_acceptors[tmp] = *it; } catch(std::exception& e) { if(m_logError) { LOG_MESSAGE(LOGTYPE_ERROR, e.what(), "NETWORK") pendingIps.push_back(*it); if(!error) error = true; } } } if(error) { m_logError = false; m_pendingStart = true; Scheduler::getInstance().addEvent(createSchedulerTask(5000, boost::bind( &ServicePort::services, boost::weak_ptr<ServicePort>(shared_from_this()), pendingIps, m_serverPort))); } }
C_DLLEXPORT int Meta_Query(char *ifvers, plugin_info_t **pPlugInfo, mutil_funcs_t *pMetaUtilFuncs) { // this function is the first function ever called by metamod in the plugin DLL. Its purpose // is for metamod to retrieve basic information about the plugin, such as its meta-interface // version, for ensuring compatibility with the current version of the running metamod. // keep track of the pointers to metamod function tables metamod gives us gpMetaUtilFuncs = pMetaUtilFuncs; *pPlugInfo = &Plugin_info; // check for interface version compatibility if (strcmp(ifvers, Plugin_info.ifvers) != 0) { int mmajor = 0, mminor = 0, pmajor = 0, pminor = 0; LOG_CONSOLE(PLID, "%s: meta-interface version mismatch (metamod: %s, %s: %s)", Plugin_info.name, ifvers, Plugin_info.name, Plugin_info.ifvers); LOG_MESSAGE(PLID, "%s: meta-interface version mismatch (metamod: %s, %s: %s)", Plugin_info.name, ifvers, Plugin_info.name, Plugin_info.ifvers); // if plugin has later interface version, it's incompatible (update metamod) sscanf (ifvers, "%d:%d", &mmajor, &mminor); sscanf (META_INTERFACE_VERSION, "%d:%d", &pmajor, &pminor); if (pmajor > mmajor || (pmajor == mmajor && pminor > mminor)) { LOG_CONSOLE(PLID, "metamod version is too old for this plugin; update metamod"); LOG_ERROR(PLID, "metamod version is too old for this plugin; update metamod"); } // if plugin has older major interface version, it's incompatible (update plugin) else if (pmajor < mmajor) { LOG_CONSOLE(PLID, "metamod version is incompatible with this plugin; please find a newer version of this plugin"); LOG_ERROR(PLID, "metamod version is incompatible with this plugin; please find a newer version of this plugin"); } } return TRUE; // tell metamod this plugin looks safe }
Move AspirationSearch::chooseMove(GameState& gameState) { transpositionTable.clear(); // clean up data from previous searches #ifdef GATHER_STATISTICS nodesVisited = 0; Timer timer; timer.start(); Move moveToPlay = startAspirationSearch(gameState); timer.stop(); #ifdef LOG_STATS_PER_TURN if(gameState.getCurrentPlayer() == EPlayerColors::Type::BLACK_PLAYER) { LOG_MESSAGE(StringBuilder() << "Aspiration Search engine searching move for Black Player") } else { LOG_MESSAGE(StringBuilder() << "Aspiration Search engine searching move for White Player") } LOG_MESSAGE(StringBuilder() << "Search depth: " << searchDepth) LOG_MESSAGE(StringBuilder() << "Number of nodes visited: " << nodesVisited) LOG_MESSAGE(StringBuilder() << "Time spent: " << timer.getElapsedTimeInMilliSec() << " ms") LOG_MESSAGE(StringBuilder() << "% of Transposition Table entries used: " << ((double)transpositionTable.getNumEntriesUsed() / (TRANSPOSITION_TABLE_NUM_ENTRIES * 2.0))) LOG_MESSAGE(StringBuilder() << "% of Transposition Table entries replaced: " << ((double)transpositionTable.getNumReplacementsRequired() / (TRANSPOSITION_TABLE_NUM_ENTRIES * 2.0))) LOG_MESSAGE("") #endif // LOG_STATS_PER_TURN #ifdef LOG_STATS_END_OF_MATCH totalNodesVisited += nodesVisited; totalTimeSpent += timer.getElapsedTimeInMilliSec(); ++turnsPlayed; #endif // LOG_STATS_END_OF_MATCH return moveToPlay; #else return startAspirationSearch(gameState); #endif // GATHER_STATISTICS }
void ServicePort::accept() { if(!m_acceptor){ #ifdef __DEBUG_NET__ std::cout << "Error: [ServerPort::accept] NULL m_acceptor." << std::endl; #endif return; } try{ boost::asio::ip::tcp::socket* socket = new boost::asio::ip::tcp::socket(m_io_service); m_acceptor->async_accept(*socket, boost::bind(&ServicePort::onAccept, this, socket, boost::asio::placeholders::error)); } catch(boost::system::system_error& e){ if(m_logError){ LOG_MESSAGE("NETWORK", LOGTYPE_ERROR, 1, e.what()); m_logError = false; } } }
int prepareServerAddress(char* address, int port, struct sockaddr_in * server_addr) { memset((char *) server_addr , 0, sizeof(struct sockaddr_in)); if (address != NULL) { struct hostent *server; server = gethostbyname(address); if (server == NULL) { LOG_MESSAGE("could not find server host by name %s\n", address); return -1; } memcpy((char *) &(server_addr->sin_addr.s_addr), (char *) server->h_addr, server->h_length); } else server_addr->sin_addr.s_addr = htonl(INADDR_ANY); server_addr->sin_family = AF_INET; server_addr->sin_port = htons(port); return 0; }
AbstractWindow::AbstractWindow(const CeGuiString& xmlfile, int inputType, bool closeOnEscape, bool modal) : mVisible(false), mModal(modal), mWindowInputType(inputType), mCloseOnEscape(closeOnEscape) { LOG_MESSAGE(Logger::UI, "Lade Fenster '" + Ogre::String(xmlfile.c_str()) + "'"); mWindow = AbstractWindow::loadWindow(xmlfile, mNamePrefix); if (mWindow == NULL) { Throw(rl::IllegalStateException, Ogre::String("Could not load window '")+xmlfile.c_str()+"'."); } getRoot()->addChildWindow(mWindow); if (modal) { mWindow->setModalState(true); mWindow->setAlwaysOnTop(true); mWindow->moveToFront(); mWindow->show(); } else { mWindow->hide(); } mNormalAlpha = mWindow->getAlpha(); mName = mWindow->getName(); WindowManager::getSingleton().registerWindow(this); mWindow->subscribeEvent(Window::EventActivated, boost::bind( &rl::WindowManager::handleMovedToFront, rl::WindowManager::getSingletonPtr(), this)); }
void MapSpecials::applyPlaneAlign(MapLine* line, MapSector* target, MapSector* model) { vector<MapVertex*> vertices; target->getVertices(vertices); // The slope is between the line with Plane_Align, and the point in the // sector furthest away from it, which can only be at a vertex double this_dist; MapVertex* this_vertex; double furthest_dist = 0.0; MapVertex* furthest_vertex = nullptr; for (unsigned a = 0; a < vertices.size(); a++) { this_vertex = vertices[a]; this_dist = line->distanceTo(this_vertex->point()); if (this_dist > furthest_dist) { furthest_dist = this_dist; furthest_vertex = this_vertex; } } if (!furthest_vertex || furthest_dist < 0.01) { LOG_MESSAGE(1, "Ignoring Plane_Align on line %d; sector %d has no appropriate reference vertex", line->getIndex(), target->getIndex()); return; } // Calculate slope plane from our three points: this line's endpoints // (at the model sector's height) and the found vertex (at this sector's height). double modelz = model->getPlaneHeight<p>(); double targetz = target->getPlaneHeight<p>(); fpoint3_t p1(line->x1(), line->y1(), modelz); fpoint3_t p2(line->x2(), line->y2(), modelz); fpoint3_t p3(furthest_vertex->point(), targetz); target->setPlane<p>(MathStuff::planeFromTriangle(p1, p2, p3)); }
/* UndoManager::undo * Performs an undo operation *******************************************************************/ string UndoManager::undo() { // Can't while currently recording if (current_level) return ""; // Can't if no more levels to undo if (current_level_index < 0) return ""; // Perform undo level undo_running = true; current_undo_manager = this; UndoLevel* level = undo_levels[current_level_index]; if (!level->doUndo()) LOG_MESSAGE(3, "Undo operation \"%s\" failed", level->getName()); undo_running = false; current_undo_manager = NULL; current_level_index--; announce("undo"); return level->getName(); }
CAuthHelperTest::UserInfo CAuthHelperTest::getCurrentUser() { UserInfo userInfo; #ifdef _WIN_ TCHAR pszUname[100]; ZeroMemory(pszUname, sizeof(pszUname)); DWORD dwSize = 100; if (GetUserName(pszUname, &dwSize)) userInfo.name = UTF16SZ_2QSTR(pszUname, dwSize-1); else LOG_MESSAGE(DBG_FATAL, "Couldn't to extract user name. Error code: %d", GetLastError()); #else #endif return userInfo; }
void Connection::accept() { try { ++m_pendingRead; m_readTimer.expires_from_now(boost::posix_time::seconds(Connection::readTimeout)); m_readTimer.async_wait(boost::bind(&Connection::handleReadTimeout, boost::weak_ptr<Connection>(shared_from_this()), boost::asio::placeholders::error)); // Read size of the first packet boost::asio::async_read(getHandle(), boost::asio::buffer(m_msg.buffer(), NETWORK_HEADER_SIZE), boost::bind(&Connection::parseHeader, shared_from_this(), boost::asio::placeholders::error)); } catch(boost::system::system_error& e) { if(m_logError) { LOG_MESSAGE(LOGTYPE_ERROR, e.what(), "NETWORK"); m_logError = false; close(); } } }
/* MemChunk::reSize * Resizes the memory chunk, preserving existing data if specified * Returns false if new size is invalid, true otherwise *******************************************************************/ bool MemChunk::reSize(uint32_t new_size, bool preserve_data) { // Check for invalid new size if (new_size == 0) { LOG_MESSAGE(1, "MemChunk::reSize: new_size cannot be 0"); return false; } // Attempt to allocate memory for new size uint8_t* ndata = allocData(new_size, false); if (!ndata) return false; // Preserve existing data if specified if (preserve_data) { memcpy(ndata, data, size * sizeof(uint8_t)); delete[] data; data = ndata; } else { clear(); data = ndata; } // Update variables size = new_size; // Check position if (cur_ptr > size) cur_ptr = size; return true; }
void StepRecognitionMovement::calculateForceAndTorque(Vector3 &force, Vector3 &torque, Real timestep) { // move to nextTarget if( mMoveToNextTarget ) { Real mass; Vector3 inertia; OgreNewt::Body *body = mMovingCreature->getCreature()->getActor()->getPhysicalThing()->_getBody(); body->getMassMatrix(mass, inertia); Vector3 pos = mMovingCreature->getCreature()->getPosition(); Vector3 diff = mNextTarget - pos; Vector3 vel = body->getVelocity(); force.y = mass*( mLinearSpringK*diff.y - mLinearDampingK*vel.y ); std::ostringstream oss; oss << "Step-Recognition: diff: " << diff.y << " vel: " << vel.y << " Step force: " << force.y; oss << " DiffToTarget: " << mMovingCreature->getCreature()->getOrientation().Inverse() * (mNextTarget - mMovingCreature->getCreature()->getPosition()); LOG_MESSAGE(Logger::RULES, oss.str()); } }
void Connection::closeSocket() { LOGt("Connection::closeSocket()"); boost::recursive_mutex::scoped_lock lock(m_connectionLock); if(m_socket->is_open()) { m_pendingRead = m_pendingWrite = 0; try { boost::system::error_code error; m_socket->shutdown(boost::asio::ip::tcp::socket::shutdown_both, error); m_socket->close(error); } catch(boost::system::system_error& e) { if(m_logError) { LOG_MESSAGE(LogType::ERROR, e.what(), "NETWORK"); m_logError = false; } } } }
int UnitBomb::update( const Uint32 &delta ) { if ( isFlashing ) activeSprite = flashing; else activeSprite = idle; if ( !bombTimer.isStopped() ) { float radius = BOMB_EXPLOSION_RADIUS * (float)(BOMB_EXPLOSION_TIME - bombTimer.getTime()) / (float)BOMB_EXPLOSION_TIME; shape.radius = radius; activeSprite = NULL; } if ( bombTimer.wasStarted() && bombTimer.isStopped() ) { LOG_MESSAGE("Removing exploded bomb"); toBeRemoved = true; EventUnitDeath *event = new EventUnitDeath( this, NULL ); parent->addEvent( event ); } return UnitBase::update( delta ); }
int main(int argc, char *argv[]) { Server server; int r; if (argc > 1) { log_error("This program does not take arguments."); return EXIT_FAILURE; } log_set_target(LOG_TARGET_SAFE); log_set_facility(LOG_SYSLOG); log_parse_environment(); log_open(); umask(0022); sigbus_install(); r = server_init(&server); if (r < 0) goto finish; server_vacuum(&server, false); server_flush_to_var(&server, true); server_flush_dev_kmsg(&server); log_debug("systemd-journald running as pid "PID_FMT, getpid_cached()); server_driver_message(&server, 0, "MESSAGE_ID=" SD_MESSAGE_JOURNAL_START_STR, LOG_MESSAGE("Journal started"), NULL); /* Make sure to send the usage message *after* flushing the * journal so entries from the runtime journals are ordered * before this message. See #4190 for some details. */ server_space_usage_message(&server, NULL); for (;;) { usec_t t = USEC_INFINITY, n; r = sd_event_get_state(server.event); if (r < 0) goto finish; if (r == SD_EVENT_FINISHED) break; n = now(CLOCK_REALTIME); if (server.max_retention_usec > 0 && server.oldest_file_usec > 0) { /* The retention time is reached, so let's vacuum! */ if (server.oldest_file_usec + server.max_retention_usec < n) { log_info("Retention time reached."); server_rotate(&server); server_vacuum(&server, false); continue; } /* Calculate when to rotate the next time */ t = server.oldest_file_usec + server.max_retention_usec - n; } #if HAVE_GCRYPT if (server.system_journal) { usec_t u; if (journal_file_next_evolve_usec(server.system_journal, &u)) { if (n >= u) t = 0; else t = MIN(t, u - n); } } #endif r = sd_event_run(server.event, t); if (r < 0) { log_error_errno(r, "Failed to run event loop: %m"); goto finish; } server_maybe_append_tags(&server); server_maybe_warn_forward_syslog_missed(&server); } log_debug("systemd-journald stopped as pid "PID_FMT, getpid_cached()); server_driver_message(&server, 0, "MESSAGE_ID=" SD_MESSAGE_JOURNAL_STOP_STR, LOG_MESSAGE("Journal stopped"), NULL); finish: server_done(&server); return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS; }
void UnitBomb::ai( const Uint32 &delta, UnitBase *const player ) { if ( bombTimer.wasStarted() ) return; Vector2d<float> diff( *player->x - *x, *player->y - *y ); float dist = diff.lengthSquared(); // player close -> +pressure if ( dist < BOMB_PRESSURE_RADIUS_SQR_HI ) { pressure += BOMB_PRESSURE_ADD_1 * delta; maxVel = BOMB_EVASION_MAX_VEL; } else if ( dist < BOMB_PRESSURE_RADIUS_SQR_MID ) pressure += BOMB_PRESSURE_ADD_2 * delta; else if ( dist < BOMB_PRESSURE_RADIUS_SQR_LOW ) pressure += BOMB_PRESSURE_ADD_3 * delta; else if ( pressure > 0 ) pressure -= BOMB_PRESSURE_REL * delta; bool idleRoaming = true; // evasion if ( dist < BOMB_EVASION_RADIUS_SQR ) { Vector2d<float> playerAcc = player->accel.unit(); Vector2d<float> distUnit = -diff.unit(); if ( dist < BOMB_PRESSURE_RADIUS_SQR_HI || ((playerAcc.x != 0 || playerAcc.y != 0) && fabs(playerAcc.x - distUnit.x) < 0.5f && fabs(playerAcc.y - distUnit.y) < 0.5f) ) { accel = distUnit * BOMB_EVASION_ACCEL; maxVel = BOMB_EVASION_MAX_VEL; status = 1; idleRoaming = false; } } // min evade - when exiting evasion radius (to prevent immediate re-enter) if ( idleRoaming && status == 1 ) { idleRoaming = false; status = 2; evadeTimer.start( BOMB_MIN_EVADE_TIME ); } if ( evadeTimer.getStatus() == 1 ) idleRoaming = false; // idle movement if ( idleRoaming ) { // reset evasion status if ( status > 0 ) { status = 0; accel = Vector2d<float>(0,0); } maxVel = BOMB_IDLE_MAX_VEL; Vector2d<float> temp( Utility::randomRange( -1, 1 ), Utility::randomRange( -1, 1 ) ); accel += temp.unit() * BOMB_IDLE_ACCEL * delta; if ( ( *x < shape.radius && accel.x < 0 ) || ( *x > APP_SCREEN_WIDTH - shape.radius && accel.x > 0 ) ) accel.x *= -1; if ( ( *y < shape.radius && accel.y < 0 ) || ( *y > APP_SCREEN_HEIGHT - shape.radius && accel.y > 0 ) ) accel.y *= -1; } // pressure levels - flashing and explosion if ( pressure > BOMB_PRESSURE_LEVEL_4 ) { bombTimer.start( BOMB_EXPLOSION_TIME ); accel = Vector2d<float>(0,0); vel = Vector2d<float>(0,0); flags.add( ufDeadlyOnTouch ); flags.add( ufInvincible ); LOG_MESSAGE("Bomb exploding"); } else if ( pressure > BOMB_PRESSURE_LEVEL_3 ) { if ( flashTimer.isStopped() ) { flashTimer.start( BOMB_PRESSURE_TIMER_3 ); isFlashing = !isFlashing; } } else if ( pressure > BOMB_PRESSURE_LEVEL_2 ) { if ( flashTimer.isStopped() ) { flashTimer.start( BOMB_PRESSURE_TIMER_2 ); isFlashing = !isFlashing; } } else if ( pressure > BOMB_PRESSURE_LEVEL_1 ) { if ( flashTimer.isStopped() ) { flashTimer.start( BOMB_PRESSURE_TIMER_1 ); isFlashing = !isFlashing; } } else { flashTimer.stop(); isFlashing = false; } if ( *x < 0 ) *x = 0; else if ( *x > APP_SCREEN_WIDTH ) *x = APP_SCREEN_WIDTH; if ( *y < 0 ) *y = 0; else if ( *y > APP_SCREEN_HEIGHT ) *y = APP_SCREEN_HEIGHT; }
// ----------------------------------------------------------------------------- // Reads Chasm bin format data from a MemChunk // Returns true if successful, false otherwise // ----------------------------------------------------------------------------- bool ChasmBinArchive::open(MemChunk& mc) { // Check given data is valid if (mc.getSize() < HEADER_SIZE) { return false; } // Read .bin header and check it char magic[4] = {}; mc.read(magic, sizeof magic); if (magic[0] != 'C' || magic[1] != 'S' || magic[2] != 'i' || magic[3] != 'd') { LOG_MESSAGE(1, "ChasmBinArchive::open: Opening failed, invalid header"); Global::error = "Invalid Chasm bin header"; return false; } // Stop announcements (don't want to be announcing modification due to entries being added etc) setMuted(true); uint16_t num_entries = 0; mc.read(&num_entries, sizeof num_entries); num_entries = wxUINT16_SWAP_ON_BE(num_entries); // Read the directory UI::setSplashProgressMessage("Reading Chasm bin archive data"); for (uint16_t i = 0; i < num_entries; ++i) { // Update splash window progress UI::setSplashProgress(static_cast<float>(i) / num_entries); // Read entry info char name[NAME_SIZE] = {}; mc.read(name, sizeof name); uint32_t size; mc.read(&size, sizeof size); size = wxUINT32_SWAP_ON_BE(size); uint32_t offset; mc.read(&offset, sizeof offset); offset = wxUINT32_SWAP_ON_BE(offset); // Check offset+size if (offset + size > mc.getSize()) { LOG_MESSAGE(1, "ChasmBinArchive::open: Bin archive is invalid or corrupt (entry goes past end of file)"); Global::error = "Archive is invalid and/or corrupt"; setMuted(false); return false; } // Convert Pascal to zero-terminated string memmove(name, name + 1, sizeof name - 1); name[sizeof name - 1] = '\0'; // Create entry ArchiveEntry* const entry = new ArchiveEntry(name, size); entry->exProp("Offset") = static_cast<int>(offset); entry->setLoaded(false); entry->setState(0); rootDir()->addEntry(entry); } // Detect all entry types UI::setSplashProgressMessage("Detecting entry types"); vector<ArchiveEntry*> all_entries; getEntryTreeAsList(all_entries); MemChunk edata; for (size_t i = 0; i < all_entries.size(); ++i) { // Update splash window progress UI::setSplashProgress(static_cast<float>(i) / num_entries); // Get entry ArchiveEntry* const entry = all_entries[i]; // Read entry data if it isn't zero-sized if (entry->getSize() > 0) { // Read the entry data mc.exportMemChunk(edata, static_cast<int>(entry->exProp("Offset")), entry->getSize()); entry->importMemChunk(edata); } // Detect entry type EntryType::detectEntryType(entry); fixBrokenWave(entry); // Unload entry data if needed if (!archive_load_data) { entry->unloadData(); } // Set entry to unchanged entry->setState(0); } // Setup variables setMuted(false); setModified(false); announce("opened"); UI::setSplashProgressMessage(""); return true; }
// ----------------------------------------------------------------------------- // Writes Chasm bin archive to a MemChunk // Returns true if successful, false otherwise // ----------------------------------------------------------------------------- bool ChasmBinArchive::write(MemChunk& mc, bool update) { // Clear current data mc.clear(); // Get archive tree as a list vector<ArchiveEntry*> entries; getEntryTreeAsList(entries); // Check limit of entries count const uint16_t num_entries = static_cast<uint16_t>(entries.size()); if (num_entries > MAX_ENTRY_COUNT) { LOG_MESSAGE(1, "ChasmBinArchive::write: Bin archive can contain no more than %u entries", MAX_ENTRY_COUNT); Global::error = "Maximum number of entries exceeded for Chasm: The Rift bin archive"; return false; } // Init data size static const uint32_t HEADER_TOC_SIZE = HEADER_SIZE + ENTRY_SIZE * MAX_ENTRY_COUNT; mc.reSize(HEADER_TOC_SIZE, false); mc.fillData(0); // Write header const char magic[4] = { 'C', 'S', 'i', 'd' }; mc.seek(0, SEEK_SET); mc.write(magic, 4); mc.write(&num_entries, sizeof num_entries); // Write directory uint32_t offset = HEADER_TOC_SIZE; for (uint16_t i = 0; i < num_entries; ++i) { ArchiveEntry* const entry = entries[i]; // Update entry if (update) { entry->setState(0); entry->exProp("Offset") = static_cast<int>(offset); } // Check entry name string name = entry->getName(); uint8_t name_length = static_cast<uint8_t>(name.Length()); if (name_length > NAME_SIZE - 1) { LOG_MESSAGE(1, "Warning: Entry %s name is too long, it will be truncated", name); name.Truncate(NAME_SIZE - 1); name_length = static_cast<uint8_t>(NAME_SIZE - 1); } // Write entry name char name_data[NAME_SIZE] = {}; memcpy(name_data, &name_length, 1); memcpy(name_data + 1, CHR(name), name_length); mc.write(name_data, NAME_SIZE); // Write entry size const uint32_t size = entry->getSize(); mc.write(&size, sizeof size); // Write entry offset mc.write(&offset, sizeof offset); // Increment/update offset offset += size; } // Write entry data mc.reSize(offset); mc.seek(HEADER_TOC_SIZE, SEEK_SET); for (uint16_t i = 0; i < num_entries; ++i) { ArchiveEntry* const entry = entries[i]; mc.write(entry->getData(), entry->getSize()); } return true; }