sort_link *sort_getmatch(sort_info *i, long post, long overlap, int value) { sort_link *ret; if (i->sortbegin == -1) sort_sort(i, i->lo, i->hi); /* * Now we reuse lo and hi */ post = max(0, min(i->size, post)); i->val = value + 32768; i->lo = max(0, post - overlap); /* absolute position */ i->hi = min(i->size, post + overlap); /* absolute position */ ret = i->head[i->val]; while (ret) { if (ipos(i, ret) < i->lo) { ret = ret->next; } else { if (ipos(i, ret) >= i->hi) ret = NULL; break; } } /* i->head[i->val]=ret; */ return (ret); }
/// Reads a null-terminated string into \p str. void istream::read_strz (string& str) { const_iterator zp = find (ipos(), end(), '\0'); if (zp == end()) zp = ipos(); const size_type strl = distance (ipos(), zp); str.assign (ipos(), strl); m_Pos += strl + 1; }
static void cline(float *musigma, float *l, int n, float *x, int w, int h, float angle) { float an = angle*3.1416/180; float c = cos(an); float s = sin(an); float t[2] = {(fmin(w,h)-1)/2.0, 0}; float dir[2] = {c*t[0]+s*t[1], -s*t[0]+c*t[1]}; float zer[2] = {(w-1.0)/2, (h-1.0)/2}; float from[2], toto[2]; for (int i = 0; i < 2; i++) { from[i] = zer[i] - dir[i]; toto[i] = zer[i] + dir[i]; } fprintf(stderr, "c,s = %g %g\n", c, s); fprintf(stderr, "dir = %g %g\n", dir[0], dir[1]); fprintf(stderr, "zer = %g %g\n", zer[0], zer[1]); fprintf(stderr, "(%g %g)=>(%g %g)\n",from[0],from[1],toto[0],toto[1]); double mu = 0, sigma = 0, nn = 0; for (int i = 0; i < n; i++) { float a = i/(n - 1.0), p[2]; for (int j = 0; j < 2; j++) p[j] = (1-a)*from[j] + a*toto[j]; //bicubic_interpolation(l + i, x, w, h, 1, p[0], p[1]); bilinear_interpolation_vec_at(l + i, x, w, h, 1, p[0], p[1]); if (isfinite(l[i])) { //double posi = hypot(p[0]-zer[0], p[1]-zer[1]); //if (p[0] < 0) posi = -posi; double posi = ipos(i, n); mu += l[i]*posi; nn += l[i]; } } mu /= nn; for (int i = 0; i < n; i++) { float a = i/(n - 1.0), p[2]; for (int j = 0; j < 2; j++) p[j] = (1-a)*from[j] + a*toto[j]; double posi = ipos(i, n); if (isfinite(l[i])) sigma += l[i]*(posi-mu)*(posi-mu); } sigma = sqrt(sigma/nn); if (musigma) { musigma[0] = mu; musigma[1] = sigma; } fprintf(stderr, "mu sigma = %g %g\n", mu, sigma); }
void Airport::generate_flight() { std::cerr<<"Generate new flight"; float angle, x, y, z; float bear, inc; char id[6]; angle = toRadians((float)(rand() % 360 - 180)); x = fabs(AIRPORT_DISTANCE_MAX * cos(angle)); //Only positive, for GyV3D!!!!!!!!!!! y = AIRPORT_DISTANCE_MAX * sin(angle); z = FLIGHT_HEIGHT + (float)(rand() % 2000); Position ipos(x, y, z); Position pos0(0.0, 0.0, 0.0); pos0.angles(ipos, bear, inc); sprintf(id, "IB%4.4d", sec++); std::cerr<<": ["<<id; Flight *aux; aux = new Flight(id, ipos, bear, 0.0, 200.0); flights.push_back(aux); if(flights.size() == 1) NextFocus(); std::cerr<<"]"<<std::endl; }
void Airport::generate_storm() { float angle, x, y, z, rad, height, bearing, speed; //Storm Pos angle = toRadians((float)(rand() % 360 - 180)); x = fabs(AIRPORT_DISTANCE_MAX*1.5 * cos(angle)); //Only positive, for GyV3D!!!!!!!!!!! y = AIRPORT_DISTANCE_MAX*1.5 * sin(angle); z = ((float)rand() / RAND_MAX)*(STORM_MIN_ELEVATION-STORM_MIN_ELEVATION)+STORM_MIN_ELEVATION; //Storm height height = ((float)rand() / RAND_MAX)*(STORM_MAX_HEIGHT-STORM_MIN_HEIGHT)+STORM_MIN_HEIGHT; //Radius rad = ((float)rand() / RAND_MAX)*(STORM_MAX_RAD-STORM_MIN_RAD)+STORM_MIN_RAD; //Bearing bearing = toRadians((float)(rand() % 360 - 180)); //Speed speed = ((float)rand() / RAND_MAX)*(STORM_MAX_SPEED-STORM_MIN_SPEED)+STORM_MIN_SPEED; Position ipos(x, y, z); storm = new Storm(ipos, bearing, speed, rad, height); }
static void plot_cline(float *l, int n, char *title, float mu, float sigma) { if (title) printf("set title \"%s\"\n", title); printf("set samples 1000\n"); printf("plot \"-\" w lines title \"data\""); if (isfinite(mu) && sigma > 0) { double mass = 0; for (int i = 0; i < n; i++) if (isfinite(l[i])) mass += l[i]; mass *= 2*3.1416/n; float alpha_g = mass/(sigma*sqrt(2*3.1416)); float alpha_l = mass/(sigma*sqrt(2)); fprintf(stderr, "mass = %g\n", mass); printf(",%g*exp(-(x-%g)**2/(2*(%g)**2)) title \"normal\"", alpha_g, mu, sigma); printf(",%g*exp(-abs(x-%g)*sqrt(2)/%g) title \"laplacian\"", alpha_l, mu, sigma); } printf("\n"); for (int i = 0; i < n; i++) { float ipoz = ipos(i, n); printf("\t%g %g\n", ipoz, l[i]); } printf("end\n"); }
sort_link *sort_nextmatch(sort_info *i, sort_link *prev) { sort_link *ret = prev->next; if (!ret || ipos(i, ret) >= i->hi) return (NULL); return (ret); }
sort_link_t * sort_getmatch(sort_info_t *i, long post, long overlap, int value) { sort_link_t *ret; /* If the vector hasn't been indexed yet, index it now. */ if (i->sortbegin==-1) sort_sort(i,i->lo,i->hi); /* Now we reuse lo and hi */ /* We'll only return samples within (overlap) samples of (post). * Clamp the boundaries to search to the boundaries of the array, * convert the signed sample to an unsigned offset, and store the * state so that future calls to sort_nextmatch do the right thing. * * Reusing lo and hi this way is awful. */ post=max(0,min(i->size,post)); i->val=value+32768; i->lo=max(0,post-overlap); /* absolute position */ i->hi=min(i->size,post+overlap); /* absolute position */ /* Walk through the linked list of samples with this value, until * we find the first one within the bounds specified. If there * aren't any, return NULL. */ ret=i->head[i->val]; while (ret) { /* ipos() calculates the offset (in terms of the original vector) * of this hit. */ if (ipos(i,ret)<i->lo) { ret=ret->next; } else { if (ipos(i,ret)>=i->hi) ret=NULL; break; } } /*i->head[i->val]=ret;*/ return(ret); }
PlanIter_t fn_subsequence::codegen( CompilerCB* /*cb*/, static_context* aSctx, const QueryLoc& aLoc, std::vector<PlanIter_t>& aArgs, expr& aAnn) const { fo_expr& subseqExpr = static_cast<fo_expr&>(aAnn); const expr* inputExpr = subseqExpr.get_arg(0); const expr* posExpr = subseqExpr.get_arg(1); const expr* lenExpr = (subseqExpr.num_args() > 2 ? subseqExpr.get_arg(2) : NULL); if (inputExpr->get_expr_kind() == relpath_expr_kind && posExpr->get_expr_kind() == const_expr_kind && lenExpr != NULL && lenExpr->get_expr_kind() == const_expr_kind) { xs_double dpos = static_cast<const const_expr*>(posExpr)-> get_val()->getDoubleValue().round(); xs_integer ipos(dpos.getNumber()); xs_double dlen = static_cast<const const_expr*>(lenExpr)-> get_val()->getDoubleValue().round(); xs_integer ilen(dlen.getNumber()); xs_long pos; xs_long len; try { pos = to_xs_long(ipos); len = to_xs_long(ilen); } catch (std::range_error const&) { goto done; } const relpath_expr* pathExpr = static_cast<const relpath_expr*>(inputExpr); csize numSteps = pathExpr->numSteps(); if (pos > 0 && len == 1 && numSteps == 2) { AxisIteratorHelper* input = dynamic_cast<AxisIteratorHelper*>(aArgs[0].getp()); assert(input != NULL); if (input->setTargetPos(pos-1)) return aArgs[0]; } } done: return new FnSubsequenceIterator(aSctx, aLoc, aArgs); }
void GameHandler::handlePickup(GameClient &client, MessageIn &message) { const int x = message.readInt16(); const int y = message.readInt16(); const Point ppos = client.character->getComponent<ActorComponent>()->getPosition(); // TODO: use a less arbitrary value. if (std::abs(x - ppos.x) + std::abs(y - ppos.y) < 48) { MapComposite *map = client.character->getMap(); Point ipos(x, y); for (FixedActorIterator i(map->getAroundPointIterator(ipos, 0)); i; ++i) { Entity *o = *i; Point opos = o->getComponent<ActorComponent>()->getPosition(); if (o->getType() == OBJECT_ITEM && opos.x == x && opos.y == y) { ItemComponent *item = o->getComponent<ItemComponent>(); ItemClass *ic = item->getItemClass(); int amount = item->getAmount(); if (!Inventory(client.character).insert(ic->getDatabaseID(), amount)) { GameState::remove(o); // We only do this when items are to be kept in memory // between two server restart. if (!Configuration::getValue("game_floorItemDecayTime", 0)) { // Remove the floor item from map accountHandler->removeFloorItems(map->getID(), ic->getDatabaseID(), amount, x, y); } // log transaction std::stringstream str; str << "User picked up item " << ic->getDatabaseID() << " at " << opos.x << "x" << opos.y; auto *characterComponent = client.character ->getComponent<CharacterComponent>(); accountHandler->sendTransaction( characterComponent->getDatabaseID(), TRANS_ITEM_PICKUP, str.str() ); } break; } } } }
static inline long int try_sort_sync(cdrom_paranoia_t *p, sort_info_t *A, unsigned char *Aflags, c_block_t *B, long int post, long int *begin, long int *end, long *offset, void (*callback)(long int, paranoia_cb_mode_t)) { long dynoverlap=p->dynoverlap; sort_link *ptr=NULL; unsigned char *Bflags=B->flags; /* block flag matches 0x02 (unmatchable) */ if(Bflags==NULL || (Bflags[post-cb(B)]&2)==0){ /* always try absolute offset zero first! */ { long zeropos=post-ib(A); if (zeropos>=0 && zeropos<is(A)) { if ( cv(B)[post-cb(B)] == iv(A)[zeropos] ) { if (do_const_sync(B, A, Aflags, post-cb(B), zeropos, begin, end, offset) ) { offset_add_value(p,&(p->stage1),*offset,callback); return(1); } } } } } else return(0); ptr=sort_getmatch(A,post-ib(A),dynoverlap,cv(B)[post-cb(B)]); while(ptr){ if(do_const_sync(B,A,Aflags, post-cb(B),ipos(A,ptr), begin,end,offset)){ offset_add_value(p,&(p->stage1),*offset,callback); return(1); } ptr=sort_nextmatch(A,ptr); } *begin=-1; *end=-1; *offset=-1; return(0); }
/// Equivalent to a vsprintf on the string. int ostringstream::vformat (const char* fmt, va_list args) { size_t rv, space; do { space = remaining(); rv = vsnprintf (const_cast<char *>(ipos()), space, fmt, args); if (ssize_t(rv) < 0) rv = space; } while (rv >= space && rv < overflow(rv + 1)); SetPos (pos() + minV (rv, space)); return (int)(rv); }
sort_link_t * sort_nextmatch(sort_info_t *i, sort_link_t *prev) { sort_link_t *ret=prev->next; /* If there aren't any more hits, or we've passed the boundary requested * of sort_getmatch(), we're done. */ if (!ret || ipos(i,ret)>=i->hi) return(NULL); return(ret); }
void Lyrics::layout() { // setPos(_textStyle.offset(spatium())); layout1(); QPointF rp(readPos()); if (!rp.isNull()) { if (score()->mscVersion() <= 114) { rp.ry() += lineSpacing() + 2; rp.rx() += bbox().width() * .5; } setUserOff(rp - ipos()); setReadPos(QPointF()); } }
/// Aligns the write pointer on \p grain. The skipped bytes are zeroed. void ostream::align (size_type grain) { assert (!((grain-1)&grain) && "grain must be a power of 2"); iterator ip = ipos(); iterator ipa = iterator((uintptr_t(ip) + (grain-1)) & ~(grain-1)); size_t nb = distance (ip, ipa); #if WANT_STREAM_BOUNDS_CHECKING if (!verify_remaining ("align", "padding", nb)) return; #else assert (remaining() >= nb && "Buffer overrun. Check your stream size calculations."); #endif memset (const_cast<void *>(reinterpret_cast<const void *>(ip)), '\x0', nb); m_Pos += nb; }
static void getmusigmamass(float musigmamass[3], float *l, int n) { double mu = 0, sigma = 0, mass = 0, nn = 0; for (int i = 0; i < n; i++) if (isfinite(l[i])) mass += l[i]; mass *= 2*3.1416/n; for (int i = 0; i < n; i++) if (isfinite(l[i])) { mu += l[i] * ipos(i, n); nn += l[i]; } mu /= nn; for (int i = 0; i < n; i++) { double posi = ipos(i, n); if (isfinite(l[i])) sigma += l[i]*(posi-mu)*(posi-mu); } sigma = sqrt(sigma/nn); fprintf(stderr, "mu sigma mass nn = %g %g %g %g\n", mu, sigma, mass,nn); musigmamass[0] = mu; musigmamass[1] = sigma; musigmamass[2] = mass; }
void CTeam::ClampStartPosInStartBox(float3* pos) const { const int allyTeam = teamHandler->AllyTeam(teamNum); const std::vector<AllyTeam>& allyStartData = CGameSetup::GetAllyStartingData(); const AllyTeam& allyTeamData = allyStartData[allyTeam]; const SRectangle rect( allyTeamData.startRectLeft * gs->mapx * SQUARE_SIZE, allyTeamData.startRectTop * gs->mapy * SQUARE_SIZE, allyTeamData.startRectRight * gs->mapx * SQUARE_SIZE, allyTeamData.startRectBottom * gs->mapy * SQUARE_SIZE ); int2 ipos(pos->x, pos->z); rect.ClampPos(&ipos); pos->x = ipos.x; pos->z = ipos.y; }
ArrayGridNodeContainer::ArrayGridNodeContainer(Pathfinder *pathf, v3s16 dimensions) : m_x_stride(dimensions.Y * dimensions.Z), m_y_stride(dimensions.Z) { m_pathf = pathf; m_nodes_array.resize(dimensions.X * dimensions.Y * dimensions.Z); INFO_TARGET << "Pathfinder ArrayGridNodeContainer constructor." << std::endl; for (int x = 0; x < dimensions.X; x++) { for (int y = 0; y < dimensions.Y; y++) { for (int z= 0; z < dimensions.Z; z++) { v3s16 ipos(x, y, z); initNode(ipos, &access(ipos)); } } } }
void WorldHelper::shootPortal(int button, Scene *scene) { Vector3f cameraDir = Math::toDirection(scene->camera.getOrientation()); btVector3 btFrom = scene->camera.getPosition(); btVector3 btTo = btFrom + cameraDir*10000; btCollisionWorld::ClosestRayResultCallback res(btFrom, btTo); scene->physics.world->rayTest(btFrom, btTo, res); if (res.hasHit()) { const Entity *pEnt = reinterpret_cast<Entity*>(res.m_collisionObject->getUserPointer()); // All RigidBodies should have their pointer set, but check anyway if (pEnt) { const Entity &ent = *pEnt; // TODO: material in separate Component, + 1 mat per face if (ent.hasComponent<MeshDrawable>() and ent.getComponent<MeshDrawable>().material.portalable) { EntityPair &pPair = SceneHelper::getPortalPairFromScene(0, scene); Vector3f ipos(res.m_hitPointWorld); Entity &pEnt = (button == 1) ? *pPair.first : *pPair.second; Portal &portal = pEnt.getComponent<Portal>(); portal.openSince = scene->world->getTime(); portal.maskTex.diffuse = TextureLoader::getTexture("portalmask.png"); // TODO: ditch AACollisionBoxes portal.placeOnWall(scene->camera.getPosition(), ipos, res.m_hitNormalWorld); const Entity& otherPortalEntity = (button==1) ? *pPair.second : *pPair.first; Portal& otherPortal = otherPortalEntity.getComponent<Portal>(); if(otherPortal.open) { otherPortal.isUncolliderActive = true; portal.isUncolliderActive = true; } LightSource &pLight = pEnt.getComponent<LightSource>(); if (button == 1) { portal.overlayTex.diffuse = TextureLoader::getTexture("blueportal.png"); portal.color = pLight.color = Portal::BLUE_COLOR; } else { portal.overlayTex.diffuse = TextureLoader::getTexture("orangeportal.png"); portal.color = pLight.color = Portal::ORANGE_COLOR; } } } } }
void Marker::adjustReadPos() { if (!readPos().isNull()) { QPointF uo; if (score()->mscVersion() <= 114) { // rebase from Measure to Segment uo = userOff(); uo.rx() -= segment()->pos().x(); // 1.2 is always HCENTER aligned if ((align() & ALIGN_HMASK) == 0) // ALIGN_LEFT uo.rx() -= bbox().width() * .5; } else uo = readPos() - ipos(); setUserOff(uo); setReadPos(QPointF()); } }
/// Equivalent to a vsprintf on the string. int ostringstream::vformat (const char* fmt, va_list args) { #if HAVE_VA_COPY va_list args2; #else #define args2 args #undef __va_copy #define __va_copy(x,y) #endif int rv, space; do { space = remaining(); __va_copy (args2, args); if (0 > (rv = vsnprintf (ipos(), space, fmt, args2))) return rv; } while (rv >= space && rv < (int)overflow(rv+1)); SetPos (pos() + min (rv, space)); return rv; }
static void plot_cline2(float *l, int n) { printf("set samples 1000\n"); printf("plot \"-\" w lines title \"data\""); float musigmamass[3]; getmusigmamass(musigmamass, l, n); float mu = musigmamass[0]; float sigma = musigmamass[1]; float mass = musigmamass[2]; float alpha_g = mass/(sigma*sqrt(2*3.1416)); float alpha_l = mass/(sigma*sqrt(2)); fprintf(stderr, "mass = %g\n", mass); printf(",(%g)*exp(-(x-(%g))**2/(2*(%g)**2)) title \"normal\"", alpha_g, mu, sigma); printf(",(%g)*exp(-abs(x-(%g))*sqrt(2)/(%g)) title \"laplacian\"", alpha_l, mu, sigma); printf("\n"); for (int i = 0; i < n; i++) { float ipoz = ipos(i, n); printf("\t%g %g\n", ipoz, l[i]); } printf("end\n"); }
void GameHandler::processMessage(NetComputer *comp, MessageIn &message) { GameClient &computer = *static_cast< GameClient * >(comp); MessageOut result; if (computer.status == CLIENT_LOGIN) { if (message.getId() != PGMSG_CONNECT) return; std::string magic_token = message.readString(MAGIC_TOKEN_LENGTH); computer.status = CLIENT_QUEUED; // Before the addPendingClient mTokenCollector.addPendingClient(magic_token, &computer); return; } else if (computer.status != CLIENT_CONNECTED) { return; } switch (message.getId()) { case PGMSG_SAY: { std::string say = message.readString(); if (say.empty()) break; if (say[0] == '@') { CommandHandler::handleCommand(computer.character, say); break; } GameState::sayAround(computer.character, say); std::string msg = computer.character->getName() + " said " + say; accountHandler->sendTransaction(computer.character->getDatabaseID(), TRANS_MSG_PUBLIC, msg); } break; case PGMSG_NPC_TALK: case PGMSG_NPC_TALK_NEXT: case PGMSG_NPC_SELECT: case PGMSG_NPC_NUMBER: case PGMSG_NPC_STRING: { int id = message.readShort(); Actor *o = findActorNear(computer.character, id); if (!o || o->getType() != OBJECT_NPC) { sendError(comp, id, "Not close enough to NPC\n"); break; } NPC *q = static_cast< NPC * >(o); if (message.getId() == PGMSG_NPC_SELECT) { q->select(computer.character, message.readByte()); } else if (message.getId() == PGMSG_NPC_NUMBER) { q->integerReceived(computer.character, message.readLong()); } else if (message.getId() == PGMSG_NPC_STRING) { q->stringReceived(computer.character, message.readString()); } else { q->prompt(computer.character, message.getId() == PGMSG_NPC_TALK); } } break; case PGMSG_PICKUP: { int x = message.readShort(); int y = message.readShort(); Point ppos = computer.character->getPosition(); // TODO: use a less arbitrary value. if (std::abs(x - ppos.x) + std::abs(y - ppos.y) < 48) { MapComposite *map = computer.character->getMap(); Point ipos(x, y); for (FixedActorIterator i(map->getAroundPointIterator(ipos, 0)); i; ++i) { Actor *o = *i; Point opos = o->getPosition(); if (o->getType() == OBJECT_ITEM && opos.x == x && opos.y == y) { Item *item = static_cast< Item * >(o); ItemClass *ic = item->getItemClass(); Inventory(computer.character) .insert(ic->getDatabaseID(), item->getAmount()); GameState::remove(item); // log transaction std::stringstream str; str << "User picked up item " << ic->getDatabaseID() << " at " << opos.x << "x" << opos.y; accountHandler->sendTransaction(computer.character->getDatabaseID(), TRANS_ITEM_PICKUP, str.str()); break; } } } } break; case PGMSG_USE_ITEM: { int slot = message.readByte(); Inventory inv(computer.character); if (ItemClass *ic = ItemManager::getItem(inv.getItem(slot))) { if (ic->use(computer.character)) { inv.removeFromSlot(slot, 1); // log transaction std::stringstream str; str << "User used item " << ic->getDatabaseID() << " from slot " << slot; accountHandler->sendTransaction(computer.character->getDatabaseID(), TRANS_ITEM_USED, str.str()); } } } break; case PGMSG_DROP: { int slot = message.readByte(); int amount = message.readByte(); Inventory inv(computer.character); if (ItemClass *ic = ItemManager::getItem(inv.getItem(slot))) { int nb = inv.removeFromSlot(slot, amount); Item *item = new Item(ic, amount - nb); item->setMap(computer.character->getMap()); item->setPosition(computer.character->getPosition()); if (!GameState::insert(item)) { // The map is full. Put back into inventory. inv.insert(ic->getDatabaseID(), amount - nb); delete item; break; } // log transaction Point pt = computer.character->getPosition(); std::stringstream str; str << "User dropped item " << ic->getDatabaseID() << " at " << pt.x << "x" << pt.y; accountHandler->sendTransaction(computer.character->getDatabaseID(), TRANS_ITEM_DROP, str.str()); } } break; case PGMSG_WALK: { handleWalk(&computer, message); } break; case PGMSG_EQUIP: { int slot = message.readByte(); Inventory(computer.character).equip(slot); } break; case PGMSG_UNEQUIP: { int slot = message.readByte(); if (slot >= 0 && slot < EQUIP_PROJECTILE_SLOT) { Inventory(computer.character).unequip(slot); } } break; case PGMSG_MOVE_ITEM: { int slot1 = message.readByte(); int slot2 = message.readByte(); int amount = message.readByte(); Inventory(computer.character).move(slot1, slot2, amount); // log transaction std::stringstream str; str << "User moved item " << " from slot " << slot1 << " to slot " << slot2; accountHandler->sendTransaction(computer.character->getDatabaseID(), TRANS_ITEM_MOVE, str.str()); } break; case PGMSG_ATTACK: { int id = message.readShort(); LOG_DEBUG("Character " << computer.character->getPublicID() << " attacked being " << id); Actor *o = findActorNear(computer.character, id); if (o && o->getType() != OBJECT_NPC) { Being *being = static_cast<Being*>(o); computer.character->setTarget(being); computer.character->setAction(Being::ATTACK); } } break; case PGMSG_USE_SPECIAL: { int specialID = message.readByte(); LOG_DEBUG("Character " << computer.character->getPublicID() << " tries to use his special attack "<<specialID); computer.character->useSpecial(specialID); } case PGMSG_ACTION_CHANGE: { Being::Action action = (Being::Action)message.readByte(); Being::Action current = (Being::Action)computer.character->getAction(); bool logActionChange = true; switch (action) { case Being::STAND: { if (current == Being::SIT) { computer.character->setAction(Being::STAND); logActionChange = false; } } break; case Being::SIT: { if (current == Being::STAND) { computer.character->setAction(Being::SIT); logActionChange = false; } } break; default: break; } // Log the action change only when this is relevant. if (logActionChange) { // log transaction std::stringstream str; str << "User changed action from " << current << " to " << action; accountHandler->sendTransaction( computer.character->getDatabaseID(), TRANS_ACTION_CHANGE, str.str()); } } break; case PGMSG_DIRECTION_CHANGE: { computer.character->setDirection(message.readByte()); } break; case PGMSG_DISCONNECT: { bool reconnectAccount = (bool) message.readByte(); result.writeShort(GPMSG_DISCONNECT_RESPONSE); result.writeByte(ERRMSG_OK); // It is, when control reaches here if (reconnectAccount) { std::string magic_token(utils::getMagicToken()); result.writeString(magic_token, MAGIC_TOKEN_LENGTH); // No accountserver data, the client should remember that accountHandler->playerReconnectAccount( computer.character->getDatabaseID(), magic_token); } // TODO: implement a delayed remove GameState::remove(computer.character); accountHandler->sendCharacterData(computer.character); // Done with the character computer.character->disconnected(); delete computer.character; computer.character = NULL; computer.status = CLIENT_LOGIN; } break; case PGMSG_TRADE_REQUEST: { int id = message.readShort(); if (Trade *t = computer.character->getTrading()) { if (t->request(computer.character, id)) break; } Character *q = findCharacterNear(computer.character, id); if (!q || q->isBusy()) { result.writeShort(GPMSG_TRADE_CANCEL); break; } new Trade(computer.character, q); // log transaction std::string str; str = "User requested trade with " + q->getName(); accountHandler->sendTransaction(computer.character->getDatabaseID(), TRANS_TRADE_REQUEST, str); } break; case PGMSG_TRADE_CANCEL: case PGMSG_TRADE_AGREED: case PGMSG_TRADE_CONFIRM: case PGMSG_TRADE_ADD_ITEM: case PGMSG_TRADE_SET_MONEY: { std::stringstream str; Trade *t = computer.character->getTrading(); if (!t) break; switch (message.getId()) { case PGMSG_TRADE_CANCEL: t->cancel(); break; case PGMSG_TRADE_CONFIRM: t->confirm(computer.character); break; case PGMSG_TRADE_AGREED: t->agree(computer.character); // log transaction accountHandler->sendTransaction(computer.character->getDatabaseID(), TRANS_TRADE_END, "User finished trading"); break; case PGMSG_TRADE_SET_MONEY: { int money = message.readLong(); t->setMoney(computer.character, money); // log transaction str << "User added " << money << " money to trade."; accountHandler->sendTransaction(computer.character->getDatabaseID(), TRANS_TRADE_MONEY, str.str()); } break; case PGMSG_TRADE_ADD_ITEM: { int slot = message.readByte(); t->addItem(computer.character, slot, message.readByte()); // log transaction str << "User add item from slot " << slot; accountHandler->sendTransaction(computer.character->getDatabaseID(), TRANS_TRADE_ITEM, str.str()); } break; } } break; case PGMSG_NPC_BUYSELL: { BuySell *t = computer.character->getBuySell(); if (!t) break; int id = message.readShort(); int amount = message.readShort(); t->perform(id, amount); } break; case PGMSG_RAISE_ATTRIBUTE: { int attribute = message.readByte(); AttribmodResponseCode retCode; retCode = computer.character->useCharacterPoint(attribute); result.writeShort(GPMSG_RAISE_ATTRIBUTE_RESPONSE); result.writeByte(retCode); result.writeByte(attribute); if (retCode == ATTRIBMOD_OK ) { accountHandler->updateCharacterPoints( computer.character->getDatabaseID(), computer.character->getCharacterPoints(), computer.character->getCorrectionPoints(), attribute, computer.character->getAttribute(attribute)); // log transaction std::stringstream str; str << "User increased attribute " << attribute; accountHandler->sendTransaction(computer.character->getDatabaseID(), TRANS_ATTR_INCREASE, str.str()); } } break; case PGMSG_LOWER_ATTRIBUTE: { int attribute = message.readByte(); AttribmodResponseCode retCode; retCode = computer.character->useCorrectionPoint(attribute); result.writeShort(GPMSG_LOWER_ATTRIBUTE_RESPONSE); result.writeByte(retCode); result.writeByte(attribute); if (retCode == ATTRIBMOD_OK ) { accountHandler->updateCharacterPoints( computer.character->getDatabaseID(), computer.character->getCharacterPoints(), computer.character->getCorrectionPoints(), attribute, computer.character->getAttribute(attribute)); // log transaction std::stringstream str; str << "User decreased attribute " << attribute; accountHandler->sendTransaction(computer.character->getDatabaseID(), TRANS_ATTR_DECREASE, str.str()); } } break; case PGMSG_RESPAWN: { computer.character->respawn(); // plausibility check is done by character class } break; case PGMSG_NPC_POST_SEND: { handleSendPost(&computer, message); } break; default: LOG_WARN("Invalid message type"); result.writeShort(XXMSG_INVALID); break; } if (result.getLength() > 0) computer.send(result); }
bool pathfinder::build_costmap() { INFO_TARGET << "Pathfinder build costmap: (" << m_limits.X.min << "," << m_limits.Z.min << ") (" << m_limits.X.max << "," << m_limits.Z.max << ")" << std::endl; m_data.resize(m_max_index_x); for (int x = 0; x < m_max_index_x; x++) { m_data[x].resize(m_max_index_z); for (int z = 0; z < m_max_index_z; z++) { m_data[x][z].resize(m_max_index_y); int surfaces = 0; for (int y = 0; y < m_max_index_y; y++) { v3s16 ipos(x,y,z); v3s16 realpos = getRealPos(ipos); MapNode current = m_env->getMap().getNodeNoEx(realpos); MapNode below = m_env->getMap().getNodeNoEx(realpos + v3s16(0,-1,0)); if ((current.param0 == CONTENT_IGNORE) || (below.param0 == CONTENT_IGNORE)) { DEBUG_OUT("Pathfinder: " << PPOS(realpos) << " current or below is invalid element" << std::endl); if (current.param0 == CONTENT_IGNORE) { m_data[x][z][y].type = 'i'; DEBUG_OUT(x << "," << y << "," << z << ": " << 'i' << std::endl); } continue; } //don't add anything if it isn't an air node if ((current.param0 != CONTENT_AIR) || (below.param0 == CONTENT_AIR )) { DEBUG_OUT("Pathfinder: " << PPOS(realpos) << " not on surface" << std::endl); if (current.param0 != CONTENT_AIR) { m_data[x][z][y].type = 's'; DEBUG_OUT(x << "," << y << "," << z << ": " << 's' << std::endl); } else { m_data[x][z][y].type = '-'; DEBUG_OUT(x << "," << y << "," << z << ": " << '-' << std::endl); } continue; } surfaces++; m_data[x][z][y].valid = true; m_data[x][z][y].pos = realpos; m_data[x][z][y].type = 'g'; DEBUG_OUT(x << "," << y << "," << z << ": " << 'a' << std::endl); if (m_prefetch) { m_data[x][z][y].directions[DIR_XP] = calc_cost(realpos,v3s16( 1,0, 0)); m_data[x][z][y].directions[DIR_XM] = calc_cost(realpos,v3s16(-1,0, 0)); m_data[x][z][y].directions[DIR_ZP] = calc_cost(realpos,v3s16( 0,0, 1)); m_data[x][z][y].directions[DIR_ZM] = calc_cost(realpos,v3s16( 0,0,-1)); } } if (surfaces >= 1 ) { for (int y = 0; y < m_max_index_y; y++) { if (m_data[x][z][y].valid) { m_data[x][z][y].surfaces = surfaces; } } } } } return true; }
/// Writes the object to stream \p os. void istream::text_write (ostringstream& os) const { os.write (ipos(), remaining()); }
void Fingering::layout() { if (parent()) { Fraction tick = parent()->tick(); const Staff* st = staff(); if (st && st->isTabStaff(tick) && !st->staffType(tick)->showTabFingering()) { setbbox(QRectF()); return; } } TextBase::layout(); rypos() = 0.0; // handle placement below if (autoplace() && note()) { Note* n = note(); Chord* chord = n->chord(); bool voices = chord->measure()->hasVoices(chord->staffIdx()); bool tight = voices && chord->notes().size() == 1 && !chord->beam() && tid() != Tid::STRING_NUMBER; qreal headWidth = n->bboxRightPos(); // update offset after drag qreal rebase = 0.0; if (offsetChanged() != OffsetChange::NONE) rebase = rebaseOffset(); // temporarily exclude self from chord shape setAutoplace(false); if (layoutType() == ElementType::CHORD) { Stem* stem = chord->stem(); Segment* s = chord->segment(); Measure* m = s->measure(); qreal sp = spatium(); qreal md = minDistance().val() * sp; SysStaff* ss = m->system()->staff(chord->vStaffIdx()); Staff* vStaff = chord->staff(); // TODO: use current height at tick if (n->mirror()) rxpos() -= n->ipos().x(); rxpos() += headWidth * .5; if (placeAbove()) { if (tight) { if (chord->stem()) rxpos() -= 0.8 * sp; rypos() -= 1.5 * sp; } else { QRectF r = bbox().translated(m->pos() + s->pos() + chord->pos() + n->pos() + pos()); SkylineLine sk(false); sk.add(r.x(), r.bottom(), r.width()); qreal d = sk.minDistance(ss->skyline().north()); qreal yd = 0.0; if (d > 0.0 && isStyled(Pid::MIN_DISTANCE)) yd -= d + height() * .25; // force extra space above staff & chord (but not other fingerings) qreal top; if (chord->up() && chord->beam() && stem) { top = stem->y() + stem->bbox().top(); } else { Note* un = chord->upNote(); top = qMin(0.0, un->y() + un->bbox().top()); } top -= md; qreal diff = (bbox().bottom() + ipos().y() + yd + n->y()) - top; if (diff > 0.0) yd -= diff; if (offsetChanged() != OffsetChange::NONE) { // user moved element within the skyline // we may need to adjust minDistance, yd, and/or offset bool inStaff = placeAbove() ? r.bottom() + rebase > 0.0 : r.top() + rebase < staff()->height(); rebaseMinDistance(md, yd, sp, rebase, inStaff); } rypos() += yd; } } else { if (tight) { if (chord->stem()) rxpos() += 0.8 * sp; rypos() += 1.5 * sp; } else { QRectF r = bbox().translated(m->pos() + s->pos() + chord->pos() + n->pos() + pos()); SkylineLine sk(true); sk.add(r.x(), r.top(), r.width()); qreal d = ss->skyline().south().minDistance(sk); qreal yd = 0.0; if (d > 0.0 && isStyled(Pid::MIN_DISTANCE)) yd += d + height() * .25; // force extra space below staff & chord (but not other fingerings) qreal bottom; if (!chord->up() && chord->beam() && stem) { bottom = stem->y() + stem->bbox().bottom(); } else { Note* dn = chord->downNote(); bottom = qMax(vStaff->height(), dn->y() + dn->bbox().bottom()); } bottom += md; qreal diff = bottom - (bbox().top() + ipos().y() + yd + n->y()); if (diff > 0.0) yd += diff; if (offsetChanged() != OffsetChange::NONE) { // user moved element within the skyline // we may need to adjust minDistance, yd, and/or offset bool inStaff = placeAbove() ? r.bottom() + rebase > 0.0 : r.top() + rebase < staff()->height(); rebaseMinDistance(md, yd, sp, rebase, inStaff); } rypos() += yd; } } } else if (tid() == Tid::LH_GUITAR_FINGERING) { // place to left of note qreal left = n->shape().left(); if (left - n->x() > 0.0) rxpos() -= left; else rxpos() -= n->x(); } // for other fingering styles, do not autoplace // restore autoplace setAutoplace(true); } else if (offsetChanged() != OffsetChange::NONE) { // rebase horizontally too, as autoplace may have adjusted it rebaseOffset(false); } setOffsetChanged(false); }