hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
8d25e275e77ecf688f89e3006df811ff396213ef
1,529
cpp
C++
src/util/signal_catcher.cpp
ZGoriely/cbmc
d10e44dd98b21d04bdfc3052e2eaee6b2475a2b8
[ "BSD-4-Clause" ]
1
2021-09-09T06:09:03.000Z
2021-09-09T06:09:03.000Z
src/util/signal_catcher.cpp
polgreen/cbmc
dd42ef89dabcd010ed63e089ced04f9a7b6f1199
[ "BSD-4-Clause" ]
39
2017-11-07T16:48:51.000Z
2017-12-04T15:24:01.000Z
src/util/signal_catcher.cpp
danpoe/cbmc
9ae35de4db89e59e6bdbdfe5b2f77229d7f82eda
[ "BSD-4-Clause" ]
null
null
null
/*******************************************************************\ Module: Author: Daniel Kroening, kroening@kroening.com Date: \*******************************************************************/ #include "signal_catcher.h" #if defined(_WIN32) #include <process.h> #else #include <cstdlib> #include <csignal> #endif #include <vector> // Here we have an instance of an ugly global object. // It keeps track of any child processes that we'll kill // when we are told to terminate. #ifdef _WIN32 #else std::vector<pid_t> pids_of_children; #endif void install_signal_catcher() { #if defined(_WIN32) #else // declare act to deal with action on signal set // NOLINTNEXTLINE(readability/identifiers) static struct sigaction act; act.sa_handler=signal_catcher; act.sa_flags=0; sigfillset(&(act.sa_mask)); // install signal handler sigaction(SIGTERM, &act, nullptr); #endif } void remove_signal_catcher() { #if defined(_WIN32) #else // declare act to deal with action on signal set // NOLINTNEXTLINE(readability/identifiers) static struct sigaction act; act.sa_handler=SIG_DFL; act.sa_flags=0; sigfillset(&(act.sa_mask)); sigaction(SIGTERM, &act, nullptr); #endif } void signal_catcher(int sig) { #if defined(_WIN32) #else #if 1 // kill any children by killing group killpg(0, sig); #else // pass on to any children for(const auto &pid : pids_of_children) kill(pid, sig); #endif exit(sig); // should contemplate something from sysexits.h #endif }
18.876543
69
0.646828
ZGoriely
8d2ae03d437b155e5145b3755f7746e440dfe36e
41,376
cpp
C++
src/wl_state.cpp
TobiasKarnat/Wolf4GW
a49ead44cb4a6476255e355c4c5e3e48bb7f1d55
[ "Unlicense" ]
8
2015-06-28T09:38:45.000Z
2021-10-02T16:33:47.000Z
src/wl_state.cpp
TobiasKarnat/Wolf4GW
a49ead44cb4a6476255e355c4c5e3e48bb7f1d55
[ "Unlicense" ]
null
null
null
src/wl_state.cpp
TobiasKarnat/Wolf4GW
a49ead44cb4a6476255e355c4c5e3e48bb7f1d55
[ "Unlicense" ]
2
2018-09-08T08:30:38.000Z
2019-03-24T18:10:52.000Z
// WL_STATE.C /* ============================================================================= LOCAL CONSTANTS ============================================================================= */ /* ============================================================================= GLOBAL VARIABLES ============================================================================= */ dirtype opposite[9] = {west,southwest,south,southeast,east,northeast,north,northwest,nodir}; dirtype diagonal[9][9] = { /* east */ {nodir,nodir,northeast,nodir,nodir,nodir,southeast,nodir,nodir}, {nodir,nodir,nodir,nodir,nodir,nodir,nodir,nodir,nodir}, /* north */ {northeast,nodir,nodir,nodir,northwest,nodir,nodir,nodir,nodir}, {nodir,nodir,nodir,nodir,nodir,nodir,nodir,nodir,nodir}, /* west */ {nodir,nodir,northwest,nodir,nodir,nodir,southwest,nodir,nodir}, {nodir,nodir,nodir,nodir,nodir,nodir,nodir,nodir,nodir}, /* south */ {southeast,nodir,nodir,nodir,southwest,nodir,nodir,nodir,nodir}, {nodir,nodir,nodir,nodir,nodir,nodir,nodir,nodir,nodir}, {nodir,nodir,nodir,nodir,nodir,nodir,nodir,nodir,nodir} }; void SpawnNewObj (unsigned tilex, unsigned tiley, statetype *state); void NewState (objtype *ob, statetype *state); boolean TryWalk (objtype *ob); void MoveObj (objtype *ob, long move); void KillActor (objtype *ob); void DamageActor (objtype *ob, unsigned damage); boolean CheckLine (objtype *ob); void FirstSighting (objtype *ob); boolean CheckSight (objtype *ob); /* ============================================================================= LOCAL VARIABLES ============================================================================= */ //=========================================================================== /* =================== = = SpawnNewObj = = Spaws a new actor at the given TILE coordinates, with the given state, and = the given size in GLOBAL units. = = new = a pointer to an initialized new actor = =================== */ void SpawnNewObj (unsigned tilex, unsigned tiley, statetype *state) { GetNewActor (); newobj->state = state; if (state->tictime) newobj->ticcount = US_RndT () % state->tictime + 1; // Chris' moonwalk bugfix ;D else newobj->ticcount = 0; newobj->tilex = (short) tilex; newobj->tiley = (short) tiley; newobj->x = ((long)tilex<<TILESHIFT)+TILEGLOBAL/2; newobj->y = ((long)tiley<<TILESHIFT)+TILEGLOBAL/2; newobj->dir = nodir; actorat[tilex][tiley] = newobj; newobj->areanumber = *(mapsegs[0] + (newobj->tiley<<mapshift)+newobj->tilex) - AREATILE; } /* =================== = = NewState = = Changes ob to a new state, setting ticcount to the max for that state = =================== */ void NewState (objtype *ob, statetype *state) { ob->state = state; ob->ticcount = state->tictime; } /* ============================================================================= ENEMY TILE WORLD MOVEMENT CODE ============================================================================= */ /* ================================== = = TryWalk = = Attempts to move ob in its current (ob->dir) direction. = = If blocked by either a wall or an actor returns FALSE = = If move is either clear or blocked only by a door, returns TRUE and sets = = ob->tilex = new destination = ob->tiley = ob->areanumber = the floor tile number (0-(NUMAREAS-1)) of destination = ob->distance = TILEGLOBAl, or -doornumber if a door is blocking the way = = If a door is in the way, an OpenDoor call is made to start it opening. = The actor code should wait until = doorobjlist[-ob->distance].action = dr_open, meaning the door has been = fully opened = ================================== */ #define CHECKDIAG(x,y) \ { \ temp=(unsigned)actorat[x][y]; \ if (temp) \ { \ if (temp<256) \ return false; \ if (((objtype *)temp)->flags&FL_SHOOTABLE) \ return false; \ } \ } #define CHECKSIDE(x,y) \ { \ temp=(unsigned)actorat[x][y]; \ if (temp) \ { \ if (temp<128) \ return false; \ if (temp<256) \ { \ doornum = temp&127; \ OpenDoor (doornum); \ ob->distance = -doornum-1; \ return true; \ } \ else if (((objtype *)temp)->flags&FL_SHOOTABLE)\ return false; \ } \ } boolean TryWalk (objtype *ob) { int doornum; unsigned temp; if (ob->obclass == inertobj) { switch (ob->dir) { case north: ob->tiley--; break; case northeast: ob->tilex++; ob->tiley--; break; case east: ob->tilex++; break; case southeast: ob->tilex++; ob->tiley++; break; case south: ob->tiley++; break; case southwest: ob->tilex--; ob->tiley++; break; case west: ob->tilex--; break; case northwest: ob->tilex--; ob->tiley--; break; } } else switch (ob->dir) { case north: if (ob->obclass == dogobj || ob->obclass == fakeobj) { CHECKDIAG(ob->tilex,ob->tiley-1); } else { CHECKSIDE(ob->tilex,ob->tiley-1); } ob->tiley--; break; case northeast: CHECKDIAG(ob->tilex+1,ob->tiley-1); CHECKDIAG(ob->tilex+1,ob->tiley); CHECKDIAG(ob->tilex,ob->tiley-1); ob->tilex++; ob->tiley--; break; case east: if (ob->obclass == dogobj || ob->obclass == fakeobj) { CHECKDIAG(ob->tilex+1,ob->tiley); } else { CHECKSIDE(ob->tilex+1,ob->tiley); } ob->tilex++; break; case southeast: CHECKDIAG(ob->tilex+1,ob->tiley+1); CHECKDIAG(ob->tilex+1,ob->tiley); CHECKDIAG(ob->tilex,ob->tiley+1); ob->tilex++; ob->tiley++; break; case south: if (ob->obclass == dogobj || ob->obclass == fakeobj) { CHECKDIAG(ob->tilex,ob->tiley+1); } else { CHECKSIDE(ob->tilex,ob->tiley+1); } ob->tiley++; break; case southwest: CHECKDIAG(ob->tilex-1,ob->tiley+1); CHECKDIAG(ob->tilex-1,ob->tiley); CHECKDIAG(ob->tilex,ob->tiley+1); ob->tilex--; ob->tiley++; break; case west: if (ob->obclass == dogobj || ob->obclass == fakeobj) { CHECKDIAG(ob->tilex-1,ob->tiley); } else { CHECKSIDE(ob->tilex-1,ob->tiley); } ob->tilex--; break; case northwest: CHECKDIAG(ob->tilex-1,ob->tiley-1); CHECKDIAG(ob->tilex-1,ob->tiley); CHECKDIAG(ob->tilex,ob->tiley-1); ob->tilex--; ob->tiley--; break; case nodir: return false; default: Quit ("Walk: Bad dir"); } ob->areanumber = *(mapsegs[0] + (ob->tiley<<mapshift)+ob->tilex) - AREATILE; ob->distance = TILEGLOBAL; return true; } /* ================================== = = SelectDodgeDir = = Attempts to choose and initiate a movement for ob that sends it towards = the player while dodging = = If there is no possible move (ob is totally surrounded) = = ob->dir = nodir = = Otherwise = = ob->dir = new direction to follow = ob->distance = TILEGLOBAL or -doornumber = ob->tilex = new destination = ob->tiley = ob->areanumber = the floor tile number (0-(NUMAREAS-1)) of destination = ================================== */ void SelectDodgeDir (objtype *ob) { int deltax,deltay,i; unsigned absdx,absdy; dirtype dirtry[5]; dirtype turnaround,tdir; if (ob->flags & FL_FIRSTATTACK) { // // turning around is only ok the very first time after noticing the // player // turnaround = nodir; ob->flags &= ~FL_FIRSTATTACK; } else turnaround=opposite[ob->dir]; deltax = player->tilex - ob->tilex; deltay = player->tiley - ob->tiley; // // arange 5 direction choices in order of preference // the four cardinal directions plus the diagonal straight towards // the player // if (deltax>0) { dirtry[1]= east; dirtry[3]= west; } else { dirtry[1]= west; dirtry[3]= east; } if (deltay>0) { dirtry[2]= south; dirtry[4]= north; } else { dirtry[2]= north; dirtry[4]= south; } // // randomize a bit for dodging // absdx = abs(deltax); absdy = abs(deltay); if (absdx > absdy) { tdir = dirtry[1]; dirtry[1] = dirtry[2]; dirtry[2] = tdir; tdir = dirtry[3]; dirtry[3] = dirtry[4]; dirtry[4] = tdir; } if (US_RndT() < 128) { tdir = dirtry[1]; dirtry[1] = dirtry[2]; dirtry[2] = tdir; tdir = dirtry[3]; dirtry[3] = dirtry[4]; dirtry[4] = tdir; } dirtry[0] = diagonal [ dirtry[1] ] [ dirtry[2] ]; // // try the directions util one works // for (i=0;i<5;i++) { if ( dirtry[i] == nodir || dirtry[i] == turnaround) continue; ob->dir = dirtry[i]; if (TryWalk(ob)) return; } // // turn around only as a last resort // if (turnaround != nodir) { ob->dir = turnaround; if (TryWalk(ob)) return; } ob->dir = nodir; } /* ============================ = = SelectChaseDir = = As SelectDodgeDir, but doesn't try to dodge = ============================ */ void SelectChaseDir (objtype *ob) { int deltax,deltay; dirtype d[3]; dirtype tdir, olddir, turnaround; olddir=ob->dir; turnaround=opposite[olddir]; deltax=player->tilex - ob->tilex; deltay=player->tiley - ob->tiley; d[1]=nodir; d[2]=nodir; if (deltax>0) d[1]= east; else if (deltax<0) d[1]= west; if (deltay>0) d[2]=south; else if (deltay<0) d[2]=north; if (abs(deltay)>abs(deltax)) { tdir=d[1]; d[1]=d[2]; d[2]=tdir; } if (d[1]==turnaround) d[1]=nodir; if (d[2]==turnaround) d[2]=nodir; if (d[1]!=nodir) { ob->dir=d[1]; if (TryWalk(ob)) return; /*either moved forward or attacked*/ } if (d[2]!=nodir) { ob->dir=d[2]; if (TryWalk(ob)) return; } /* there is no direct path to the player, so pick another direction */ if (olddir!=nodir) { ob->dir=olddir; if (TryWalk(ob)) return; } if (US_RndT()>128) /*randomly determine direction of search*/ { for (tdir=north;tdir<=west;tdir=(dirtype)(tdir+1)) { if (tdir!=turnaround) { ob->dir=tdir; if ( TryWalk(ob) ) return; } } } else { for (tdir=west;tdir>=north;tdir=(dirtype)(tdir-1)) { if (tdir!=turnaround) { ob->dir=tdir; if ( TryWalk(ob) ) return; } } } if (turnaround != nodir) { ob->dir=turnaround; if (ob->dir != nodir) { if ( TryWalk(ob) ) return; } } ob->dir = nodir; // can't move } /* ============================ = = SelectRunDir = = Run Away from player = ============================ */ void SelectRunDir (objtype *ob) { int deltax,deltay; dirtype d[3]; dirtype tdir; deltax=player->tilex - ob->tilex; deltay=player->tiley - ob->tiley; if (deltax<0) d[1]= east; else d[1]= west; if (deltay<0) d[2]=south; else d[2]=north; if (abs(deltay)>abs(deltax)) { tdir=d[1]; d[1]=d[2]; d[2]=tdir; } ob->dir=d[1]; if (TryWalk(ob)) return; /*either moved forward or attacked*/ ob->dir=d[2]; if (TryWalk(ob)) return; /* there is no direct path to the player, so pick another direction */ if (US_RndT()>128) /*randomly determine direction of search*/ { for (tdir=north;tdir<=west;tdir=(dirtype)(tdir+1)) { ob->dir=tdir; if ( TryWalk(ob) ) return; } } else { for (tdir=west;tdir>=north;tdir=(dirtype)(tdir-1)) { ob->dir=tdir; if ( TryWalk(ob) ) return; } } ob->dir = nodir; // can't move } /* ================= = = MoveObj = = Moves ob be move global units in ob->dir direction = Actors are not allowed to move inside the player = Does NOT check to see if the move is tile map valid = = ob->x = adjusted for new position = ob->y = ================= */ void MoveObj (objtype *ob, long move) { long deltax,deltay; switch (ob->dir) { case north: ob->y -= move; break; case northeast: ob->x += move; ob->y -= move; break; case east: ob->x += move; break; case southeast: ob->x += move; ob->y += move; break; case south: ob->y += move; break; case southwest: ob->x -= move; ob->y += move; break; case west: ob->x -= move; break; case northwest: ob->x -= move; ob->y -= move; break; case nodir: return; default: Quit ("MoveObj: bad dir!"); } // // check to make sure it's not on top of player // if (areabyplayer[ob->areanumber]) { deltax = ob->x - player->x; if (deltax < -MINACTORDIST || deltax > MINACTORDIST) goto moveok; deltay = ob->y - player->y; if (deltay < -MINACTORDIST || deltay > MINACTORDIST) goto moveok; if (ob->hidden) // move closer until he meets CheckLine goto moveok; if (ob->obclass == ghostobj || ob->obclass == spectreobj) TakeDamage (tics*2,ob); // // back up // switch (ob->dir) { case north: ob->y += move; break; case northeast: ob->x -= move; ob->y += move; break; case east: ob->x -= move; break; case southeast: ob->x -= move; ob->y -= move; break; case south: ob->y -= move; break; case southwest: ob->x += move; ob->y -= move; break; case west: ob->x += move; break; case northwest: ob->x += move; ob->y += move; break; case nodir: return; } return; } moveok: ob->distance -=move; } /* ============================================================================= STUFF ============================================================================= */ /* =============== = = KillActor = =============== */ void KillActor (objtype *ob) { int tilex,tiley; tilex = ob->tilex = (word)(ob->x >> TILESHIFT); // drop item on center tiley = ob->tiley = (word)(ob->y >> TILESHIFT); switch (ob->obclass) { case guardobj: GivePoints (100); NewState (ob,&s_grddie1); PlaceItemType (bo_clip2,tilex,tiley); break; case officerobj: GivePoints (400); NewState (ob,&s_ofcdie1); PlaceItemType (bo_clip2,tilex,tiley); break; case mutantobj: GivePoints (700); NewState (ob,&s_mutdie1); PlaceItemType (bo_clip2,tilex,tiley); break; case ssobj: GivePoints (500); NewState (ob,&s_ssdie1); if (gamestate.bestweapon < wp_machinegun) PlaceItemType (bo_machinegun,tilex,tiley); else PlaceItemType (bo_clip2,tilex,tiley); break; case dogobj: GivePoints (200); NewState (ob,&s_dogdie1); break; #ifndef SPEAR case bossobj: GivePoints (5000); NewState (ob,&s_bossdie1); PlaceItemType (bo_key1,tilex,tiley); break; case gretelobj: GivePoints (5000); NewState (ob,&s_greteldie1); PlaceItemType (bo_key1,tilex,tiley); break; case giftobj: GivePoints (5000); gamestate.killx = player->x; gamestate.killy = player->y; NewState (ob,&s_giftdie1); break; case fatobj: GivePoints (5000); gamestate.killx = player->x; gamestate.killy = player->y; NewState (ob,&s_fatdie1); break; case schabbobj: GivePoints (5000); gamestate.killx = player->x; gamestate.killy = player->y; NewState (ob,&s_schabbdie1); A_DeathScream(ob); break; case fakeobj: GivePoints (2000); NewState (ob,&s_fakedie1); break; case mechahitlerobj: GivePoints (5000); NewState (ob,&s_mechadie1); break; case realhitlerobj: GivePoints (5000); gamestate.killx = player->x; gamestate.killy = player->y; NewState (ob,&s_hitlerdie1); A_DeathScream(ob); break; #else case spectreobj: if (ob->flags&FL_BONUS) { GivePoints (200); // Get points once for each ob->flags &= ~FL_BONUS; } NewState (ob,&s_spectredie1); break; case angelobj: GivePoints (5000); NewState (ob,&s_angeldie1); break; case transobj: GivePoints (5000); NewState (ob,&s_transdie0); PlaceItemType (bo_key1,tilex,tiley); break; case uberobj: GivePoints (5000); NewState (ob,&s_uberdie0); PlaceItemType (bo_key1,tilex,tiley); break; case willobj: GivePoints (5000); NewState (ob,&s_willdie1); PlaceItemType (bo_key1,tilex,tiley); break; case deathobj: GivePoints (5000); NewState (ob,&s_deathdie1); PlaceItemType (bo_key1,tilex,tiley); break; #endif } gamestate.killcount++; ob->flags &= ~FL_SHOOTABLE; actorat[ob->tilex][ob->tiley] = NULL; ob->flags |= FL_NONMARK; } /* =================== = = DamageActor = = Called when the player succesfully hits an enemy. = = Does damage points to enemy ob, either putting it into a stun frame or = killing it. = =================== */ void DamageActor (objtype *ob, unsigned damage) { madenoise = true; // // do double damage if shooting a non attack mode actor // if ( !(ob->flags & FL_ATTACKMODE) ) damage <<= 1; ob->hitpoints -= (short)damage; if (ob->hitpoints<=0) KillActor (ob); else { if (! (ob->flags & FL_ATTACKMODE) ) FirstSighting (ob); // put into combat mode switch (ob->obclass) // dogs only have one hit point { case guardobj: if (ob->hitpoints&1) NewState (ob,&s_grdpain); else NewState (ob,&s_grdpain1); break; case officerobj: if (ob->hitpoints&1) NewState (ob,&s_ofcpain); else NewState (ob,&s_ofcpain1); break; case mutantobj: if (ob->hitpoints&1) NewState (ob,&s_mutpain); else NewState (ob,&s_mutpain1); break; case ssobj: if (ob->hitpoints&1) NewState (ob,&s_sspain); else NewState (ob,&s_sspain1); break; } } } /* ============================================================================= CHECKSIGHT ============================================================================= */ /* ===================== = = CheckLine = = Returns true if a straight line between the player and ob is unobstructed = ===================== */ boolean CheckLine (objtype *ob) { int x1,y1,xt1,yt1,x2,y2,xt2,yt2; int x,y; int xdist,ydist,xstep,ystep; int partial,delta; long ltemp; int xfrac,yfrac,deltafrac; unsigned value,intercept; x1 = ob->x >> UNSIGNEDSHIFT; // 1/256 tile precision y1 = ob->y >> UNSIGNEDSHIFT; xt1 = x1 >> 8; yt1 = y1 >> 8; x2 = plux; y2 = pluy; xt2 = player->tilex; yt2 = player->tiley; xdist = abs(xt2-xt1); if (xdist > 0) { if (xt2 > xt1) { partial = 256-(x1&0xff); xstep = 1; } else { partial = x1&0xff; xstep = -1; } deltafrac = abs(x2-x1); delta = y2-y1; ltemp = ((long)delta<<8)/deltafrac; if (ltemp > 0x7fffl) ystep = 0x7fff; else if (ltemp < -0x7fffl) ystep = -0x7fff; else ystep = ltemp; yfrac = y1 + (((long)ystep*partial) >>8); x = xt1+xstep; xt2 += xstep; do { y = yfrac>>8; yfrac += ystep; value = (unsigned)tilemap[x][y]; x += xstep; if (!value) continue; if (value<128 || value>256) return false; // // see if the door is open enough // value &= ~0x80; intercept = yfrac-ystep/2; if (intercept>doorposition[value]) return false; } while (x != xt2); } ydist = abs(yt2-yt1); if (ydist > 0) { if (yt2 > yt1) { partial = 256-(y1&0xff); ystep = 1; } else { partial = y1&0xff; ystep = -1; } deltafrac = abs(y2-y1); delta = x2-x1; ltemp = ((long)delta<<8)/deltafrac; if (ltemp > 0x7fffl) xstep = 0x7fff; else if (ltemp < -0x7fffl) xstep = -0x7fff; else xstep = ltemp; xfrac = x1 + (((long)xstep*partial) >>8); y = yt1 + ystep; yt2 += ystep; do { x = xfrac>>8; xfrac += xstep; value = (unsigned)tilemap[x][y]; y += ystep; if (!value) continue; if (value<128 || value>256) return false; // // see if the door is open enough // value &= ~0x80; intercept = xfrac-xstep/2; if (intercept>doorposition[value]) return false; } while (y != yt2); } return true; } /* ================ = = CheckSight = = Checks a straight line between player and current object = = If the sight is ok, check alertness and angle to see if they notice = = returns true if the player has been spoted = ================ */ #define MINSIGHT 0x18000l boolean CheckSight (objtype *ob) { long deltax,deltay; // // don't bother tracing a line if the area isn't connected to the player's // if (!areabyplayer[ob->areanumber]) return false; // // if the player is real close, sight is automatic // deltax = player->x - ob->x; deltay = player->y - ob->y; if (deltax > -MINSIGHT && deltax < MINSIGHT && deltay > -MINSIGHT && deltay < MINSIGHT) return true; // // see if they are looking in the right direction // switch (ob->dir) { case north: if (deltay > 0) return false; break; case east: if (deltax < 0) return false; break; case south: if (deltay < 0) return false; break; case west: if (deltax > 0) return false; break; // check diagonal moving guards fix case northwest: if (deltay > -deltax) return false; break; case northeast: if (deltay > deltax) return false; break; case southwest: if (deltax > deltay) return false; break; case southeast: if (-deltax > deltay) return false; break; } // // trace a line to check for blocking tiles (corners) // return CheckLine (ob); } /* =============== = = FirstSighting = = Puts an actor into attack mode and possibly reverses the direction = if the player is behind it = =============== */ void FirstSighting (objtype *ob) { // // react to the player // switch (ob->obclass) { case guardobj: PlaySoundLocActor(HALTSND,ob); NewState (ob,&s_grdchase1); ob->speed *= 3; // go faster when chasing player break; case officerobj: PlaySoundLocActor(SPIONSND,ob); NewState (ob,&s_ofcchase1); ob->speed *= 5; // go faster when chasing player break; case mutantobj: NewState (ob,&s_mutchase1); ob->speed *= 3; // go faster when chasing player break; case ssobj: PlaySoundLocActor(SCHUTZADSND,ob); NewState (ob,&s_sschase1); ob->speed *= 4; // go faster when chasing player break; case dogobj: PlaySoundLocActor(DOGBARKSND,ob); NewState (ob,&s_dogchase1); ob->speed *= 2; // go faster when chasing player break; #ifndef SPEAR case bossobj: SD_PlaySound(GUTENTAGSND); NewState (ob,&s_bosschase1); ob->speed = SPDPATROL*3; // go faster when chasing player break; case gretelobj: SD_PlaySound(KEINSND); NewState (ob,&s_gretelchase1); ob->speed *= 3; // go faster when chasing player break; case giftobj: SD_PlaySound(EINESND); NewState (ob,&s_giftchase1); ob->speed *= 3; // go faster when chasing player break; case fatobj: SD_PlaySound(ERLAUBENSND); NewState (ob,&s_fatchase1); ob->speed *= 3; // go faster when chasing player break; case schabbobj: SD_PlaySound(SCHABBSHASND); NewState (ob,&s_schabbchase1); ob->speed *= 3; // go faster when chasing player break; case fakeobj: SD_PlaySound(TOT_HUNDSND); NewState (ob,&s_fakechase1); ob->speed *= 3; // go faster when chasing player break; case mechahitlerobj: SD_PlaySound(DIESND); NewState (ob,&s_mechachase1); ob->speed *= 3; // go faster when chasing player break; case realhitlerobj: SD_PlaySound(DIESND); NewState (ob,&s_hitlerchase1); ob->speed *= 5; // go faster when chasing player break; case ghostobj: NewState (ob,&s_blinkychase1); ob->speed *= 2; // go faster when chasing player break; #else case spectreobj: SD_PlaySound(GHOSTSIGHTSND); NewState (ob,&s_spectrechase1); ob->speed = 800; // go faster when chasing player break; case angelobj: SD_PlaySound(ANGELSIGHTSND); NewState (ob,&s_angelchase1); ob->speed = 1536; // go faster when chasing player break; case transobj: SD_PlaySound(TRANSSIGHTSND); NewState (ob,&s_transchase1); ob->speed = 1536; // go faster when chasing player break; case uberobj: NewState (ob,&s_uberchase1); ob->speed = 3000; // go faster when chasing player break; case willobj: SD_PlaySound(WILHELMSIGHTSND); NewState (ob,&s_willchase1); ob->speed = 2048; // go faster when chasing player break; case deathobj: SD_PlaySound(KNIGHTSIGHTSND); NewState (ob,&s_deathchase1); ob->speed = 2048; // go faster when chasing player break; #endif } if (ob->distance < 0) ob->distance = 0; // ignore the door opening command ob->flags |= FL_ATTACKMODE|FL_FIRSTATTACK; } /* =============== = = SightPlayer = = Called by actors that ARE NOT chasing the player. If the player = is detected (by sight, noise, or proximity), the actor is put into = it's combat frame and true is returned. = = Incorporates a random reaction delay = =============== */ boolean SightPlayer (objtype *ob) { if (ob->flags & FL_ATTACKMODE) Quit ("An actor in ATTACKMODE called SightPlayer!"); if (ob->temp2) { // // count down reaction time // ob->temp2 -= (short) tics; if (ob->temp2 > 0) return false; ob->temp2 = 0; // time to react } else { if (!areabyplayer[ob->areanumber]) return false; if (ob->flags & FL_AMBUSH) { if (!CheckSight (ob)) return false; ob->flags &= ~FL_AMBUSH; } else { if (!madenoise && !CheckSight (ob)) return false; } switch (ob->obclass) { case guardobj: ob->temp2 = 1+US_RndT()/4; break; case officerobj: ob->temp2 = 2; break; case mutantobj: ob->temp2 = 1+US_RndT()/6; break; case ssobj: ob->temp2 = 1+US_RndT()/6; break; case dogobj: ob->temp2 = 1+US_RndT()/8; break; case bossobj: case schabbobj: case fakeobj: case mechahitlerobj: case realhitlerobj: case gretelobj: case giftobj: case fatobj: case spectreobj: case angelobj: case transobj: case uberobj: case willobj: case deathobj: ob->temp2 = 1; break; } return false; } FirstSighting (ob); return true; }
28.339726
101
0.357284
TobiasKarnat
8d2bd7d6a9dfa98cf123dc64d71bb01ca37b79d1
26,078
cpp
C++
editor/gui/src/renderersettingsdialog.cpp
lizardkinger/blacksun
0119948726d2a057c13d208044c7664a8348a1ea
[ "Linux-OpenIB" ]
null
null
null
editor/gui/src/renderersettingsdialog.cpp
lizardkinger/blacksun
0119948726d2a057c13d208044c7664a8348a1ea
[ "Linux-OpenIB" ]
null
null
null
editor/gui/src/renderersettingsdialog.cpp
lizardkinger/blacksun
0119948726d2a057c13d208044c7664a8348a1ea
[ "Linux-OpenIB" ]
null
null
null
/*************************************************************************** * Copyright (C) 2006 by The Hunter * * hunter@localhost * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #include "./../include/renderersettingsdialog.h" namespace BSGui { RendererSettingsDialog::RendererSettingsDialog() { ui.setupUi(this); renderer = BSRenderer::Renderer::getInstance(); rendererSettings = renderer->getSettings(); setColors(); setNumbers(); setCheckboxses(); connect(ui.saveColorButton, SIGNAL(clicked()), this, SLOT(saveColorButtonClicked())); connect(ui.loadColorButton, SIGNAL(clicked()), this, SLOT(loadColorButtonClicked())); connect(ui.resetColorsButton, SIGNAL(clicked()), this, SLOT(resetColorsButtonClicked())); connect(ui.lineColorLabel, SIGNAL(colorChanged(QColor)), this, SLOT(optionsChanged())); connect(ui.lineSelectedColorLabel, SIGNAL(colorChanged(QColor)), this, SLOT(optionsChanged())); connect(ui.pointColorLabel, SIGNAL(colorChanged(QColor)), this, SLOT(optionsChanged())); connect(ui.pointSelectedColorLabel, SIGNAL(colorChanged(QColor)), this, SLOT(optionsChanged())); connect(ui.freezeColorLabel, SIGNAL(colorChanged(QColor)), this, SLOT(optionsChanged())); connect(ui.normalColorLabel, SIGNAL(colorChanged(QColor)), this, SLOT(optionsChanged())); connect(ui.selectionAABBColorLabel, SIGNAL(colorChanged(QColor)), this, SLOT(optionsChanged())); connect(ui.orthogonalViewColorLabel, SIGNAL(colorChanged(QColor)), this, SLOT(optionsChanged())); connect(ui.perspectiveViewColorLabel, SIGNAL(colorChanged(QColor)), this, SLOT(optionsChanged())); connect(ui.majorGridLineColorLabel, SIGNAL(colorChanged(QColor)), this, SLOT(optionsChanged())); connect(ui.minorGridLineColorLabel, SIGNAL(colorChanged(QColor)), this, SLOT(optionsChanged())); connect(ui.rubberBandColorLabel, SIGNAL(colorChanged(QColor)), this, SLOT(optionsChanged())); connect(ui.overpaintingColorLabel, SIGNAL(colorChanged(QColor)), this, SLOT(optionsChanged())); connect(ui.gridSize, SIGNAL(valueChanged(int)), this, SLOT(optionsChanged())); connect(ui.lineWidth, SIGNAL(valueChanged(double)), this, SLOT(optionsChanged())); connect(ui.pointSize, SIGNAL(valueChanged(double)), this, SLOT(optionsChanged())); connect(ui.normalScaling, SIGNAL(valueChanged(double)), this, SLOT(optionsChanged())); connect(ui.selectionAABBScaling, SIGNAL(valueChanged(double)), this, SLOT(optionsChanged())); connect(ui.wireframeOverlayScaling, SIGNAL(valueChanged(double)), this, SLOT(optionsChanged())); connect(ui.cameraFOV, SIGNAL(valueChanged(double)), this, SLOT(optionsChanged())); connect(ui.nearPlane, SIGNAL(valueChanged(double)), this, SLOT(optionsChanged())); connect(ui.farPlane, SIGNAL(valueChanged(double)), this, SLOT(optionsChanged())); connect(ui.mouseWheelSpeed, SIGNAL(valueChanged(double)), this, SLOT(optionsChanged())); connect(ui.cullingCheckBox, SIGNAL(stateChanged(int)), this, SLOT(optionsChanged())); connect(ui.lineSmoothingCheckBox, SIGNAL(stateChanged(int)), this, SLOT(optionsChanged())); connect(ui.pointSmoothingCheckBox, SIGNAL(stateChanged(int)), this, SLOT(optionsChanged())); connect(ui.polygonSmoothingCheckBox, SIGNAL(stateChanged(int)), this, SLOT(optionsChanged())); } void RendererSettingsDialog::optionsChanged() { emit statusChanged(checkOptionsChanged()); } void RendererSettingsDialog::dialogAccept() { writeColors(); writeNumbers(); writeCheckboxses(); emit statusChanged(false); } void RendererSettingsDialog::reset() { setColors(); setNumbers(); setCheckboxses(); } void RendererSettingsDialog::setColors() { Color wireframeColor = rendererSettings->getWireframeColor(); ui.lineColorLabel->setColor(ColorToQColor(wireframeColor)); Color wireframeSelectionColor = rendererSettings->getWireframeSelectionColor(); ui.lineSelectedColorLabel->setColor(ColorToQColor(wireframeSelectionColor)); Color pointColor = rendererSettings->getPointColor(); ui.pointColorLabel->setColor(ColorToQColor(pointColor)); Color selectedPointsColor = rendererSettings->getPointSelectionColor(); ui.pointSelectedColorLabel->setColor(ColorToQColor(selectedPointsColor)); Color freezedColor = rendererSettings->getFreezeColor(); ui.freezeColorLabel->setColor(ColorToQColor(freezedColor)); Color normalColor = rendererSettings->getNormalColor(); ui.normalColorLabel->setColor(ColorToQColor(normalColor)); Color selectionAABBColor = rendererSettings->getSelectionAABBColor(); ui.selectionAABBColorLabel->setColor(ColorToQColor(selectionAABBColor)); Color colorOrtho = rendererSettings->getClearColorOrtho(); ui.orthogonalViewColorLabel->setColor(ColorToQColor(colorOrtho)); Color colorPerspective = rendererSettings->getClearColorPerspective(); ui.perspectiveViewColorLabel->setColor(ColorToQColor(colorPerspective)); Color majorLineColor = rendererSettings->getGridMajorLineColor(); ui.majorGridLineColorLabel->setColor(ColorToQColor(majorLineColor)); Color minorLineColor = rendererSettings->getGridMinorLineColor(); ui.minorGridLineColorLabel->setColor(ColorToQColor(minorLineColor)); ui.rubberBandColorLabel->setColor(MainWindow::getInstance()->getContainer()->getSelectionBoxColor()); ui.overpaintingColorLabel->setColor(MainWindow::getInstance()->getContainer()->getOverpaintingColor()); } void RendererSettingsDialog::writeColors() { QColor wireframeColor = ui.lineColorLabel->getColor(); rendererSettings->setWireframeColor(QColorToColor(wireframeColor)); QColor wireframeSelectionColor = ui.lineSelectedColorLabel->getColor(); rendererSettings->setWireframeSelectionColor(QColorToColor(wireframeSelectionColor)); QColor pointColor = ui.pointColorLabel->getColor(); rendererSettings->setPointColor(QColorToColor(pointColor)); QColor selectedPointsColor = ui.pointSelectedColorLabel->getColor(); rendererSettings->setPointSelectionColor(QColorToColor(selectedPointsColor)); QColor freezedColor = ui.freezeColorLabel->getColor(); rendererSettings->setFreezeColor(QColorToColor(freezedColor)); QColor normalColor = ui.normalColorLabel->getColor(); rendererSettings->setNormalColor(QColorToColor(normalColor)); QColor selectionAABBColor = ui.selectionAABBColorLabel->getColor(); rendererSettings->setSelectionAABBColor(QColorToColor(selectionAABBColor)); QColor colorOrtho = ui.orthogonalViewColorLabel->getColor(); rendererSettings->setClearColorOrtho(QColorToColor(colorOrtho)); QColor colorPerspective = ui.perspectiveViewColorLabel->getColor(); rendererSettings->setClearColorPerspective(QColorToColor(colorPerspective)); QColor majorLineColor = ui.majorGridLineColorLabel->getColor(); rendererSettings->setGridMajorLineColor(QColorToColor(majorLineColor)); QColor minorLineColor = ui.minorGridLineColorLabel->getColor(); rendererSettings->setGridMinorLineColor(QColorToColor(minorLineColor)); MainWindow::getInstance()->getContainer()->setSelectionBoxColor(ui.rubberBandColorLabel->getColor()); MainWindow::getInstance()->getContainer()->setOverpaintingColor(ui.overpaintingColorLabel->getColor()); } void RendererSettingsDialog::setNumbers() { int gridSize = rendererSettings->getGridSize(); ui.gridSize->setValue(gridSize); double lineWidth = rendererSettings->getLineWidth(); ui.lineWidth->setValue(lineWidth); double pointSize = rendererSettings->getPointSize(); ui.pointSize->setValue(pointSize); double normalScaling = rendererSettings->getNormalScaling(); ui.normalScaling->setValue(normalScaling); double selectionAABBScaling = rendererSettings->getSelectionAABBScaling(); ui.selectionAABBScaling->setValue(selectionAABBScaling); double wireframeOverlayScaling = rendererSettings->getWireframeOverlayScaling(); ui.wireframeOverlayScaling->setValue(wireframeOverlayScaling); double FOV = rendererSettings->getFOV(); ui.cameraFOV->setValue(FOV); double nearPlane = rendererSettings->getNearPlane(); ui.nearPlane->setValue(nearPlane); double farPlane = rendererSettings->getFarPlane(); ui.farPlane->setValue(farPlane); double mouseWheelSpeed = rendererSettings->getMouseWheelSpeed(); ui.mouseWheelSpeed->setValue(mouseWheelSpeed); } void RendererSettingsDialog::writeNumbers() { int gridSize = ui.gridSize->value(); rendererSettings->setGridSize(gridSize); double lineWidth = ui.lineWidth->value(); rendererSettings->setLineWidth(lineWidth); double pointSize = ui.pointSize->value(); rendererSettings->setPointSize(pointSize); double normalScaling = ui.normalScaling->value(); rendererSettings->setNormalScaling(normalScaling); double selectionAABBScaling = ui.selectionAABBScaling->value(); rendererSettings->setSelectionAABBScaling(selectionAABBScaling); double wireframeOverlayScaling = ui.wireframeOverlayScaling->value(); rendererSettings->setWireframeOverlayScaling(wireframeOverlayScaling); double FOV = ui.cameraFOV->value(); rendererSettings->setFOV(FOV); double nearPlane = ui.nearPlane->value(); rendererSettings->setNearPlane(nearPlane); double farPlane = ui.farPlane->value(); rendererSettings->setFarPlane(farPlane); double mouseWheelSpeed = ui.mouseWheelSpeed->value(); rendererSettings->setMouseWheelSpeed(mouseWheelSpeed); } void RendererSettingsDialog::saveColorButtonClicked() { QFileDialog* fileDialog = new QFileDialog(this, "Please select the destination", QDir::currentPath(), "Blacksun Color Schemes (*.bsscheme)"); fileDialog->setDefaultSuffix("bsscheme"); fileDialog->setFileMode(QFileDialog::AnyFile); fileDialog->setAcceptMode(QFileDialog::AcceptSave); QString pathToFile = ""; if (fileDialog->exec()) { QStringList pathToFiles; pathToFiles = fileDialog->selectedFiles(); if (!pathToFiles.isEmpty()) { pathToFile = pathToFiles.at(0); } } if (pathToFile == "") { return; } QFile file(pathToFile); if(!file.open(QIODevice::WriteOnly | QIODevice::Text)) { QMessageBox::critical(this, "Error", "Unable to open file"); return; } QTextStream outputStream(&file); outputStream << getColorScheme(); } void RendererSettingsDialog::loadColorButtonClicked() { QString pathToFile = QFileDialog::getOpenFileName(this, "Please select the Scheme File", QDir::currentPath(), "Blacksun Color Schemes (*.bsscheme)"); if (pathToFile == "") { return; } QFile file(pathToFile); if(!file.open(QIODevice::ReadOnly | QIODevice::Text)) { QMessageBox::critical(this, "Error", "Unable to open file"); return; } QString colorScheme; while (!file.atEnd()) { colorScheme.append(file.readLine()); } if(!setColorScheme(colorScheme)) { QMessageBox::critical(this, "Error", "File is not a valid Blacksun Scheme file"); } } void RendererSettingsDialog::setCheckboxses() { ui.cullingCheckBox->setChecked(rendererSettings->getEnableFrustumCulling()); ui.lineSmoothingCheckBox->setChecked(rendererSettings->getLineSmoothing()); ui.pointSmoothingCheckBox->setChecked(rendererSettings->getPointSmoothing()); ui.polygonSmoothingCheckBox->setChecked(rendererSettings->getPolygonSmoothing()); } void RendererSettingsDialog::writeCheckboxses() { rendererSettings->enableFrustumCulling(ui.cullingCheckBox->isChecked()); rendererSettings->setLineSmoothing(ui.lineSmoothingCheckBox->isChecked()); rendererSettings->setPointSmoothing(ui.pointSmoothingCheckBox->isChecked()); rendererSettings->setPolygonSmoothing(ui.polygonSmoothingCheckBox->isChecked()); } QString RendererSettingsDialog::getColorScheme() { QDomDocument scheme("BSColorScheme"); QDomElement root = scheme.createElement("ColorScheme"); scheme.appendChild(root); QDomElement wireframeColor = scheme.createElement("wireframeColor"); wireframeColor.setAttribute("Red", ui.lineColorLabel->getColor().redF()); wireframeColor.setAttribute("Green", ui.lineColorLabel->getColor().greenF()); wireframeColor.setAttribute("Blue", ui.lineColorLabel->getColor().blueF()); root.appendChild(wireframeColor); QDomElement wireframeSelectionColor = scheme.createElement("wireframeSelectionColor"); wireframeSelectionColor.setAttribute("Red", ui.lineSelectedColorLabel->getColor().redF()); wireframeSelectionColor.setAttribute("Green", ui.lineSelectedColorLabel->getColor().greenF()); wireframeSelectionColor.setAttribute("Blue", ui.lineSelectedColorLabel->getColor().blueF()); root.appendChild(wireframeSelectionColor); QDomElement pointColor = scheme.createElement("pointColor"); pointColor.setAttribute("Red", ui.pointColorLabel->getColor().redF()); pointColor.setAttribute("Green", ui.pointColorLabel->getColor().greenF()); pointColor.setAttribute("Blue", ui.pointColorLabel->getColor().blueF()); root.appendChild(pointColor); QDomElement selectedPointsColor = scheme.createElement("selectedPointsColor"); selectedPointsColor.setAttribute("Red", ui.pointSelectedColorLabel->getColor().redF()); selectedPointsColor.setAttribute("Green", ui.pointSelectedColorLabel->getColor().greenF()); selectedPointsColor.setAttribute("Blue", ui.pointSelectedColorLabel->getColor().blueF()); root.appendChild(selectedPointsColor); QDomElement freezedColor = scheme.createElement("freezedColor"); freezedColor.setAttribute("Red", ui.freezeColorLabel->getColor().redF()); freezedColor.setAttribute("Green", ui.freezeColorLabel->getColor().greenF()); freezedColor.setAttribute("Blue", ui.freezeColorLabel->getColor().blueF()); root.appendChild(freezedColor); QDomElement normalColor = scheme.createElement("normalColor"); normalColor.setAttribute("Red", ui.normalColorLabel->getColor().redF()); normalColor.setAttribute("Green", ui.normalColorLabel->getColor().greenF()); normalColor.setAttribute("Blue", ui.normalColorLabel->getColor().blueF()); root.appendChild(normalColor); QDomElement selectionAABBColor = scheme.createElement("selectionAABBColor"); selectionAABBColor.setAttribute("Red", ui.selectionAABBColorLabel->getColor().redF()); selectionAABBColor.setAttribute("Green", ui.selectionAABBColorLabel->getColor().greenF()); selectionAABBColor.setAttribute("Blue", ui.selectionAABBColorLabel->getColor().blueF()); root.appendChild(selectionAABBColor); QDomElement colorOrtho = scheme.createElement("colorOrtho"); colorOrtho.setAttribute("Red", ui.orthogonalViewColorLabel->getColor().redF()); colorOrtho.setAttribute("Green", ui.orthogonalViewColorLabel->getColor().greenF()); colorOrtho.setAttribute("Blue", ui.orthogonalViewColorLabel->getColor().blueF()); root.appendChild(colorOrtho); QDomElement colorPerspective = scheme.createElement("colorPerspective"); colorPerspective.setAttribute("Red", ui.perspectiveViewColorLabel->getColor().redF()); colorPerspective.setAttribute("Green", ui.perspectiveViewColorLabel->getColor().greenF()); colorPerspective.setAttribute("Blue", ui.perspectiveViewColorLabel->getColor().blueF()); root.appendChild(colorPerspective); QDomElement majorLineColor = scheme.createElement("majorLineColor"); majorLineColor.setAttribute("Red", ui.majorGridLineColorLabel->getColor().redF()); majorLineColor.setAttribute("Green", ui.majorGridLineColorLabel->getColor().greenF()); majorLineColor.setAttribute("Blue", ui.majorGridLineColorLabel->getColor().blueF()); root.appendChild(majorLineColor); QDomElement minorLineColor = scheme.createElement("minorLineColor"); minorLineColor.setAttribute("Red", ui.minorGridLineColorLabel->getColor().redF()); minorLineColor.setAttribute("Green", ui.minorGridLineColorLabel->getColor().greenF()); minorLineColor.setAttribute("Blue", ui.minorGridLineColorLabel->getColor().blueF()); root.appendChild(minorLineColor); QDomElement rubberBandColor = scheme.createElement("rubberBandColor"); rubberBandColor.setAttribute("Red", ui.rubberBandColorLabel->getColor().redF()); rubberBandColor.setAttribute("Green", ui.rubberBandColorLabel->getColor().greenF()); rubberBandColor.setAttribute("Blue", ui.rubberBandColorLabel->getColor().blueF()); root.appendChild(rubberBandColor); QDomElement overpaintingColor = scheme.createElement("overpaintingColor"); overpaintingColor.setAttribute("Red", ui.overpaintingColorLabel->getColor().redF()); overpaintingColor.setAttribute("Green", ui.overpaintingColorLabel->getColor().greenF()); overpaintingColor.setAttribute("Blue", ui.overpaintingColorLabel->getColor().blueF()); root.appendChild(overpaintingColor); return scheme.toString(); } bool RendererSettingsDialog::setColorScheme(const QString& colorScheme) { QDomDocument scheme("BSColorScheme"); scheme.setContent(colorScheme); QDomElement root = scheme.documentElement(); if ( root.tagName() != "ColorScheme") { return false; } QDomNode currentNode = root.firstChild(); while(!currentNode.isNull()) { QDomElement currentElement = currentNode.toElement(); { if(!currentElement.isNull()) { QString currentTagName = currentElement.tagName(); if(currentTagName == "wireframeColor") { ui.lineColorLabel->setColor(colorFromElement(currentElement)); } else if(currentTagName == "wireframeSelectionColor") { ui.lineSelectedColorLabel->setColor(colorFromElement(currentElement)); } else if(currentTagName == "pointColor") { ui.pointColorLabel->setColor(colorFromElement(currentElement)); } else if(currentTagName == "selectedPointsColor") { ui.pointSelectedColorLabel->setColor(colorFromElement(currentElement)); } else if(currentTagName == "freezedColor") { ui.freezeColorLabel->setColor(colorFromElement(currentElement)); } else if(currentTagName == "normalColor") { ui.normalColorLabel->setColor(colorFromElement(currentElement)); } else if(currentTagName == "selectionAABBColor") { ui.selectionAABBColorLabel->setColor(colorFromElement(currentElement)); } else if(currentTagName == "colorOrtho") { ui.orthogonalViewColorLabel->setColor(colorFromElement(currentElement)); } else if(currentTagName == "colorPerspective") { ui.perspectiveViewColorLabel->setColor(colorFromElement(currentElement)); } else if(currentTagName == "majorLineColor") { ui.majorGridLineColorLabel->setColor(colorFromElement(currentElement)); } else if(currentTagName == "minorLineColor") { ui.minorGridLineColorLabel->setColor(colorFromElement(currentElement)); } else if(currentTagName == "rubberBandColor") { ui.rubberBandColorLabel->setColor(colorFromElement(currentElement)); } else if(currentTagName == "overpaintingColor") { ui.overpaintingColorLabel->setColor(colorFromElement(currentElement)); } } } currentNode = currentNode.nextSibling(); } return true; } bool RendererSettingsDialog::checkOptionsChanged() { if( ui.lineColorLabel->getColor() == ColorToQColor(rendererSettings->getWireframeColor()) && ui.lineSelectedColorLabel->getColor() == ColorToQColor(rendererSettings->getWireframeSelectionColor()) && ui.pointColorLabel->getColor() == ColorToQColor(rendererSettings->getPointColor()) && ui.pointSelectedColorLabel->getColor() == ColorToQColor(rendererSettings->getPointSelectionColor()) && ui.freezeColorLabel->getColor() == ColorToQColor(rendererSettings->getFreezeColor()) && ui.normalColorLabel->getColor() == ColorToQColor(rendererSettings->getNormalColor()) && ui.selectionAABBColorLabel->getColor() == ColorToQColor(rendererSettings->getSelectionAABBColor()) && ui.orthogonalViewColorLabel->getColor() == ColorToQColor(rendererSettings->getClearColorOrtho()) && ui.perspectiveViewColorLabel->getColor() == ColorToQColor(rendererSettings->getClearColorPerspective()) && ui.majorGridLineColorLabel->getColor() == ColorToQColor(rendererSettings->getGridMajorLineColor()) && ui.minorGridLineColorLabel->getColor() == ColorToQColor(rendererSettings->getGridMinorLineColor()) && ui.rubberBandColorLabel->getColor() == MainWindow::getInstance()->getContainer()->getSelectionBoxColor() && ui.overpaintingColorLabel->getColor() == MainWindow::getInstance()->getContainer()->getOverpaintingColor() && ui.gridSize->value() == rendererSettings->getGridSize() && ui.lineWidth->value() == rendererSettings->getLineWidth() && ui.pointSize->value() == rendererSettings->getPointSize() && ui.normalScaling->value() == rendererSettings->getNormalScaling() && ui.selectionAABBScaling->value() == rendererSettings->getSelectionAABBScaling() && ui.wireframeOverlayScaling->value() == rendererSettings->getWireframeOverlayScaling() && ui.cameraFOV->value() == rendererSettings->getFOV() && ui.nearPlane->value() == rendererSettings->getNearPlane() && ui.farPlane->value() == rendererSettings->getFarPlane() && ui.mouseWheelSpeed->value() == rendererSettings->getMouseWheelSpeed() && ui.cullingCheckBox->isChecked() == rendererSettings->getEnableFrustumCulling() && ui.lineSmoothingCheckBox->isChecked() == rendererSettings->getLineSmoothing() && ui.pointSmoothingCheckBox->isChecked() == rendererSettings->getPointSmoothing() && ui.polygonSmoothingCheckBox->isChecked() == rendererSettings->getPolygonSmoothing() ) { return false; } else { return true; } } void RendererSettingsDialog::resetColorsButtonClicked() { QString stdColor = ""; stdColor.append("<!DOCTYPE BSColorScheme>"); stdColor.append("<ColorScheme>"); stdColor.append("<wireframeColor Blue=\"1\" Red=\"1\" Green=\"1\" />"); stdColor.append("<wireframeSelectionColor Blue=\"0\" Red=\"1\" Green=\"0\" />"); stdColor.append("<pointColor Blue=\"0\" Red=\"1\" Green=\"1\" />"); stdColor.append("<selectedPointsColor Blue=\"0\" Red=\"1\" Green=\"0.5000076295109483\" />"); stdColor.append("<freezedColor Blue=\"1\" Red=\"0.5499961852445259\" Green=\"0.6\" />"); stdColor.append("<normalColor Blue=\"1\" Red=\"1\" Green=\"0\" />"); stdColor.append("<selectionAABBColor Blue=\"0\" Red=\"0\" Green=\"1\" />"); stdColor.append("<colorOrtho Blue=\"0.8\" Red=\"0.8\" Green=\"0.8\" />"); stdColor.append("<colorPerspective Blue=\"0.6999923704890516\" Red=\"0.2\" Green=\"0.5000076295109483\" />"); stdColor.append("<majorLineColor Blue=\"0\" Red=\"0.5000076295109483\" Green=\"0.5000076295109483\" />"); stdColor.append("<minorLineColor Blue=\"0.6999923704890516\" Red=\"0.6999923704890516\" Green=\"0.6999923704890516\" />"); stdColor.append("<rubberBandColor Blue=\"1.0\" Red=\"0\" Green=\"0\" />"); stdColor.append("<overpaintingColor Blue=\"0\" Red=\"0\" Green=\"0\" />"); stdColor.append("</ColorScheme>"); setColorScheme(stdColor); } QColor RendererSettingsDialog::colorFromElement(QDomElement e) { qreal red = e.attribute("Red").toDouble(); qreal green = e.attribute("Green").toDouble(); qreal blue = e.attribute("Blue").toDouble(); return QColor::fromRgbF(red, green, blue); } }
44.884682
153
0.685904
lizardkinger
8d2d7a1a6f9488a109c822e7b22271da217db9a9
1,621
cc
C++
src/exceptions.cc
websms-com/websmscom-cpp
a9214bd7dcc02c0e058a345e353d7417597f77c9
[ "MIT" ]
null
null
null
src/exceptions.cc
websms-com/websmscom-cpp
a9214bd7dcc02c0e058a345e353d7417597f77c9
[ "MIT" ]
null
null
null
src/exceptions.cc
websms-com/websmscom-cpp
a9214bd7dcc02c0e058a345e353d7417597f77c9
[ "MIT" ]
null
null
null
/** * Copyright (C) 2012, sms.at mobile internet services gmbh * * @author Markus Opitz */ #include <websms/exceptions.h> #include <websms/misc.h> namespace websms { Exception::Exception(const char* message) : message_(Strdup(message)), error_code_(0) { } Exception::Exception(const char* message, int error_code) : message_(Strdup(message)), error_code_(error_code) { } Exception::Exception(const Exception& source) : message_(Strdup(source.message_)), error_code_(source.error_code_) { } Exception::~Exception() { Strdel(message_); } Exception& Exception::operator=(const Exception& source) { Strdel(message_); message_ = Strdup(source.message_); error_code_ = source.error_code_; return *this; } const char* Exception::What() const { return message_; } int Exception::error_code() const { return error_code_; } const char* Exception::message() const { return message_; } ApiException::ApiException(const char* status_message, int status_code) : Exception(status_message, status_code) { } int ApiException::status_code() const { return error_code(); } const char* ApiException::status_message() const { return message(); } AuthorizationFailedException::AuthorizationFailedException(const char* message) : Exception(message) { } HttpConnectionException::HttpConnectionException(const char* message, int error_code) : Exception(message, error_code) { } ParameterValidationException::ParameterValidationException(const char* message) : Exception(message) { } } /* namespace websms */
21.051948
79
0.70512
websms-com
8d2f0cb539e2222afc2dc16dd34a35133ded3e76
787
cpp
C++
Core/Driver/vf_drv_clr/vf_task_clr.cpp
sartrey/vapula
557dff9cf526eee6fe5b787f25c80a972c1451de
[ "Apache-2.0" ]
1
2019-04-17T14:45:49.000Z
2019-04-17T14:45:49.000Z
Core/Driver/vf_drv_clr/vf_task_clr.cpp
sartrey/vapula
557dff9cf526eee6fe5b787f25c80a972c1451de
[ "Apache-2.0" ]
null
null
null
Core/Driver/vf_drv_clr/vf_task_clr.cpp
sartrey/vapula
557dff9cf526eee6fe5b787f25c80a972c1451de
[ "Apache-2.0" ]
null
null
null
#include "vf_driver_clr.h" #include "vf_task_clr.h" #include "vf_library_clr.h" #include "vf_stack.h" TaskCLR::TaskCLR() { _Method = null; } TaskCLR::~TaskCLR() { } pcstr TaskCLR::GetHandle() { LibraryCLR* library = (LibraryCLR*)_Method->GetLibrary(); return library->GetHandle(); } bool TaskCLR::Bind(Method* method) { Task::Bind(method); _Method = method; return true; } void TaskCLR::OnProcess() { string args = GetHandle(); args += "|"; args += _Method->GetProcessSym(); DriverCLR* driver = DriverCLR::Instance(); driver->CallBridge("OnProcess", args.c_str()); } void TaskCLR::OnRollback() { string args = GetHandle(); args += "|"; args += _Method->GetRollbackSym(); DriverCLR* driver = DriverCLR::Instance(); driver->CallBridge("OnRollback", args.c_str()); }
17.108696
58
0.682338
sartrey
8d311bb4e267e2cbd7a1ea5b1468dbe911461477
769
hpp
C++
src/strings.hpp
Schumbi/flaschengeist
ffed5c2a858d77dd2216d2a124c2a0c5a089a924
[ "MIT" ]
null
null
null
src/strings.hpp
Schumbi/flaschengeist
ffed5c2a858d77dd2216d2a124c2a0c5a089a924
[ "MIT" ]
null
null
null
src/strings.hpp
Schumbi/flaschengeist
ffed5c2a858d77dd2216d2a124c2a0c5a089a924
[ "MIT" ]
null
null
null
#ifndef MAKELIGHT_STRINGS_H #define MAKELIGHT_STRINGS_H #include <Arduino.h> // ab in PROGMEM damit Todo String Response = ""; String html_anfang = "<!DOCTYPE html>\r\n<html>\r\n\ <head>\r\n<meta content=\"text/html; charset=ISO-8859-1\" http-equiv=\"content-type\">\r\n\ <title>WebSchalter</title>\r\n<body><p>"; String html_ende = "</p></body>\r\n</html>"; String redirect = "<!DOCTYPE html>\r\n<html>\r\n\ <head>\r\n\ <meta content=\"text/html; charset=ISO-8859-1\" \ <meta http-equiv=\"refresh\" content=\"0; URL='./'\" /> \ </head><body/></html>"; String form = "<form action='led'><input type='radio' name='state' value='1' checked>On<input type='radio' name='state' value='0'>Off<input type='submit' value='Submit'></form>"; #endif // MAKELIGHT_STRINGS_H
32.041667
178
0.668401
Schumbi
8d3399c2d26b87db717db62c90aa725594602351
777
cpp
C++
src/Credentials.cpp
lalten/aws4_auth
ba6231ed5ab512be2e33f0611b5c97b8aa27d54c
[ "MIT" ]
null
null
null
src/Credentials.cpp
lalten/aws4_auth
ba6231ed5ab512be2e33f0611b5c97b8aa27d54c
[ "MIT" ]
null
null
null
src/Credentials.cpp
lalten/aws4_auth
ba6231ed5ab512be2e33f0611b5c97b8aa27d54c
[ "MIT" ]
null
null
null
#include "Aws4Auth/Credentials.h" #include <etl/string_view.h> #include "Sha256.h" namespace Aws4Auth { Sha256::hash_str_t Credentials::sign(const etl::string_view &date_iso8601, const etl::string_view &string_to_sign) const { etl::string<44> secret_key{"AWS4"}; secret_key.append(secret_access_key_.begin(), secret_access_key_.end()); etl::string_view date_yyyymmdd{date_iso8601.begin(), 8}; Sha256::hash_t key_date = Hmac{date_yyyymmdd, secret_key}; Sha256::hash_t key_region = Hmac{aws_region_, key_date}; Sha256::hash_t key_service = Hmac{aws_service_, key_region}; Sha256::hash_t key_signing = Hmac{etl::make_string("aws4_request"), key_service}; return Hmac{string_to_sign, key_signing}; } } // namespace Aws4Auth
38.85
84
0.72973
lalten
8d357f429f5d10a3e4f308aa03cc86aa1f67d764
4,125
cpp
C++
wpilibcExamples/src/main/cpp/examples/MecanumControllerCommand/cpp/subsystems/DriveSubsystem.cpp
gcjurgiel/allwpilib
99f3a64dff0eba07be9b2e6c53753aafa0c852d8
[ "BSD-3-Clause" ]
1
2021-04-07T01:51:18.000Z
2021-04-07T01:51:18.000Z
wpilibcExamples/src/main/cpp/examples/MecanumControllerCommand/cpp/subsystems/DriveSubsystem.cpp
gcjurgiel/allwpilib
99f3a64dff0eba07be9b2e6c53753aafa0c852d8
[ "BSD-3-Clause" ]
null
null
null
wpilibcExamples/src/main/cpp/examples/MecanumControllerCommand/cpp/subsystems/DriveSubsystem.cpp
gcjurgiel/allwpilib
99f3a64dff0eba07be9b2e6c53753aafa0c852d8
[ "BSD-3-Clause" ]
1
2022-02-16T16:13:24.000Z
2022-02-16T16:13:24.000Z
// Copyright (c) FIRST and other WPILib contributors. // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. #include "subsystems/DriveSubsystem.h" #include <units/angle.h> #include <units/velocity.h> #include <units/voltage.h> #include "Constants.h" using namespace DriveConstants; DriveSubsystem::DriveSubsystem() : m_frontLeft{kFrontLeftMotorPort}, m_rearLeft{kRearLeftMotorPort}, m_frontRight{kFrontRightMotorPort}, m_rearRight{kRearRightMotorPort}, m_frontLeftEncoder{kFrontLeftEncoderPorts[0], kFrontLeftEncoderPorts[1], kFrontLeftEncoderReversed}, m_rearLeftEncoder{kRearLeftEncoderPorts[0], kRearLeftEncoderPorts[1], kRearLeftEncoderReversed}, m_frontRightEncoder{kFrontRightEncoderPorts[0], kFrontRightEncoderPorts[1], kFrontRightEncoderReversed}, m_rearRightEncoder{kRearRightEncoderPorts[0], kRearRightEncoderPorts[1], kRearRightEncoderReversed}, m_odometry{kDriveKinematics, m_gyro.GetRotation2d(), frc::Pose2d()} { // Set the distance per pulse for the encoders m_frontLeftEncoder.SetDistancePerPulse(kEncoderDistancePerPulse); m_rearLeftEncoder.SetDistancePerPulse(kEncoderDistancePerPulse); m_frontRightEncoder.SetDistancePerPulse(kEncoderDistancePerPulse); m_rearRightEncoder.SetDistancePerPulse(kEncoderDistancePerPulse); } void DriveSubsystem::Periodic() { // Implementation of subsystem periodic method goes here. m_odometry.Update( m_gyro.GetRotation2d(), frc::MecanumDriveWheelSpeeds{ units::meters_per_second_t(m_frontLeftEncoder.GetRate()), units::meters_per_second_t(m_rearLeftEncoder.GetRate()), units::meters_per_second_t(m_frontRightEncoder.GetRate()), units::meters_per_second_t(m_rearRightEncoder.GetRate())}); } void DriveSubsystem::Drive(double xSpeed, double ySpeed, double rot, bool fieldRelative) { if (fieldRelative) { m_drive.DriveCartesian(ySpeed, xSpeed, rot, -m_gyro.GetAngle()); } else { m_drive.DriveCartesian(ySpeed, xSpeed, rot); } } void DriveSubsystem::SetSpeedControllersVolts(units::volt_t frontLeftPower, units::volt_t rearLeftPower, units::volt_t frontRightPower, units::volt_t rearRightPower) { m_frontLeft.SetVoltage(frontLeftPower); m_rearLeft.SetVoltage(rearLeftPower); m_frontRight.SetVoltage(frontRightPower); m_rearRight.SetVoltage(rearRightPower); } void DriveSubsystem::ResetEncoders() { m_frontLeftEncoder.Reset(); m_rearLeftEncoder.Reset(); m_frontRightEncoder.Reset(); m_rearRightEncoder.Reset(); } frc::Encoder& DriveSubsystem::GetFrontLeftEncoder() { return m_frontLeftEncoder; } frc::Encoder& DriveSubsystem::GetRearLeftEncoder() { return m_rearLeftEncoder; } frc::Encoder& DriveSubsystem::GetFrontRightEncoder() { return m_frontRightEncoder; } frc::Encoder& DriveSubsystem::GetRearRightEncoder() { return m_rearRightEncoder; } frc::MecanumDriveWheelSpeeds DriveSubsystem::getCurrentWheelSpeeds() { return (frc::MecanumDriveWheelSpeeds{ units::meters_per_second_t(m_frontLeftEncoder.GetRate()), units::meters_per_second_t(m_rearLeftEncoder.GetRate()), units::meters_per_second_t(m_frontRightEncoder.GetRate()), units::meters_per_second_t(m_rearRightEncoder.GetRate())}); } void DriveSubsystem::SetMaxOutput(double maxOutput) { m_drive.SetMaxOutput(maxOutput); } units::degree_t DriveSubsystem::GetHeading() const { return m_gyro.GetRotation2d().Degrees(); } void DriveSubsystem::ZeroHeading() { m_gyro.Reset(); } double DriveSubsystem::GetTurnRate() { return -m_gyro.GetRate(); } frc::Pose2d DriveSubsystem::GetPose() { return m_odometry.GetPose(); } void DriveSubsystem::ResetOdometry(frc::Pose2d pose) { m_odometry.ResetPosition(pose, m_gyro.GetRotation2d()); }
33.536585
78
0.721455
gcjurgiel
8d3708e500f2bf0f134fd1b9dac83abf5b42093e
1,831
hpp
C++
jobin/worker.hpp
Marcos30004347/jobin
40eec7bf9579002426320253eae6eaaea6b50d10
[ "Apache-2.0" ]
2
2020-09-30T05:12:09.000Z
2020-10-12T23:40:32.000Z
jobin/worker.hpp
Marcos30004347/Jobin
40eec7bf9579002426320253eae6eaaea6b50d10
[ "Apache-2.0" ]
null
null
null
jobin/worker.hpp
Marcos30004347/Jobin
40eec7bf9579002426320253eae6eaaea6b50d10
[ "Apache-2.0" ]
null
null
null
#ifndef JOBIN_WORKER_H #define JOBIN_WORKER_H #include "job.hpp" #include "thread.hpp" class worker; thread_local static worker* current_worker = nullptr; class worker { friend void return_to_worker(); private: /** * handler of the worker. */ void(*handler)(void*); /** * voidless pointer to pass as argument to handler. */ void* arg = nullptr; /** * _thread of execution of this worker. */ thread* _thread = nullptr; /** * flag that signal if workers can stop pooling jobs. */ static bool should_pool; /** * number of currently running workers. */ static atomic<unsigned int> running_workers; /** * worker id. */ unsigned int id = 0; /** * Main routine of the worker, this function is responsable for * pooling and executing jobs. */ static void do_work(void *data); /** * Routine responsable for setting up a worker for * the do_work method. */ static void init_worker(void *data); public: /** * worker contructor. * @param handler: worker initial job; * @param arg: initial argument. */ worker(void(*handler)(void*), void* arg); /** * worker contructor. * @note: this contrutor dont dispatch any initial job. */ worker(); /** * wait for current worker to return. */ void wait(); /** * worker destructor. */ ~worker(); /** * Convert current thread to a worker. */ static void convert_thread_to_worker(void(*handler)(void*), void* arg); class all_workers { public: /** * Let all workers end current executing jobs and exit */ static void done(); static void begin(); }; }; #endif
17.776699
75
0.572911
Marcos30004347
8d39d3a50cf21b640e310dc9cfb7d49ead41b4d4
38,613
cpp
C++
src/math_implementation_1.cpp
tmilev/calculator
e39280f23975241985393651fe7a52db5c7fd1d5
[ "Apache-2.0" ]
7
2017-07-12T11:15:54.000Z
2021-10-29T18:33:33.000Z
src/math_implementation_1.cpp
tmilev/calculator
e39280f23975241985393651fe7a52db5c7fd1d5
[ "Apache-2.0" ]
18
2017-05-16T03:48:45.000Z
2022-03-16T19:51:26.000Z
src/math_implementation_1.cpp
tmilev/calculator
e39280f23975241985393651fe7a52db5c7fd1d5
[ "Apache-2.0" ]
1
2018-08-02T09:05:08.000Z
2018-08-02T09:05:08.000Z
// The current file is licensed under the license terms found in the main header file "calculator.h". // For additional information refer to the file "calculator.h". #include "math_extra_finite_groups_implementation.h" #include "general_lists.h" #include "math_general.h" #include "math_extra_universal_enveloping.h" #include "math_rational_function_implementation.h" void SemisimpleLieAlgebra::getChevalleyGeneratorAsLieBracketsSimpleGenerators( int generatorIndex, List<int>& outputIndicesFormatAd0Ad1Ad2etc, Rational& outputMultiplyLieBracketsToGetGenerator ) { MacroRegisterFunctionWithName("SemisimpleLieAlgebra::getChevalleyGeneratorAsLieBracketsSimpleGenerators"); outputIndicesFormatAd0Ad1Ad2etc.size = 0; if (this->isGeneratorFromCartan(generatorIndex)) { int simpleIndex = generatorIndex - this->getNumberOfPositiveRoots(); outputIndicesFormatAd0Ad1Ad2etc.addOnTop(generatorIndex + this->getRank()); outputIndicesFormatAd0Ad1Ad2etc.addOnTop(2 * this->getNumberOfPositiveRoots() - 1 - generatorIndex); outputMultiplyLieBracketsToGetGenerator = this->weylGroup.cartanSymmetric.elements[simpleIndex][simpleIndex] / 2; return; } Vector<Rational> weight = this->getWeightOfGenerator(generatorIndex); outputMultiplyLieBracketsToGetGenerator = 1; Vector<Rational> genWeight, newWeight; while (!weight.isEqualToZero()) { for (int i = 0; i < this->getRank(); i ++) { genWeight.makeEi(this->getRank(), i); if (weight.isPositive()) { genWeight.negate(); } newWeight = weight + genWeight; if (newWeight.isEqualToZero() || this->weylGroup.isARoot(newWeight)) { weight = newWeight; int index = this->getGeneratorIndexFromRoot(- genWeight); outputIndicesFormatAd0Ad1Ad2etc.addOnTop(index); if (!weight.isEqualToZero()) { int currentIndex = this->weylGroup.rootSystem.getIndex(weight); index = this->getRootIndexFromGenerator(index); if (!this->computedChevalleyConstants.elements[index][currentIndex]) { global.fatal << "For some reason I am not computed. Here is me: " << this->toString() << global.fatal; } outputMultiplyLieBracketsToGetGenerator /= this->chevalleyConstants.elements[index][currentIndex]; } break; } } } } bool PartialFractions::argumentsAllowed( Vectors<Rational>& arguments, std::string& outputWhatWentWrong ) { if (arguments.size < 1) { return false; } Cone tempCone; bool result = tempCone.createFromVertices(arguments); if (tempCone.isEntireSpace()) { outputWhatWentWrong = "Error: the vectors you gave as input span the entire space."; return false; } for (int i = 0; i < tempCone.vertices.size; i ++) { if (tempCone.isInCone(tempCone.vertices[i]) && tempCone.isInCone(- tempCone.vertices[i])) { std::stringstream out; out << "Error: the Q_{>0} span of vectors you gave as input contains zero (as it contains the vector " << tempCone.vertices[i].toString() << " as well as its opposite vector " << (- tempCone.vertices[i]).toString() << "), hence the vector partition function is " << "can only take values infinity or zero. "; outputWhatWentWrong = out.str(); return false; } } return result; } void Lattice::intersectWithLineGivenBy(Vector<Rational>& inputLine, Vector<Rational>& outputGenerator) { Vectors<Rational> roots; roots.addOnTop(inputLine); this->intersectWithLinearSubspaceSpannedBy(roots); if (this->basisRationalForm.numberOfRows > 1) { global.fatal << "This should not be possible. " << global.fatal; } if (this->basisRationalForm.numberOfRows == 0) { outputGenerator.makeZero(inputLine.size); } else { this->basisRationalForm.getVectorFromRow(0, outputGenerator); } } void LittelmannPath::actByEFDisplayIndex(int displayIndex) { if (this->owner == nullptr) { global.fatal << "LS path without initialized owner is begin acted upon. " << global.fatal; } if (displayIndex > 0) { this->actByEAlpha(displayIndex - 1); } else { this->actByFAlpha(- displayIndex - 1); } } void LittelmannPath::actByEAlpha(int indexAlpha) { if (this->owner == nullptr) { global.fatal << "LS path without initialized owner is begin acted upon. " << global.fatal; } if (indexAlpha < 0 || indexAlpha >= this->owner->getDimension()) { global.fatal << "Index of Littelmann root operator out of range. " << global.fatal; } if (this->waypoints.size == 0) { return; } Rational minimalScalarProduct = 0; int indexMinimalScalarProduct = - 1; if (this->owner == nullptr) { global.fatal << "zero owner not allowed here. " << global.fatal; } WeylGroupData& weylGroup = *this->owner; weylGroup.computeRho(true); Vector<Rational>& alpha = weylGroup.rootsOfBorel[indexAlpha]; Rational lengthAlpha = weylGroup.rootScalarCartanRoot(alpha, alpha); Vector<Rational> alphaScaled = alpha * 2 / lengthAlpha; for (int i = 0; i < this->waypoints.size; i ++) { Rational scalarProduct = this->owner->rootScalarCartanRoot(this->waypoints[i], alphaScaled); if (scalarProduct <= minimalScalarProduct) { minimalScalarProduct = scalarProduct; indexMinimalScalarProduct = i; } } if (indexMinimalScalarProduct <= 0 || minimalScalarProduct > - 1) { this->waypoints.size = 0; return; } int precedingIndex = 0; for (int i = 0; i <= indexMinimalScalarProduct; i ++) { Rational tempScalar = weylGroup.rootScalarCartanRoot(this->waypoints[i], alphaScaled); if (tempScalar >= minimalScalarProduct + 1) { precedingIndex = i; } if (tempScalar < minimalScalarProduct + 1) { break; } } Rational s2 = this->owner->rootScalarCartanRoot(this->waypoints[precedingIndex], alphaScaled); if (!this->minimaAreIntegral()) { global.comments << "<br>Something is wrong: starting path is BAD!"; } if (s2 > minimalScalarProduct + 1) { this->waypoints.setSize(this->waypoints.size + 1); for (int i = this->waypoints.size - 1; i >= precedingIndex + 2; i --) { this->waypoints[i] = this->waypoints[i - 1]; } precedingIndex ++; indexMinimalScalarProduct ++; Vector<Rational>& r1 = this->waypoints[precedingIndex]; Vector<Rational>& r2 = this->waypoints[precedingIndex - 1]; Rational s1 = weylGroup.rootScalarCartanRoot(r1, alphaScaled); Rational x = (minimalScalarProduct + 1 - s2) / (s1 - s2); this->waypoints[precedingIndex] = (r1 - r2) * x + r2; } Vectors<Rational> differences; differences.setSize(indexMinimalScalarProduct-precedingIndex); Rational currentDist = 0; Rational minDist = 0; for (int i = 0; i < differences.size; i ++) { differences[i] = this->waypoints[i + precedingIndex + 1] - this->waypoints[i + precedingIndex]; currentDist += weylGroup.rootScalarCartanRoot(differences[i], alphaScaled); if (currentDist < minDist) { weylGroup.reflectSimple(indexAlpha, differences[i]); minDist = currentDist; } } for (int i = 0; i < differences.size; i ++) { this->waypoints[i + precedingIndex + 1] = this->waypoints[i + precedingIndex] + differences[i]; } for (int i = indexMinimalScalarProduct + 1; i < this->waypoints.size; i ++) { this->waypoints[i] += alpha; } this->simplify(); } void LittelmannPath::actByFAlpha(int indexAlpha) { if (this->waypoints.size == 0) { return; } if (this->owner == nullptr) { global.fatal << "LS path without initialized owner is begin acted upon. " << global.fatal; } if (indexAlpha < 0 || indexAlpha >= this->owner->getDimension()) { global.fatal << "Index of Littelmann root operator out of range. " << global.fatal; } Rational minimalScalarProduct = 0; int indexMinimalScalarProduct = - 1; WeylGroupData& weylGroup = *this->owner; Vector<Rational>& alpha = weylGroup.rootsOfBorel[indexAlpha]; Rational LengthAlpha = this->owner->rootScalarCartanRoot(alpha, alpha); Vector<Rational> alphaScaled = alpha * 2 / LengthAlpha; for (int i = 0; i < this->waypoints.size; i ++) { Rational scalarProduct = this->owner->rootScalarCartanRoot(this->waypoints[i], alphaScaled); if (scalarProduct <= minimalScalarProduct) { minimalScalarProduct = scalarProduct; indexMinimalScalarProduct = i; } } Rational lastScalar = this->owner->rootScalarCartanRoot(*this->waypoints.lastObject(), alphaScaled); if (indexMinimalScalarProduct < 0 || lastScalar - minimalScalarProduct < 1) { this->waypoints.size = 0; return; } int succeedingIndex = 0; for (int i = this->waypoints.size - 1; i >= indexMinimalScalarProduct; i --) { Rational tempScalar = weylGroup.rootScalarCartanRoot(alphaScaled, this->waypoints[i]); if (tempScalar >= minimalScalarProduct + 1) { succeedingIndex = i; } if (tempScalar < minimalScalarProduct + 1) { break; } } Rational s1 = this->owner->rootScalarCartanRoot(this->waypoints[succeedingIndex], alphaScaled); if (s1 > minimalScalarProduct + 1) { this->waypoints.setSize(this->waypoints.size + 1); for (int i = this->waypoints.size - 1; i >= succeedingIndex + 1; i --) { this->waypoints[i] = this->waypoints[i - 1]; } //Rational scalarNext = weylGroup.rootScalarCartanRoot(this->waypoints[succeedingIndex], alphaScaled); Vector<Rational>& r1 = this->waypoints[succeedingIndex]; Vector<Rational>& r2 = this->waypoints[succeedingIndex - 1]; Rational s2 = weylGroup.rootScalarCartanRoot(r2, alphaScaled); Rational x = (minimalScalarProduct + 1 - s2) / (s1 - s2); this->waypoints[succeedingIndex] = (r1 - r2) * x + r2; } Vector<Rational> diff, oldWayPoint; oldWayPoint = this->waypoints[indexMinimalScalarProduct]; Rational currentDist = 0; for (int i = 0; i < succeedingIndex - indexMinimalScalarProduct; i ++) { diff = this->waypoints[i + indexMinimalScalarProduct + 1] - oldWayPoint; currentDist += weylGroup.rootScalarCartanRoot(diff, alphaScaled); if (currentDist > 0) { weylGroup.reflectSimple(indexAlpha, diff); currentDist = 0; } oldWayPoint = this->waypoints[i + indexMinimalScalarProduct + 1]; this->waypoints[i + indexMinimalScalarProduct + 1] = this->waypoints[i + indexMinimalScalarProduct] + diff; } for (int i = succeedingIndex + 1; i < this->waypoints.size; i ++) { this->waypoints[i] -= alpha; } this->simplify(); } void LittelmannPath::simplify() { if (this->waypoints.size == 0) { return; } Vector<Rational> d1, d2; Rational d11, d12, d22; int leftIndex = 0; int rightIndex = 2; while (rightIndex < this->waypoints.size) { Vector<Rational>& left = this->waypoints[leftIndex]; Vector<Rational>& middle = this->waypoints[rightIndex - 1]; Vector<Rational>& right = this->waypoints[rightIndex]; d1 = left - middle; d2 = right - middle; d11 = d1.scalarEuclidean(d1); d12 = d1.scalarEuclidean(d2); d22 = d2.scalarEuclidean(d2); bool isBad = ((d11 * d22 - d12 * d12).isEqualToZero() && (d12 <= 0)); if (!isBad) { leftIndex ++; this->waypoints[leftIndex] = middle; } rightIndex ++; } leftIndex ++; this->waypoints[leftIndex] = *this->waypoints.lastObject(); this->waypoints.setSize(leftIndex + 1); } bool LittelmannPath::minimaAreIntegral() { if (this->waypoints.size == 0) { return true; } List<Rational> minima; WeylGroupData& weyl = *this->owner; int dimension = weyl.getDimension(); minima.setSize(dimension); for (int i = 0; i < dimension; i ++) { minima[i] = weyl.getScalarProductSimpleRoot(this->waypoints[0], i) * 2 / weyl.cartanSymmetric.elements[i][i]; } for (int i = 1; i < this->waypoints.size; i ++) { for (int j = 0; j < dimension; j ++) { minima[j] = MathRoutines::minimum(weyl.getScalarProductSimpleRoot( this->waypoints[i], j) * 2 / weyl.cartanSymmetric.elements[j][j], minima[j] ); } } for (int i = 0; i < dimension; i ++) { if (!minima[i].isSmallInteger()) { return false; } } return true; } void LittelmannPath::makeFromWeightInSimpleCoords( const Vector<Rational>& weightInSimpleCoords, WeylGroupData& inputOwner ) { this->owner = &inputOwner; this->waypoints.setSize(2); this->waypoints[0].makeZero(inputOwner.getDimension()); this->waypoints[1] = weightInSimpleCoords; this->simplify(); } std::string LittelmannPath::toStringIndicesToCalculatorOutput(LittelmannPath& inputStartingPath, List<int>& input) { std::stringstream out; for (int i = input.size - 1; i >= 0; i --) { int displayIndex = input[i]; if (displayIndex >= 0) { displayIndex ++; } out << "eAlpha(" << displayIndex << ", "; } out << "littelmann" << inputStartingPath.owner->getFundamentalCoordinatesFromSimple(*inputStartingPath.waypoints.lastObject()).toString(); for (int i = 0; i < input.size; i ++) { out << " ) "; } return out.str(); } bool LittelmannPath::generateOrbit( List<LittelmannPath>& output, List<List<int> >& outputOperators, int UpperBoundNumElts, Selection* parabolicNonSelectedAreInLeviPart ) { HashedList<LittelmannPath> hashedOutput; hashedOutput.addOnTop(*this); int dimension = this->owner->getDimension(); outputOperators.setSize(1); outputOperators[0].setSize(0); List<int> currentSequence; if (UpperBoundNumElts > 0) { currentSequence.reserve(UpperBoundNumElts); } LittelmannPath currentPath; bool result = true; Selection parabolicSelectionSelectedAreInLeviPart; parabolicSelectionSelectedAreInLeviPart.initialize(dimension); if (parabolicNonSelectedAreInLeviPart != nullptr) { parabolicSelectionSelectedAreInLeviPart = *parabolicNonSelectedAreInLeviPart; parabolicSelectionSelectedAreInLeviPart.invertSelection(); } else { parabolicSelectionSelectedAreInLeviPart.makeFullSelection(); } for (int lowestNonExplored = 0; lowestNonExplored < hashedOutput.size; lowestNonExplored ++) { if (UpperBoundNumElts > 0 && UpperBoundNumElts < hashedOutput.size) { result = false; break; } else { for (int j = 0; j < parabolicSelectionSelectedAreInLeviPart.cardinalitySelection; j ++) { bool found = true; currentPath = hashedOutput[lowestNonExplored]; currentSequence = outputOperators[lowestNonExplored]; int index = parabolicSelectionSelectedAreInLeviPart.elements[j]; while (found) { found = false; currentPath.actByEAlpha(index); if (!currentPath.isEqualToZero()) { if (hashedOutput.addOnTopNoRepetition(currentPath)) { found = true; currentSequence.addOnTop(index); outputOperators.addOnTop(currentSequence); if (!currentPath.minimaAreIntegral()) { global.comments << "<hr>Found a bad path:<br> "; global.comments << " = " << currentPath.toString(); } } } } found = true; currentPath = hashedOutput[lowestNonExplored]; currentSequence = outputOperators[lowestNonExplored]; while (found) { found = false; currentPath.actByFAlpha(index); if (!currentPath.isEqualToZero()) { if (hashedOutput.addOnTopNoRepetition(currentPath)) { found = true; currentSequence.addOnTop(- index - 1); outputOperators.addOnTop(currentSequence); if (!currentPath.minimaAreIntegral()) { global.comments << "<hr>Found a bad path:<br> "; global.comments << " = " << currentPath.toString(); } } } } } } } output = hashedOutput; return result; } std::string LittelmannPath:: toStringOperatorSequenceStartingOnMe(List<int>& input) { MonomialTensor<Rational> tempMon; tempMon = input; tempMon.generatorsIndices.reverseElements(); tempMon.powers.reverseElements(); return tempMon.toString(); } template <class Coefficient> bool MonomialUniversalEnvelopingOrdered<Coefficient>::modOutFDRelationsExperimental( const Vector<Rational>& highestWeightSimpleCoordinates, const Coefficient& ringUnit, const Coefficient& ringZero ) { WeylGroupData& weyl = this->owner->ownerSemisimpleLieAlgebra->weylGroup; Vector<Rational> highestWeightSimpleCoordinatesTrue = highestWeightSimpleCoordinates; weyl.raiseToDominantWeight(highestWeightSimpleCoordinatesTrue); Vector<Rational> highestWeightDualCoordinates = weyl.getDualCoordinatesFromFundamental( weyl.getFundamentalCoordinatesFromSimple(highestWeightSimpleCoordinatesTrue) ); List<Coefficient> substitution; substitution.setSize(highestWeightDualCoordinates.size); for (int i = 0; i < highestWeightDualCoordinates.size; i ++) { substitution[i] = highestWeightDualCoordinates[i]; } this->modOutVermaRelations(&substitution, ringUnit, ringZero); int numberOfPositiveRoots = this->owner->ownerSemisimpleLieAlgebra->getNumberOfPositiveRoots(); Vector<Rational> currentWeight = highestWeightSimpleCoordinatesTrue; Vector<Rational> testWeight; for (int k = this->generatorsIndices.size - 1; k >= 0; k --) { int indexCurrentGenerator = this->generatorsIndices[k]; if (indexCurrentGenerator >= numberOfPositiveRoots) { return false; } ElementSemisimpleLieAlgebra<Rational>& currentElt = this->owner->elementOrder[indexCurrentGenerator]; if (!currentElt.getCartanPart().isEqualToZero() || currentElt.size() > 1) { return false; } int power = 0; if (!this->powers[k].isSmallInteger(power)) { return false; } int rootIndex = this->owner->ownerSemisimpleLieAlgebra->getRootIndexFromGenerator(currentElt[0].generatorIndex); const Vector<Rational>& currentRoot = weyl.rootSystem[rootIndex]; for (int j = 0; j < power; j ++) { currentWeight += currentRoot; testWeight = currentWeight; weyl.raiseToDominantWeight(testWeight); if (!(highestWeightSimpleCoordinatesTrue - testWeight).isPositiveOrZero()) { this->makeZero(ringZero, *this->owner); return true; } } } return true; } template <class Coefficient> bool ElementUniversalEnvelopingOrdered<Coefficient>::modOutFDRelationsExperimental( const Vector<Rational>& highestWeightSimpleCoordinates, const Coefficient& ringUnit, const Coefficient& ringZero ) { MonomialUniversalEnvelopingOrdered<Coefficient> tempMon; ElementUniversalEnvelopingOrdered<Coefficient> output; output.makeZero(*this->owner); bool result = true; for (int i = 0; i < this->size; i ++) { tempMon = this->objects[i]; if (!tempMon.modOutFDRelationsExperimental(highestWeightSimpleCoordinates, ringUnit, ringZero)) { result = false; } output.addMonomial(tempMon); } this->operator=(output); return result; } template <class Coefficient> bool ElementUniversalEnveloping<Coefficient>::getCoordinatesInBasis( List<ElementUniversalEnveloping<Coefficient> >& basis, Vector<Coefficient>& output, const Coefficient& ringUnit, const Coefficient& ringZero ) const { List<ElementUniversalEnveloping<Coefficient> > tempBasis, elements; tempBasis = basis; tempBasis.addOnTop(*this); Vectors<Coefficient> tempCoords; if (!this->getBasisFromSpanOfElements(tempBasis, tempCoords, elements, ringUnit, ringZero)) { return false; } Vector<Coefficient> root; root = *tempCoords.lastObject(); tempCoords.setSize(basis.size); return root.getCoordinatesInBasis(tempCoords, output); } template<class Coefficient> template<class CoefficientTypeQuotientField> bool ElementUniversalEnveloping<Coefficient>::getBasisFromSpanOfElements( List<ElementUniversalEnveloping<Coefficient> >& elements, Vectors<CoefficientTypeQuotientField>& outputCoords, List<ElementUniversalEnveloping<Coefficient> >& outputBasis, const CoefficientTypeQuotientField& fieldUnit, const CoefficientTypeQuotientField& fieldZero ) { if (elements.size == 0) { return false; } ElementUniversalEnveloping<Coefficient> outputCorrespondingMonomials; outputCorrespondingMonomials.makeZero(*elements[0].owner); Vectors<CoefficientTypeQuotientField> outputCoordsBeforeReduction; for (int i = 0; i < elements.size; i ++) { for (int j = 0; j < elements[i].size; j ++) { outputCorrespondingMonomials.addOnTopNoRepetition(elements[i][j]); } } outputCoordsBeforeReduction.setSize(elements.size); for (int i = 0; i < elements.size; i ++) { Vector<CoefficientTypeQuotientField>& currentList = outputCoordsBeforeReduction[i]; currentList.makeZero(outputCorrespondingMonomials.size); ElementUniversalEnveloping<Coefficient>& currentElt = elements[i]; for (int j = 0; j < currentElt.size; j ++) { MonomialUniversalEnveloping<Coefficient>& currentMon = currentElt[j]; currentList[outputCorrespondingMonomials.getIndex(currentMon)] = currentMon.coefficient; } } outputBasis.size = 0; outputBasis.reserve(elements.size); Vectors<CoefficientTypeQuotientField> basisCoordForm; basisCoordForm.reserve(elements.size); Selection selectedBasis; outputCoordsBeforeReduction.SelectABasis(basisCoordForm, fieldZero, selectedBasis); for (int i = 0; i < selectedBasis.cardinalitySelection; i ++) { outputBasis.addOnTop(elements.objects[selectedBasis.elements[i]]); } Matrix<Coefficient> bufferMat; Vectors<Coefficient> bufferVectors; outputCoordsBeforeReduction.getCoordinatesInBasis( basisCoordForm, outputCoords, bufferVectors, bufferMat, fieldUnit, fieldZero ); return true; } template<class Coefficient> void ElementUniversalEnveloping<Coefficient>::modToMinDegreeFormFDRels( const Vector<Rational>& highestWeightInSimpleCoordinates, const Coefficient& ringUnit, const Coefficient& ringZero ) { ElementUniversalEnveloping<Coefficient> result; result.makeZero(*this->owner); bool Found = true; int numPosRoots = this->owner->getNumberOfPositiveRoots(); while (Found) { Found = false; for (int j = numPosRoots - 1; j >= 0; j --) { this->owner->universalEnvelopingGeneratorOrder.swapTwoIndices(j, numPosRoots - 1); this->simplify(ringUnit); this->owner->universalEnvelopingGeneratorOrder.swapTwoIndices(j, numPosRoots - 1); if (this->modOutFDRelationsExperimental(highestWeightInSimpleCoordinates, ringUnit, ringZero)) { Found = true; } } } this->simplify(ringUnit); } template<class Coefficient> bool ElementUniversalEnveloping<Coefficient>::applyMinusTransposeAutoOnMe() { MonomialUniversalEnveloping<Coefficient> tempMon; ElementUniversalEnveloping<Coefficient> result; result.makeZero(*this->owner); int numPosRoots = this->getOwner().getNumberOfPositiveRoots(); int rank = this->getOwner().getRank(); Coefficient coefficient; for (int i = 0; i < this->size; i ++) { MonomialUniversalEnveloping<Coefficient>& currentMon = this->objects[i]; coefficient = this->coefficients[i]; tempMon.owner = currentMon.owner; tempMon.powers.size = 0; tempMon.generatorsIndices.size = 0; for (int j = 0; j < currentMon.powers.size; j ++) { int power; if (!currentMon.powers[j].isSmallInteger(&power)) { return false; } int generator = currentMon.generatorsIndices[j]; if (generator < numPosRoots) { generator = 2 * numPosRoots + rank - 1 - generator; } else if (generator >= numPosRoots + rank) { generator = - generator + 2 * numPosRoots + rank - 1; } tempMon.multiplyByGeneratorPowerOnTheRight(generator, currentMon.powers[j]); if (power % 2 == 1) { coefficient *= - 1; } } result.addMonomial(tempMon, coefficient); } *this = result; return true; } template <class Coefficient> bool ElementUniversalEnveloping<Coefficient>::highestWeightMTAbilinearForm( const ElementUniversalEnveloping<Coefficient>& right, Coefficient& output, const Vector<Coefficient>* substitutionHiGoesToIthElement, const Coefficient& ringUnit, const Coefficient& ringZero, std::stringstream* logStream ) { output = ringZero; ElementUniversalEnveloping<Coefficient> MTright; MTright = right; if (!MTright.applyMinusTransposeAutoOnMe()) { return false; } ElementUniversalEnveloping<Coefficient> Accum, intermediateAccum, element; Accum.makeZero(*this->owners, this->indexInOwners); MonomialUniversalEnveloping<Coefficient> constMon; constMon.makeConstant(); if (logStream != nullptr) { *logStream << "backtraced elt: " << MTright.toString(&global.defaultFormat.getElement()) << "<br>"; *logStream << "this element: " << this->toString(&global.defaultFormat.getElement()) << "<br>"; } for (int j = 0; j < right.size; j ++) { intermediateAccum = *this; intermediateAccum.simplify(global, ringUnit, ringZero); if (logStream != nullptr) { *logStream << "intermediate after simplification: " << intermediateAccum.toString(&global.defaultFormat.getElement()) << "<br>"; } intermediateAccum.modOutVermaRelations(&global, substitutionHiGoesToIthElement, ringUnit, ringZero); MonomialUniversalEnveloping<Coefficient>& rightMon = MTright[j]; Coefficient& rightMonCoeff = MTright.coefficients[j]; int power; for (int i = rightMon.powers.size - 1; i >= 0; i --) { if (rightMon.powers[i].isSmallInteger(&power)) { for (int k = 0; k < power; k ++) { element.makeOneGenerator(rightMon.generatorsIndices[i], *this->owners, this->indexInOwners, ringUnit); MathRoutines::swap(element, intermediateAccum); if (logStream != nullptr) { *logStream << "element before mult: " << element.toString(&global.defaultFormat) << "<br>"; *logStream << "intermediate before mult: " << intermediateAccum.toString(&global.defaultFormat.getElement()) << "<br>"; } intermediateAccum *= (element); if (logStream != nullptr) { *logStream << "intermediate before simplification: " << intermediateAccum.toString(&global.defaultFormat.getElement()) << "<br>"; } intermediateAccum.simplify(ringUnit); if (logStream != nullptr) { *logStream << "intermediate after simplification: " << intermediateAccum.toString(&global.defaultFormat.getElement()) << "<br>"; } intermediateAccum.modOutVermaRelations(substitutionHiGoesToIthElement, ringUnit, ringZero); if (logStream != nullptr) { *logStream << "intermediate after Verma rels: " << intermediateAccum.toString(&global.defaultFormat.getElement()) << "<br>"; } } } else { return false; } } intermediateAccum *= rightMonCoeff; Accum += intermediateAccum; int index = intermediateAccum.getIndex(constMon); if (index != - 1) { output += intermediateAccum.coefficients[index]; } } if (logStream != nullptr) { *logStream << "final UE element: " << Accum.toString(&global.defaultFormat.getElement()); } return true; } template <class Coefficient> std::string ElementUniversalEnveloping<Coefficient>::isInProperSubmodule( const Vector<Coefficient>* substitutionHiGoesToIthElement, const Coefficient& ringUnit, const Coefficient& ringZero ) { std::stringstream out; List<ElementUniversalEnveloping<Coefficient> > orbit; orbit.reserve(1000); ElementUniversalEnveloping<Coefficient> element; int dimension = this->getOwner().getRank(); int numPosRoots = this->getOwner().getNumberOfPositiveRoots(); orbit.addOnTop(*this); for (int i = 0; i < orbit.size; i ++) { for (int j = 0; j < dimension; j ++) { element.makeOneGenerator(j + numPosRoots + dimension, *this->owner, ringUnit); element *= orbit[i]; element.simplify(ringUnit); element.modOutVermaRelations(substitutionHiGoesToIthElement, ringUnit, ringZero); if (!element.isEqualToZero()) { orbit.addOnTop(element); } } } for (int i = 0; i < orbit.size; i ++) { ElementUniversalEnveloping<Coefficient>& current = orbit[i]; out << "<br>" << current.toString(&global.defaultFormat.getElement()); } return out.str(); } template <class Coefficient> bool ElementUniversalEnveloping<Coefficient>::convertToRationalCoefficient(ElementUniversalEnveloping<Rational>& output) { output.makeZero(*this->owner); MonomialUniversalEnveloping<Rational> tempMon; Rational coefficient; for (int i = 0; i < this->size; i ++) { MonomialUniversalEnveloping<Coefficient>& currentMon = this->objects[i]; tempMon.makeOne(*this->owner); if (!this->coefficients[i].isConstant(coefficient)) { return false; } for (int j = 0; j < currentMon.powers.size; j ++) { Rational constantPower; if (!currentMon.powers[j].isConstant(constantPower)) { return false; } tempMon.multiplyByGeneratorPowerOnTheRight(currentMon.generatorsIndices[j], constantPower); } output.addMonomial(tempMon, Coefficient(1)); } return true; } void BranchingData::initializePart1NoSubgroups() { MacroRegisterFunctionWithName("BranchingData::initAssumingParSelAndHmmInittedPart1NoSubgroups"); this->weylGroupFiniteDimensionalSmallAsSubgroupInLarge.ambientWeyl = &this->homomorphism.coDomainAlgebra().weylGroup; this->weylGroupFiniteDimensionalSmall.ambientWeyl = &this->homomorphism.domainAlgebra().weylGroup; this->weylGroupFiniteDimensional.ambientWeyl = &this->homomorphism.coDomainAlgebra().weylGroup; this->smallParabolicSelection.initialize(weylGroupFiniteDimensionalSmall.ambientWeyl->getDimension()); for (int i = 0; i < this->homomorphism.imagesCartanDomain.size; i ++) { Vector<Rational>& currentV = this->homomorphism.imagesCartanDomain[i]; this->generatorsSmallSub.addOnTop(currentV); for (int j = 0; j < currentV.size; j ++) { if (!currentV[j].isEqualToZero() && this->inducing.selected[j]) { this->generatorsSmallSub.removeLastObject(); this->smallParabolicSelection.addSelectionAppendNewIndex(i); break; } } } this->nilradicalModuloPreimageNilradical.setSize(0); this->nilradicalSmall.setSize(0); this->nilradicalLarge.setSize(0); this->weightsNilradicalLarge.setSize(0); this->weightsNilradicalSmall.setSize(0); this->weightsNilModPreNil.setSize(0); this->indicesNilradicalLarge.setSize(0); this->indicesNilradicalSmall.setSize(0); ElementSemisimpleLieAlgebra<Rational> element; WeylGroupData& largeWeylGroup = this->homomorphism.coDomainAlgebra().weylGroup; WeylGroupData& smallWeylGroup = this->homomorphism.domainAlgebra().weylGroup; int numB3NegGenerators = this->homomorphism.coDomainAlgebra().getNumberOfPositiveRoots(); int numG2NegGenerators = this->homomorphism.domainAlgebra().getNumberOfPositiveRoots(); for (int i = 0; i < numB3NegGenerators; i ++) { const Vector<Rational>& currentWeight = largeWeylGroup.rootSystem[i]; bool isInNilradical = false; for (int k = 0; k < this->inducing.cardinalitySelection; k ++) { if (!currentWeight[this->inducing.elements[k]].isEqualToZero()) { isInNilradical = true; break; } } if (isInNilradical) { this->weightsNilradicalLarge.addOnTop(currentWeight); element.makeGenerator(i, this->homomorphism.coDomainAlgebra()); this->nilradicalLarge.addOnTop(element); this->indicesNilradicalLarge.addOnTop(i); } } for (int i = 0; i < numG2NegGenerators; i ++) { const Vector<Rational>& currentWeight = smallWeylGroup.rootSystem[i]; bool isInNilradical = false; for (int k = 0; k < this->smallParabolicSelection.cardinalitySelection; k ++) { if (!currentWeight[this->smallParabolicSelection.elements[k]].isEqualToZero()) { isInNilradical = true; break; } } if (isInNilradical) { this->weightsNilradicalSmall.addOnTop(currentWeight); element.makeGenerator(i, this->homomorphism.domainAlgebra()); this->nilradicalSmall.addOnTop(element); this->indicesNilradicalSmall.addOnTop(i); } } this->nilradicalModuloPreimageNilradical = this->nilradicalLarge; this->weightsNilModPreNil = this->weightsNilradicalLarge; Vector<Rational> proj; for (int i = 0; i < this->nilradicalSmall.size; i ++) { ElementSemisimpleLieAlgebra<Rational>& eltImage = this->homomorphism.imagesAllChevalleyGenerators[this->indicesNilradicalSmall[i]]; int index = this->nilradicalModuloPreimageNilradical.getIndex(eltImage); if (index != - 1) { this->nilradicalModuloPreimageNilradical.removeIndexSwapWithLast(index); this->weightsNilModPreNil.removeIndexSwapWithLast(index); continue; } bool isGood = false; for (int j = 0; j < this->weightsNilModPreNil.size; j ++) { proj = this->projectWeight(this->weightsNilModPreNil[j]); if (proj == this->weightsNilradicalSmall[i]) { isGood = true; this->nilradicalModuloPreimageNilradical.removeIndexSwapWithLast(j); this->weightsNilModPreNil.removeIndexSwapWithLast(j); break; } } if (!isGood) { global.fatal << "This is either a programming error, or Lemma 3.3, T. Milev, P. Somberg, \"On branching...\"" << " is wrong. The question is, which is the more desirable case... The bad apple is element " << this->nilradicalSmall[i].toString() << " of weight " << this->weightsNilradicalSmall[i].toString() << ". " << global.fatal; } } } BranchingData::BranchingData() { this->flagUseNilWeightGeneratorOrder = false; this->flagAscendingGeneratorOrder = false; } void BranchingData::initializePart2NoSubgroups() { List<Vectors<Rational> > emptyList; this->weylGroupFiniteDimensionalSmallAsSubgroupInLarge.computeSubGroupFromGeneratingReflections(&this->generatorsSmallSub, &emptyList, 1000, true); this->weylGroupFiniteDimensionalSmall.makeParabolicFromSelectionSimpleRoots( *this->weylGroupFiniteDimensionalSmall.ambientWeyl, this->smallParabolicSelection, 1000 ); this->weylGroupFiniteDimensional.makeParabolicFromSelectionSimpleRoots(this->homomorphism.coDomainAlgebra().weylGroup, this->inducing, 1000); this->weylGroupFiniteDimensional.computeRootSubsystem(); this->weylGroupFiniteDimensionalSmallAsSubgroupInLarge.computeRootSubsystem(); this->weylGroupFiniteDimensionalSmall.computeRootSubsystem(); } std::string BranchingData::getStringCasimirProjector(int index, const Rational& additionalMultiple) { Vector<RationalFraction<Rational> > weightDifference; std::stringstream formulaStream1; HashedList<Vector<RationalFraction<Rational> > > accountedDiffs; accountedDiffs.setExpectedSize(this->g2Weights.size); bool found = false; for (int i = 0; i < this->g2Weights.size; i ++) { weightDifference = this->g2Weights[i] - this->g2Weights[index]; if (weightDifference.isPositive() && !accountedDiffs.contains(weightDifference)) { accountedDiffs.addOnTop(weightDifference); if (additionalMultiple != 1) { formulaStream1 << additionalMultiple.toString(&this->format); } formulaStream1 << "(i(\\bar c) - (" << this->allCharacters[i].toString(&this->format) << "))"; found = true; } } if (!found) { formulaStream1 << "id"; } return formulaStream1.str(); } LittelmannPath::LittelmannPath() { this->owner = nullptr; } LittelmannPath::LittelmannPath(const LittelmannPath& other) { *this = other; } bool LittelmannPath::isAdaptedString(MonomialTensor<int, HashFunctions::hashFunction>& inputString) { LittelmannPath tempPath = *this; LittelmannPath tempPath2; for (int i = 0; i < inputString.generatorsIndices.size; i ++) { for (int k = 0; k < inputString.powers[i]; k ++) { tempPath.actByEAlpha(- inputString.generatorsIndices[i] - 1); } if (tempPath.isEqualToZero()) { return false; } tempPath2 = tempPath; tempPath2.actByEAlpha(- inputString.generatorsIndices[i] - 1); if (!tempPath2.isEqualToZero()) { return false; } } return true; } void SubgroupWeylGroupAutomorphismsGeneratedByRootReflectionsAndAutomorphisms::getGroupElementsIndexedAsAmbientGroup( List<ElementWeylGroup>& output ) { MacroRegisterFunctionWithName("SubgroupWeylGroupAutomorphismsGeneratedByRootReflectionsAndAutomorphisms::getGroupElementsIndexedAsAmbientGroup"); if (this->externalAutomorphisms.size > 0) { global.fatal << "This is a programming error: a function meant for subgroups that are " << "Weyl groups of Levi parts of parabolics " << "is called on a subgroup that is not of that type. " << global.fatal; } output.reserve(this->allElements.size); output.setSize(0); ElementWeylGroup currentOutput; currentOutput.owner = this->ambientWeyl; Vector<int> indexShifts; indexShifts.setSize(this->simpleRootsInner.size); for (int i = 0; i < this->simpleRootsInner.size; i ++) { indexShifts[i] = this->simpleRootsInner[i].getIndexFirstNonZeroCoordinate(); } for (int i = 0; i < this->allElements.size; i ++) { const ElementSubgroupWeylGroupAutomorphismsGeneratedByRootReflectionsAndAutomorphisms& other = this->allElements[i]; currentOutput.generatorsLastAppliedFirst.setSize(other.generatorsLastAppliedFirst.size); for (int j = 0; j < currentOutput.generatorsLastAppliedFirst.size; j ++) { currentOutput.generatorsLastAppliedFirst[j].index = indexShifts[other.generatorsLastAppliedFirst[j].index]; } output.addOnTop(currentOutput); } } std::string LittelmannPath::toString(bool useSimpleCoords, bool useArrows, bool includeDominance) const { if (this->waypoints.size == 0) { return "0"; } std::stringstream out; for (int i = 0; i < this->waypoints.size; i ++) { if (useSimpleCoords) { out << this->waypoints[i].toString(); } else { out << this->owner->getFundamentalCoordinatesFromSimple(this->waypoints[i]).toString(); } if (i != this->waypoints.size - 1) { if (useArrows) { out << "->"; } else { out << ","; } } } if (includeDominance) { out << " "; for (int i = 0; i < this->owner->getDimension(); i ++) { LittelmannPath tempP = *this; tempP.actByEFDisplayIndex(i + 1); if (!tempP.isEqualToZero()) { out << "e_{" << i + 1 << "}"; } tempP = *this; tempP.actByEFDisplayIndex(- i - 1); if (!tempP.isEqualToZero()) { out << "e_{" << - i - 1 << "},"; } } } return out.str(); }
39.889463
149
0.696553
tmilev
8d3a264b07bc6b94d19707d71b211d5012035dac
307
cpp
C++
tuan_5/main.cpp
thuanpham2311/thuc-hanh-nhap-mon-cau-truc-du-lieu
04f73c98895e88b1c36b6cfc48da49cb7cec8cf4
[ "Unlicense" ]
null
null
null
tuan_5/main.cpp
thuanpham2311/thuc-hanh-nhap-mon-cau-truc-du-lieu
04f73c98895e88b1c36b6cfc48da49cb7cec8cf4
[ "Unlicense" ]
1
2021-11-29T04:37:17.000Z
2021-11-29T04:37:17.000Z
tuan_5/main.cpp
thuanpham2311/thuc-hanh-nhap-mon-cau-truc-du-lieu
04f73c98895e88b1c36b6cfc48da49cb7cec8cf4
[ "Unlicense" ]
null
null
null
#include "header.h" int main() { Nodeptr danhSachSinhVien; nhapDanhSachSinhVien(danhSachSinhVien); xuatDanhSachSinhVien(danhSachSinhVien); // xoaDau(danhSachSinhVien); xoaCuoi(danhSachSinhVien); xuatDanhSachSinhVien(danhSachSinhVien); timSinhVienBangMa(danhSachSinhVien, s); return 0; }
19.1875
41
0.775244
thuanpham2311
8d3ada0bf5d5a7d4b134819932b4f0c51972f9f9
564
cpp
C++
orario/main.cpp
Maxelweb/PaO
7c9cb18366ed6a4730519e4275e4719ec9bf0cd2
[ "MIT" ]
1
2020-02-01T10:15:31.000Z
2020-02-01T10:15:31.000Z
orario/main.cpp
Maxelweb/PaO
7c9cb18366ed6a4730519e4275e4719ec9bf0cd2
[ "MIT" ]
null
null
null
orario/main.cpp
Maxelweb/PaO
7c9cb18366ed6a4730519e4275e4719ec9bf0cd2
[ "MIT" ]
null
null
null
#include "orario.h" int main() { orario mezzanotte(12,25,30); cout << "-------- ORA ESATTA --------" << endl; cout << "Ore: " << mezzanotte.Ore() << endl; cout << "Minuti: " << mezzanotte.Minuti() << endl; orario* ptr = new orario(7, 15); cout << "-------- POINTERS --------" << endl; cout << "Sono le " << ptr->Ore() << ":" << ptr->Minuti() << endl; orario adesso(3,10,25); cout << (mezzanotte+adesso).Secondi() << endl; cout << adesso << endl; if(adesso == adesso) cout << '1' << endl; orario test; }
18.8
69
0.487589
Maxelweb
8d3fc7d747c76a2e2388db764fc4bbdf8f8dcc7c
62,446
cpp
C++
src/skel/glfw/glfw.cpp
gameblabla/reeee3
1b6d0f742b1b6fb681756de702ed618e90361139
[ "Unlicense" ]
2
2021-03-24T22:11:27.000Z
2021-05-07T06:51:04.000Z
src/skel/glfw/glfw.cpp
gameblabla/reeee3
1b6d0f742b1b6fb681756de702ed618e90361139
[ "Unlicense" ]
null
null
null
src/skel/glfw/glfw.cpp
gameblabla/reeee3
1b6d0f742b1b6fb681756de702ed618e90361139
[ "Unlicense" ]
null
null
null
#if defined RW_GL3 && !defined LIBRW_SDL2 #ifdef _WIN32 #include <shlobj.h> #include <basetsd.h> #include <mmsystem.h> #include <regstr.h> #include <shellapi.h> #include <windowsx.h> DWORD _dwOperatingSystemVersion; #include "resource.h" #else long _dwOperatingSystemVersion; #ifndef __APPLE__ #include <sys/sysinfo.h> #else #include <mach/mach_host.h> #include <sys/sysctl.h> #endif #include <errno.h> #include <locale.h> #include <signal.h> #include <stddef.h> #endif #include "common.h" #if (defined(_MSC_VER)) #include <tchar.h> #endif /* (defined(_MSC_VER)) */ #include <stdio.h> #include "rwcore.h" #include "skeleton.h" #include "platform.h" #include "crossplatform.h" #include "main.h" #include "FileMgr.h" #include "Text.h" #include "Pad.h" #include "Timer.h" #include "DMAudio.h" #include "ControllerConfig.h" #include "Frontend.h" #include "Game.h" #include "PCSave.h" #include "MemoryCard.h" #include "Sprite2d.h" #include "AnimViewer.h" #include "Font.h" #include "MemoryMgr.h" // We found out that GLFW's keyboard input handling is still pretty delayed/not stable, so now we fetch input from X11 directly on Linux. #if !defined _WIN32 && !defined __APPLE__ && !defined __SWITCH__ // && !defined WAYLAND #define GET_KEYBOARD_INPUT_FROM_X11 #endif #ifdef GET_KEYBOARD_INPUT_FROM_X11 #include <X11/Xlib.h> #include <X11/XKBlib.h> #define GLFW_EXPOSE_NATIVE_X11 #include <GLFW/glfw3native.h> #endif #ifdef _WIN32 #define GLFW_EXPOSE_NATIVE_WIN32 #include <GLFW/glfw3native.h> #endif #define MAX_SUBSYSTEMS (16) rw::EngineOpenParams openParams; static RwBool ForegroundApp = TRUE; static RwBool WindowIconified = FALSE; static RwBool WindowFocused = TRUE; static RwBool RwInitialised = FALSE; static RwSubSystemInfo GsubSysInfo[MAX_SUBSYSTEMS]; static RwInt32 GnumSubSystems = 0; static RwInt32 GcurSel = 0, GcurSelVM = 0; static RwBool useDefault; // What is that for anyway? #ifndef IMPROVED_VIDEOMODE static RwBool defaultFullscreenRes = TRUE; #else static RwBool defaultFullscreenRes = FALSE; static RwInt32 bestWndMode = -1; #endif static psGlobalType PsGlobal; #define PSGLOBAL(var) (((psGlobalType *)(RsGlobal.ps))->var) size_t _dwMemAvailPhys; RwUInt32 gGameState; #ifdef DETECT_JOYSTICK_MENU char gSelectedJoystickName[128] = ""; #endif /* ***************************************************************************** */ void _psCreateFolder(const char *path) { #ifdef _WIN32 HANDLE hfle = CreateFile(path, GENERIC_READ, FILE_SHARE_READ, nil, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS | FILE_ATTRIBUTE_NORMAL, nil); if ( hfle == INVALID_HANDLE_VALUE ) CreateDirectory(path, nil); else CloseHandle(hfle); #else struct stat info; char fullpath[PATH_MAX]; realpath(path, fullpath); if (lstat(fullpath, &info) != 0) { if (errno == ENOENT || (errno != EACCES && !S_ISDIR(info.st_mode))) { mkdir(fullpath, 0755); } } #endif } /* ***************************************************************************** */ const char *_psGetUserFilesFolder() { #if defined USE_MY_DOCUMENTS && defined _WIN32 HKEY hKey = NULL; static CHAR szUserFiles[256]; if ( RegOpenKeyEx(HKEY_CURRENT_USER, REGSTR_PATH_SPECIAL_FOLDERS, REG_OPTION_RESERVED, KEY_READ, &hKey) == ERROR_SUCCESS ) { DWORD KeyType; DWORD KeycbData = sizeof(szUserFiles); if ( RegQueryValueEx(hKey, "Personal", NULL, &KeyType, (LPBYTE)szUserFiles, &KeycbData) == ERROR_SUCCESS ) { RegCloseKey(hKey); strcat(szUserFiles, "\\GTA3 User Files"); _psCreateFolder(szUserFiles); return szUserFiles; } RegCloseKey(hKey); } strcpy(szUserFiles, "data"); return szUserFiles; #else static char szUserFiles[256]; strcpy(szUserFiles, "userfiles"); _psCreateFolder(szUserFiles); return szUserFiles; #endif } /* ***************************************************************************** */ RwBool psCameraBeginUpdate(RwCamera *camera) { if ( !RwCameraBeginUpdate(Scene.camera) ) { ForegroundApp = FALSE; RsEventHandler(rsACTIVATE, (void *)FALSE); return FALSE; } return TRUE; } /* ***************************************************************************** */ void psCameraShowRaster(RwCamera *camera) { if (CMenuManager::m_PrefsVsync) RwCameraShowRaster(camera, PSGLOBAL(window), rwRASTERFLIPWAITVSYNC); else RwCameraShowRaster(camera, PSGLOBAL(window), rwRASTERFLIPDONTWAIT); return; } /* ***************************************************************************** */ RwImage * psGrabScreen(RwCamera *pCamera) { #ifndef LIBRW RwRaster *pRaster = RwCameraGetRaster(pCamera); if (RwImage *pImage = RwImageCreate(pRaster->width, pRaster->height, 32)) { RwImageAllocatePixels(pImage); RwImageSetFromRaster(pImage, pRaster); return pImage; } #else rw::Image *image = RwCameraGetRaster(pCamera)->toImage(); image->removeMask(); if(image) return image; #endif return nil; } /* ***************************************************************************** */ #ifdef _WIN32 #pragma comment( lib, "Winmm.lib" ) // Needed for time RwUInt32 psTimer(void) { RwUInt32 time; TIMECAPS TimeCaps; timeGetDevCaps(&TimeCaps, sizeof(TIMECAPS)); timeBeginPeriod(TimeCaps.wPeriodMin); time = (RwUInt32) timeGetTime(); timeEndPeriod(TimeCaps.wPeriodMin); return time; } #else double psTimer(void) { struct timespec start; #if defined(CLOCK_MONOTONIC_RAW) clock_gettime(CLOCK_MONOTONIC_RAW, &start); #elif defined(CLOCK_MONOTONIC_FAST) clock_gettime(CLOCK_MONOTONIC_FAST, &start); #else clock_gettime(CLOCK_MONOTONIC, &start); #endif return start.tv_sec * 1000.0 + start.tv_nsec/1000000.0; } #endif /* ***************************************************************************** */ void psMouseSetPos(RwV2d *pos) { glfwSetCursorPos(PSGLOBAL(window), pos->x, pos->y); PSGLOBAL(lastMousePos.x) = (RwInt32)pos->x; PSGLOBAL(lastMousePos.y) = (RwInt32)pos->y; return; } /* ***************************************************************************** */ RwMemoryFunctions* psGetMemoryFunctions(void) { #ifdef USE_CUSTOM_ALLOCATOR return &memFuncs; #else return nil; #endif } /* ***************************************************************************** */ RwBool psInstallFileSystem(void) { return (TRUE); } /* ***************************************************************************** */ RwBool psNativeTextureSupport(void) { return true; } /* ***************************************************************************** */ #ifdef UNDER_CE #define CMDSTR LPWSTR #else #define CMDSTR LPSTR #endif /* ***************************************************************************** */ RwBool psInitialize(void) { PsGlobal.lastMousePos.x = PsGlobal.lastMousePos.y = 0.0f; RsGlobal.ps = &PsGlobal; PsGlobal.fullScreen = FALSE; PsGlobal.cursorIsInWindow = FALSE; WindowFocused = TRUE; WindowIconified = FALSE; PsGlobal.joy1id = -1; PsGlobal.joy2id = -1; CFileMgr::Initialise(); #ifdef PS2_MENU CPad::Initialise(); CPad::GetPad(0)->Mode = 0; CGame::frenchGame = false; CGame::germanGame = false; CGame::nastyGame = true; CMenuManager::m_PrefsAllowNastyGame = true; #ifndef _WIN32 // Mandatory for Linux(Unix? Posix?) to set lang. to environment lang. setlocale(LC_ALL, ""); char *systemLang, *keyboardLang; systemLang = setlocale (LC_ALL, NULL); keyboardLang = setlocale (LC_CTYPE, NULL); short lang; lang = !strncmp(systemLang, "fr_",3) ? LANG_FRENCH : !strncmp(systemLang, "de_",3) ? LANG_GERMAN : !strncmp(systemLang, "en_",3) ? LANG_ENGLISH : !strncmp(systemLang, "it_",3) ? LANG_ITALIAN : !strncmp(systemLang, "es_",3) ? LANG_SPANISH : LANG_OTHER; #else WORD lang = PRIMARYLANGID(GetSystemDefaultLCID()); #endif if ( lang == LANG_ITALIAN ) CMenuManager::m_PrefsLanguage = CMenuManager::LANGUAGE_ITALIAN; else if ( lang == LANG_SPANISH ) CMenuManager::m_PrefsLanguage = CMenuManager::LANGUAGE_SPANISH; else if ( lang == LANG_GERMAN ) { CGame::germanGame = true; CGame::nastyGame = false; CMenuManager::m_PrefsAllowNastyGame = false; CMenuManager::m_PrefsLanguage = CMenuManager::LANGUAGE_GERMAN; } else if ( lang == LANG_FRENCH ) { CGame::frenchGame = true; CGame::nastyGame = false; CMenuManager::m_PrefsAllowNastyGame = false; CMenuManager::m_PrefsLanguage = CMenuManager::LANGUAGE_FRENCH; } else CMenuManager::m_PrefsLanguage = CMenuManager::LANGUAGE_AMERICAN; FrontEndMenuManager.InitialiseMenuContentsAfterLoadingGame(); TheMemoryCard.Init(); #else C_PcSave::SetSaveDirectory(_psGetUserFilesFolder()); InitialiseLanguage(); #if GTA_VERSION < GTA3_PC_11 FrontEndMenuManager.LoadSettings(); #endif #endif gGameState = GS_START_UP; TRACE("gGameState = GS_START_UP"); #ifdef _WIN32 OSVERSIONINFO verInfo; verInfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); GetVersionEx(&verInfo); _dwOperatingSystemVersion = OS_WIN95; if ( verInfo.dwPlatformId == VER_PLATFORM_WIN32_NT ) { if ( verInfo.dwMajorVersion == 4 ) { debug("Operating System is WinNT\n"); _dwOperatingSystemVersion = OS_WINNT; } else if ( verInfo.dwMajorVersion == 5 ) { debug("Operating System is Win2000\n"); _dwOperatingSystemVersion = OS_WIN2000; } else if ( verInfo.dwMajorVersion > 5 ) { debug("Operating System is WinXP or greater\n"); _dwOperatingSystemVersion = OS_WINXP; } } else if ( verInfo.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS ) { if ( verInfo.dwMajorVersion > 4 || verInfo.dwMajorVersion == 4 && verInfo.dwMinorVersion != 0 ) { debug("Operating System is Win98\n"); _dwOperatingSystemVersion = OS_WIN98; } else { debug("Operating System is Win95\n"); _dwOperatingSystemVersion = OS_WIN95; } } #else _dwOperatingSystemVersion = OS_WINXP; // To fool other classes #endif #ifndef PS2_MENU #if GTA_VERSION >= GTA3_PC_11 FrontEndMenuManager.LoadSettings(); #endif #endif #ifdef _WIN32 MEMORYSTATUS memstats; GlobalMemoryStatus(&memstats); _dwMemAvailPhys = memstats.dwAvailPhys; debug("Physical memory size %u\n", memstats.dwTotalPhys); debug("Available physical memory %u\n", memstats.dwAvailPhys); #elif defined (__APPLE__) uint64_t size = 0; uint64_t page_size = 0; size_t uint64_len = sizeof(uint64_t); size_t ull_len = sizeof(unsigned long long); sysctl((int[]){CTL_HW, HW_PAGESIZE}, 2, &page_size, &ull_len, NULL, 0); sysctl((int[]){CTL_HW, HW_MEMSIZE}, 2, &size, &uint64_len, NULL, 0); vm_statistics_data_t vm_stat; mach_msg_type_number_t count = HOST_VM_INFO_COUNT; host_statistics(mach_host_self(), HOST_VM_INFO, (host_info_t)&vm_stat, &count); _dwMemAvailPhys = (uint64_t)(vm_stat.free_count * page_size); debug("Physical memory size %llu\n", _dwMemAvailPhys); debug("Available physical memory %llu\n", size); #else struct sysinfo systemInfo; sysinfo(&systemInfo); _dwMemAvailPhys = systemInfo.freeram; debug("Physical memory size %u\n", systemInfo.totalram); debug("Available physical memory %u\n", systemInfo.freeram); #endif TheText.Unload(); return TRUE; } /* ***************************************************************************** */ void psTerminate(void) { return; } /* ***************************************************************************** */ static RwChar **_VMList; RwInt32 _psGetNumVideModes() { return RwEngineGetNumVideoModes(); } /* ***************************************************************************** */ RwBool _psFreeVideoModeList() { RwInt32 numModes; RwInt32 i; numModes = _psGetNumVideModes(); if ( _VMList == nil ) return TRUE; for ( i = 0; i < numModes; i++ ) { RwFree(_VMList[i]); } RwFree(_VMList); _VMList = nil; return TRUE; } /* ***************************************************************************** */ RwChar **_psGetVideoModeList() { RwInt32 numModes; RwInt32 i; if ( _VMList != nil ) { return _VMList; } numModes = RwEngineGetNumVideoModes(); _VMList = (RwChar **)RwCalloc(numModes, sizeof(RwChar*)); for ( i = 0; i < numModes; i++ ) { RwVideoMode vm; RwEngineGetVideoModeInfo(&vm, i); if ( vm.flags & rwVIDEOMODEEXCLUSIVE ) { _VMList[i] = (RwChar*)RwCalloc(100, sizeof(RwChar)); rwsprintf(_VMList[i],"%d X %d X %d", vm.width, vm.height, vm.depth); } else _VMList[i] = nil; } return _VMList; } /* ***************************************************************************** */ void _psSelectScreenVM(RwInt32 videoMode) { RwTexDictionarySetCurrent( nil ); FrontEndMenuManager.UnloadTextures(); if (!_psSetVideoMode(RwEngineGetCurrentSubSystem(), videoMode)) { RsGlobal.quit = TRUE; printf("ERROR: Failed to select new screen resolution\n"); } else FrontEndMenuManager.LoadAllTextures(); } /* ***************************************************************************** */ RwBool IsForegroundApp() { return !!ForegroundApp; } /* UINT GetBestRefreshRate(UINT width, UINT height, UINT depth) { LPDIRECT3D8 d3d = Direct3DCreate8(D3D_SDK_VERSION); ASSERT(d3d != nil); UINT refreshRate = INT_MAX; D3DFORMAT format; if ( depth == 32 ) format = D3DFMT_X8R8G8B8; else if ( depth == 24 ) format = D3DFMT_R8G8B8; else format = D3DFMT_R5G6B5; UINT modeCount = d3d->GetAdapterModeCount(GcurSel); for ( UINT i = 0; i < modeCount; i++ ) { D3DDISPLAYMODE mode; d3d->EnumAdapterModes(GcurSel, i, &mode); if ( mode.Width == width && mode.Height == height && mode.Format == format ) { if ( mode.RefreshRate == 0 ) return 0; if ( mode.RefreshRate < refreshRate && mode.RefreshRate >= 60 ) refreshRate = mode.RefreshRate; } } #ifdef FIX_BUGS d3d->Release(); #endif if ( refreshRate == -1 ) return -1; return refreshRate; } */ /* ***************************************************************************** */ RwBool psSelectDevice() { RwVideoMode vm; RwInt32 subSysNum; RwInt32 AutoRenderer = 0; RwBool modeFound = FALSE; if ( !useDefault ) { GnumSubSystems = RwEngineGetNumSubSystems(); if ( !GnumSubSystems ) { return FALSE; } /* Just to be sure ... */ GnumSubSystems = (GnumSubSystems > MAX_SUBSYSTEMS) ? MAX_SUBSYSTEMS : GnumSubSystems; /* Get the names of all the sub systems */ for (subSysNum = 0; subSysNum < GnumSubSystems; subSysNum++) { RwEngineGetSubSystemInfo(&GsubSysInfo[subSysNum], subSysNum); } /* Get the default selection */ GcurSel = RwEngineGetCurrentSubSystem(); #ifdef IMPROVED_VIDEOMODE if(FrontEndMenuManager.m_nPrefsSubsystem < GnumSubSystems) GcurSel = FrontEndMenuManager.m_nPrefsSubsystem; #endif } /* Set the driver to use the correct sub system */ if (!RwEngineSetSubSystem(GcurSel)) { return FALSE; } #ifdef IMPROVED_VIDEOMODE FrontEndMenuManager.m_nPrefsSubsystem = GcurSel; #endif #ifndef IMPROVED_VIDEOMODE if ( !useDefault ) { if ( _psGetVideoModeList()[FrontEndMenuManager.m_nDisplayVideoMode] && FrontEndMenuManager.m_nDisplayVideoMode ) { FrontEndMenuManager.m_nPrefsVideoMode = FrontEndMenuManager.m_nDisplayVideoMode; GcurSelVM = FrontEndMenuManager.m_nDisplayVideoMode; } else { #ifdef DEFAULT_NATIVE_RESOLUTION // get the native video mode HDC hDevice = GetDC(NULL); int w = GetDeviceCaps(hDevice, HORZRES); int h = GetDeviceCaps(hDevice, VERTRES); int d = GetDeviceCaps(hDevice, BITSPIXEL); #else const int w = 640; const int h = 480; const int d = 16; #endif while ( !modeFound && GcurSelVM < RwEngineGetNumVideoModes() ) { RwEngineGetVideoModeInfo(&vm, GcurSelVM); if ( defaultFullscreenRes && vm.width != w || vm.height != h || vm.depth != d || !(vm.flags & rwVIDEOMODEEXCLUSIVE) ) ++GcurSelVM; else modeFound = TRUE; } if ( !modeFound ) { #ifdef DEFAULT_NATIVE_RESOLUTION GcurSelVM = 1; #else printf("WARNING: Cannot find 640x480 video mode, selecting device cancelled\n"); return FALSE; #endif } } } #else if ( !useDefault ) { if(FrontEndMenuManager.m_nPrefsWidth == 0 || FrontEndMenuManager.m_nPrefsHeight == 0 || FrontEndMenuManager.m_nPrefsDepth == 0){ // Defaults if nothing specified const GLFWvidmode *mode = glfwGetVideoMode(glfwGetPrimaryMonitor()); FrontEndMenuManager.m_nPrefsWidth = mode->width; FrontEndMenuManager.m_nPrefsHeight = mode->height; FrontEndMenuManager.m_nPrefsDepth = 32; FrontEndMenuManager.m_nPrefsWindowed = 0; } // Find the videomode that best fits what we got from the settings file RwInt32 bestFsMode = -1; RwInt32 bestWidth = -1; RwInt32 bestHeight = -1; RwInt32 bestDepth = -1; for(GcurSelVM = 0; GcurSelVM < RwEngineGetNumVideoModes(); GcurSelVM++){ RwEngineGetVideoModeInfo(&vm, GcurSelVM); if (!(vm.flags & rwVIDEOMODEEXCLUSIVE)){ bestWndMode = GcurSelVM; } else { // try the largest one that isn't larger than what we wanted if(vm.width >= bestWidth && vm.width <= FrontEndMenuManager.m_nPrefsWidth && vm.height >= bestHeight && vm.height <= FrontEndMenuManager.m_nPrefsHeight && vm.depth >= bestDepth && vm.depth <= FrontEndMenuManager.m_nPrefsDepth){ bestWidth = vm.width; bestHeight = vm.height; bestDepth = vm.depth; bestFsMode = GcurSelVM; } } } if(bestFsMode < 0){ printf("WARNING: Cannot find desired video mode, selecting device cancelled\n"); return FALSE; } GcurSelVM = bestFsMode; FrontEndMenuManager.m_nDisplayVideoMode = GcurSelVM; FrontEndMenuManager.m_nPrefsVideoMode = FrontEndMenuManager.m_nDisplayVideoMode; FrontEndMenuManager.m_nSelectedScreenMode = FrontEndMenuManager.m_nPrefsWindowed; } #endif RwEngineGetVideoModeInfo(&vm, GcurSelVM); #ifdef IMPROVED_VIDEOMODE if (FrontEndMenuManager.m_nPrefsWindowed) GcurSelVM = bestWndMode; // Now GcurSelVM is 0 but vm has sizes(and fullscreen flag) of the video mode we want, that's why we changed the rwVIDEOMODEEXCLUSIVE conditions below FrontEndMenuManager.m_nPrefsWidth = vm.width; FrontEndMenuManager.m_nPrefsHeight = vm.height; FrontEndMenuManager.m_nPrefsDepth = vm.depth; #endif #ifndef PS2_MENU FrontEndMenuManager.m_nCurrOption = 0; #endif /* Set up the video mode and set the apps window * dimensions to match */ if (!RwEngineSetVideoMode(GcurSelVM)) { return FALSE; } /* TODO if (vm.flags & rwVIDEOMODEEXCLUSIVE) { debug("%dx%dx%d", vm.width, vm.height, vm.depth); UINT refresh = GetBestRefreshRate(vm.width, vm.height, vm.depth); if ( refresh != (UINT)-1 ) { debug("refresh %d", refresh); RwD3D8EngineSetRefreshRate((RwUInt32)refresh); } } */ #ifndef IMPROVED_VIDEOMODE if (vm.flags & rwVIDEOMODEEXCLUSIVE) { RsGlobal.maximumWidth = vm.width; RsGlobal.maximumHeight = vm.height; RsGlobal.width = vm.width; RsGlobal.height = vm.height; PSGLOBAL(fullScreen) = TRUE; } #else RsGlobal.maximumWidth = FrontEndMenuManager.m_nPrefsWidth; RsGlobal.maximumHeight = FrontEndMenuManager.m_nPrefsHeight; RsGlobal.width = FrontEndMenuManager.m_nPrefsWidth; RsGlobal.height = FrontEndMenuManager.m_nPrefsHeight; PSGLOBAL(fullScreen) = !FrontEndMenuManager.m_nPrefsWindowed; #endif #ifdef MULTISAMPLING RwD3D8EngineSetMultiSamplingLevels(1 << FrontEndMenuManager.m_nPrefsMSAALevel); #endif return TRUE; } #ifndef GET_KEYBOARD_INPUT_FROM_X11 void keypressCB(GLFWwindow* window, int key, int scancode, int action, int mods); #endif void resizeCB(GLFWwindow* window, int width, int height); void scrollCB(GLFWwindow* window, double xoffset, double yoffset); void cursorCB(GLFWwindow* window, double xpos, double ypos); void cursorEnterCB(GLFWwindow* window, int entered); void windowFocusCB(GLFWwindow* window, int focused); void windowIconifyCB(GLFWwindow* window, int iconified); void joysChangeCB(int jid, int event); bool IsThisJoystickBlacklisted(int i) { #ifndef DETECT_JOYSTICK_MENU return false; #else if (glfwJoystickIsGamepad(i)) return false; const char* joyname = glfwGetJoystickName(i); if (gSelectedJoystickName[0] != '\0' && strncmp(joyname, gSelectedJoystickName, strlen(gSelectedJoystickName)) == 0) return false; return true; #endif } void _InputInitialiseJoys() { PSGLOBAL(joy1id) = -1; PSGLOBAL(joy2id) = -1; // Load our gamepad mappings. #define SDL_GAMEPAD_DB_PATH "gamecontrollerdb.txt" FILE *f = fopen(SDL_GAMEPAD_DB_PATH, "rb"); if (f) { fseek(f, 0, SEEK_END); size_t fsize = ftell(f); fseek(f, 0, SEEK_SET); char *db = (char*)malloc(fsize + 1); if (fread(db, 1, fsize, f) == fsize) { db[fsize] = '\0'; if (glfwUpdateGamepadMappings(db) == GLFW_FALSE) Error("glfwUpdateGamepadMappings didn't succeed, check " SDL_GAMEPAD_DB_PATH ".\n"); } else Error("fread on " SDL_GAMEPAD_DB_PATH " wasn't successful.\n"); free(db); fclose(f); } else printf("You don't seem to have copied " SDL_GAMEPAD_DB_PATH " file from re3/gamefiles to GTA3 directory. Some gamepads may not be recognized.\n"); #undef SDL_GAMEPAD_DB_PATH // But always overwrite it with the one in SDL_GAMECONTROLLERCONFIG. char const* EnvControlConfig = getenv("SDL_GAMECONTROLLERCONFIG"); if (EnvControlConfig != nil) { glfwUpdateGamepadMappings(EnvControlConfig); } for (int i = 0; i <= GLFW_JOYSTICK_LAST; i++) { if (glfwJoystickPresent(i) && !IsThisJoystickBlacklisted(i)) { if (PSGLOBAL(joy1id) == -1) PSGLOBAL(joy1id) = i; else if (PSGLOBAL(joy2id) == -1) PSGLOBAL(joy2id) = i; else break; } } if (PSGLOBAL(joy1id) != -1) { int count; glfwGetJoystickButtons(PSGLOBAL(joy1id), &count); #ifdef DETECT_JOYSTICK_MENU strcpy(gSelectedJoystickName, glfwGetJoystickName(PSGLOBAL(joy1id))); #endif ControlsManager.InitDefaultControlConfigJoyPad(count); } } long _InputInitialiseMouse() { glfwSetInputMode(PSGLOBAL(window), GLFW_CURSOR, GLFW_CURSOR_HIDDEN); return 0; } void psPostRWinit(void) { RwVideoMode vm; RwEngineGetVideoModeInfo(&vm, GcurSelVM); #ifndef GET_KEYBOARD_INPUT_FROM_X11 glfwSetKeyCallback(PSGLOBAL(window), keypressCB); #endif glfwSetFramebufferSizeCallback(PSGLOBAL(window), resizeCB); glfwSetScrollCallback(PSGLOBAL(window), scrollCB); glfwSetCursorPosCallback(PSGLOBAL(window), cursorCB); glfwSetCursorEnterCallback(PSGLOBAL(window), cursorEnterCB); glfwSetWindowIconifyCallback(PSGLOBAL(window), windowIconifyCB); glfwSetWindowFocusCallback(PSGLOBAL(window), windowFocusCB); glfwSetJoystickCallback(joysChangeCB); _InputInitialiseJoys(); _InputInitialiseMouse(); if(!(vm.flags & rwVIDEOMODEEXCLUSIVE)) glfwSetWindowSize(PSGLOBAL(window), RsGlobal.maximumWidth, RsGlobal.maximumHeight); // Make sure all keys are released CPad::GetPad(0)->Clear(true); CPad::GetPad(1)->Clear(true); } /* ***************************************************************************** */ RwBool _psSetVideoMode(RwInt32 subSystem, RwInt32 videoMode) { RwInitialised = FALSE; RsEventHandler(rsRWTERMINATE, nil); GcurSel = subSystem; GcurSelVM = videoMode; useDefault = TRUE; if ( RsEventHandler(rsRWINITIALIZE, &openParams) == rsEVENTERROR ) return FALSE; RwInitialised = TRUE; useDefault = FALSE; RwRect r; r.x = 0; r.y = 0; r.w = RsGlobal.maximumWidth; r.h = RsGlobal.maximumHeight; RsEventHandler(rsCAMERASIZE, &r); psPostRWinit(); return TRUE; } /* ***************************************************************************** */ static RwChar ** CommandLineToArgv(RwChar *cmdLine, RwInt32 *argCount) { RwInt32 numArgs = 0; RwBool inArg, inString; RwInt32 i, len; RwChar *res, *str, **aptr; len = strlen(cmdLine); /* * Count the number of arguments... */ inString = FALSE; inArg = FALSE; for(i=0; i<=len; i++) { if( cmdLine[i] == '"' ) { inString = !inString; } if( (cmdLine[i] <= ' ' && !inString) || i == len ) { if( inArg ) { inArg = FALSE; numArgs++; } } else if( !inArg ) { inArg = TRUE; } } /* * Allocate memory for result... */ res = (RwChar *)malloc(sizeof(RwChar *) * numArgs + len + 1); str = res + sizeof(RwChar *) * numArgs; aptr = (RwChar **)res; strcpy(str, cmdLine); /* * Walk through cmdLine again this time setting pointer to each arg... */ inArg = FALSE; inString = FALSE; for(i=0; i<=len; i++) { if( cmdLine[i] == '"' ) { inString = !inString; } if( (cmdLine[i] <= ' ' && !inString) || i == len ) { if( inArg ) { if( str[i-1] == '"' ) { str[i-1] = '\0'; } else { str[i] = '\0'; } inArg = FALSE; } } else if( !inArg && cmdLine[i] != '"' ) { inArg = TRUE; *aptr++ = &str[i]; } } *argCount = numArgs; return (RwChar **)res; } /* ***************************************************************************** */ void InitialiseLanguage() { #ifndef _WIN32 // Mandatory for Linux(Unix? Posix?) to set lang. to environment lang. setlocale(LC_ALL, ""); char *systemLang, *keyboardLang; systemLang = setlocale (LC_ALL, NULL); keyboardLang = setlocale (LC_CTYPE, NULL); short primUserLCID, primSystemLCID; primUserLCID = primSystemLCID = !strncmp(systemLang, "fr_",3) ? LANG_FRENCH : !strncmp(systemLang, "de_",3) ? LANG_GERMAN : !strncmp(systemLang, "en_",3) ? LANG_ENGLISH : !strncmp(systemLang, "it_",3) ? LANG_ITALIAN : !strncmp(systemLang, "es_",3) ? LANG_SPANISH : LANG_OTHER; short primLayout = !strncmp(keyboardLang, "fr_",3) ? LANG_FRENCH : (!strncmp(keyboardLang, "de_",3) ? LANG_GERMAN : LANG_ENGLISH); short subUserLCID, subSystemLCID; subUserLCID = subSystemLCID = !strncmp(systemLang, "en_AU",5) ? SUBLANG_ENGLISH_AUS : SUBLANG_OTHER; short subLayout = !strncmp(keyboardLang, "en_AU",5) ? SUBLANG_ENGLISH_AUS : SUBLANG_OTHER; #else WORD primUserLCID = PRIMARYLANGID(GetSystemDefaultLCID()); WORD primSystemLCID = PRIMARYLANGID(GetUserDefaultLCID()); WORD primLayout = PRIMARYLANGID((DWORD)GetKeyboardLayout(0)); WORD subUserLCID = SUBLANGID(GetSystemDefaultLCID()); WORD subSystemLCID = SUBLANGID(GetUserDefaultLCID()); WORD subLayout = SUBLANGID((DWORD)GetKeyboardLayout(0)); #endif if ( primUserLCID == LANG_GERMAN || primSystemLCID == LANG_GERMAN || primLayout == LANG_GERMAN ) { CGame::nastyGame = false; CMenuManager::m_PrefsAllowNastyGame = false; CGame::germanGame = true; } if ( primUserLCID == LANG_FRENCH || primSystemLCID == LANG_FRENCH || primLayout == LANG_FRENCH ) { CGame::nastyGame = false; CMenuManager::m_PrefsAllowNastyGame = false; CGame::frenchGame = true; } if ( subUserLCID == SUBLANG_ENGLISH_AUS || subSystemLCID == SUBLANG_ENGLISH_AUS || subLayout == SUBLANG_ENGLISH_AUS ) CGame::noProstitutes = true; #ifdef NASTY_GAME CGame::nastyGame = true; CMenuManager::m_PrefsAllowNastyGame = true; CGame::noProstitutes = false; #endif int32 lang; switch ( primSystemLCID ) { case LANG_GERMAN: { lang = LANG_GERMAN; break; } case LANG_FRENCH: { lang = LANG_FRENCH; break; } case LANG_SPANISH: { lang = LANG_SPANISH; break; } case LANG_ITALIAN: { lang = LANG_ITALIAN; break; } default: { lang = ( subSystemLCID == SUBLANG_ENGLISH_AUS ) ? -99 : LANG_ENGLISH; break; } } CMenuManager::OS_Language = primUserLCID; switch ( lang ) { case LANG_GERMAN: { CMenuManager::m_PrefsLanguage = CMenuManager::LANGUAGE_GERMAN; break; } case LANG_SPANISH: { CMenuManager::m_PrefsLanguage = CMenuManager::LANGUAGE_SPANISH; break; } case LANG_FRENCH: { CMenuManager::m_PrefsLanguage = CMenuManager::LANGUAGE_FRENCH; break; } case LANG_ITALIAN: { CMenuManager::m_PrefsLanguage = CMenuManager::LANGUAGE_ITALIAN; break; } default: { CMenuManager::m_PrefsLanguage = CMenuManager::LANGUAGE_AMERICAN; break; } } #ifndef _WIN32 // TODO this is needed for strcasecmp to work correctly across all languages, but can these cause other problems?? setlocale(LC_CTYPE, "C"); setlocale(LC_COLLATE, "C"); setlocale(LC_NUMERIC, "C"); #endif TheText.Unload(); TheText.Load(); } /* ***************************************************************************** */ void HandleExit() { #ifdef _WIN32 MSG message; while ( PeekMessage(&message, nil, 0U, 0U, PM_REMOVE|PM_NOYIELD) ) { if( message.message == WM_QUIT ) { RsGlobal.quit = TRUE; } else { TranslateMessage(&message); DispatchMessage(&message); } } #else // We now handle terminate message always, why handle on some cases? return; #endif } #ifndef _WIN32 void terminateHandler(int sig, siginfo_t *info, void *ucontext) { RsGlobal.quit = TRUE; } #ifdef FLUSHABLE_STREAMING void dummyHandler(int sig){ // Don't kill the app pls } #endif #endif void resizeCB(GLFWwindow* window, int width, int height) { /* * Handle event to ensure window contents are displayed during re-size * as this can be disabled by the user, then if there is not enough * memory things don't work. */ /* redraw window */ if (RwInitialised && gGameState == GS_PLAYING_GAME) { RsEventHandler(rsIDLE, (void *)TRUE); } if (RwInitialised && height > 0 && width > 0) { RwRect r; // TODO fix artifacts of resizing with mouse RsGlobal.maximumHeight = height; RsGlobal.maximumWidth = width; r.x = 0; r.y = 0; r.w = width; r.h = height; RsEventHandler(rsCAMERASIZE, &r); } // glfwSetWindowPos(window, 0, 0); } void scrollCB(GLFWwindow* window, double xoffset, double yoffset) { PSGLOBAL(mouseWheel) = yoffset; } bool lshiftStatus = false; bool rshiftStatus = false; #ifndef GET_KEYBOARD_INPUT_FROM_X11 int keymap[GLFW_KEY_LAST + 1]; static void initkeymap(void) { int i; for (i = 0; i < GLFW_KEY_LAST + 1; i++) keymap[i] = rsNULL; keymap[GLFW_KEY_SPACE] = ' '; keymap[GLFW_KEY_APOSTROPHE] = '\''; keymap[GLFW_KEY_COMMA] = ','; keymap[GLFW_KEY_MINUS] = '-'; keymap[GLFW_KEY_PERIOD] = '.'; keymap[GLFW_KEY_SLASH] = '/'; keymap[GLFW_KEY_0] = '0'; keymap[GLFW_KEY_1] = '1'; keymap[GLFW_KEY_2] = '2'; keymap[GLFW_KEY_3] = '3'; keymap[GLFW_KEY_4] = '4'; keymap[GLFW_KEY_5] = '5'; keymap[GLFW_KEY_6] = '6'; keymap[GLFW_KEY_7] = '7'; keymap[GLFW_KEY_8] = '8'; keymap[GLFW_KEY_9] = '9'; keymap[GLFW_KEY_SEMICOLON] = ';'; keymap[GLFW_KEY_EQUAL] = '='; keymap[GLFW_KEY_A] = 'A'; keymap[GLFW_KEY_B] = 'B'; keymap[GLFW_KEY_C] = 'C'; keymap[GLFW_KEY_D] = 'D'; keymap[GLFW_KEY_E] = 'E'; keymap[GLFW_KEY_F] = 'F'; keymap[GLFW_KEY_G] = 'G'; keymap[GLFW_KEY_H] = 'H'; keymap[GLFW_KEY_I] = 'I'; keymap[GLFW_KEY_J] = 'J'; keymap[GLFW_KEY_K] = 'K'; keymap[GLFW_KEY_L] = 'L'; keymap[GLFW_KEY_M] = 'M'; keymap[GLFW_KEY_N] = 'N'; keymap[GLFW_KEY_O] = 'O'; keymap[GLFW_KEY_P] = 'P'; keymap[GLFW_KEY_Q] = 'Q'; keymap[GLFW_KEY_R] = 'R'; keymap[GLFW_KEY_S] = 'S'; keymap[GLFW_KEY_T] = 'T'; keymap[GLFW_KEY_U] = 'U'; keymap[GLFW_KEY_V] = 'V'; keymap[GLFW_KEY_W] = 'W'; keymap[GLFW_KEY_X] = 'X'; keymap[GLFW_KEY_Y] = 'Y'; keymap[GLFW_KEY_Z] = 'Z'; keymap[GLFW_KEY_LEFT_BRACKET] = '['; keymap[GLFW_KEY_BACKSLASH] = '\\'; keymap[GLFW_KEY_RIGHT_BRACKET] = ']'; keymap[GLFW_KEY_GRAVE_ACCENT] = '`'; keymap[GLFW_KEY_ESCAPE] = rsESC; keymap[GLFW_KEY_ENTER] = rsENTER; keymap[GLFW_KEY_TAB] = rsTAB; keymap[GLFW_KEY_BACKSPACE] = rsBACKSP; keymap[GLFW_KEY_INSERT] = rsINS; keymap[GLFW_KEY_DELETE] = rsDEL; keymap[GLFW_KEY_RIGHT] = rsRIGHT; keymap[GLFW_KEY_LEFT] = rsLEFT; keymap[GLFW_KEY_DOWN] = rsDOWN; keymap[GLFW_KEY_UP] = rsUP; keymap[GLFW_KEY_PAGE_UP] = rsPGUP; keymap[GLFW_KEY_PAGE_DOWN] = rsPGDN; keymap[GLFW_KEY_HOME] = rsHOME; keymap[GLFW_KEY_END] = rsEND; keymap[GLFW_KEY_CAPS_LOCK] = rsCAPSLK; keymap[GLFW_KEY_SCROLL_LOCK] = rsSCROLL; keymap[GLFW_KEY_NUM_LOCK] = rsNUMLOCK; keymap[GLFW_KEY_PRINT_SCREEN] = rsNULL; keymap[GLFW_KEY_PAUSE] = rsPAUSE; keymap[GLFW_KEY_F1] = rsF1; keymap[GLFW_KEY_F2] = rsF2; keymap[GLFW_KEY_F3] = rsF3; keymap[GLFW_KEY_F4] = rsF4; keymap[GLFW_KEY_F5] = rsF5; keymap[GLFW_KEY_F6] = rsF6; keymap[GLFW_KEY_F7] = rsF7; keymap[GLFW_KEY_F8] = rsF8; keymap[GLFW_KEY_F9] = rsF9; keymap[GLFW_KEY_F10] = rsF10; keymap[GLFW_KEY_F11] = rsF11; keymap[GLFW_KEY_F12] = rsF12; keymap[GLFW_KEY_F13] = rsNULL; keymap[GLFW_KEY_F14] = rsNULL; keymap[GLFW_KEY_F15] = rsNULL; keymap[GLFW_KEY_F16] = rsNULL; keymap[GLFW_KEY_F17] = rsNULL; keymap[GLFW_KEY_F18] = rsNULL; keymap[GLFW_KEY_F19] = rsNULL; keymap[GLFW_KEY_F20] = rsNULL; keymap[GLFW_KEY_F21] = rsNULL; keymap[GLFW_KEY_F22] = rsNULL; keymap[GLFW_KEY_F23] = rsNULL; keymap[GLFW_KEY_F24] = rsNULL; keymap[GLFW_KEY_F25] = rsNULL; keymap[GLFW_KEY_KP_0] = rsPADINS; keymap[GLFW_KEY_KP_1] = rsPADEND; keymap[GLFW_KEY_KP_2] = rsPADDOWN; keymap[GLFW_KEY_KP_3] = rsPADPGDN; keymap[GLFW_KEY_KP_4] = rsPADLEFT; keymap[GLFW_KEY_KP_5] = rsPAD5; keymap[GLFW_KEY_KP_6] = rsPADRIGHT; keymap[GLFW_KEY_KP_7] = rsPADHOME; keymap[GLFW_KEY_KP_8] = rsPADUP; keymap[GLFW_KEY_KP_9] = rsPADPGUP; keymap[GLFW_KEY_KP_DECIMAL] = rsPADDEL; keymap[GLFW_KEY_KP_DIVIDE] = rsDIVIDE; keymap[GLFW_KEY_KP_MULTIPLY] = rsTIMES; keymap[GLFW_KEY_KP_SUBTRACT] = rsMINUS; keymap[GLFW_KEY_KP_ADD] = rsPLUS; keymap[GLFW_KEY_KP_ENTER] = rsPADENTER; keymap[GLFW_KEY_KP_EQUAL] = rsNULL; keymap[GLFW_KEY_LEFT_SHIFT] = rsLSHIFT; keymap[GLFW_KEY_LEFT_CONTROL] = rsLCTRL; keymap[GLFW_KEY_LEFT_ALT] = rsLALT; keymap[GLFW_KEY_LEFT_SUPER] = rsLWIN; keymap[GLFW_KEY_RIGHT_SHIFT] = rsRSHIFT; keymap[GLFW_KEY_RIGHT_CONTROL] = rsRCTRL; keymap[GLFW_KEY_RIGHT_ALT] = rsRALT; keymap[GLFW_KEY_RIGHT_SUPER] = rsRWIN; keymap[GLFW_KEY_MENU] = rsNULL; } void keypressCB(GLFWwindow* window, int key, int scancode, int action, int mods) { if (key >= 0 && key <= GLFW_KEY_LAST && action != GLFW_REPEAT) { RsKeyCodes ks = (RsKeyCodes)keymap[key]; if (key == GLFW_KEY_LEFT_SHIFT) lshiftStatus = action != GLFW_RELEASE; if (key == GLFW_KEY_RIGHT_SHIFT) rshiftStatus = action != GLFW_RELEASE; if (action == GLFW_RELEASE) RsKeyboardEventHandler(rsKEYUP, &ks); else if (action == GLFW_PRESS) RsKeyboardEventHandler(rsKEYDOWN, &ks); } } #else uint32 keymap[512]; // 256 ascii + 256 KeySyms between 0xff00 - 0xffff bool keyStates[512]; uint32 keyCodeToKeymapIndex[256]; // cache for physical keys #define KEY_MAP_OFFSET (0xff00 - 256) static void initkeymap(void) { Display *display = glfwGetX11Display(); int i; for (i = 0; i < ARRAY_SIZE(keymap); i++) keymap[i] = rsNULL; // You can add new ASCII mappings to here freely (but beware that if right hand side of assignment isn't supported on CFont, it'll be blank/won't work on binding screen) // Right hand side of assigments should always be uppercase counterpart of character keymap[XK_space] = ' '; keymap[XK_apostrophe] = '\''; keymap[XK_ampersand] = '&'; keymap[XK_percent] = '%'; keymap[XK_dollar] = '$'; keymap[XK_comma] = ','; keymap[XK_minus] = '-'; keymap[XK_period] = '.'; keymap[XK_slash] = '/'; keymap[XK_question] = '?'; keymap[XK_exclam] = '!'; keymap[XK_quotedbl] = '"'; keymap[XK_colon] = ':'; keymap[XK_semicolon] = ';'; keymap[XK_equal] = '='; keymap[XK_bracketleft] = '['; keymap[XK_backslash] = '\\'; keymap[XK_bracketright] = ']'; keymap[XK_grave] = '`'; keymap[XK_0] = '0'; keymap[XK_1] = '1'; keymap[XK_2] = '2'; keymap[XK_3] = '3'; keymap[XK_4] = '4'; keymap[XK_5] = '5'; keymap[XK_6] = '6'; keymap[XK_7] = '7'; keymap[XK_8] = '8'; keymap[XK_9] = '9'; keymap[XK_a] = 'A'; keymap[XK_b] = 'B'; keymap[XK_c] = 'C'; keymap[XK_d] = 'D'; keymap[XK_e] = 'E'; keymap[XK_f] = 'F'; keymap[XK_g] = 'G'; keymap[XK_h] = 'H'; keymap[XK_i] = 'I'; keymap[XK_I] = 'I'; // Turkish I problem keymap[XK_j] = 'J'; keymap[XK_k] = 'K'; keymap[XK_l] = 'L'; keymap[XK_m] = 'M'; keymap[XK_n] = 'N'; keymap[XK_o] = 'O'; keymap[XK_p] = 'P'; keymap[XK_q] = 'Q'; keymap[XK_r] = 'R'; keymap[XK_s] = 'S'; keymap[XK_t] = 'T'; keymap[XK_u] = 'U'; keymap[XK_v] = 'V'; keymap[XK_w] = 'W'; keymap[XK_x] = 'X'; keymap[XK_y] = 'Y'; keymap[XK_z] = 'Z'; // Some of regional but ASCII characters that GTA supports keymap[XK_agrave] = 0x00c0; keymap[XK_aacute] = 0x00c1; keymap[XK_acircumflex] = 0x00c2; keymap[XK_adiaeresis] = 0x00c4; keymap[XK_ae] = 0x00c6; keymap[XK_egrave] = 0x00c8; keymap[XK_eacute] = 0x00c9; keymap[XK_ecircumflex] = 0x00ca; keymap[XK_ediaeresis] = 0x00cb; keymap[XK_igrave] = 0x00cc; keymap[XK_iacute] = 0x00cd; keymap[XK_icircumflex] = 0x00ce; keymap[XK_idiaeresis] = 0x00cf; keymap[XK_ccedilla] = 0x00c7; keymap[XK_odiaeresis] = 0x00d6; keymap[XK_udiaeresis] = 0x00dc; // These are 0xff00 - 0xffff range of KeySym's, and subtracting KEY_MAP_OFFSET is needed keymap[XK_Escape - KEY_MAP_OFFSET] = rsESC; keymap[XK_Return - KEY_MAP_OFFSET] = rsENTER; keymap[XK_Tab - KEY_MAP_OFFSET] = rsTAB; keymap[XK_BackSpace - KEY_MAP_OFFSET] = rsBACKSP; keymap[XK_Insert - KEY_MAP_OFFSET] = rsINS; keymap[XK_Delete - KEY_MAP_OFFSET] = rsDEL; keymap[XK_Right - KEY_MAP_OFFSET] = rsRIGHT; keymap[XK_Left - KEY_MAP_OFFSET] = rsLEFT; keymap[XK_Down - KEY_MAP_OFFSET] = rsDOWN; keymap[XK_Up - KEY_MAP_OFFSET] = rsUP; keymap[XK_Page_Up - KEY_MAP_OFFSET] = rsPGUP; keymap[XK_Page_Down - KEY_MAP_OFFSET] = rsPGDN; keymap[XK_Home - KEY_MAP_OFFSET] = rsHOME; keymap[XK_End - KEY_MAP_OFFSET] = rsEND; keymap[XK_Caps_Lock - KEY_MAP_OFFSET] = rsCAPSLK; keymap[XK_Scroll_Lock - KEY_MAP_OFFSET] = rsSCROLL; keymap[XK_Num_Lock - KEY_MAP_OFFSET] = rsNUMLOCK; keymap[XK_Pause - KEY_MAP_OFFSET] = rsPAUSE; keymap[XK_F1 - KEY_MAP_OFFSET] = rsF1; keymap[XK_F2 - KEY_MAP_OFFSET] = rsF2; keymap[XK_F3 - KEY_MAP_OFFSET] = rsF3; keymap[XK_F4 - KEY_MAP_OFFSET] = rsF4; keymap[XK_F5 - KEY_MAP_OFFSET] = rsF5; keymap[XK_F6 - KEY_MAP_OFFSET] = rsF6; keymap[XK_F7 - KEY_MAP_OFFSET] = rsF7; keymap[XK_F8 - KEY_MAP_OFFSET] = rsF8; keymap[XK_F9 - KEY_MAP_OFFSET] = rsF9; keymap[XK_F10 - KEY_MAP_OFFSET] = rsF10; keymap[XK_F11 - KEY_MAP_OFFSET] = rsF11; keymap[XK_F12 - KEY_MAP_OFFSET] = rsF12; keymap[XK_F13 - KEY_MAP_OFFSET] = rsNULL; keymap[XK_F14 - KEY_MAP_OFFSET] = rsNULL; keymap[XK_F15 - KEY_MAP_OFFSET] = rsNULL; keymap[XK_F16 - KEY_MAP_OFFSET] = rsNULL; keymap[XK_F17 - KEY_MAP_OFFSET] = rsNULL; keymap[XK_F18 - KEY_MAP_OFFSET] = rsNULL; keymap[XK_F19 - KEY_MAP_OFFSET] = rsNULL; keymap[XK_F20 - KEY_MAP_OFFSET] = rsNULL; keymap[XK_F21 - KEY_MAP_OFFSET] = rsNULL; keymap[XK_F22 - KEY_MAP_OFFSET] = rsNULL; keymap[XK_F23 - KEY_MAP_OFFSET] = rsNULL; keymap[XK_F24 - KEY_MAP_OFFSET] = rsNULL; keymap[XK_F25 - KEY_MAP_OFFSET] = rsNULL; keymap[XK_KP_0 - KEY_MAP_OFFSET] = rsPADINS; keymap[XK_KP_1 - KEY_MAP_OFFSET] = rsPADEND; keymap[XK_KP_2 - KEY_MAP_OFFSET] = rsPADDOWN; keymap[XK_KP_3 - KEY_MAP_OFFSET] = rsPADPGDN; keymap[XK_KP_4 - KEY_MAP_OFFSET] = rsPADLEFT; keymap[XK_KP_5 - KEY_MAP_OFFSET] = rsPAD5; keymap[XK_KP_6 - KEY_MAP_OFFSET] = rsPADRIGHT; keymap[XK_KP_7 - KEY_MAP_OFFSET] = rsPADHOME; keymap[XK_KP_8 - KEY_MAP_OFFSET] = rsPADUP; keymap[XK_KP_9 - KEY_MAP_OFFSET] = rsPADPGUP; keymap[XK_KP_Insert - KEY_MAP_OFFSET] = rsPADINS; keymap[XK_KP_End - KEY_MAP_OFFSET] = rsPADEND; keymap[XK_KP_Down - KEY_MAP_OFFSET] = rsPADDOWN; keymap[XK_KP_Page_Down - KEY_MAP_OFFSET] = rsPADPGDN; keymap[XK_KP_Left - KEY_MAP_OFFSET] = rsPADLEFT; keymap[XK_KP_Begin - KEY_MAP_OFFSET] = rsPAD5; keymap[XK_KP_Right - KEY_MAP_OFFSET] = rsPADRIGHT; keymap[XK_KP_Home - KEY_MAP_OFFSET] = rsPADHOME; keymap[XK_KP_Up - KEY_MAP_OFFSET] = rsPADUP; keymap[XK_KP_Page_Up - KEY_MAP_OFFSET] = rsPADPGUP; keymap[XK_KP_Decimal - KEY_MAP_OFFSET] = rsPADDEL; keymap[XK_KP_Divide - KEY_MAP_OFFSET] = rsDIVIDE; keymap[XK_KP_Multiply - KEY_MAP_OFFSET] = rsTIMES; keymap[XK_KP_Subtract - KEY_MAP_OFFSET] = rsMINUS; keymap[XK_KP_Add - KEY_MAP_OFFSET] = rsPLUS; keymap[XK_KP_Enter - KEY_MAP_OFFSET] = rsPADENTER; keymap[XK_KP_Equal - KEY_MAP_OFFSET] = rsNULL; keymap[XK_Shift_L - KEY_MAP_OFFSET] = rsLSHIFT; keymap[XK_Control_L - KEY_MAP_OFFSET] = rsLCTRL; keymap[XK_Alt_L - KEY_MAP_OFFSET] = rsLALT; keymap[XK_Super_L - KEY_MAP_OFFSET] = rsLWIN; keymap[XK_Shift_R - KEY_MAP_OFFSET] = rsRSHIFT; keymap[XK_Control_R - KEY_MAP_OFFSET] = rsRCTRL; keymap[XK_Alt_R - KEY_MAP_OFFSET] = rsRALT; keymap[XK_Super_R - KEY_MAP_OFFSET] = rsRWIN; keymap[XK_Menu - KEY_MAP_OFFSET] = rsNULL; // Cache the key codes' key symbol equivelants, otherwise we will have to do it on each frame // KeyCode is always in [0,255], and represents a physical key int min_keycode, max_keycode, keysyms_per_keycode; KeySym *keymap, *origkeymap; char *keyboardLang = setlocale (LC_CTYPE, NULL); setlocale(LC_CTYPE, ""); XDisplayKeycodes(display, &min_keycode, &max_keycode); origkeymap = XGetKeyboardMapping(display, min_keycode, (max_keycode - min_keycode + 1), &keysyms_per_keycode); keymap = origkeymap; for (int i = min_keycode; i <= max_keycode; i++) { int j, lastKeysym; lastKeysym = keysyms_per_keycode - 1; while ((lastKeysym >= 0) && (keymap[lastKeysym] == NoSymbol)) lastKeysym--; for (j = 0; j <= lastKeysym; j++) { KeySym ks = keymap[j]; if (ks == NoSymbol) continue; if (ks < 256) { keyCodeToKeymapIndex[i] = ks; break; } else if (ks >= 0xff00 && ks < 0xffff) { keyCodeToKeymapIndex[i] = ks - KEY_MAP_OFFSET; break; } } keymap += keysyms_per_keycode; } XFree(origkeymap); setlocale(LC_CTYPE, keyboardLang); } #undef KEY_MAP_OFFSET void checkKeyPresses() { Display *display = glfwGetX11Display(); char keys[32]; XQueryKeymap(display, keys); for (int i = 0; i < sizeof(keys); i++) { for (int j = 0; j < 8; j++) { KeyCode keycode = 8 * i + j; uint32 keymapIndex = keyCodeToKeymapIndex[keycode]; if (keymapIndex != 0) { int rsCode = keymap[keymapIndex]; if (rsCode == rsNULL) continue; bool pressed = WindowFocused && !!(keys[i] & (1 << j)); // idk why R* does that if (rsCode == rsLSHIFT) lshiftStatus = pressed; else if (rsCode == rsRSHIFT) rshiftStatus = pressed; if (keyStates[keymapIndex] != pressed) { if (pressed) { RsKeyboardEventHandler(rsKEYDOWN, &rsCode); } else { RsKeyboardEventHandler(rsKEYUP, &rsCode); } } keyStates[keymapIndex] = pressed; } } } } #endif // R* calls that in ControllerConfig, idk why void _InputTranslateShiftKeyUpDown(RsKeyCodes *rs) { RsKeyboardEventHandler(lshiftStatus ? rsKEYDOWN : rsKEYUP, &(*rs = rsLSHIFT)); RsKeyboardEventHandler(rshiftStatus ? rsKEYDOWN : rsKEYUP, &(*rs = rsRSHIFT)); } // TODO this only works in frontend(and luckily only frontend use this). Fun fact: if I get pos manually in game, glfw reports that it's > 32000 void cursorCB(GLFWwindow* window, double xpos, double ypos) { if (!FrontEndMenuManager.m_bMenuActive) return; int winw, winh; glfwGetWindowSize(PSGLOBAL(window), &winw, &winh); FrontEndMenuManager.m_nMouseTempPosX = xpos * (RsGlobal.maximumWidth / winw); FrontEndMenuManager.m_nMouseTempPosY = ypos * (RsGlobal.maximumHeight / winh); } void cursorEnterCB(GLFWwindow* window, int entered) { PSGLOBAL(cursorIsInWindow) = !!entered; } void windowFocusCB(GLFWwindow* window, int focused) { WindowFocused = !!focused; } void windowIconifyCB(GLFWwindow* window, int iconified) { WindowIconified = !!iconified; } /* ***************************************************************************** */ #ifdef _WIN32 int PASCAL WinMain(HINSTANCE instance, HINSTANCE prevInstance __RWUNUSED__, CMDSTR cmdLine, int cmdShow) { RwInt32 argc; RwChar** argv; SystemParametersInfo(SPI_SETFOREGROUNDLOCKTIMEOUT, 0, nil, SPIF_SENDCHANGE); #ifndef MASTER if (strstr(cmdLine, "-console")) { AllocConsole(); freopen("CONIN$", "r", stdin); freopen("CONOUT$", "w", stdout); freopen("CONOUT$", "w", stderr); } #endif #else int main(int argc, char *argv[]) { #endif RwV2d pos; RwInt32 i; #ifdef USE_CUSTOM_ALLOCATOR InitMemoryMgr(); #endif #ifndef _WIN32 struct sigaction act; act.sa_sigaction = terminateHandler; act.sa_flags = SA_SIGINFO; sigaction(SIGTERM, &act, NULL); #ifdef FLUSHABLE_STREAMING struct sigaction sa; sigemptyset(&sa.sa_mask); sa.sa_handler = dummyHandler; sa.sa_flags = 0; sigaction(SIGUSR1, &sa, NULL); #endif #endif /* * Initialize the platform independent data. * This will in turn initialize the platform specific data... */ if( RsEventHandler(rsINITIALIZE, nil) == rsEVENTERROR ) { return FALSE; } #ifdef _WIN32 /* * Get proper command line params, cmdLine passed to us does not * work properly under all circumstances... */ cmdLine = GetCommandLine(); /* * Parse command line into standard (argv, argc) parameters... */ argv = CommandLineToArgv(cmdLine, &argc); /* * Parse command line parameters (except program name) one at * a time BEFORE RenderWare initialization... */ #endif for(i=1; i<argc; i++) { RsEventHandler(rsPREINITCOMMANDLINE, argv[i]); } /* * Parameters to be used in RwEngineOpen / rsRWINITIALISE event */ openParams.width = RsGlobal.maximumWidth; openParams.height = RsGlobal.maximumHeight; openParams.windowtitle = RsGlobal.appName; openParams.window = &PSGLOBAL(window); ControlsManager.MakeControllerActionsBlank(); ControlsManager.InitDefaultControlConfiguration(); /* * Initialize the 3D (RenderWare) components of the app... */ if( rsEVENTERROR == RsEventHandler(rsRWINITIALIZE, &openParams) ) { RsEventHandler(rsTERMINATE, nil); return 0; } #ifdef _WIN32 HWND wnd = glfwGetWin32Window(PSGLOBAL(window)); HICON icon = LoadIcon(instance, MAKEINTRESOURCE(IDI_MAIN_ICON)); SendMessage(wnd, WM_SETICON, ICON_BIG, (LPARAM)icon); SendMessage(wnd, WM_SETICON, ICON_SMALL, (LPARAM)icon); #endif psPostRWinit(); ControlsManager.InitDefaultControlConfigMouse(MousePointerStateHelper.GetMouseSetUp()); // glfwSetWindowPos(PSGLOBAL(window), 0, 0); /* * Parse command line parameters (except program name) one at * a time AFTER RenderWare initialization... */ for(i=1; i<argc; i++) { RsEventHandler(rsCOMMANDLINE, argv[i]); } /* * Force a camera resize event... */ { RwRect r; r.x = 0; r.y = 0; r.w = RsGlobal.maximumWidth; r.h = RsGlobal.maximumHeight; RsEventHandler(rsCAMERASIZE, &r); } #ifdef _WIN32 SystemParametersInfo(SPI_SETPOWEROFFACTIVE, FALSE, nil, SPIF_SENDCHANGE); SystemParametersInfo(SPI_SETLOWPOWERACTIVE, FALSE, nil, SPIF_SENDCHANGE); STICKYKEYS SavedStickyKeys; SavedStickyKeys.cbSize = sizeof(STICKYKEYS); SystemParametersInfo(SPI_GETSTICKYKEYS, sizeof(STICKYKEYS), &SavedStickyKeys, SPIF_SENDCHANGE); STICKYKEYS NewStickyKeys; NewStickyKeys.cbSize = sizeof(STICKYKEYS); NewStickyKeys.dwFlags = SKF_TWOKEYSOFF; SystemParametersInfo(SPI_SETSTICKYKEYS, sizeof(STICKYKEYS), &NewStickyKeys, SPIF_SENDCHANGE); #endif { CFileMgr::SetDirMyDocuments(); #ifdef LOAD_INI_SETTINGS // At this point InitDefaultControlConfigJoyPad must have set all bindings to default and ms_padButtonsInited to number of detected buttons. // We will load stored bindings below, but let's cache ms_padButtonsInited before LoadINIControllerSettings and LoadSettings clears it, // so we can add new joy bindings **on top of** stored bindings. int connectedPadButtons = ControlsManager.ms_padButtonsInited; #endif int32 gta3set = CFileMgr::OpenFile("gta3.set", "r"); if ( gta3set ) { ControlsManager.LoadSettings(gta3set); CFileMgr::CloseFile(gta3set); } CFileMgr::SetDir(""); #ifdef LOAD_INI_SETTINGS LoadINIControllerSettings(); if (connectedPadButtons != 0) { ControlsManager.InitDefaultControlConfigJoyPad(connectedPadButtons); SaveINIControllerSettings(); } #endif } #ifdef _WIN32 SetErrorMode(SEM_FAILCRITICALERRORS); #endif #ifdef PS2_MENU int32 r = TheMemoryCard.CheckCardStateAtGameStartUp(CARD_ONE); if ( r == CMemoryCard::ERR_DIRNOENTRY || r == CMemoryCard::ERR_NOFORMAT && r != CMemoryCard::ERR_OPENNOENTRY && r != CMemoryCard::ERR_NONE ) { LoadingScreen(nil, nil, "loadsc0"); TheText.Unload(); TheText.Load(); CFont::Initialise(); FrontEndMenuManager.DrawMemoryCardStartUpMenus(); } #endif initkeymap(); while ( TRUE ) { RwInitialised = TRUE; /* * Set the initial mouse position... */ pos.x = RsGlobal.maximumWidth * 0.5f; pos.y = RsGlobal.maximumHeight * 0.5f; RsMouseSetPos(&pos); /* * Enter the message processing loop... */ #ifndef MASTER if (gbModelViewer) { // This is TheModelViewer in LCS, but not compiled on III Mobile. LoadingScreen("Loading the ModelViewer", NULL, GetRandomSplashScreen()); CAnimViewer::Initialise(); CTimer::Update(); #ifndef PS2_MENU FrontEndMenuManager.m_bGameNotLoaded = false; #endif } #endif #ifdef PS2_MENU if (TheMemoryCard.m_bWantToLoad) LoadSplash(GetLevelSplashScreen(CGame::currLevel)); TheMemoryCard.m_bWantToLoad = false; CTimer::Update(); while( !RsGlobal.quit && !(FrontEndMenuManager.m_bWantToRestart || TheMemoryCard.b_FoundRecentSavedGameWantToLoad) && !glfwWindowShouldClose(PSGLOBAL(window)) ) #else while( !RsGlobal.quit && !FrontEndMenuManager.m_bWantToRestart && !glfwWindowShouldClose(PSGLOBAL(window))) #endif { glfwPollEvents(); #ifdef GET_KEYBOARD_INPUT_FROM_X11 checkKeyPresses(); #endif #ifndef MASTER if (gbModelViewer) { // This is TheModelViewerCore in LCS, but TheModelViewer on other state-machine III-VCs. TheModelViewer(); } else #endif if ( ForegroundApp ) { switch ( gGameState ) { case GS_START_UP: { #ifdef NO_MOVIES gGameState = GS_INIT_ONCE; #else gGameState = GS_INIT_LOGO_MPEG; #endif TRACE("gGameState = GS_INIT_ONCE"); break; } case GS_INIT_LOGO_MPEG: { //if (!startupDeactivate) // PlayMovieInWindow(cmdShow, "movies\\Logo.mpg"); gGameState = GS_LOGO_MPEG; TRACE("gGameState = GS_LOGO_MPEG;"); break; } case GS_LOGO_MPEG: { // CPad::UpdatePads(); // if (startupDeactivate || ControlsManager.GetJoyButtonJustDown() != 0) ++gGameState; // else if (CPad::GetPad(0)->GetLeftMouseJustDown()) // ++gGameState; // else if (CPad::GetPad(0)->GetEnterJustDown()) // ++gGameState; // else if (CPad::GetPad(0)->GetCharJustDown(' ')) // ++gGameState; // else if (CPad::GetPad(0)->GetAltJustDown()) // ++gGameState; // else if (CPad::GetPad(0)->GetTabJustDown()) // ++gGameState; break; } case GS_INIT_INTRO_MPEG: { //#ifndef NO_MOVIES // CloseClip(); // CoUninitialize(); //#endif // // if (CMenuManager::OS_Language == LANG_FRENCH || CMenuManager::OS_Language == LANG_GERMAN) // PlayMovieInWindow(cmdShow, "movies\\GTAtitlesGER.mpg"); // else // PlayMovieInWindow(cmdShow, "movies\\GTAtitles.mpg"); gGameState = GS_INTRO_MPEG; TRACE("gGameState = GS_INTRO_MPEG;"); break; } case GS_INTRO_MPEG: { // CPad::UpdatePads(); // // if (startupDeactivate || ControlsManager.GetJoyButtonJustDown() != 0) ++gGameState; // else if (CPad::GetPad(0)->GetLeftMouseJustDown()) // ++gGameState; // else if (CPad::GetPad(0)->GetEnterJustDown()) // ++gGameState; // else if (CPad::GetPad(0)->GetCharJustDown(' ')) // ++gGameState; // else if (CPad::GetPad(0)->GetAltJustDown()) // ++gGameState; // else if (CPad::GetPad(0)->GetTabJustDown()) // ++gGameState; break; } case GS_INIT_ONCE: { //CoUninitialize(); #ifdef PS2_MENU extern char version_name[64]; if ( CGame::frenchGame || CGame::germanGame ) LoadingScreen(NULL, version_name, "loadsc24"); else LoadingScreen(NULL, version_name, "loadsc0"); printf("Into TheGame!!!\n"); #else LoadingScreen(nil, nil, "loadsc0"); #endif if ( !CGame::InitialiseOnceAfterRW() ) RsGlobal.quit = TRUE; #ifdef PS2_MENU gGameState = GS_INIT_PLAYING_GAME; #else gGameState = GS_INIT_FRONTEND; TRACE("gGameState = GS_INIT_FRONTEND;"); #endif break; } #ifndef PS2_MENU case GS_INIT_FRONTEND: { LoadingScreen(nil, nil, "loadsc0"); FrontEndMenuManager.m_bGameNotLoaded = true; CMenuManager::m_bStartUpFrontEndRequested = true; if ( defaultFullscreenRes ) { defaultFullscreenRes = FALSE; FrontEndMenuManager.m_nPrefsVideoMode = GcurSelVM; FrontEndMenuManager.m_nDisplayVideoMode = GcurSelVM; } gGameState = GS_FRONTEND; TRACE("gGameState = GS_FRONTEND;"); break; } case GS_FRONTEND: { if(!WindowIconified) RsEventHandler(rsFRONTENDIDLE, nil); #ifdef PS2_MENU if ( !FrontEndMenuManager.m_bMenuActive || TheMemoryCard.m_bWantToLoad ) #else if ( !FrontEndMenuManager.m_bMenuActive || FrontEndMenuManager.m_bWantToLoad ) #endif { gGameState = GS_INIT_PLAYING_GAME; TRACE("gGameState = GS_INIT_PLAYING_GAME;"); } #ifdef PS2_MENU if (TheMemoryCard.m_bWantToLoad ) #else if ( FrontEndMenuManager.m_bWantToLoad ) #endif { InitialiseGame(); FrontEndMenuManager.m_bGameNotLoaded = false; gGameState = GS_PLAYING_GAME; TRACE("gGameState = GS_PLAYING_GAME;"); } break; } #endif case GS_INIT_PLAYING_GAME: { #ifdef PS2_MENU CGame::Initialise("DATA\\GTA3.DAT"); //LoadingScreen("Starting Game", NULL, GetRandomSplashScreen()); if ( TheMemoryCard.CheckCardInserted(CARD_ONE) == CMemoryCard::NO_ERR_SUCCESS && TheMemoryCard.ChangeDirectory(CARD_ONE, TheMemoryCard.Cards[CARD_ONE].dir) && TheMemoryCard.FindMostRecentFileName(CARD_ONE, TheMemoryCard.MostRecentFile) == true && TheMemoryCard.CheckDataNotCorrupt(TheMemoryCard.MostRecentFile)) { strcpy(TheMemoryCard.LoadFileName, TheMemoryCard.MostRecentFile); TheMemoryCard.b_FoundRecentSavedGameWantToLoad = true; if (CMenuManager::m_PrefsLanguage != TheMemoryCard.GetLanguageToLoad()) { CMenuManager::m_PrefsLanguage = TheMemoryCard.GetLanguageToLoad(); TheText.Unload(); TheText.Load(); } CGame::currLevel = (eLevelName)TheMemoryCard.GetLevelToLoad(); } #else InitialiseGame(); FrontEndMenuManager.m_bGameNotLoaded = false; #endif gGameState = GS_PLAYING_GAME; TRACE("gGameState = GS_PLAYING_GAME;"); break; } case GS_PLAYING_GAME: { float ms = (float)CTimer::GetCurrentTimeInCycles() / (float)CTimer::GetCyclesPerMillisecond(); if ( RwInitialised ) { if (!CMenuManager::m_PrefsFrameLimiter || (1000.0f / (float)RsGlobal.maxFPS) < ms) RsEventHandler(rsIDLE, (void *)TRUE); } break; } } } else { if ( RwCameraBeginUpdate(Scene.camera) ) { RwCameraEndUpdate(Scene.camera); ForegroundApp = TRUE; RsEventHandler(rsACTIVATE, (void *)TRUE); } } } /* * About to shut down - block resize events again... */ RwInitialised = FALSE; FrontEndMenuManager.UnloadTextures(); #ifdef PS2_MENU if ( !(FrontEndMenuManager.m_bWantToRestart || TheMemoryCard.b_FoundRecentSavedGameWantToLoad)) break; #else if ( !FrontEndMenuManager.m_bWantToRestart ) break; #endif CPad::ResetCheats(); CPad::StopPadsShaking(); DMAudio.ChangeMusicMode(MUSICMODE_DISABLE); #ifdef PS2_MENU CGame::ShutDownForRestart(); #endif CTimer::Stop(); #ifdef PS2_MENU if (FrontEndMenuManager.m_bWantToRestart || TheMemoryCard.b_FoundRecentSavedGameWantToLoad) { if (TheMemoryCard.b_FoundRecentSavedGameWantToLoad) { FrontEndMenuManager.m_bWantToRestart = true; TheMemoryCard.m_bWantToLoad = true; } CGame::InitialiseWhenRestarting(); DMAudio.ChangeMusicMode(MUSICMODE_GAME); FrontEndMenuManager.m_bWantToRestart = false; continue; } CGame::ShutDown(); CTimer::Stop(); break; #else if ( FrontEndMenuManager.m_bWantToLoad ) { CGame::ShutDownForRestart(); CGame::InitialiseWhenRestarting(); DMAudio.ChangeMusicMode(MUSICMODE_GAME); LoadSplash(GetLevelSplashScreen(CGame::currLevel)); FrontEndMenuManager.m_bWantToLoad = false; } else { #ifndef MASTER if ( gbModelViewer ) CAnimViewer::Shutdown(); else #endif if ( gGameState == GS_PLAYING_GAME ) CGame::ShutDown(); CTimer::Stop(); if ( FrontEndMenuManager.m_bFirstTime == true ) { gGameState = GS_INIT_FRONTEND; TRACE("gGameState = GS_INIT_FRONTEND;"); } else { gGameState = GS_INIT_PLAYING_GAME; TRACE("gGameState = GS_INIT_PLAYING_GAME;"); } } FrontEndMenuManager.m_bFirstTime = false; FrontEndMenuManager.m_bWantToRestart = false; #endif } #ifndef MASTER if ( gbModelViewer ) CAnimViewer::Shutdown(); else #endif if ( gGameState == GS_PLAYING_GAME ) CGame::ShutDown(); DMAudio.Terminate(); _psFreeVideoModeList(); /* * Tidy up the 3D (RenderWare) components of the application... */ RsEventHandler(rsRWTERMINATE, nil); /* * Free the platform dependent data... */ RsEventHandler(rsTERMINATE, nil); #ifdef _WIN32 /* * Free the argv strings... */ free(argv); SystemParametersInfo(SPI_SETSTICKYKEYS, sizeof(STICKYKEYS), &SavedStickyKeys, SPIF_SENDCHANGE); SystemParametersInfo(SPI_SETPOWEROFFACTIVE, TRUE, nil, SPIF_SENDCHANGE); SystemParametersInfo(SPI_SETLOWPOWERACTIVE, TRUE, nil, SPIF_SENDCHANGE); SetErrorMode(0); #endif return 0; } /* ***************************************************************************** */ RwV2d leftStickPos; RwV2d rightStickPos; void CapturePad(RwInt32 padID) { int8 glfwPad = -1; if( padID == 0 ) glfwPad = PSGLOBAL(joy1id); else if( padID == 1) glfwPad = PSGLOBAL(joy2id); else assert("invalid padID"); if ( glfwPad == -1 ) return; int numButtons, numAxes; const uint8 *buttons = glfwGetJoystickButtons(glfwPad, &numButtons); const float *axes = glfwGetJoystickAxes(glfwPad, &numAxes); GLFWgamepadstate gamepadState; if (ControlsManager.m_bFirstCapture == false) { memcpy(&ControlsManager.m_OldState, &ControlsManager.m_NewState, sizeof(ControlsManager.m_NewState)); } else { // In case connected gamepad doesn't have L-R trigger axes. ControlsManager.m_NewState.mappedButtons[15] = ControlsManager.m_NewState.mappedButtons[16] = 0; } ControlsManager.m_NewState.buttons = (uint8*)buttons; ControlsManager.m_NewState.numButtons = numButtons; ControlsManager.m_NewState.id = glfwPad; ControlsManager.m_NewState.isGamepad = glfwGetGamepadState(glfwPad, &gamepadState); if (ControlsManager.m_NewState.isGamepad) { memcpy(&ControlsManager.m_NewState.mappedButtons, gamepadState.buttons, sizeof(gamepadState.buttons)); float lt = gamepadState.axes[GLFW_GAMEPAD_AXIS_LEFT_TRIGGER], rt = gamepadState.axes[GLFW_GAMEPAD_AXIS_RIGHT_TRIGGER]; // glfw returns 0.0 for non-existent axises(which is bullocks) so we treat it as deadzone, and keep value of previous frame. // otherwise if this axis is present, -1 = released, 1 = pressed if (lt != 0.0f) ControlsManager.m_NewState.mappedButtons[15] = lt > -0.8f; if (rt != 0.0f) ControlsManager.m_NewState.mappedButtons[16] = rt > -0.8f; } // TODO? L2-R2 axes(not buttons-that's fine) on joysticks that don't have SDL gamepad mapping AREN'T handled, and I think it's impossible to do without mapping. if (ControlsManager.m_bFirstCapture == true) { memcpy(&ControlsManager.m_OldState, &ControlsManager.m_NewState, sizeof(ControlsManager.m_NewState)); ControlsManager.m_bFirstCapture = false; } RsPadButtonStatus bs; bs.padID = padID; RsPadEventHandler(rsPADBUTTONUP, (void *)&bs); // Gamepad axes are guaranteed to return 0.0f if that particular gamepad doesn't have that axis. // And that's really good for sticks, because gamepads return 0.0 for them when sticks are in released state. if ( glfwPad != -1 ) { leftStickPos.x = ControlsManager.m_NewState.isGamepad ? gamepadState.axes[GLFW_GAMEPAD_AXIS_LEFT_X] : numAxes >= 1 ? axes[0] : 0.0f; leftStickPos.y = ControlsManager.m_NewState.isGamepad ? gamepadState.axes[GLFW_GAMEPAD_AXIS_LEFT_Y] : numAxes >= 2 ? axes[1] : 0.0f; rightStickPos.x = ControlsManager.m_NewState.isGamepad ? gamepadState.axes[GLFW_GAMEPAD_AXIS_RIGHT_X] : numAxes >= 3 ? axes[2] : 0.0f; rightStickPos.y = ControlsManager.m_NewState.isGamepad ? gamepadState.axes[GLFW_GAMEPAD_AXIS_RIGHT_Y] : numAxes >= 4 ? axes[3] : 0.0f; } { if (CPad::m_bMapPadOneToPadTwo) bs.padID = 1; RsPadEventHandler(rsPADBUTTONUP, (void *)&bs); RsPadEventHandler(rsPADBUTTONDOWN, (void *)&bs); } { if (CPad::m_bMapPadOneToPadTwo) bs.padID = 1; CPad *pad = CPad::GetPad(bs.padID); if ( Abs(leftStickPos.x) > 0.3f ) pad->PCTempJoyState.LeftStickX = (int32)(leftStickPos.x * 128.0f); if ( Abs(leftStickPos.y) > 0.3f ) pad->PCTempJoyState.LeftStickY = (int32)(leftStickPos.y * 128.0f); if ( Abs(rightStickPos.x) > 0.3f ) pad->PCTempJoyState.RightStickX = (int32)(rightStickPos.x * 128.0f); if ( Abs(rightStickPos.y) > 0.3f ) pad->PCTempJoyState.RightStickY = (int32)(rightStickPos.y * 128.0f); } return; } void joysChangeCB(int jid, int event) { if (event == GLFW_CONNECTED && !IsThisJoystickBlacklisted(jid)) { if (PSGLOBAL(joy1id) == -1) { PSGLOBAL(joy1id) = jid; #ifdef DETECT_JOYSTICK_MENU strcpy(gSelectedJoystickName, glfwGetJoystickName(jid)); #endif // This is behind LOAD_INI_SETTINGS, because otherwise the Init call below will destroy/overwrite your bindings. #ifdef LOAD_INI_SETTINGS int count; glfwGetJoystickButtons(PSGLOBAL(joy1id), &count); ControlsManager.InitDefaultControlConfigJoyPad(count); #endif } else if (PSGLOBAL(joy2id) == -1) PSGLOBAL(joy2id) = jid; } else if (event == GLFW_DISCONNECTED) { if (PSGLOBAL(joy1id) == jid) { PSGLOBAL(joy1id) = -1; } else if (PSGLOBAL(joy2id) == jid) PSGLOBAL(joy2id) = -1; } } #if (defined(_MSC_VER)) int strcasecmp(const char* str1, const char* str2) { return _strcmpi(str1, str2); } #endif #endif
25.058587
170
0.677081
gameblabla
8d4081ed745d1943e7891a42f2269a77bd288039
2,810
cpp
C++
playground/ExampleApps/ExampleAppSimpleOverlay.cpp
pthom/imgui_manual
7857f8e58c7374772c0f25f353afbb5f6e753ff2
[ "MIT" ]
146
2020-07-04T05:58:05.000Z
2022-03-24T00:00:23.000Z
playground/ExampleApps/ExampleAppSimpleOverlay.cpp
pthom/imgui_manual
7857f8e58c7374772c0f25f353afbb5f6e753ff2
[ "MIT" ]
7
2020-07-03T20:17:04.000Z
2022-03-19T13:56:14.000Z
playground/ExampleApps/ExampleAppSimpleOverlay.cpp
pthom/imgui_manual
7857f8e58c7374772c0f25f353afbb5f6e753ff2
[ "MIT" ]
10
2020-07-06T09:26:47.000Z
2022-02-18T20:10:49.000Z
#include "Common_ExampleApp.h" // The code below was copy-pasted verbatim from imgui_demo.cpp // Do not edit!!! //----------------------------------------------------------------------------- // [SECTION] Example App: Simple overlay / ShowExampleAppSimpleOverlay() //----------------------------------------------------------------------------- // Demonstrate creating a simple static window with no decoration // + a context-menu to choose which corner of the screen to use. static void ShowExampleAppSimpleOverlay(bool* p_open) { static int corner = 0; ImGuiIO& io = ImGui::GetIO(); ImGuiWindowFlags window_flags = ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_NoDocking | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoNav; if (corner != -1) { const float PAD = 10.0f; const ImGuiViewport* viewport = ImGui::GetMainViewport(); ImVec2 work_pos = viewport->WorkPos; // Use work area to avoid menu-bar/task-bar, if any! ImVec2 work_size = viewport->WorkSize; ImVec2 window_pos, window_pos_pivot; window_pos.x = (corner & 1) ? (work_pos.x + work_size.x - PAD) : (work_pos.x + PAD); window_pos.y = (corner & 2) ? (work_pos.y + work_size.y - PAD) : (work_pos.y + PAD); window_pos_pivot.x = (corner & 1) ? 1.0f : 0.0f; window_pos_pivot.y = (corner & 2) ? 1.0f : 0.0f; ImGui::SetNextWindowPos(window_pos, ImGuiCond_Always, window_pos_pivot); ImGui::SetNextWindowViewport(viewport->ID); window_flags |= ImGuiWindowFlags_NoMove; } ImGui::SetNextWindowBgAlpha(0.35f); // Transparent background if (ImGui::Begin("Example: Simple overlay", p_open, window_flags)) { DEMO_MARKER("Examples/Simple Overlay"); ImGui::Text("Simple overlay\n" "in the corner of the screen.\n" "(right-click to change position)"); ImGui::Separator(); if (ImGui::IsMousePosValid()) ImGui::Text("Mouse Position: (%.1f,%.1f)", io.MousePos.x, io.MousePos.y); else ImGui::Text("Mouse Position: <invalid>"); if (ImGui::BeginPopupContextWindow()) { if (ImGui::MenuItem("Custom", NULL, corner == -1)) corner = -1; if (ImGui::MenuItem("Top-left", NULL, corner == 0)) corner = 0; if (ImGui::MenuItem("Top-right", NULL, corner == 1)) corner = 1; if (ImGui::MenuItem("Bottom-left", NULL, corner == 2)) corner = 2; if (ImGui::MenuItem("Bottom-right", NULL, corner == 3)) corner = 3; if (p_open && ImGui::MenuItem("Close")) *p_open = false; ImGui::EndPopup(); } } ImGui::End(); } void Playground() { ShowExampleAppSimpleOverlay(nullptr); }
46.065574
229
0.602135
pthom
1d25d0e43330f662c626ff764f1988dd531debb1
3,194
cpp
C++
src/third_party/angle/src/tests/egl_tests/EGLAndroidFrameBufferTargetTest.cpp
rhencke/engine
1016db292c4e73374a0a11536b18303c9522a224
[ "BSD-3-Clause" ]
6
2021-07-05T16:09:39.000Z
2022-03-06T22:44:42.000Z
src/third_party/angle/src/tests/egl_tests/EGLAndroidFrameBufferTargetTest.cpp
rhencke/engine
1016db292c4e73374a0a11536b18303c9522a224
[ "BSD-3-Clause" ]
7
2022-03-15T13:25:39.000Z
2022-03-15T13:25:44.000Z
src/third_party/angle/src/tests/egl_tests/EGLAndroidFrameBufferTargetTest.cpp
rhencke/engine
1016db292c4e73374a0a11536b18303c9522a224
[ "BSD-3-Clause" ]
null
null
null
// // Copyright 2019 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // EGLAndroidFrameBufferTargetTest.cpp: // This test verifies the extension EGL_ANDROID_framebuffer_target // 1. When the EGLFRAME_BUFFER_TARGET_ANDROID attribute is used with eglChooseConfig // It should match with configs according to Config selection rules and the extension // #include <gtest/gtest.h> #include "common/string_utils.h" #include "test_utils/ANGLETest.h" using namespace angle; class EGLAndroidFrameBufferTargetTest : public ANGLETest { protected: EGLAndroidFrameBufferTargetTest() {} void testSetUp() override { mDisplay = getEGLWindow()->getDisplay(); ASSERT_TRUE(mDisplay != EGL_NO_DISPLAY); } EGLDisplay mDisplay = EGL_NO_DISPLAY; }; namespace { EGLint GetAttrib(EGLDisplay display, EGLConfig config, EGLint attrib) { EGLint value = 0; EXPECT_EGL_TRUE(eglGetConfigAttrib(display, config, attrib, &value)); return value; } } // namespace // Verify config matching is working. TEST_P(EGLAndroidFrameBufferTargetTest, MatchFramebufferTargetConfigs) { ANGLE_SKIP_TEST_IF(!IsEGLDisplayExtensionEnabled(mDisplay, "EGL_ANDROID_framebuffer_target")); // Get all the configs EGLint count; EXPECT_EGL_TRUE(eglGetConfigs(mDisplay, nullptr, 0, &count)); EXPECT_TRUE(count > 0); std::vector<EGLConfig> configs(count); EXPECT_EGL_TRUE(eglGetConfigs(mDisplay, configs.data(), count, &count)); ASSERT_EQ(configs.size(), static_cast<size_t>(count)); // Filter out all non-framebuffertarget configs std::vector<EGLConfig> filterConfigs(0); for (auto config : configs) { if (GetAttrib(mDisplay, config, EGL_FRAMEBUFFER_TARGET_ANDROID) == EGL_TRUE) { filterConfigs.push_back(config); } } // sort configs by increaing ID std::sort(filterConfigs.begin(), filterConfigs.end(), [this](EGLConfig a, EGLConfig b) -> bool { return GetAttrib(mDisplay, a, EGL_CONFIG_ID) < GetAttrib(mDisplay, b, EGL_CONFIG_ID); }); // Now get configs that selection algorithm identifies EGLint attribs[] = {EGL_FRAMEBUFFER_TARGET_ANDROID, EGL_TRUE, EGL_COLOR_BUFFER_TYPE, EGL_DONT_CARE, EGL_COLOR_COMPONENT_TYPE_EXT, EGL_DONT_CARE, EGL_NONE}; EXPECT_EGL_TRUE(eglChooseConfig(mDisplay, attribs, nullptr, 0, &count)); std::vector<EGLConfig> matchConfigs(count); EXPECT_EGL_TRUE(eglChooseConfig(mDisplay, attribs, matchConfigs.data(), count, &count)); matchConfigs.resize(count); // sort configs by increasing ID std::sort(matchConfigs.begin(), matchConfigs.end(), [this](EGLConfig a, EGLConfig b) -> bool { return GetAttrib(mDisplay, a, EGL_CONFIG_ID) < GetAttrib(mDisplay, b, EGL_CONFIG_ID); }); EXPECT_EQ(matchConfigs, filterConfigs) << "Filtered configs do not match selection Configs"; } ANGLE_INSTANTIATE_TEST(EGLAndroidFrameBufferTargetTest, ES2_VULKAN(), ES3_VULKAN());
35.098901
100
0.69975
rhencke
1d26539f6ed1354a4349a32e2902c9036b32081e
1,021
hpp
C++
src/cpp/ee/ad_mob/AdMobNativeAdLayout.hpp
enrevol/ee-x
60a66ad3dc6e14802a7c5d8d585a8499be13f5b8
[ "MIT" ]
null
null
null
src/cpp/ee/ad_mob/AdMobNativeAdLayout.hpp
enrevol/ee-x
60a66ad3dc6e14802a7c5d8d585a8499be13f5b8
[ "MIT" ]
null
null
null
src/cpp/ee/ad_mob/AdMobNativeAdLayout.hpp
enrevol/ee-x
60a66ad3dc6e14802a7c5d8d585a8499be13f5b8
[ "MIT" ]
null
null
null
// // AdMobNativeAdBuilder.hpp // ee_x // // Created by Zinge on 10/16/17. // // #ifndef EE_X_ADMOB_NATIVE_AD_LAYOUT_HPP #define EE_X_ADMOB_NATIVE_AD_LAYOUT_HPP #ifdef __cplusplus #include <string> #include <unordered_map> #include "ee/ad_mob/AdMobFwd.hpp" namespace ee { namespace ad_mob { class NativeAdLayout { private: using Self = NativeAdLayout; public: NativeAdLayout(); ~NativeAdLayout(); Self& setBody(const std::string& id); Self& setCallToAction(const std::string& id); Self& setHeadline(const std::string& id); Self& setIcon(const std::string& id); Self& setImage(const std::string& id); Self& setMedia(const std::string& id); Self& setPrice(const std::string& id); Self& setStarRating(const std::string& id); Self& setStore(const std::string& id); protected: friend Bridge; std::unordered_map<std::string, std::string> params_; }; } // namespace ad_mob } // namespace ee #endif // __cplusplus #endif /* EE_X_ADMOB_NATIVE_AD_LAYOUT_HPP */
20.42
57
0.697356
enrevol
1d2990c78d18728be266a655616234fdc333c4b5
10,233
cpp
C++
src/headless/image/jpeg_codec.cpp
primatelabs/litehtml
f103057ddb1d81411d75eea9ca4f5bf007ecc9e4
[ "BSD-3-Clause" ]
null
null
null
src/headless/image/jpeg_codec.cpp
primatelabs/litehtml
f103057ddb1d81411d75eea9ca4f5bf007ecc9e4
[ "BSD-3-Clause" ]
null
null
null
src/headless/image/jpeg_codec.cpp
primatelabs/litehtml
f103057ddb1d81411d75eea9ca4f5bf007ecc9e4
[ "BSD-3-Clause" ]
null
null
null
// Copyright (C) 2020-2021 Primate Labs Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the names of the copyright holders nor the names of their // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "image/jpeg_codec.h" #include <algorithm> #include "math/clamp.h" #include "litehtml/logging.h" // HACK: Work around macro redefinitions in jmorecfh.h. #if defined(PLATFORM_WINDOWS) #define XMD_H #endif extern "C" { #include "jpeglib.h" #include "jerror.h" } // HACK: Work around macro redefinitions in jmorecfh.h. #if defined(PLATFORM_WINDOWS) #undef XMD_H #endif namespace headless { namespace { struct MemorySource { jpeg_source_mgr pub; uint8_t* data; uint32_t length; uint32_t offset; }; void init_source(j_decompress_ptr cinfo) { MemorySource* src = reinterpret_cast<MemorySource*>(cinfo->src); src->pub.bytes_in_buffer = 0; } boolean fill_input_buffer(j_decompress_ptr cinfo) { MemorySource* src = reinterpret_cast<MemorySource*>(cinfo->src); static const uint8_t eof[] = { 0xFF, JPEG_EOI }; if (src->offset >= src->length) { WARNMS(cinfo, JWRN_JPEG_EOF); src->pub.next_input_byte = eof; src->pub.bytes_in_buffer = 2; } else { src->pub.next_input_byte = src->data + src->offset; src->pub.bytes_in_buffer = src->length - src->offset; src->offset = src->length; } return TRUE; } void skip_input_data(j_decompress_ptr cinfo, long num_bytes) { MemorySource* src = reinterpret_cast<MemorySource*>(cinfo->src); if (num_bytes > 0) { while (num_bytes > static_cast<long>(src->pub.bytes_in_buffer)) { num_bytes -= src->pub.bytes_in_buffer; fill_input_buffer(cinfo); } src->pub.next_input_byte += num_bytes; src->pub.bytes_in_buffer -= num_bytes; } } void term_source(j_decompress_ptr cinfo) { } void jpeg_memory_source(j_decompress_ptr cinfo, uint8_t* data, size_t length) { if(cinfo->src == nullptr) { cinfo->src = (jpeg_source_mgr*)(*cinfo->mem->alloc_small)((j_common_ptr)cinfo, JPOOL_PERMANENT, sizeof(MemorySource)); } MemorySource* src = reinterpret_cast<MemorySource*>(cinfo->src); src->pub.init_source = init_source; src->pub.fill_input_buffer = fill_input_buffer; src->pub.skip_input_data = skip_input_data; src->pub.resync_to_restart = jpeg_resync_to_restart; src->pub.term_source = term_source; src->length = length; src->offset = 0; src->data = data; } struct MemoryDestination { jpeg_destination_mgr pub; uint32_t length; uint32_t offset; uint8_t* data; }; void init_destination(j_compress_ptr cinfo) { MemoryDestination* dest = reinterpret_cast<MemoryDestination*>(cinfo->dest); dest->pub.next_output_byte = dest->data; dest->pub.free_in_buffer = dest->length; } boolean empty_output_buffer(j_compress_ptr cinfo) { MemoryDestination* dest = reinterpret_cast<MemoryDestination*>(cinfo->dest); // Double the length of the buffer; this should minimize the total number of // reallocations needed at the expense of overallocating memory. With the // heuristic in JPEGCodec::compress() we should never need to reallocate // memory, but if we do the least we can do is be smart about it. uint32_t realloc_length = dest->length * 2; dest->data = static_cast<uint8_t*>(realloc(dest->data, realloc_length)); dest->pub.next_output_byte = dest->data + dest->length; dest->pub.free_in_buffer = realloc_length - dest->length; dest->length = realloc_length; return TRUE; } void term_destination(j_compress_ptr cinfo) { MemoryDestination* dest = reinterpret_cast<MemoryDestination*>(cinfo->dest); dest->offset = dest->length - dest->pub.free_in_buffer; } void jpeg_memory_destination(j_compress_ptr cinfo, uint8_t * data, uint32_t length) { MemoryDestination* dest; if(cinfo->dest == nullptr) { cinfo->dest = (jpeg_destination_mgr *)(*cinfo->mem->alloc_small)((j_common_ptr)cinfo, JPOOL_PERMANENT, sizeof(MemoryDestination)); } dest = reinterpret_cast<MemoryDestination*>(cinfo->dest); dest->pub.init_destination = init_destination; dest->pub.empty_output_buffer = empty_output_buffer; dest->pub.term_destination = term_destination; dest->length = length; dest->offset = 0; dest->data = data; } } // namespace Image<uint8_t> JPEGCodec::decompress(uint8_t* data, size_t length, ImageFormat format) { jpeg_decompress_struct cinfo; jpeg_error_mgr jerr; JSAMPROW row; cinfo.err = jpeg_std_error(&jerr); jpeg_create_decompress(&cinfo); jpeg_memory_source(&cinfo, data, length); jpeg_read_header(&cinfo, TRUE); // RGB is the default format for JPEG images because we assume all JPEG // images are RGB images (see the assertion above). if (format == kImageFormatDefault) { format = kImageFormatRGB; } // Decompress JPEG images to a temporary RGB buffer then convert to RGBA or // grayscale ourselves when the target image format is not RGB. switch (format) { case kImageFormatRGB: case kImageFormatRGBA: case kImageFormatGrayscale: default: cinfo.out_color_space = JCS_RGB; break; } jpeg_start_decompress(&cinfo); int row_stride = cinfo.output_width * cinfo.output_components; JSAMPARRAY row_buffer = (*cinfo.mem->alloc_sarray)((j_common_ptr)&cinfo, JPOOL_IMAGE, row_stride, 1); int width = cinfo.output_width; int height = cinfo.output_height; int channels = cinfo.output_components; Image<uint8_t> image(width, height, format); if (format == kImageFormatRGB) { // Thanks to the libjpeg-turbo colorspace extensions we can just copy the // decompressed image from the row buffer to the image without performing // any conversion. while (cinfo.output_scanline < cinfo.output_height) { jpeg_read_scanlines(&cinfo, row_buffer, 1); row = row_buffer[0]; memcpy(image.row(cinfo.output_scanline - 1), row, width * channels); } } else if (format == kImageFormatRGBA) { while (cinfo.output_scanline < cinfo.output_height) { jpeg_read_scanlines(&cinfo, row_buffer, 1); JSAMPROW row = row_buffer[0]; uint8_t* dst_row = image.row(cinfo.output_scanline - 1); for (int i = 0; i < width; i++) { dst_row[i * 4 + 0] = *row++; dst_row[i * 4 + 1] = *row++; dst_row[i * 4 + 2] = *row++; dst_row[i * 4 + 3] = 255; } } } else if (format == kImageFormatGrayscale) { // Convert the pixels from RGB to grayscale while copying the decompressed // image from the row buffer to the image. while (cinfo.output_scanline < cinfo.output_height) { jpeg_read_scanlines(&cinfo, row_buffer, 1); JSAMPROW row = row_buffer[0]; uint8_t* dst_row = image.row(cinfo.output_scanline - 1); for (int i = 0; i < width; i++) { int r = *row++; int g = *row++; int b = *row++; int gray = (9798 * r + 19235 * g + 3735 * b) / 32768; dst_row[i] = clamp(gray, 0, 255); } } } jpeg_finish_decompress(&cinfo); jpeg_destroy_decompress(&cinfo); return image; } void JPEGCodec::compress(Image<uint8_t>& image, uint8_t** data, size_t* length, int quality) { jpeg_compress_struct cinfo; jpeg_error_mgr jerr; JSAMPROW row_pointer[1]; cinfo.err = jpeg_std_error(&jerr); jpeg_create_compress(&cinfo); // Heuristic to guess the amount of memory to allocate upfront (we'd like to // avoid reallocating memory). Assume that the JPEG compression ratio is // approximately 10:1, so that the JPEG data should fit inside a buffer 1/10 // the size of the raw pixel data. This assumption falls apart for small // images, so set a minimum size of 64KB. // // TODO: Allow the caller to provide the expected size of the compressed // data so we can avoid over-allocating when using this function as part of // a workload. *length = image.width() * image.height() * image.channels() / 10; *length = std::max(static_cast<size_t>(65536), *length); *data = static_cast<uint8_t*>(malloc(*length)); jpeg_memory_destination(&cinfo, *data, *length); cinfo.image_width = image.width(); cinfo.image_height = image.height(); cinfo.input_components = image.channels(); // We currently only support compressing RGB images to JPEG. switch (image.format()) { case kImageFormatRGB: cinfo.in_color_space = JCS_RGB; break; default: assert(false); break; } jpeg_set_defaults(&cinfo); jpeg_set_quality(&cinfo, quality, TRUE); jpeg_start_compress(&cinfo, TRUE); while(cinfo.next_scanline < cinfo.image_height) { row_pointer[0] = image.row(cinfo.next_scanline); jpeg_write_scanlines(&cinfo, row_pointer, 1); } jpeg_finish_compress(&cinfo); MemoryDestination* dest = reinterpret_cast<MemoryDestination*>(cinfo.dest); *data = dest->data; *length = dest->offset; jpeg_destroy_compress(&cinfo); } } // namespace headless
30.915408
134
0.712792
primatelabs
1d2ad9a8b2c8b8d69a051d12971d181f678bf912
16,284
cc
C++
src/4txn/txn_local.cc
cflaviu/upscaledb
2d9aec05fd5c32e12115eed37695c828faac5472
[ "Apache-2.0" ]
350
2015-11-05T00:49:19.000Z
2022-03-23T16:27:36.000Z
src/4txn/txn_local.cc
veloman-yunkan/upscaledb
80d01b843719d5ca4c6fdfcf474fa0d66cf877e6
[ "Apache-2.0" ]
71
2015-11-05T19:26:57.000Z
2021-08-20T14:52:21.000Z
src/4txn/txn_local.cc
veloman-yunkan/upscaledb
80d01b843719d5ca4c6fdfcf474fa0d66cf877e6
[ "Apache-2.0" ]
55
2015-11-04T15:09:16.000Z
2021-12-23T20:45:24.000Z
/* * Copyright (C) 2005-2017 Christoph Rupp (chris@crupp.de). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * See the file COPYING for License information. */ #include "0root/root.h" // Always verify that a file of level N does not include headers > N! #include "3btree/btree_index.h" #include "3journal/journal.h" #include "4db/db_local.h" #include "4txn/txn_local.h" #include "4txn/txn_factory.h" #include "4txn/txn_cursor.h" #include "4env/env_local.h" #include "4cursor/cursor_local.h" #include "4context/context.h" #ifndef UPS_ROOT_H # error "root.h was not included" #endif namespace upscaledb { // stuff for rb.h #ifndef __ssize_t_defined typedef signed ssize_t; #endif #ifndef __cplusplus typedef int bool; #define true 1 #define false (!true) #endif // __cpluscplus static int compare(void *vlhs, void *vrhs) { TxnNode *lhs = (TxnNode *)vlhs; TxnNode *rhs = (TxnNode *)vrhs; LocalDb *db = lhs->db; if (unlikely(lhs == rhs)) return 0; ups_key_t *lhskey = lhs->key(); ups_key_t *rhskey = rhs->key(); assert(lhskey && rhskey); return db->btree_index->compare_keys(lhskey, rhskey); } rb_proto(static, rbt_, TxnIndex, TxnNode) rb_gen(static, rbt_, TxnIndex, TxnNode, node, compare) static inline int count_flushable_transactions(LocalTxnManager *tm) { int to_flush = 0; LocalTxn *oldest = (LocalTxn *)tm->oldest_txn(); for (; oldest; oldest = (LocalTxn *)oldest->next()) { // a transaction can be flushed if it's committed or aborted, and if there // are no cursors coupled to it if (oldest->is_committed() || oldest->is_aborted()) { for (TxnOperation *op = oldest->oldest_op; op != 0; op = op->next_in_txn) if (unlikely(op->cursor_list != 0)) return to_flush; to_flush++; } else return to_flush; } return to_flush; } static inline void flush_committed_txns_impl(LocalTxnManager *tm, Context *context) { LocalTxn *oldest; uint64_t highest_lsn = 0; assert(context->changeset.is_empty()); // always get the oldest transaction; if it was committed: flush // it; if it was aborted: discard it; otherwise return while ((oldest = (LocalTxn *)tm->oldest_txn())) { if (oldest->is_committed()) { uint64_t lsn = tm->flush_txn_to_changeset(context, (LocalTxn *)oldest); if (lsn > highest_lsn) highest_lsn = lsn; } else if (oldest->is_aborted()) { ; // nop } else break; // now remove the txn from the linked list tm->remove_txn_from_head(oldest); // and release the memory delete oldest; } // now flush the changeset and write the modified pages to disk if (highest_lsn && tm->lenv()->journal.get()) context->changeset.flush(tm->lenv()->lsn_manager.next()); else context->changeset.clear(); assert(context->changeset.is_empty()); } void TxnOperation::initialize(LocalTxn *txn_, TxnNode *node_, uint32_t flags_, uint32_t original_flags_, uint64_t lsn_, ups_key_t *key_, ups_record_t *record_) { ::memset(this, 0, sizeof(*this)); txn = txn_; node = node_; lsn = lsn_; flags = flags_; original_flags = original_flags_; // copy the key data if (key_) { key = *key_; if (likely(key.size)) { key.data = &_data[0]; ::memcpy(key.data, key_->data, key.size); } } // copy the record data if (record_) { record = *record_; if (likely(record.size)) { record.data = &_data[key_ ? key.size : 0]; ::memcpy(record.data, record_->data, record.size); } } } void TxnOperation::destroy() { bool delete_node = false; if (node->newest_op == this) node->newest_op = previous_in_node; // remove this op from the node if (node->oldest_op == this) { // if the node is empty: remove the node from the tree // TODO should this be done in here?? if (next_in_node == 0) { node->db->txn_index->remove(node); delete_node = true; } node->oldest_op = next_in_node; } // remove this operation from the two linked lists if (next_in_node) next_in_node->previous_in_node = previous_in_node; if (previous_in_node) previous_in_node->next_in_node = next_in_node; if (next_in_txn) next_in_txn->previous_in_txn = previous_in_txn; if (previous_in_txn) previous_in_txn->next_in_txn = next_in_txn; if (delete_node) delete node; Memory::release(this); } TxnNode * TxnNode::next_sibling() { return rbt_next(db->txn_index.get(), this); } TxnNode * TxnNode::previous_sibling() { return rbt_prev(db->txn_index.get(), this); } TxnNode::TxnNode(LocalDb *db_, ups_key_t *key) : db(db_), oldest_op(0), newest_op(0), _key(key) { } TxnOperation * TxnNode::append(LocalTxn *txn, uint32_t orig_flags, uint32_t flags, uint64_t lsn, ups_key_t *key, ups_record_t *record) { TxnOperation *op = TxnFactory::create_operation(txn, this, flags, orig_flags, lsn, key, record); // store it in the chronological list which is managed by the node if (!newest_op) { assert(oldest_op == 0); newest_op = op; oldest_op = op; } else { TxnOperation *newest = newest_op; newest->next_in_node = op; op->previous_in_node = newest; newest_op = op; } // store it in the chronological list which is managed by the transaction if (!txn->newest_op) { assert(txn->oldest_op == 0); txn->newest_op = op; txn->oldest_op = op; } else { TxnOperation *newest = txn->newest_op; newest->next_in_txn = op; op->previous_in_txn = newest; txn->newest_op = op; } // now that an operation is attached make sure that the node no // longer uses the temporary key pointer _key = 0; return op; } TxnNode * TxnIndex::store(ups_key_t *key, bool *node_created) { *node_created = false; TxnNode *node = get(key, 0); if (!node) { node = new TxnNode(db, key); *node_created = true; rbt_insert(this, node); } return node; } void TxnIndex::remove(TxnNode *node) { rbt_remove(this, node); } static inline void flush_transaction_to_journal(LocalTxn *txn) { LocalEnv *lenv = (LocalEnv *)txn->env; Journal *journal = lenv->journal.get(); if (unlikely(journal == 0)) return; if (NOTSET(txn->flags, UPS_TXN_TEMPORARY)) journal->append_txn_begin(txn, txn->name.empty() ? 0 : txn->name.c_str(), txn->lsn); for (TxnOperation *op = txn->oldest_op; op != 0; op = op->next_in_txn) { if (ISSET(op->flags, TxnOperation::kErase)) { journal->append_erase(op->node->db, txn, op->node->key(), op->referenced_duplicate, op->original_flags, op->lsn); continue; } if (ISSET(op->flags, TxnOperation::kInsert)) { journal->append_insert(op->node->db, txn, op->node->key(), &op->record, op->original_flags, op->lsn); continue; } if (ISSET(op->flags, TxnOperation::kInsertOverwrite)) { journal->append_insert(op->node->db, txn, op->node->key(), &op->record, op->original_flags | UPS_OVERWRITE, op->lsn); continue; } if (ISSET(op->flags, TxnOperation::kInsertDuplicate)) { journal->append_insert(op->node->db, txn, op->node->key(), &op->record, op->original_flags | UPS_DUPLICATE, op->lsn); continue; } assert(!"shouldn't be here"); } if (NOTSET(txn->flags, UPS_TXN_TEMPORARY)) journal->append_txn_commit(txn, lenv->lsn_manager.next()); } LocalTxn::LocalTxn(LocalEnv *env, const char *name, uint32_t flags) : Txn(env, name, flags), log_descriptor(0), oldest_op(0), newest_op(0) { LocalTxnManager *ltm = (LocalTxnManager *)env->txn_manager.get(); id = ltm->incremented_txn_id(); lsn = env->lsn_manager.next(); } LocalTxn::~LocalTxn() { free_operations(); } void LocalTxn::commit() { // are cursors attached to this txn? if yes, fail if (unlikely(refcounter > 0)) { ups_trace(("Txn cannot be committed till all attached Cursors are closed")); throw Exception(UPS_CURSOR_STILL_OPEN); } // this transaction is now committed! flags |= kStateCommitted; } void LocalTxn::abort() { // are cursors attached to this txn? if yes, fail if (unlikely(refcounter > 0)) { ups_trace(("Txn cannot be aborted till all attached Cursors are closed")); throw Exception(UPS_CURSOR_STILL_OPEN); } // this transaction is now aborted! flags |= kStateAborted; // immediately release memory of the cached operations free_operations(); } void LocalTxn::free_operations() { TxnOperation *n, *op = oldest_op; while (op) { n = op->next_in_txn; TxnFactory::destroy_operation(op); op = n; } oldest_op = 0; newest_op = 0; } TxnIndex::TxnIndex(LocalDb *db) : db(db) { rbt_new(this); } TxnIndex::~TxnIndex() { TxnNode *node; while ((node = rbt_last(this))) { remove(node); delete node; } // re-initialize the tree rbt_new(this); } TxnNode * TxnIndex::get(ups_key_t *key, uint32_t flags) { TxnNode *node = 0; int match = 0; // create a temporary node that we can search for TxnNode tmp(db, key); // search if node already exists - if yes, return it if (ISSET(flags, UPS_FIND_GEQ_MATCH)) { node = rbt_nsearch(this, &tmp); if (node) match = compare(&tmp, node); } else if (ISSET(flags, UPS_FIND_LEQ_MATCH)) { node = rbt_psearch(this, &tmp); if (node) match = compare(&tmp, node); } else if (ISSET(flags, UPS_FIND_GT_MATCH)) { node = rbt_search(this, &tmp); if (node) node = node->next_sibling(); else node = rbt_nsearch(this, &tmp); match = 1; } else if (ISSET(flags, UPS_FIND_LT_MATCH)) { node = rbt_search(this, &tmp); if (node) node = node->previous_sibling(); else node = rbt_psearch(this, &tmp); match = -1; } else return rbt_search(this, &tmp); // Nothing found? if (!node) return 0; // approx. matching: set the key flag if (match < 0) ups_key_set_intflags(key, (ups_key_get_intflags(key) & ~BtreeKey::kApproximate) | BtreeKey::kLower); else if (match > 0) ups_key_set_intflags(key, (ups_key_get_intflags(key) & ~BtreeKey::kApproximate) | BtreeKey::kGreater); return node; } TxnNode * TxnIndex::first() { return rbt_first(this); } TxnNode * TxnIndex::last() { return rbt_last(this); } void TxnIndex::enumerate(Context *context, TxnIndex::Visitor *visitor) { TxnNode *node = rbt_first(this); while (node) { visitor->visit(context, node); node = rbt_next(this, node); } } struct KeyCounter : TxnIndex::Visitor { KeyCounter(LocalDb *_db, LocalTxn *_txn, bool _distinct) : counter(0), distinct(_distinct), txn(_txn), db(_db) { } void visit(Context *context, TxnNode *node) { BtreeIndex *be = db->btree_index.get(); // // look at each tree_node and walk through each operation // in reverse chronological order (from newest to oldest): // - is this op part of an aborted txn? then skip it // - is this op part of a committed txn? then include it // - is this op part of an txn which is still active? then include it // - if a committed txn has erased the item then there's no need // to continue checking older, committed txns of the same key // // !! // if keys are overwritten or a duplicate key is inserted, then // we have to consolidate the btree keys with the txn-tree keys. // for (TxnOperation *op = node->newest_op; op != 0; op = op->previous_in_node) { LocalTxn *optxn = op->txn; if (optxn->is_aborted()) continue; if (optxn->is_committed() || txn == optxn) { if (ISSET(op->flags, TxnOperation::kIsFlushed)) continue; // if key was erased then it doesn't exist if (ISSET(op->flags, TxnOperation::kErase)) { counter--; return; } if (ISSET(op->flags, TxnOperation::kInsert)) { counter++; return; } // key exists - include it if (ISSET(op->flags, TxnOperation::kInsert) || (ISSET(op->flags, TxnOperation::kInsertOverwrite))) { // check if the key already exists in the btree - if yes, // we do not count it (it will be counted later) if (UPS_KEY_NOT_FOUND == be->find(context, 0, node->key(), 0, 0, 0, 0)) counter++; return; } if (ISSET(op->flags, TxnOperation::kInsertDuplicate)) { // check if btree has other duplicates if (0 == be->find(context, 0, node->key(), 0, 0, 0, 0)) { // yes, there's another one if (distinct) return; counter++; } else { // check if other key is in this node counter++; if (distinct) return; } continue; } if (NOTSET(op->flags, TxnOperation::kNop)) { assert(!"shouldn't be here"); return; } } // txn is still active - ignore it } } int64_t counter; bool distinct; LocalTxn *txn; LocalDb *db; }; uint64_t TxnIndex::count(Context *context, LocalTxn *txn, bool distinct) { KeyCounter k(db, txn, distinct); enumerate(context, &k); return k.counter; } void LocalTxnManager::begin(Txn *txn) { append_txn_at_tail(txn); } ups_status_t LocalTxnManager::commit(Txn *htxn) { LocalTxn *txn = dynamic_cast<LocalTxn *>(htxn); Context context(lenv(), txn, 0); try { txn->commit(); // if this transaction can NOT be flushed immediately then write its // operations to the journal; otherwise skip this step flush_transaction_to_journal(txn); // flush committed transactions if (likely(NOTSET(lenv()->flags(), UPS_DONT_FLUSH_TRANSACTIONS))) { if (unlikely(ISSET(lenv()->flags(), UPS_FLUSH_TRANSACTIONS_IMMEDIATELY) || count_flushable_transactions(this) >= Globals::ms_flush_threshold)) { flush_committed_txns_impl(this, &context); return 0; } } } catch (Exception &ex) { return ex.code; } return 0; } ups_status_t LocalTxnManager::abort(Txn *htxn) { LocalTxn *txn = dynamic_cast<LocalTxn *>(htxn); Context context(lenv(), txn, 0); try { txn->abort(); // flush committed transactions if (likely(NOTSET(lenv()->flags(), UPS_DONT_FLUSH_TRANSACTIONS))) { if (unlikely(ISSET(lenv()->flags(), UPS_FLUSH_TRANSACTIONS_IMMEDIATELY) || count_flushable_transactions(this) >= Globals::ms_flush_threshold)) { flush_committed_txns_impl(this, &context); return 0; } } } catch (Exception &ex) { return ex.code; } return 0; } void LocalTxnManager::flush_committed_txns(Context *context /* = 0 */) { if (!context) { Context new_context(lenv(), 0, 0); flush_committed_txns_impl(this, &new_context); } else flush_committed_txns_impl(this, context); } uint64_t LocalTxnManager::flush_txn_to_changeset(Context *context, LocalTxn *txn) { uint64_t highest_lsn = 0; for (TxnOperation *op = txn->oldest_op; op != 0; op = op->next_in_txn) { TxnNode *node = op->node; // perform the actual operation in the btree if (NOTSET(op->flags, TxnOperation::kIsFlushed)) node->db->flush_txn_operation(context, txn, op); assert(op->lsn > highest_lsn); highest_lsn = op->lsn; } return highest_lsn; } } // namespace upscaledb
24.635401
80
0.626873
cflaviu
1d2b2260aeade2b92ec8bf0275380440dedbff4c
12,952
cpp
C++
src/cpp/rtps/writer/StatelessWriter.cpp
nuclearsandwich/fastrtps-debian
c2919b4433b545ca7deb10d8c82cfdfb119b4960
[ "Apache-2.0" ]
3
2017-05-10T11:03:52.000Z
2021-05-27T09:38:00.000Z
src/cpp/rtps/writer/StatelessWriter.cpp
tedostrem/Fast-RTPS
f730847ff84a7980d5cb39bafa0158df73e3acbd
[ "Apache-2.0" ]
null
null
null
src/cpp/rtps/writer/StatelessWriter.cpp
tedostrem/Fast-RTPS
f730847ff84a7980d5cb39bafa0158df73e3acbd
[ "Apache-2.0" ]
null
null
null
// Copyright 2016 Proyectos y Sistemas de Mantenimiento SL (eProsima). // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /* * @file StatelessWriter.cpp * */ #include <fastrtps/rtps/writer/StatelessWriter.h> #include <fastrtps/rtps/history/WriterHistory.h> #include <fastrtps/rtps/resources/AsyncWriterThread.h> #include "../participant/RTPSParticipantImpl.h" #include "../flowcontrol/FlowController.h" #include <mutex> #include <fastrtps/log/Log.h> namespace eprosima { namespace fastrtps{ namespace rtps { StatelessWriter::StatelessWriter(RTPSParticipantImpl* pimpl,GUID_t& guid, WriterAttributes& att,WriterHistory* hist,WriterListener* listen): RTPSWriter(pimpl,guid,att,hist,listen) {} StatelessWriter::~StatelessWriter() { AsyncWriterThread::removeWriter(*this); logInfo(RTPS_WRITER,"StatelessWriter destructor";); } std::vector<GUID_t> StatelessWriter::get_remote_readers() { std::vector<GUID_t> remote_readers; if(this->m_guid.entityId == ENTITYID_SPDP_BUILTIN_RTPSParticipant_WRITER) remote_readers.emplace_back(GuidPrefix_t(), c_EntityId_SPDPReader); #if HAVE_SECURITY else if(this->m_guid.entityId == ENTITYID_P2P_BUILTIN_PARTICIPANT_STATELESS_WRITER) remote_readers.emplace_back(GuidPrefix_t(), participant_stateless_message_reader_entity_id); #endif else for(auto& reader : m_matched_readers) remote_readers.push_back(reader.guid); return remote_readers; } /* * CHANGE-RELATED METHODS */ // TODO(Ricardo) This function only can be used by history. Private it and frined History. // TODO(Ricardo) Look for other functions void StatelessWriter::unsent_change_added_to_history(CacheChange_t* cptr) { std::lock_guard<std::recursive_mutex> guard(*mp_mutex); if(!isAsync()) { this->setLivelinessAsserted(true); // TODO(Ricardo) ReaderLocators should store remote reader GUIDs std::vector<GUID_t> remote_readers = get_remote_readers(); for(auto& reader_locator : reader_locators) { //TODO(Ricardo) Temporal. LocatorList_t locators; locators.push_back(reader_locator.locator); RTPSMessageGroup group(mp_RTPSParticipant, this, RTPSMessageGroup::WRITER, m_cdrmessages); if(!group.add_data(*cptr, remote_readers, locators, false)) { logError(RTPS_WRITER, "Error sending change " << cptr->sequenceNumber); } } } else { for(auto& reader_locator : reader_locators) reader_locator.unsent_changes.push_back(ChangeForReader_t(cptr)); AsyncWriterThread::wakeUp(this); } } bool StatelessWriter::change_removed_by_history(CacheChange_t* change) { std::lock_guard<std::recursive_mutex> guard(*mp_mutex); for(auto& reader_locator : reader_locators) reader_locator.unsent_changes.erase(std::remove_if( reader_locator.unsent_changes.begin(), reader_locator.unsent_changes.end(), [change](ChangeForReader_t& cptr) { return cptr.getChange() == change || cptr.getChange()->sequenceNumber == change->sequenceNumber; }), reader_locator.unsent_changes.end()); return true; } void StatelessWriter::update_unsent_changes(ReaderLocator& reader_locator, const std::vector<CacheChange_t*>& changes) { //TODO(Ricardo) //for (const auto* change : changes) for (auto* change : changes) { auto it = std::find_if(reader_locator.unsent_changes.begin(), reader_locator.unsent_changes.end(), [change](const ChangeForReader_t& unsent_change) { return change == unsent_change.getChange(); }); if (change->getFragmentSize() != 0) { FragmentNumberSet_t fragment_sns = it->getUnsentFragments(); // We remove the ones we are already sending. auto frag_sn_it = fragment_sns.set.begin(); while(frag_sn_it != fragment_sns.set.end()) { if(change->getDataFragments()->at(*frag_sn_it - 1) == PRESENT) { it->markFragmentsAsSent(*frag_sn_it++); } else break; } if (frag_sn_it == fragment_sns.set.end()) reader_locator.unsent_changes.erase(it); } else reader_locator.unsent_changes.erase(it); } } void StatelessWriter::send_any_unsent_changes() { std::lock_guard<std::recursive_mutex> guard(*mp_mutex); std::vector<GUID_t> remote_readers = get_remote_readers(); for(auto& reader_locator : reader_locators) { // Shallow copy the list std::vector<CacheChange_t*> changes_to_send; for(auto cit = reader_locator.unsent_changes.begin() ; cit != reader_locator.unsent_changes.end(); ++cit) { changes_to_send.push_back(cit->getChange()); if(cit->getChange()->getFragmentSize() > 0) { cit->getChange()->getDataFragments()->assign(cit->getChange()->getDataFragments()->size(), NOT_PRESENT); FragmentNumberSet_t frag_sns = cit->getUnsentFragments(); for(auto sn = frag_sns.get_begin(); sn != frag_sns.get_end(); ++sn) { assert(*sn <= cit->getChange()->getDataFragments()->size()); cit->getChange()->getDataFragments()->at(*sn - 1) = PRESENT; } } } // Clear through local controllers for (auto& controller : m_controllers) (*controller)(changes_to_send); // Clear through parent controllers for (auto& controller : mp_RTPSParticipant->getFlowControllers()) (*controller)(changes_to_send); // Remove the messages selected for sending from the original list, // and update those that were fragmented with the new sent index update_unsent_changes(reader_locator, changes_to_send); if(!changes_to_send.empty()) { if(m_pushMode) { RTPSMessageGroup group(mp_RTPSParticipant, this, RTPSMessageGroup::WRITER, m_cdrmessages); for (auto* change : changes_to_send) { // Notify the controllers FlowController::NotifyControllersChangeSent(change); // TODO(Ricardo) Temporal LocatorList_t locators; locators.push_back(reader_locator.locator); if(change->getFragmentSize() != 0) { for(uint32_t fragment = 0; fragment < change->getDataFragments()->size(); ++fragment) { if(change->getDataFragments()->at(fragment) == PRESENT) { //TODO(Ricardo) Frag = 0 if(!group.add_data_frag(*change, fragment + 1, remote_readers, locators, false)) { logError(RTPS_WRITER, "Error sending fragment (" << change->sequenceNumber << ", " << fragment + 1 << ")"); } } } } else { if(!group.add_data(*change, remote_readers, locators, false)) { logError(RTPS_WRITER, "Error sending change " << change->sequenceNumber); } } } } } } logInfo(RTPS_WRITER, "Finish sending unsent changes";); } /* * MATCHED_READER-RELATED METHODS */ bool StatelessWriter::matched_reader_add(RemoteReaderAttributes& rdata) { std::lock_guard<std::recursive_mutex> guard(*mp_mutex); if(rdata.guid != c_Guid_Unknown) { for(auto it=m_matched_readers.begin();it!=m_matched_readers.end();++it) { if((*it).guid == rdata.guid) { logWarning(RTPS_WRITER, "Attempting to add existing reader"); return false; } } } bool send_any_unsent_changes = false; for(std::vector<Locator_t>::iterator lit = rdata.endpoint.unicastLocatorList.begin(); lit!=rdata.endpoint.unicastLocatorList.end();++lit) { send_any_unsent_changes |= add_locator(rdata,*lit); } for(std::vector<Locator_t>::iterator lit = rdata.endpoint.multicastLocatorList.begin(); lit!=rdata.endpoint.multicastLocatorList.end();++lit) { send_any_unsent_changes |= add_locator(rdata,*lit); } this->m_matched_readers.push_back(rdata); logInfo(RTPS_READER,"Reader " << rdata.guid << " added to "<<m_guid.entityId); return true; } bool StatelessWriter::add_locator(RemoteReaderAttributes& rdata,Locator_t& loc) { logInfo(RTPS_WRITER, "Adding Locator: " << loc << " to StatelessWriter";); auto rit = std::find_if(reader_locators.rbegin(), reader_locators.rend(), [loc](const ReaderLocator& reader_locator) { if(reader_locator.locator == loc) return true; return false; }); if(rit != reader_locators.rend()) { ++rit->n_used; } else { ReaderLocator rl; rl.expectsInlineQos = rdata.expectsInlineQos; rl.locator = loc; reader_locators.push_back(rl); rit = reader_locators.rbegin(); } if(rdata.endpoint.durabilityKind >= TRANSIENT_LOCAL) { rit->unsent_changes.assign(mp_history->changesBegin(), mp_history->changesEnd()); AsyncWriterThread::wakeUp(this); } return true; } bool StatelessWriter::matched_reader_remove(RemoteReaderAttributes& rdata) { std::lock_guard<std::recursive_mutex> guard(*mp_mutex); bool found = false; if(rdata.guid == c_Guid_Unknown) found = true; else { for(auto rit = m_matched_readers.begin(); rit!=m_matched_readers.end();++rit) { if((*rit).guid == rdata.guid) { found = true; m_matched_readers.erase(rit); break; } } } if(found) { logInfo(RTPS_WRITER, "Reader Proxy removed: " << rdata.guid;); for(std::vector<Locator_t>::iterator lit = rdata.endpoint.unicastLocatorList.begin(); lit!=rdata.endpoint.unicastLocatorList.end();++lit) { remove_locator(*lit); } for(std::vector<Locator_t>::iterator lit = rdata.endpoint.multicastLocatorList.begin(); lit!=rdata.endpoint.multicastLocatorList.end();++lit) { remove_locator(*lit); } return true; } return false; } bool StatelessWriter::matched_reader_is_matched(RemoteReaderAttributes& rdata) { std::lock_guard<std::recursive_mutex> guard(*mp_mutex); for(auto rit = m_matched_readers.begin(); rit!=m_matched_readers.end();++rit) { if((*rit).guid == rdata.guid) { return true; } } return false; } bool StatelessWriter::remove_locator(Locator_t& loc) { for(auto rit = reader_locators.begin(); rit != reader_locators.end(); ++rit) { if(rit->locator == loc) { rit->n_used--; if(rit->n_used == 0) { reader_locators.erase(rit); } break; } } return true; } void StatelessWriter::unsent_changes_reset() { std::lock_guard<std::recursive_mutex> guard(*mp_mutex); for(auto& reader_locator : reader_locators) reader_locator.unsent_changes.assign(mp_history->changesBegin(), mp_history->changesEnd()); AsyncWriterThread::wakeUp(this); } void StatelessWriter::add_flow_controller(std::unique_ptr<FlowController> controller) { m_controllers.push_back(std::move(controller)); } } /* namespace rtps */ } /* namespace eprosima */ }
31.980247
113
0.592187
nuclearsandwich
1d2d18c955ae182cd871b346a3b9741534a546df
5,621
hpp
C++
msvc/3rdparty/ade/ade-0.1.1d/sources/ade/include/ade/typed_metadata.hpp
gajgeospatial/opencv-4.1.0
4b6cf76e12e846bc7fb5dbdce0054faca6963229
[ "BSD-3-Clause" ]
45
2018-07-17T16:38:43.000Z
2022-02-10T10:46:00.000Z
msvc/3rdparty/ade/ade-0.1.1d/sources/ade/include/ade/typed_metadata.hpp
gajgeospatial/opencv-4.1.0
4b6cf76e12e846bc7fb5dbdce0054faca6963229
[ "BSD-3-Clause" ]
11
2018-10-15T10:11:01.000Z
2021-07-30T18:53:41.000Z
msvc/3rdparty/ade/ade-0.1.1d/sources/ade/include/ade/typed_metadata.hpp
gajgeospatial/opencv-4.1.0
4b6cf76e12e846bc7fb5dbdce0054faca6963229
[ "BSD-3-Clause" ]
41
2018-07-26T01:43:35.000Z
2022-03-26T20:33:33.000Z
// Copyright (C) 2018 Intel Corporation // // // SPDX-License-Identifier: Apache-2.0 // /// @file typed_metadata.hpp #ifndef ADE_TYPED_METADATA_HPP #define ADE_TYPED_METADATA_HPP #include <array> #include <memory> #include <type_traits> #include <unordered_map> #include "ade/util/algorithm.hpp" #include "ade/util/range.hpp" namespace ade { class Graph; namespace details { class Metadata; class MetadataId final { friend class ::ade::Graph; friend class ::ade::details::Metadata; MetadataId(void* id); void* m_id = nullptr; public: MetadataId() = default; MetadataId(std::nullptr_t) {} MetadataId(const MetadataId&) = default; MetadataId& operator=(const MetadataId&) = default; MetadataId& operator=(std::nullptr_t) { m_id = nullptr; return *this; } bool operator==(const MetadataId& other) const; bool operator!=(const MetadataId& other) const; bool isNull() const; }; bool operator==(std::nullptr_t, const MetadataId& other); bool operator==(const MetadataId& other, std::nullptr_t); bool operator!=(std::nullptr_t, const MetadataId& other); bool operator!=(const MetadataId& other, std::nullptr_t); class Metadata final { struct IdHash final { std::size_t operator()(const MetadataId& id) const; }; struct MetadataHolderBase; using MetadataHolderPtr = std::unique_ptr<MetadataHolderBase>; struct MetadataHolderBase { virtual ~MetadataHolderBase() = default; virtual MetadataHolderPtr clone() const = 0; }; template<typename T> struct MetadataHolder : public MetadataHolderBase { T data; MetadataHolder(const MetadataHolder&) = default; MetadataHolder(MetadataHolder&&) = default; template<typename T1> MetadataHolder(T1&& val): data(std::forward<T1>(val)) {} MetadataHolder& operator=(const MetadataHolder&) = delete; virtual MetadataHolderPtr clone() const override { return MetadataHolderPtr(new MetadataHolder<T>(*this)); } }; template<typename T> static T& access(MetadataHolderBase& holder) { using DT = typename std::decay<T>::type; #if defined(__GXX_RTTI) || defined(_CPPRTTI) ADE_ASSERT(nullptr != dynamic_cast<MetadataHolder<DT>*>(&holder)); #endif return static_cast<MetadataHolder<DT>*>(&holder)->data; } template<typename T> static const T& access(const MetadataHolderBase& holder) { using DT = typename std::decay<T>::type; #if defined(__GXX_RTTI) || defined(_CPPRTTI) ADE_ASSERT(nullptr != dynamic_cast<const MetadataHolder<DT>*>(&holder)); #endif return static_cast<const MetadataHolder<DT>*>(&holder)->data; } template<typename T> static MetadataHolderPtr createHolder(T&& val) { using DT = typename std::decay<T>::type; return MetadataHolderPtr(new MetadataHolder<DT>{std::forward<T>(val)}); } public: using MetadataStore = std::unordered_map<MetadataId, MetadataHolderPtr, IdHash>; Metadata() = default; Metadata(const Metadata&) = delete ; Metadata& operator=(const Metadata&) = delete; Metadata(Metadata&&) = default; Metadata& operator=(Metadata&&) = default; bool contains(const MetadataId& id) const; void erase(const MetadataId& id); template<typename T> void set(const MetadataId& id, T&& val) { ADE_ASSERT(nullptr != id); m_data.erase(id); m_data.emplace(id, createHolder(std::forward<T>(val))); } template<typename T> T& get(const MetadataId& id) { ADE_ASSERT(nullptr != id); ADE_ASSERT(contains(id)); return access<T>(*(m_data.find(id)->second)); } template<typename T> const T& get(const MetadataId& id) const { ADE_ASSERT(nullptr != id); ADE_ASSERT(contains(id)); return access<T>(*(m_data.find(id)->second)); } private: MetadataStore m_data; }; } template<bool IsConst, typename... Types> class TypedMetadata { using IdArray = std::array<ade::details::MetadataId, sizeof...(Types)>; using MetadataT = typename std::conditional<IsConst, const ade::details::Metadata&, ade::details::Metadata&>::type; const IdArray& m_ids; MetadataT m_metadata; template<typename T> ade::details::MetadataId getId() const { const auto index = util::type_list_index<typename std::decay<T>::type, Types...>::value; return m_ids[index]; } public: TypedMetadata(const IdArray& ids, MetadataT meta): m_ids(ids), m_metadata(meta) {} TypedMetadata(const TypedMetadata& other): m_ids(other.m_ids), m_metadata(other.m_metadata) {} TypedMetadata& operator=(const TypedMetadata&) = delete; template<bool, typename...> friend class TypedMetadata; template<typename T> bool contains() const { return m_metadata.contains(getId<T>()); } template<typename T> void erase() { m_metadata.erase(getId<T>()); } template<typename T> void set(T&& val) { m_metadata.set(getId<T>(), std::forward<T>(val)); } template<typename T> auto get() const ->typename std::conditional<IsConst, const T&, T&>::type { return m_metadata.template get<T>(getId<T>()); } template<typename T> T get(T&& def) const { if (contains<T>()) { return m_metadata.template get<T>(getId<T>()); } else { return std::forward<T>(def); } } }; } #endif // ADE_TYPED_METADATA_HPP
24.982222
119
0.642946
gajgeospatial
1d2d72f6e0343e754981f03119ee091631eba3cd
269
cpp
C++
shared/scene.cpp
industry-advance/nin10kit
dbf81c62c0fa2f544cfd22b1f7d008a885c2b589
[ "Apache-2.0" ]
45
2015-03-26T17:14:55.000Z
2022-03-29T20:27:32.000Z
shared/scene.cpp
industry-advance/nin10kit
dbf81c62c0fa2f544cfd22b1f7d008a885c2b589
[ "Apache-2.0" ]
35
2015-01-06T16:16:37.000Z
2021-06-19T05:03:13.000Z
shared/scene.cpp
industry-advance/nin10kit
dbf81c62c0fa2f544cfd22b1f7d008a885c2b589
[ "Apache-2.0" ]
5
2017-03-26T04:48:02.000Z
2020-07-10T22:55:49.000Z
#include "scene.hpp" void Scene::WriteData(std::ostream& file) const { for (const auto& image : images) image->WriteData(file); } void Scene::WriteExport(std::ostream& file) const { for (const auto& image : images) image->WriteExport(file); }
19.214286
49
0.650558
industry-advance
1d2f0fce6e5ff379b5038ce73c4eb0149c51bfb7
6,601
cpp
C++
tests/main.cpp
lukka/yagbe
8f66d55f455e8a13db84cd521eabb498a1165f44
[ "MIT" ]
1
2018-06-10T14:45:53.000Z
2018-06-10T14:45:53.000Z
tests/main.cpp
Kaosumaru/yagbe
13a2dea9dd50ae4b548bec3704fdc88c2a48d956
[ "MIT" ]
1
2020-02-16T02:50:36.000Z
2020-02-24T20:50:38.000Z
tests/main.cpp
lukka/yagbe
8f66d55f455e8a13db84cd521eabb498a1165f44
[ "MIT" ]
1
2020-02-16T00:36:38.000Z
2020-02-16T00:36:38.000Z
#include <iostream> #include <stdexcept> #include "vm/context.hpp" #include "vm/instructions.hpp" #include "vm/instructions_map.hpp" #ifndef _MSC_VER #define lest_FEATURE_COLOURISE 1 #endif #include "lest.hpp" using namespace std; using namespace yagbe; using namespace yagbe::instructions; using namespace yagbe::instructions::automap; bool test_opus5() { std::string path = YAGBE_ROMS; path += "../test_roms/opus5.gb"; context c; if (!c.load_rom(path)) return false; int steps = 100; for (int i = 0; i < steps; i++) { c.cpu_step(); //endian... if (c.registers.pc == 0x017E) break; } if (c.registers.pc != 0x017E) return false; bool s = true; auto m = [&](uint16_t a) { return c.memory.raw_at(a); }; s &= m(0xFFFF) == 0x01; s &= m(0xFF41) == 0x00; s &= m(0xFF40) == 0x00; s &= m(0xFF43) == 0x10; s &= m(0xC1C9) == 0x10; s &= m(0xE1C9) == 0x10; //shadow RAM s &= m(0xC1CC) == 0x10; s &= m(0xE1CC) == 0x10; s &= m(0xFF42) == 0x08; s &= m(0xC1CB) == 0x08; s &= m(0xE1CB) == 0x08; s &= m(0xC1CD) == 0x08; s &= m(0xE1CD) == 0x08; s &= m(0xC1C8) == 0x00; s &= m(0xE1C8) == 0x00; s &= m(0xC1CA) == 0x00; s &= m(0xE1CA) == 0x00; s &= m(0xC0A0) == 0x00; s &= m(0xE0A0) == 0x00; //endian... s &= c.registers.bc == 0x4000; return true; } const lest::test specification[] = { CASE("01-special-5") { context ctx; ctx.registers.bc = 0x1200; do { PUSH<BC>::execute(ctx); static_assert(&(instruction<0xC5>::execute) == &(PUSH<BC>::execute), "Wrong mapping"); POP<AF>::execute(ctx); static_assert(&(instruction<0xF1>::execute) == &(POP<AF>::execute), "Wrong mapping"); PUSH<AF>::execute(ctx); static_assert(&(instruction<0xF5>::execute) == &(PUSH<AF>::execute), "Wrong mapping"); POP<DE>::execute(ctx); static_assert(&(instruction<0xD1>::execute) == &(POP<DE>::execute), "Wrong mapping"); LD<A, C>::execute(ctx); static_assert(&(instruction<0x79>::execute) == &(LD<A, C>::execute), "Wrong mapping"); ctx.registers.a &= 0xF0; CP<E>::execute(ctx); static_assert(&(instruction<0xBB>::execute) == &(CP<E>::execute), "Wrong mapping"); bool condition = (bool)ctx.flags.z == true; EXPECT(condition); INC<B>::execute(ctx); INC<C>::execute(ctx); } while (!ctx.flags.z); }, CASE("ROM") { context ctx; ctx.memory.raw_at(0) = 1; ctx.memory.at(0) = 2; EXPECT(ctx.memory.at(0) == 1); }, CASE("SHADOW RAM") { context ctx; for (uint16_t i = 0xC000; i <= 0xDFFF; i++) ctx.memory.at(i) = i % 256; for (uint16_t i = 0xE000; i <= 0xFDFF; i++) EXPECT(ctx.memory.read_at(i) == ctx.memory.read_at(i - 0x2000)); }, CASE("OPUS5") { EXPECT(test_opus5()); }, CASE("INC") { context ctx; { ctx.registers.b = 1; ctx.registers.c = 2; using inc_bc = INC<BC>; inc_bc::execute(ctx); EXPECT(ctx.registers.b == 1); EXPECT(ctx.registers.c == 3); } }, CASE("LD") { context ctx; //LD B,A { ctx.registers.a = 1; ctx.registers.b = 2; using ld_b_a = LD<B, A>; ld_b_a::execute(ctx); EXPECT(ctx.registers.b == 1); EXPECT(ctx.registers.b == ctx.registers.a); EXPECT(ld_b_a::size() == 1); EXPECT(ld_b_a::cycles() == 4); } //LD B,(HL) { using ld_b_hl = LD<B, HL_pointer>; EXPECT(ld_b_hl::cycles() == 8); } //LD BC,d16 { using ld_bc_d16 = LD<BC, d16>; ctx.registers.pc = 0; ctx.memory.raw_at(0) = 6; ctx.memory.raw_at(1) = 0; ld_bc_d16::execute(ctx); EXPECT(ctx.registers.bc == 6); EXPECT(ld_bc_d16::cycles() == 12); } //LD (HLI)/(HLD),A { using ld_hli_a = LD<HLI, A>; using ld_hld_a = LD<HLD, A>; ctx.memory.raw_at(0xC000) = 6; ctx.memory.raw_at(0xC001) = 6; ctx.registers.a = 5; ctx.registers.hl = 0xC000; ld_hli_a::execute(ctx); EXPECT(ctx.registers.hl == 0xC001); EXPECT(ctx.memory.at(0xC000) == 5); EXPECT(ctx.memory.at(0xE000) == 5); //shadow ctx.registers.a = 1; ld_hld_a::execute(ctx); EXPECT(ctx.registers.hl == 0xC000); EXPECT(ctx.memory.at(0xC001) == 1); EXPECT(ctx.memory.at(0xE001) == 1); //shadow EXPECT(ld_hli_a::cycles() == 8); EXPECT(ld_hld_a::cycles() == 8); } //LD<HL, SP_p_r8> //TODO seems like this sets h & c - good test case }, CASE("JP") { context ctx; //JP d16 { using jp_d16 = JP<condition::_, d16>; ctx.registers.pc = 0; ctx.memory.raw_at(0) = 6; ctx.memory.raw_at(1) = 0; auto cycles = jp_d16::execute(ctx); EXPECT(ctx.registers.pc == 6); EXPECT(cycles == 16); } //JP (HL) { using jp_HL = JP<condition::_, HL>; ctx.registers.pc = 0; ctx.registers.hl = 6; auto cycles = jp_HL::execute(ctx); EXPECT(ctx.registers.pc == 6); EXPECT(cycles == 4); } //JP NC,d16 { using JP_NC_HL = instructions::JP<condition::NC, d16>; { ctx.registers.pc = 0; ctx.memory.raw_at(0) = 6; ctx.memory.raw_at(1) = 0; ctx.flags.c = 1; auto cycles = JP_NC_HL::execute(ctx); EXPECT(ctx.registers.pc == 2); EXPECT(cycles == 12); } { ctx.registers.pc = 0; ctx.memory.raw_at(0) = 6; ctx.memory.raw_at(1) = 0; ctx.flags.c = 0; auto cycles = JP_NC_HL::execute(ctx); EXPECT(ctx.registers.pc == 6); EXPECT(cycles == 16); } } //JP NZ,d16 { using JP_NZ_HL = instructions::JP<condition::NZ, d16>; { ctx.registers.pc = 0; ctx.memory.raw_at(0) = 6; ctx.memory.raw_at(1) = 0; ctx.flags.z = 1; auto cycles = JP_NZ_HL::execute(ctx); EXPECT(ctx.registers.pc == 2); EXPECT(cycles == 12); } { ctx.registers.pc = 0; ctx.memory.raw_at(0) = 6; ctx.memory.raw_at(1) = 0; ctx.flags.z = 0; auto cycles = JP_NZ_HL::execute(ctx); EXPECT(ctx.registers.pc == 6); EXPECT(cycles == 16); } } }, CASE("JR") { context ctx; //JR r8 { using JR_D8 = JR<condition::_, r8>; ctx.registers.pc = 0; ctx.memory.raw_at(0) = 6; auto cycles = JR_D8::execute(ctx); EXPECT(ctx.registers.pc == 7); EXPECT(cycles == 12); } //JR NC,r8 { using JR_NC_D8 = instructions::JR<condition::NC, r8>; { ctx.registers.pc = 0; ctx.memory.raw_at(0) = 6; ctx.flags.c = 1; auto cycles = JR_NC_D8::execute(ctx); EXPECT(ctx.registers.pc == 1); EXPECT(cycles == 8); } { ctx.registers.pc = 0; ctx.memory.raw_at(0) = 6; ctx.flags.c = 0; auto cycles = JR_NC_D8::execute(ctx); EXPECT(ctx.registers.pc == 7); EXPECT(cycles == 12); } } } }; int main (int argc, char * argv[]) { return lest::run(specification, argc, argv); }
18.542135
118
0.5787
lukka
1d2f2bd273e73a4c30b092cfa355c46524fe6188
22,414
cc
C++
chromeos/dbus/power_manager_client_unittest.cc
google-ar/chromium
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
777
2017-08-29T15:15:32.000Z
2022-03-21T05:29:41.000Z
chromeos/dbus/power_manager_client_unittest.cc
harrymarkovskiy/WebARonARCore
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
66
2017-08-30T18:31:18.000Z
2021-08-02T10:59:35.000Z
chromeos/dbus/power_manager_client_unittest.cc
harrymarkovskiy/WebARonARCore
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
123
2017-08-30T01:19:34.000Z
2022-03-17T22:55:31.000Z
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chromeos/dbus/power_manager_client.h" #include <map> #include <string> #include "base/bind.h" #include "base/macros.h" #include "base/memory/ref_counted.h" #include "base/memory/weak_ptr.h" #include "base/message_loop/message_loop.h" #include "base/run_loop.h" #include "chromeos/dbus/power_manager/suspend.pb.h" #include "dbus/mock_bus.h" #include "dbus/mock_object_proxy.h" #include "dbus/object_path.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/cros_system_api/dbus/service_constants.h" using ::testing::_; using ::testing::Return; using ::testing::SaveArg; namespace chromeos { namespace { // Shorthand for a few commonly-used constants. const char* kInterface = power_manager::kPowerManagerInterface; const char* kSuspendImminent = power_manager::kSuspendImminentSignal; const char* kDarkSuspendImminent = power_manager::kDarkSuspendImminentSignal; const char* kHandleSuspendReadiness = power_manager::kHandleSuspendReadinessMethod; const char* kHandleDarkSuspendReadiness = power_manager::kHandleDarkSuspendReadinessMethod; // Matcher that verifies that a dbus::Message has member |name|. MATCHER_P(HasMember, name, "") { if (arg->GetMember() != name) { *result_listener << "has member " << arg->GetMember(); return false; } return true; } // Matcher that verifies that a dbus::MethodCall has member |method_name| and // contains a SuspendReadinessInfo protobuf referring to |suspend_id| and // |delay_id|. MATCHER_P3(IsSuspendReadiness, method_name, suspend_id, delay_id, "") { if (arg->GetMember() != method_name) { *result_listener << "has member " << arg->GetMember(); return false; } power_manager::SuspendReadinessInfo proto; if (!dbus::MessageReader(arg).PopArrayOfBytesAsProto(&proto)) { *result_listener << "does not contain SuspendReadinessInfo protobuf"; return false; } if (proto.suspend_id() != suspend_id) { *result_listener << "suspend ID is " << proto.suspend_id(); return false; } if (proto.delay_id() != delay_id) { *result_listener << "delay ID is " << proto.delay_id(); return false; } return true; } // Runs |callback| with |response|. Needed due to ResponseCallback expecting a // bare pointer rather than an std::unique_ptr. void RunResponseCallback(dbus::ObjectProxy::ResponseCallback callback, std::unique_ptr<dbus::Response> response) { callback.Run(response.get()); } // Stub implementation of PowerManagerClient::Observer. class TestObserver : public PowerManagerClient::Observer { public: explicit TestObserver(PowerManagerClient* client) : client_(client) { client_->AddObserver(this); } ~TestObserver() override { client_->RemoveObserver(this); } int num_suspend_imminent() const { return num_suspend_imminent_; } int num_suspend_done() const { return num_suspend_done_; } int num_dark_suspend_imminent() const { return num_dark_suspend_imminent_; } base::Closure suspend_readiness_callback() const { return suspend_readiness_callback_; } void set_take_suspend_readiness_callback(bool take_callback) { take_suspend_readiness_callback_ = take_callback; } void set_run_suspend_readiness_callback_immediately(bool run) { run_suspend_readiness_callback_immediately_ = run; } // Runs |suspend_readiness_callback_|. bool RunSuspendReadinessCallback() WARN_UNUSED_RESULT { if (suspend_readiness_callback_.is_null()) return false; auto cb = suspend_readiness_callback_; suspend_readiness_callback_.Reset(); cb.Run(); return true; } // PowerManagerClient::Observer: void SuspendImminent() override { num_suspend_imminent_++; if (take_suspend_readiness_callback_) suspend_readiness_callback_ = client_->GetSuspendReadinessCallback(); if (run_suspend_readiness_callback_immediately_) CHECK(RunSuspendReadinessCallback()); } void SuspendDone(const base::TimeDelta& sleep_duration) override { num_suspend_done_++; } void DarkSuspendImminent() override { num_dark_suspend_imminent_++; if (take_suspend_readiness_callback_) suspend_readiness_callback_ = client_->GetSuspendReadinessCallback(); if (run_suspend_readiness_callback_immediately_) CHECK(RunSuspendReadinessCallback()); } private: PowerManagerClient* client_; // Not owned. // Number of times SuspendImminent(), SuspendDone(), and DarkSuspendImminent() // have been called. int num_suspend_imminent_ = 0; int num_suspend_done_ = 0; int num_dark_suspend_imminent_ = 0; // Should SuspendImminent() and DarkSuspendImminent() call |client_|'s // GetSuspendReadinessCallback() method? bool take_suspend_readiness_callback_ = false; // Should SuspendImminent() and DarkSuspendImminent() run the suspend // readiness callback synchronously after taking it? Only has an effect if // |take_suspend_readiness_callback_| is true. bool run_suspend_readiness_callback_immediately_ = false; // Callback returned by |client_|'s GetSuspendReadinessCallback() method. base::Closure suspend_readiness_callback_; DISALLOW_COPY_AND_ASSIGN(TestObserver); }; // Stub implementation of PowerManagerClient::RenderProcessManagerDelegate. class TestDelegate : public PowerManagerClient::RenderProcessManagerDelegate { public: explicit TestDelegate(PowerManagerClient* client) : weak_ptr_factory_(this) { client->SetRenderProcessManagerDelegate(weak_ptr_factory_.GetWeakPtr()); } ~TestDelegate() override {} int num_suspend_imminent() const { return num_suspend_imminent_; } int num_suspend_done() const { return num_suspend_done_; } // PowerManagerClient::RenderProcessManagerDelegate: void SuspendImminent() override { num_suspend_imminent_++; } void SuspendDone() override { num_suspend_done_++; } private: // Number of times SuspendImminent() and SuspendDone() have been called. int num_suspend_imminent_ = 0; int num_suspend_done_ = 0; base::WeakPtrFactory<TestDelegate> weak_ptr_factory_; DISALLOW_COPY_AND_ASSIGN(TestDelegate); }; } // namespace class PowerManagerClientTest : public testing::Test { public: PowerManagerClientTest() {} ~PowerManagerClientTest() override {} void SetUp() override { dbus::Bus::Options options; options.bus_type = dbus::Bus::SYSTEM; bus_ = new dbus::MockBus(options); proxy_ = new dbus::MockObjectProxy( bus_.get(), power_manager::kPowerManagerServiceName, dbus::ObjectPath(power_manager::kPowerManagerServicePath)); // |client_|'s Init() method should request a proxy for communicating with // powerd. EXPECT_CALL(*bus_.get(), GetObjectProxy( power_manager::kPowerManagerServiceName, dbus::ObjectPath(power_manager::kPowerManagerServicePath))) .WillRepeatedly(Return(proxy_.get())); // Save |client_|'s signal and name-owner-changed callbacks. EXPECT_CALL(*proxy_.get(), ConnectToSignal(kInterface, _, _, _)) .WillRepeatedly(Invoke(this, &PowerManagerClientTest::ConnectToSignal)); EXPECT_CALL(*proxy_.get(), SetNameOwnerChangedCallback(_)) .WillRepeatedly(SaveArg<0>(&name_owner_changed_callback_)); // |client_|'s Init() method should register regular and dark suspend // delays. EXPECT_CALL( *proxy_.get(), CallMethod(HasMember(power_manager::kRegisterSuspendDelayMethod), _, _)) .WillRepeatedly( Invoke(this, &PowerManagerClientTest::RegisterSuspendDelay)); EXPECT_CALL( *proxy_.get(), CallMethod(HasMember(power_manager::kRegisterDarkSuspendDelayMethod), _, _)) .WillRepeatedly( Invoke(this, &PowerManagerClientTest::RegisterSuspendDelay)); client_.reset(PowerManagerClient::Create(REAL_DBUS_CLIENT_IMPLEMENTATION)); client_->Init(bus_.get()); // Execute callbacks posted by Init(). base::RunLoop().RunUntilIdle(); } void TearDown() override { client_.reset(); } protected: // Synchronously passes |signal| to |client_|'s handler, simulating the signal // being emitted by powerd. void EmitSignal(dbus::Signal* signal) { const std::string signal_name = signal->GetMember(); const auto it = signal_callbacks_.find(signal_name); ASSERT_TRUE(it != signal_callbacks_.end()) << "Client didn't register for signal " << signal_name; it->second.Run(signal); } // Passes a SuspendImminent or DarkSuspendImminent signal to |client_|. void EmitSuspendImminentSignal(const std::string& signal_name, int suspend_id) { power_manager::SuspendImminent proto; proto.set_suspend_id(suspend_id); dbus::Signal signal(kInterface, signal_name); dbus::MessageWriter(&signal).AppendProtoAsArrayOfBytes(proto); EmitSignal(&signal); } // Passes a SuspendDone signal to |client_|. void EmitSuspendDoneSignal(int suspend_id) { power_manager::SuspendDone proto; proto.set_suspend_id(suspend_id); dbus::Signal signal(kInterface, power_manager::kSuspendDoneSignal); dbus::MessageWriter(&signal).AppendProtoAsArrayOfBytes(proto); EmitSignal(&signal); } // Adds an expectation to |proxy_| for a HandleSuspendReadiness or // HandleDarkSuspendReadiness method call. void ExpectSuspendReadiness(const std::string& method_name, int suspend_id, int delay_id) { EXPECT_CALL( *proxy_.get(), CallMethod(IsSuspendReadiness(method_name, suspend_id, delay_id), _, _)); } // Arbitrary delay IDs returned to |client_|. static const int kSuspendDelayId = 100; static const int kDarkSuspendDelayId = 200; base::MessageLoop message_loop_; // Mock bus and proxy for simulating calls to powerd. scoped_refptr<dbus::MockBus> bus_; scoped_refptr<dbus::MockObjectProxy> proxy_; std::unique_ptr<PowerManagerClient> client_; // Maps from powerd signal name to the corresponding callback provided by // |client_|. std::map<std::string, dbus::ObjectProxy::SignalCallback> signal_callbacks_; // Callback passed to |proxy_|'s SetNameOwnerChangedCallback() method. // TODO(derat): Test that |client_| handles powerd restarts. dbus::ObjectProxy::NameOwnerChangedCallback name_owner_changed_callback_; private: // Handles calls to |proxy_|'s ConnectToSignal() method. void ConnectToSignal( const std::string& interface_name, const std::string& signal_name, dbus::ObjectProxy::SignalCallback signal_callback, dbus::ObjectProxy::OnConnectedCallback on_connected_callback) { CHECK_EQ(interface_name, power_manager::kPowerManagerInterface); signal_callbacks_[signal_name] = signal_callback; message_loop_.task_runner()->PostTask( FROM_HERE, base::Bind(on_connected_callback, interface_name, signal_name, true /* success */)); } // Handles calls to |proxy_|'s CallMethod() method to register suspend delays. void RegisterSuspendDelay(dbus::MethodCall* method_call, int timeout_ms, dbus::ObjectProxy::ResponseCallback callback) { power_manager::RegisterSuspendDelayReply proto; proto.set_delay_id(method_call->GetMember() == power_manager::kRegisterDarkSuspendDelayMethod ? kDarkSuspendDelayId : kSuspendDelayId); method_call->SetSerial(123); // Arbitrary but needed by FromMethodCall(). std::unique_ptr<dbus::Response> response( dbus::Response::FromMethodCall(method_call)); CHECK(dbus::MessageWriter(response.get()).AppendProtoAsArrayOfBytes(proto)); message_loop_.task_runner()->PostTask( FROM_HERE, base::Bind(&RunResponseCallback, callback, base::Passed(&response))); } DISALLOW_COPY_AND_ASSIGN(PowerManagerClientTest); }; // Tests that suspend readiness is reported immediately when there are no // observers. TEST_F(PowerManagerClientTest, ReportSuspendReadinessWithoutObservers) { const int kSuspendId = 1; ExpectSuspendReadiness(kHandleSuspendReadiness, kSuspendId, kSuspendDelayId); EmitSuspendImminentSignal(kSuspendImminent, kSuspendId); EmitSuspendDoneSignal(kSuspendId); } // Tests that synchronous observers are notified about impending suspend // attempts and completion. TEST_F(PowerManagerClientTest, ReportSuspendReadinessWithoutCallbacks) { TestObserver observer_1(client_.get()); TestObserver observer_2(client_.get()); // Observers should be notified when suspend is imminent. Readiness should be // reported synchronously since GetSuspendReadinessCallback() hasn't been // called. const int kSuspendId = 1; ExpectSuspendReadiness(kHandleSuspendReadiness, kSuspendId, kSuspendDelayId); EmitSuspendImminentSignal(kSuspendImminent, kSuspendId); EXPECT_EQ(1, observer_1.num_suspend_imminent()); EXPECT_EQ(0, observer_1.num_suspend_done()); EXPECT_EQ(1, observer_2.num_suspend_imminent()); EXPECT_EQ(0, observer_2.num_suspend_done()); EmitSuspendDoneSignal(kSuspendId); EXPECT_EQ(1, observer_1.num_suspend_imminent()); EXPECT_EQ(1, observer_1.num_suspend_done()); EXPECT_EQ(1, observer_2.num_suspend_imminent()); EXPECT_EQ(1, observer_2.num_suspend_done()); } // Tests that readiness is deferred until asynchronous observers have run their // callbacks. TEST_F(PowerManagerClientTest, ReportSuspendReadinessWithCallbacks) { TestObserver observer_1(client_.get()); observer_1.set_take_suspend_readiness_callback(true); TestObserver observer_2(client_.get()); observer_2.set_take_suspend_readiness_callback(true); TestObserver observer_3(client_.get()); // When observers call GetSuspendReadinessCallback() from their // SuspendImminent() methods, the HandleSuspendReadiness method call should be // deferred until all callbacks are run. const int kSuspendId = 1; EmitSuspendImminentSignal(kSuspendImminent, kSuspendId); EXPECT_TRUE(observer_1.RunSuspendReadinessCallback()); ExpectSuspendReadiness(kHandleSuspendReadiness, kSuspendId, kSuspendDelayId); EXPECT_TRUE(observer_2.RunSuspendReadinessCallback()); EmitSuspendDoneSignal(kSuspendId); EXPECT_EQ(1, observer_1.num_suspend_done()); EXPECT_EQ(1, observer_2.num_suspend_done()); } // Tests that RenderProcessManagerDelegate is notified about suspend and resume // in the common case where suspend readiness is reported. TEST_F(PowerManagerClientTest, NotifyRenderProcessManagerDelegate) { TestDelegate delegate(client_.get()); TestObserver observer(client_.get()); observer.set_take_suspend_readiness_callback(true); const int kSuspendId = 1; EmitSuspendImminentSignal(kSuspendImminent, kSuspendId); EXPECT_EQ(0, delegate.num_suspend_imminent()); EXPECT_EQ(0, delegate.num_suspend_done()); // The RenderProcessManagerDelegate should be notified that suspend is // imminent only after observers have reported readiness. ExpectSuspendReadiness(kHandleSuspendReadiness, kSuspendId, kSuspendDelayId); EXPECT_TRUE(observer.RunSuspendReadinessCallback()); EXPECT_EQ(1, delegate.num_suspend_imminent()); EXPECT_EQ(0, delegate.num_suspend_done()); // The delegate should be notified immediately after the attempt completes. EmitSuspendDoneSignal(kSuspendId); EXPECT_EQ(1, delegate.num_suspend_imminent()); EXPECT_EQ(1, delegate.num_suspend_done()); } // Tests that DarkSuspendImminent is handled in a manner similar to // SuspendImminent. TEST_F(PowerManagerClientTest, ReportDarkSuspendReadiness) { TestDelegate delegate(client_.get()); TestObserver observer(client_.get()); observer.set_take_suspend_readiness_callback(true); const int kSuspendId = 1; EmitSuspendImminentSignal(kSuspendImminent, kSuspendId); EXPECT_EQ(1, observer.num_suspend_imminent()); EXPECT_EQ(0, delegate.num_suspend_imminent()); ExpectSuspendReadiness(kHandleSuspendReadiness, kSuspendId, kSuspendDelayId); EXPECT_TRUE(observer.RunSuspendReadinessCallback()); EXPECT_EQ(1, delegate.num_suspend_imminent()); // The RenderProcessManagerDelegate shouldn't be notified about dark suspend // attempts. const int kDarkSuspendId = 5; EmitSuspendImminentSignal(kDarkSuspendImminent, kDarkSuspendId); EXPECT_EQ(1, observer.num_dark_suspend_imminent()); EXPECT_EQ(1, delegate.num_suspend_imminent()); EXPECT_EQ(0, delegate.num_suspend_done()); ExpectSuspendReadiness(kHandleDarkSuspendReadiness, kDarkSuspendId, kDarkSuspendDelayId); EXPECT_TRUE(observer.RunSuspendReadinessCallback()); EXPECT_EQ(0, delegate.num_suspend_done()); EmitSuspendDoneSignal(kSuspendId); EXPECT_EQ(1, observer.num_suspend_done()); EXPECT_EQ(1, delegate.num_suspend_done()); } // Tests the case where a SuspendDone signal is received while a readiness // callback is still pending. TEST_F(PowerManagerClientTest, SuspendCancelledWhileCallbackPending) { TestDelegate delegate(client_.get()); TestObserver observer(client_.get()); observer.set_take_suspend_readiness_callback(true); const int kSuspendId = 1; EmitSuspendImminentSignal(kSuspendImminent, kSuspendId); EXPECT_EQ(1, observer.num_suspend_imminent()); // If the suspend attempt completes (probably due to cancellation) before the // observer has run its readiness callback, the observer (but not the // delegate, which hasn't been notified about suspend being imminent yet) // should be notified about completion. EmitSuspendDoneSignal(kSuspendId); EXPECT_EQ(1, observer.num_suspend_done()); EXPECT_EQ(0, delegate.num_suspend_done()); // Ensure that the delegate doesn't receive late notification of suspend being // imminent if the readiness callback runs at this point, since that would // leave the renderers in a frozen state (http://crbug.com/646912). There's an // implicit expectation that powerd doesn't get notified about readiness here, // too. EXPECT_TRUE(observer.RunSuspendReadinessCallback()); EXPECT_EQ(0, delegate.num_suspend_imminent()); EXPECT_EQ(0, delegate.num_suspend_done()); } // Tests the case where a SuspendDone signal is received while a dark suspend // readiness callback is still pending. TEST_F(PowerManagerClientTest, SuspendDoneWhileDarkSuspendCallbackPending) { TestDelegate delegate(client_.get()); TestObserver observer(client_.get()); observer.set_take_suspend_readiness_callback(true); const int kSuspendId = 1; EmitSuspendImminentSignal(kSuspendImminent, kSuspendId); ExpectSuspendReadiness(kHandleSuspendReadiness, kSuspendId, kSuspendDelayId); EXPECT_TRUE(observer.RunSuspendReadinessCallback()); EXPECT_EQ(1, delegate.num_suspend_imminent()); const int kDarkSuspendId = 5; EmitSuspendImminentSignal(kDarkSuspendImminent, kDarkSuspendId); EXPECT_EQ(1, observer.num_dark_suspend_imminent()); // The delegate should be notified if the attempt completes now. EmitSuspendDoneSignal(kSuspendId); EXPECT_EQ(1, observer.num_suspend_done()); EXPECT_EQ(1, delegate.num_suspend_done()); // Dark suspend readiness shouldn't be reported even if the callback runs at // this point, since the suspend attempt is already done. The delegate also // shouldn't receive any more calls. EXPECT_TRUE(observer.RunSuspendReadinessCallback()); EXPECT_EQ(1, delegate.num_suspend_imminent()); EXPECT_EQ(1, delegate.num_suspend_done()); } // Tests the case where dark suspend is announced while readiness hasn't been // reported for the initial regular suspend attempt. TEST_F(PowerManagerClientTest, DarkSuspendImminentWhileCallbackPending) { TestDelegate delegate(client_.get()); TestObserver observer(client_.get()); observer.set_take_suspend_readiness_callback(true); // Announce that suspend is imminent and grab, but don't run, the readiness // callback. const int kSuspendId = 1; EmitSuspendImminentSignal(kSuspendImminent, kSuspendId); EXPECT_EQ(1, observer.num_suspend_imminent()); base::Closure regular_callback = observer.suspend_readiness_callback(); // Before readiness is reported, announce that dark suspend is imminent. const int kDarkSuspendId = 1; EmitSuspendImminentSignal(kDarkSuspendImminent, kDarkSuspendId); EXPECT_EQ(1, observer.num_dark_suspend_imminent()); base::Closure dark_callback = observer.suspend_readiness_callback(); // Complete the suspend attempt and run both of the earlier callbacks. Neither // should result in readiness being reported. EmitSuspendDoneSignal(kSuspendId); EXPECT_EQ(1, observer.num_suspend_done()); regular_callback.Run(); dark_callback.Run(); } // Tests that PowerManagerClient handles a single observer that requests a // suspend-readiness callback and then runs it synchronously from within // SuspendImminent() instead of running it asynchronously: // http://crosbug.com/p/58295 TEST_F(PowerManagerClientTest, SyncCallbackWithSingleObserver) { TestObserver observer(client_.get()); observer.set_take_suspend_readiness_callback(true); observer.set_run_suspend_readiness_callback_immediately(true); const int kSuspendId = 1; ExpectSuspendReadiness(kHandleSuspendReadiness, kSuspendId, kSuspendDelayId); EmitSuspendImminentSignal(kSuspendImminent, kSuspendId); EmitSuspendDoneSignal(kSuspendId); } // Tests the case where one observer reports suspend readiness by running its // callback before a second observer even gets notified about the suspend // attempt. We shouldn't report suspend readiness until the second observer has // been notified and confirmed readiness. TEST_F(PowerManagerClientTest, SyncCallbackWithMultipleObservers) { TestObserver observer1(client_.get()); observer1.set_take_suspend_readiness_callback(true); observer1.set_run_suspend_readiness_callback_immediately(true); TestObserver observer2(client_.get()); observer2.set_take_suspend_readiness_callback(true); const int kSuspendId = 1; EmitSuspendImminentSignal(kSuspendImminent, kSuspendId); ExpectSuspendReadiness(kHandleSuspendReadiness, kSuspendId, kSuspendDelayId); EXPECT_TRUE(observer2.RunSuspendReadinessCallback()); EmitSuspendDoneSignal(kSuspendId); } } // namespace chromeos
39.322807
80
0.758455
google-ar
1d33ff8649bbd88b5afe5b268068ceec416cece4
7,936
cc
C++
examples/external/OpenMesh/include/OpenMesh/Tools/Smoother/JacobiLaplaceSmootherT.cc
zhangxaochen/Opt
7f1af802bfc84cc9ef1adb9facbe4957078f529a
[ "MIT" ]
260
2017-03-02T19:57:51.000Z
2022-01-21T03:52:03.000Z
examples/external/OpenMesh/include/OpenMesh/Tools/Smoother/JacobiLaplaceSmootherT.cc
zhangxaochen/Opt
7f1af802bfc84cc9ef1adb9facbe4957078f529a
[ "MIT" ]
102
2017-03-03T00:42:56.000Z
2022-03-30T14:15:20.000Z
examples/external/OpenMesh/include/OpenMesh/Tools/Smoother/JacobiLaplaceSmootherT.cc
zhangxaochen/Opt
7f1af802bfc84cc9ef1adb9facbe4957078f529a
[ "MIT" ]
71
2017-03-02T20:22:33.000Z
2022-01-02T03:49:04.000Z
/* ========================================================================= * * * * OpenMesh * * Copyright (c) 2001-2015, RWTH-Aachen University * * Department of Computer Graphics and Multimedia * * All rights reserved. * * www.openmesh.org * * * *---------------------------------------------------------------------------* * This file is part of OpenMesh. * *---------------------------------------------------------------------------* * * * Redistribution and use in source and binary forms, with or without * * modification, are permitted provided that the following conditions * * are met: * * * * 1. Redistributions of source code must retain the above copyright notice, * * this list of conditions and the following disclaimer. * * * * 2. Redistributions in binary form must reproduce the above copyright * * notice, this list of conditions and the following disclaimer in the * * documentation and/or other materials provided with the distribution. * * * * 3. Neither the name of the copyright holder nor the names of its * * contributors may be used to endorse or promote products derived from * * this software without specific prior written permission. * * * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER * * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * * * ========================================================================= */ /*===========================================================================*\ * * * $Revision$ * * $Date$ * * * \*===========================================================================*/ /** \file JacobiLaplaceSmootherT.cc */ //============================================================================= // // CLASS JacobiLaplaceSmootherT - IMPLEMENTATION // //============================================================================= #define OPENMESH_JACOBI_LAPLACE_SMOOTHERT_C //== INCLUDES ================================================================= #include <OpenMesh/Tools/Smoother/JacobiLaplaceSmootherT.hh> //== NAMESPACES =============================================================== namespace OpenMesh { namespace Smoother { //== IMPLEMENTATION ========================================================== template <class Mesh> void JacobiLaplaceSmootherT<Mesh>:: smooth(unsigned int _n) { if (Base::continuity() > Base::C0) { Base::mesh_.add_property(umbrellas_); if (Base::continuity() > Base::C1) Base::mesh_.add_property(squared_umbrellas_); } LaplaceSmootherT<Mesh>::smooth(_n); if (Base::continuity() > Base::C0) { Base::mesh_.remove_property(umbrellas_); if (Base::continuity() > Base::C1) Base::mesh_.remove_property(squared_umbrellas_); } } //----------------------------------------------------------------------------- template <class Mesh> void JacobiLaplaceSmootherT<Mesh>:: compute_new_positions_C0() { typename Mesh::VertexIter v_it, v_end(Base::mesh_.vertices_end()); typename Mesh::ConstVertexOHalfedgeIter voh_it; typename Mesh::Normal u, p, zero(0,0,0); typename Mesh::Scalar w; for (v_it=Base::mesh_.vertices_begin(); v_it!=v_end; ++v_it) { if (this->is_active(*v_it)) { // compute umbrella u = zero; for (voh_it = Base::mesh_.cvoh_iter(*v_it); voh_it.is_valid(); ++voh_it) { w = this->weight(Base::mesh_.edge_handle(*voh_it)); u += vector_cast<typename Mesh::Normal>(Base::mesh_.point(Base::mesh_.to_vertex_handle(*voh_it))) * w; } u *= this->weight(*v_it); u -= vector_cast<typename Mesh::Normal>(Base::mesh_.point(*v_it)); // damping u *= 0.5; // store new position p = vector_cast<typename Mesh::Normal>(Base::mesh_.point(*v_it)); p += u; this->set_new_position(*v_it, p); } } } //----------------------------------------------------------------------------- template <class Mesh> void JacobiLaplaceSmootherT<Mesh>:: compute_new_positions_C1() { typename Mesh::VertexIter v_it, v_end(Base::mesh_.vertices_end()); typename Mesh::ConstVertexOHalfedgeIter voh_it; typename Mesh::Normal u, uu, p, zero(0,0,0); typename Mesh::Scalar w, diag; // 1st pass: compute umbrellas for (v_it=Base::mesh_.vertices_begin(); v_it!=v_end; ++v_it) { u = zero; for (voh_it = Base::mesh_.cvoh_iter(*v_it); voh_it.is_valid(); ++voh_it) { w = this->weight(Base::mesh_.edge_handle(*voh_it)); u -= vector_cast<typename Mesh::Normal>(Base::mesh_.point(Base::mesh_.to_vertex_handle(*voh_it)))*w; } u *= this->weight(*v_it); u += vector_cast<typename Mesh::Normal>(Base::mesh_.point(*v_it)); Base::mesh_.property(umbrellas_, *v_it) = u; } // 2nd pass: compute updates for (v_it=Base::mesh_.vertices_begin(); v_it!=v_end; ++v_it) { if (this->is_active(*v_it)) { uu = zero; diag = 0.0; for (voh_it = Base::mesh_.cvoh_iter(*v_it); voh_it.is_valid(); ++voh_it) { w = this->weight(Base::mesh_.edge_handle(*voh_it)); uu -= Base::mesh_.property(umbrellas_, Base::mesh_.to_vertex_handle(*voh_it)); diag += (w * this->weight(Base::mesh_.to_vertex_handle(*voh_it)) + static_cast<typename Mesh::Scalar>(1.0) ) * w; } uu *= this->weight(*v_it); diag *= this->weight(*v_it); uu += Base::mesh_.property(umbrellas_, *v_it); if (diag) uu *= static_cast<typename Mesh::Scalar>(1.0) / diag; // damping uu *= 0.25; // store new position p = vector_cast<typename Mesh::Normal>(Base::mesh_.point(*v_it)); p -= uu; this->set_new_position(*v_it, p); } } } //============================================================================= } // namespace Smoother } // namespace OpenMesh //=============================================================================
39.879397
121
0.455771
zhangxaochen
1d35be5672c49d86924c7d34911e267133d8ba20
1,327
hpp
C++
src/3rd party/boost/boost/preprocessor/facilities/is_empty_or_1.hpp
OLR-xray/OLR-3.0
b6a9bb2a0c1fb849b8c6cea2e831e1ceea5cc611
[ "Apache-2.0" ]
8
2016-01-25T20:18:51.000Z
2019-03-06T07:00:04.000Z
src/3rd party/boost/boost/preprocessor/facilities/is_empty_or_1.hpp
OLR-xray/OLR-3.0
b6a9bb2a0c1fb849b8c6cea2e831e1ceea5cc611
[ "Apache-2.0" ]
null
null
null
src/3rd party/boost/boost/preprocessor/facilities/is_empty_or_1.hpp
OLR-xray/OLR-3.0
b6a9bb2a0c1fb849b8c6cea2e831e1ceea5cc611
[ "Apache-2.0" ]
3
2016-02-14T01:20:43.000Z
2021-02-03T11:19:11.000Z
# /* ************************************************************************** # * * # * (C) Copyright Paul Mensonides 2003. Permission to copy, use, * # * modify, sell, and distribute this software is granted provided * # * this copyright notice appears in all copies. This software is * # * provided "as is" without express or implied warranty, and with * # * no claim at to its suitability for any purpose. * # * * # ************************************************************************** */ # # /* See http://www.boost.org for most recent version. */ # # ifndef BOOST_PREPROCESSOR_FACILITIES_IS_EMPTY_OR_1_HPP # define BOOST_PREPROCESSOR_FACILITIES_IS_EMPTY_OR_1_HPP # # include <boost/preprocessor/control/iif.hpp> # include <boost/preprocessor/facilities/empty.hpp> # include <boost/preprocessor/facilities/is_1.hpp> # include <boost/preprocessor/facilities/is_empty.hpp> # # /* BOOST_PP_IS_EMPTY_OR_1 */ # # define BOOST_PP_IS_EMPTY_OR_1(x) \ BOOST_PP_IIF( \ BOOST_PP_IS_EMPTY(x BOOST_PP_EMPTY()), \ 1 BOOST_PP_EMPTY, \ BOOST_PP_IS_1 \ )(x) \ /**/ # # endif
41.46875
80
0.50942
OLR-xray
1d386eab0ba517deef2b5b0fc69d05e864e12f08
4,035
cpp
C++
src_ana/bdcs_effs.cpp
serjinio/thesis_ana
633a61dee56cf2cf4dcb67997ac87338537fb578
[ "MIT" ]
null
null
null
src_ana/bdcs_effs.cpp
serjinio/thesis_ana
633a61dee56cf2cf4dcb67997ac87338537fb578
[ "MIT" ]
null
null
null
src_ana/bdcs_effs.cpp
serjinio/thesis_ana
633a61dee56cf2cf4dcb67997ac87338537fb578
[ "MIT" ]
null
null
null
#include <fstream> #include "TROOT.h" #include "cli.hpp" #include "init_ds.hpp" #include "consts.hpp" #include "csalg.hpp" #include "drawing.hpp" #include "scattyield.hpp" #include "treewalk.hpp" #include "cuts_conf.hpp" #include "rootscript.hpp" static s13::misc::CliOptions cli_opts; using ElaCuts = s13::ana::ElasticScatteringCuts; using Evt = s13::ana::ScatteringEvent; class BdcsEffsAlg : public s13::ana::SimpleTTreeAlgorithmBase { public: BdcsEffsAlg(const ElaCuts& cuts) : logger_{"BdcsEffsAlg"}, cuts_{cuts} { init(); } virtual void process_event(Evt& evt) { if (cuts_.IsSignalEvent(evt)) { compute_bdcs_effs(evt); } } virtual void finalize() { double bdc1_eff = bdcs_eff_hits_[0] / (double)bdcs_ref_hits_[1] * 100; double bdc2_eff = bdcs_eff_hits_[1] / (double)bdcs_ref_hits_[0] * 100; logger_.info("Total number of events: %d", total_events_); logger_.info("BDC1 in pos. cut hits: %d", bdcs_ref_hits_[0]); logger_.info("BDC2 in pos. cut hits: %d", bdcs_ref_hits_[1]); logger_.info("BDC2*BDC1 hits: %d", bdcs_eff_hits_[0]); logger_.info("BDC1*BDC2 hits: %d", bdcs_eff_hits_[1]); logger_.info("BDC1 efficiency: %.1f%%", bdc1_eff); logger_.info("BDC2 efficiency: %.1f%%", bdc2_eff); double bdc1_eff_to_sbt = sbt_bdc1_hits_ / (double)sbt_hits_ * 100; logger_.info("\nBDC1 efficiency relative to SBT:"); logger_.info("\tSBT hits: %d", sbt_hits_); logger_.info("\tSBT*BDC1 hits: %d", sbt_bdc1_hits_); logger_.info("\tBDC1 efficiency: %.1f%%", bdc1_eff_to_sbt); } ElaCuts cuts() { return cuts_; } private: void init() { // auto th1 = &s13::ana::make_th1; bdcs_ref_hits_ = { { 0, 0 } }; bdcs_eff_hits_ = { { 0, 0 } }; } bool is_bdc1_pos_cut(Evt& evt) { double evt_r = std::sqrt(std::pow(evt.bdc1_xpos, 2) + std::pow(evt.bdc1_ypos, 2)); if (evt_r < 1) { return true; } return false; } bool is_bdc2_pos_cut(Evt& evt) { double evt_r = std::sqrt(std::pow(evt.bdc2_xpos, 2) + std::pow(evt.bdc2_ypos, 2)); if (evt_r < 1) { return true; } return false; } bool is_bdc1_hit(Evt& evt) { if (is_well_defined(evt.bdc1_xpos) && is_well_defined(evt.bdc1_ypos)) { return true; } return false; } bool is_bdc2_hit(Evt& evt) { if (is_well_defined(evt.bdc2_xpos) && is_well_defined(evt.bdc2_ypos)) { return true; } return false; } bool is_sbt_hit(Evt& evt) { return true; } void compute_bdcs_effs(Evt& evt) { total_events_ += 1; if (is_bdc1_pos_cut(evt)) { ++bdcs_ref_hits_[0]; if (is_bdc2_hit(evt)) { ++bdcs_eff_hits_[1]; } } if (is_bdc2_pos_cut(evt)) { ++bdcs_ref_hits_[1]; if (is_bdc1_hit(evt)) { ++bdcs_eff_hits_[0]; } } if (is_sbt_hit(evt)) { ++sbt_hits_; if (is_bdc1_hit(evt)) { ++sbt_bdc1_hits_; } } } s13::misc::MessageLogger logger_; ElaCuts cuts_; int total_events_ = 0; int sbt_hits_ = 0; int sbt_bdc1_hits_ = 0; std::array<int, 2> bdcs_ref_hits_; std::array<int, 2> bdcs_eff_hits_; }; void draw_bdcs_effs(s13::ana::RootScript& script, std::shared_ptr<BdcsEffsAlg> alg) { script.NewPage(1).cd(); } void bdcs_effs() { auto cuts = s13::io::parse_cuts_config(std::fstream(cli_opts.cuts_config())); auto alg = s13::ana::walk_alg<BdcsEffsAlg>(cuts, init_dataset_from_cli(cli_opts), cli_opts.use_mt()); s13::ana::RootScript script("bdcs_effs"); gStyle->SetOptStat(1111111); // gStyle->SetOptFit(); draw_bdcs_effs(script, alg); } int main(int argc, char** argv) { s13::misc::MessageLogger log("main()"); gROOT->SetStyle("Modern"); TThread::Initialize(); cli_opts.require_cuts_conf_opt(true); try { cli_opts.parse_options(argc, argv); } catch (std::exception& ex) { log.error("Invalid argument provided: %s", ex.what()); return -1; } bdcs_effs(); }
23.596491
86
0.626022
serjinio
1d38f5ac604c69a83473dea8500ac50163dd1387
775
cpp
C++
leetcode/07-Bit/0067E-AddBinary/AddBinary.cpp
BinRay/Learning
36a2380a9686e6922632e6b85ddb3d1f0903b37a
[ "MIT" ]
null
null
null
leetcode/07-Bit/0067E-AddBinary/AddBinary.cpp
BinRay/Learning
36a2380a9686e6922632e6b85ddb3d1f0903b37a
[ "MIT" ]
null
null
null
leetcode/07-Bit/0067E-AddBinary/AddBinary.cpp
BinRay/Learning
36a2380a9686e6922632e6b85ddb3d1f0903b37a
[ "MIT" ]
null
null
null
#include <iostream> #include <string> #include <bitset> #include <algorithm> using namespace std; // 通过“异或”和“移位”模拟加法 // 借助bitset class Solution { public: string addBinary(string a, string b) { // len必须是常量 const int len = 128; bitset<len> bs_a(a); bitset<len> bs_b(b); bitset<len> bs_zero; bitset<len> carry; while ( bs_b != bs_zero ){ carry = (bs_a & bs_b) << 1; bs_a ^= bs_b; bs_b = carry; } string s = bs_a.to_string(); auto it = find( s.begin(), s.end(), '1' ); string s_new(it, s.end()); return bs_a==bs_zero ? "0" : s_new; } }; int main( int argc, char** argv ){ Solution s; cout << s.addBinary( "010" , "110"); }
20.945946
50
0.516129
BinRay
1d3afb1d0ed6c5a9815a22ff324f347d4c80f47c
772
cpp
C++
day2/day2.cpp
offonrynk/30_days_of_code
6b6e4ce05e07a3065fc9db2fff7dc62ac81a7289
[ "MIT" ]
null
null
null
day2/day2.cpp
offonrynk/30_days_of_code
6b6e4ce05e07a3065fc9db2fff7dc62ac81a7289
[ "MIT" ]
null
null
null
day2/day2.cpp
offonrynk/30_days_of_code
6b6e4ce05e07a3065fc9db2fff7dc62ac81a7289
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #include <cmath> #include <iostream> using std::cin; using std::cout; using std::endl; void solve(double meal_cost, int tip_percent, int tax_percent) { double tip_cost = meal_cost * tip_percent / 100; double tax_cost = meal_cost * tax_percent / 100; double total_cost = meal_cost + tip_cost + tax_cost; cout << round(total_cost) << endl; } int main() { double meal_cost; cin >> meal_cost; cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); int tip_percent; cin >> tip_percent; cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); int tax_percent; cin >> tax_percent; cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); solve(meal_cost, tip_percent, tax_percent); return 0; }
20.864865
64
0.686528
offonrynk
1d3d2b5203ebfcf3410a21301102296d397ec443
1,014
hpp
C++
include/kip/xml/qname.hpp
kei10in/kip
23d83ffa4f40431ef8bd6983e928ae889bfc3872
[ "MIT" ]
null
null
null
include/kip/xml/qname.hpp
kei10in/kip
23d83ffa4f40431ef8bd6983e928ae889bfc3872
[ "MIT" ]
null
null
null
include/kip/xml/qname.hpp
kei10in/kip
23d83ffa4f40431ef8bd6983e928ae889bfc3872
[ "MIT" ]
null
null
null
#ifndef KIP_XML_QNAME_HPP_ #define KIP_XML_QNAME_HPP_ #include <string> #include "kip/hash-combine.hpp" namespace kip { namespace xml { struct qname { std::string name; std::string url; qname() {} qname(std::string const& name, std::string const& url) : name(name) , url(url) {} bool empty() const { return name.empty() && url.empty(); } size_t hash() const { size_t h = 0; hash_combine(h, name); hash_combine(h, url); return h; } }; inline bool operator==(qname const& lhs, qname const& rhs) { return lhs.name == rhs.name && lhs.url == rhs.url; } inline bool operator!=(qname const& lhs, qname const& rhs) { return !(lhs == rhs); } } // namespace qname } // namespace pst namespace std { template <> struct hash<kip::xml::qname> { using result_type = size_t; using argument_type = kip::xml::qname; size_t operator()(kip::xml::qname const& v) const { return v.hash(); } }; } // namespace std #endif // KIP_XML_QNAME_HPP_
16.095238
60
0.627219
kei10in
1d3e23ead9343bebdf8cf053fe8fbe0baa32ce5b
11,725
cpp
C++
samples/threat_level/src/PlayerWeaponsSystem.cpp
fallahn/crogine
f6cf3ade1f4e5de610d52e562bf43e852344bca0
[ "FTL", "Zlib" ]
41
2017-08-29T12:14:36.000Z
2022-02-04T23:49:48.000Z
samples/threat_level/src/PlayerWeaponsSystem.cpp
fallahn/crogine
f6cf3ade1f4e5de610d52e562bf43e852344bca0
[ "FTL", "Zlib" ]
11
2017-09-02T15:32:45.000Z
2021-12-27T13:34:56.000Z
samples/threat_level/src/PlayerWeaponsSystem.cpp
fallahn/crogine
f6cf3ade1f4e5de610d52e562bf43e852344bca0
[ "FTL", "Zlib" ]
5
2020-01-25T17:51:45.000Z
2022-03-01T05:20:30.000Z
/*----------------------------------------------------------------------- Matt Marchant 2017 http://trederia.blogspot.com crogine test application - Zlib license. This software is provided 'as-is', without any express or implied warranty.In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions : 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. -----------------------------------------------------------------------*/ #include "PlayerWeaponsSystem.hpp" #include "ItemSystem.hpp" #include "Messages.hpp" #include "ResourceIDs.hpp" #include "PhysicsObject.hpp" #include <crogine/core/App.hpp> #include <crogine/core/Clock.hpp> #include <crogine/ecs/components/Transform.hpp> #include <crogine/ecs/components/Sprite.hpp> #include <crogine/ecs/Scene.hpp> namespace { const float pulseMoveSpeed = 18.f; constexpr float pulseFireRate = 0.2f; constexpr float pulseDoubleFireRate = pulseFireRate / 2.f; constexpr float pulseTripleFireRate = pulseFireRate / 3.f; const float pulseOffset = 0.6f; const float pulseDamageSingle = 5.f; const float pulseDamageDouble = 2.5f; const float pulseDamageTriple = 1.2f; const float laserDamage = 0.4f; const float buddyDamage = 5.f; const float laserRate = 0.025f; const float weaponDowngradeTime = 5.f; const glm::vec3 idlePos(-100.f); //be careful with this. When setting inactive actors to the same postion they cause collisions off screen } PlayerWeaponSystem::PlayerWeaponSystem(cro::MessageBus& mb) : cro::System (mb, typeid(PlayerWeaponSystem)), m_systemActive (false), m_allowFiring (false), m_fireMode (FireMode::Single), m_fireTime (pulseFireRate), m_weaponDowngradeTime (0.f), m_playerID (0), m_aliveCount (0), m_deadPulseCount (0), m_deadLaserCount (0) { requireComponent<PlayerWeapon>(); requireComponent<cro::Transform>(); requireComponent<cro::PhysicsObject>(); } //public void PlayerWeaponSystem::process(float dt) { //DPRINT("Dead Pulse", std::to_string(m_deadPulseCount)); //DPRINT("Alive Pulse", std::to_string(m_aliveCount)); //DPRINT("Fire Time", std::to_string(m_fireTime)); //DPRINT("Laser cooldown", std::to_string(m_laserCooldownTime)); m_fireTime += dt; auto spawnPulse = [&](glm::vec3 position, float damage) { m_deadPulseCount--; m_aliveList[m_aliveCount] = m_deadPulses[m_deadPulseCount]; auto entity = getScene()->getEntity(m_aliveList[m_aliveCount]); entity.getComponent<cro::Transform>().setPosition(position); entity.getComponent<PlayerWeapon>().damage = damage; m_aliveCount++; auto* msg = postMessage<PlayerEvent>(MessageID::PlayerMessage); msg->position = position; msg->type = PlayerEvent::FiredLaser; }; //if active spawn more pulses or activate laser if (m_systemActive) { switch (m_fireMode) { default: case FireMode::Single: if (m_fireTime > pulseFireRate && m_deadPulseCount > 0) { spawnPulse(m_playerPosition, pulseDamageSingle); m_fireTime = 0.f; } break; case FireMode::Double: if (m_fireTime > pulseDoubleFireRate && m_deadPulseCount > 0) { static std::int32_t side = 0; glm::vec3 offset = glm::vec3(0.f); offset.z = (side) ? -pulseOffset : pulseOffset; offset = getScene()->getEntity(m_playerID).getComponent<cro::Transform>().getWorldTransform() * glm::vec4(offset, 1.f); spawnPulse(offset, pulseDamageDouble); side = (side + 1) % 2; m_fireTime = 0.f; } break; case FireMode::Triple: if (m_fireTime > pulseTripleFireRate && m_deadPulseCount > 0) { static std::int32_t side = 0; glm::vec3 offset = glm::vec3(0.f); offset.z = -pulseOffset + (pulseOffset * side); offset = getScene()->getEntity(m_playerID).getComponent<cro::Transform>().getWorldTransform() * glm::vec4(offset, 1.f); spawnPulse(offset, pulseDamageTriple); side = (side + 1) % 3; m_fireTime = 0.f; } break; case FireMode::Laser: if (m_deadLaserCount > 0) { m_deadLaserCount--; m_aliveList[m_aliveCount] = m_deadLasers[m_deadLaserCount]; auto laserEnt = getScene()->getEntity(m_aliveList[m_aliveCount]); laserEnt.getComponent<cro::Transform>().setPosition(glm::vec3(0.f, -0.1f, 0.f)); laserEnt.getComponent<cro::Transform>().setScale(glm::vec3(1.f)); m_aliveCount++; } break; } } //downgrade weapon over time if (m_fireMode > FireMode::Single) { m_weaponDowngradeTime -= dt; if (m_weaponDowngradeTime < 0) { m_weaponDowngradeTime = weaponDowngradeTime; m_fireMode = static_cast<FireMode>(m_fireMode - 1); } auto* msg = postMessage<WeaponEvent>(MessageID::WeaponMessage); msg->downgradeTime = weaponDowngradeTime - m_weaponDowngradeTime; msg->fireMode = m_fireMode; } //update alive for (auto i = 0u; i < m_aliveCount; ++i) { auto e = getScene()->getEntity(m_aliveList[i]); auto& weaponData = e.getComponent<PlayerWeapon>(); if (weaponData.type == PlayerWeapon::Type::Pulse) { //update position e.getComponent<cro::Transform>().move({ dt * pulseMoveSpeed, 0.f, 0.f }); //handle collision with NPCs or end of map const auto& collision = e.getComponent<cro::PhysicsObject>(); auto count = collision.getCollisionCount(); //const auto& IDs = collision.getCollisionIDs(); for (auto j = 0u; j < count; ++j) { //other entities handle their own reaction - we just want to reset the pulse e.getComponent<cro::Transform>().setPosition(idlePos); //move to dead list m_deadPulses[m_deadPulseCount] = m_aliveList[i]; m_deadPulseCount++; //and remove from alive list m_aliveCount--; m_aliveList[i] = m_aliveList[m_aliveCount]; i--; //decrement so the newly inserted ID doesn't get skipped, and we can be sure we're still < m_aliveCount count = 0; //only want to handle one collision at most, else we might kill this ent more than once } } else //laser is firing { static float laserTime = 0.f; laserTime += dt; if (laserTime > laserRate) { //animates the laser beam auto scale = e.getComponent<cro::Transform>().getScale(); scale.y = scale.y < 1 ? 1.3f : 0.25f; e.getComponent<cro::Transform>().setScale(scale); laserTime = 0.f; } if (m_fireMode != FireMode::Laser || !m_systemActive) { //remove from alive list e.getComponent<cro::Transform>().setPosition(idlePos); e.getComponent<cro::Transform>().setScale(glm::vec3(0.f)); //move to dead list m_deadLasers[m_deadLaserCount] = m_aliveList[i]; m_deadLaserCount++; //and remove from alive list m_aliveCount--; m_aliveList[i] = m_aliveList[m_aliveCount]; i--; } } } } void PlayerWeaponSystem::handleMessage(const cro::Message& msg) { if (msg.id == MessageID::PlayerMessage) { const auto& data = msg.getData<PlayerEvent>(); switch (data.type) { case PlayerEvent::Died: m_fireMode = FireMode::Single; m_systemActive = false; m_allowFiring = false; { auto* msg = postMessage<WeaponEvent>(MessageID::WeaponMessage); msg->downgradeTime = 0.f; msg->fireMode = m_fireMode; } break; case PlayerEvent::Moved: m_playerPosition = data.position; m_playerID = data.entityID; break; case PlayerEvent::Spawned: m_allowFiring = true; LOG("Enabled weapon", cro::Logger::Type::Info); break; case PlayerEvent::WeaponStateChange: m_systemActive = (data.weaponActivated && m_allowFiring); if (!data.weaponActivated) { m_fireTime = pulseFireRate; } break; case PlayerEvent::CollectedItem: if (data.itemID == CollectableItem::WeaponUpgrade) { m_weaponDowngradeTime = weaponDowngradeTime; //HAH wtf? if (m_fireMode < FireMode::Laser) { m_fireMode = static_cast<FireMode>(m_fireMode + 1); } } break; default: break; } } else if (msg.id == MessageID::BuddyMessage) { const auto& data = msg.getData<BuddyEvent>(); if (data.type == BuddyEvent::FiredWeapon) { if (m_deadPulseCount > 0) { m_deadPulseCount--; m_aliveList[m_aliveCount] = m_deadPulses[m_deadPulseCount]; auto entity = getScene()->getEntity(m_aliveList[m_aliveCount]); entity.getComponent<cro::Transform>().setPosition(data.position); entity.getComponent<PlayerWeapon>().damage = buddyDamage; m_aliveCount++; } } } else if (msg.id == MessageID::GameMessage) { const auto& data = msg.getData<GameEvent>(); if (data.type == GameEvent::RoundStart) { m_aliveCount = 0; m_deadPulseCount = m_deadPulses.size(); m_deadLaserCount = m_deadLasers.size(); } } } //private void PlayerWeaponSystem::onEntityAdded(cro::Entity entity) { //add entity to dead list based on type if (entity.getComponent<PlayerWeapon>().type == PlayerWeapon::Type::Pulse) { m_deadPulses.push_back(entity.getIndex()); m_deadPulseCount = m_deadPulses.size(); } else { m_deadLasers.push_back(entity.getIndex()); m_deadLaserCount = m_deadLasers.size(); entity.getComponent<PlayerWeapon>().damage = laserDamage; } //pad alive list to correct size (we're assuming no entities are actually //created or destroyed at runtime) m_aliveList.push_back(-1); }
34.689349
142
0.574584
fallahn
1d42f60b9415a3a67e89a862132cbebb7635c888
1,096
cpp
C++
Dia1/G-ClockSolitaire.cpp
pauolivares/ICPCCL2018
72708a14ff5c1911ab87f7b758f131603603c808
[ "Apache-2.0" ]
null
null
null
Dia1/G-ClockSolitaire.cpp
pauolivares/ICPCCL2018
72708a14ff5c1911ab87f7b758f131603603c808
[ "Apache-2.0" ]
null
null
null
Dia1/G-ClockSolitaire.cpp
pauolivares/ICPCCL2018
72708a14ff5c1911ab87f7b758f131603603c808
[ "Apache-2.0" ]
null
null
null
#include <bits/stdc++.h> using namespace std; bool solve(vector<char> &cards,vector<int> &acum, int pos, int l){ if(l==52) return true; if(acum[pos]==4) return false; char carta = cards[4*pos + acum[pos]]; acum[pos]++; if(carta>='2' && carta<='9'){ return solve(cards,acum,carta-'1',l+1); } if(carta=='J'){ return solve(cards,acum,0,l+1); } if(carta=='T'){ return solve(cards,acum,9,l+1); } if(carta=='A'){ return solve(cards,acum,10,l+1); } if(carta=='Q'){ return solve(cards,acum,11,l+1); } if(carta=='K'){ return solve(cards,acum,12,l+1); } } int main(){ char c; while(cin >> c){ if(c=='0') break; vector<char> cards(52); cards[0] = c; for(int i=1;i<52;i++){ cin >> cards[i]; } int resp = 0; for(int i=0;i<52;i++){ vector<int> acum(13,0); vector<char> aux(52); int k=0; for(int j=i;j<52;j++,k++){ aux[k]=cards[j]; } for(int j=0;j<i;j++,k++){ aux[k]=cards[j]; } if(solve(aux,acum,12,0)) resp++; } cout << resp << endl; } return 0; }
18.896552
66
0.514599
pauolivares
1d446f6f4d917f5e087e01c85c22dbef65af8aaf
699
ipp
C++
ThirdParty/oglplus-develop/implement/oglplus/link_error.ipp
vif/3D-STG
721402e76a9b9b99b88ba3eb06beb6abb17a9254
[ "MIT" ]
null
null
null
ThirdParty/oglplus-develop/implement/oglplus/link_error.ipp
vif/3D-STG
721402e76a9b9b99b88ba3eb06beb6abb17a9254
[ "MIT" ]
null
null
null
ThirdParty/oglplus-develop/implement/oglplus/link_error.ipp
vif/3D-STG
721402e76a9b9b99b88ba3eb06beb6abb17a9254
[ "MIT" ]
null
null
null
/** * @file oglplus/link_error.ipp * @brief Implementation of * * @author Matus Chochlik * * Copyright 2010-2013 Matus Chochlik. Distributed under the Boost * Software License, Version 1.0. (See accompanying file * LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ namespace oglplus { OGLPLUS_LIB_FUNC LinkError::LinkError(const String& log, const ErrorInfo& info) : ProgramBuildError( "OpenGL shading language program link error", log, info ) { } OGLPLUS_LIB_FUNC ValidationError::ValidationError(const String& log, const ErrorInfo& info) : ProgramBuildError( "OpenGL shading language program validation error", log, info ) { } } // namespace oglplus
20.558824
74
0.738197
vif
1d45394ec14a2e0211876d5487ec88b544a2cd36
1,705
cxx
C++
Modules/Logger/TestingLog/TestAlgorithm.cxx
Hurna/Hurna-Lib
61c267fc6ccf617e92560a84800f6a719cc5c6c8
[ "MIT" ]
2
2019-03-29T21:23:02.000Z
2019-04-02T19:13:32.000Z
Modules/Logger/TestingLog/TestAlgorithm.cxx
Hurna/Hurna-Lib
61c267fc6ccf617e92560a84800f6a719cc5c6c8
[ "MIT" ]
null
null
null
Modules/Logger/TestingLog/TestAlgorithm.cxx
Hurna/Hurna-Lib
61c267fc6ccf617e92560a84800f6a719cc5c6c8
[ "MIT" ]
null
null
null
/*=========================================================================================================== * * HUL - Hurna Lib * * Copyright (c) Michael Jeulin-Lagarrigue * * Licensed under the MIT License, you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://github.com/Hurna/Hurna-Lib/blob/master/LICENSE * * Unless required by applicable law or agreed to in writing, software distributed under the License is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and limitations under the License. * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * *=========================================================================================================*/ #include <gtest/gtest.h> #include <algorithm.hxx> using namespace hul; #ifndef DOXYGEN_SKIP namespace { class Algo_Quick { public: static const std::string GetAuthor() { return "Michael Jeulin-L"; } static const std::string GetDoc() { return "Documentation."; } static const std::string GetModule() { return "Sort"; } static const std::string GetName() { return "QuickSort"; } static const std::string GetVersion() { return "1.0"; } }; } #endif /* DOXYGEN_SKIP */ // Test TestAlgo Construction TEST(TestAlgo_Traits, build) { // @todo Passing arguement as: Algo_Quick::Build(std::cout, x1, x2...) // { Algo_Traits<Algo_Quick>::Build() }; //Algo_Traits<Algo_Quick>::Build(std::cout, OpGetAll); }
37.065217
109
0.615836
Hurna
1d48bca05e6a78d129bb3332af97ac60a438e184
86
cpp
C++
subprojects/kxview/context.cpp
kod-kristoff/kx
bc6ec4ad3720234ac6ae7e90343809a67c0fab27
[ "MIT" ]
null
null
null
subprojects/kxview/context.cpp
kod-kristoff/kx
bc6ec4ad3720234ac6ae7e90343809a67c0fab27
[ "MIT" ]
null
null
null
subprojects/kxview/context.cpp
kod-kristoff/kx
bc6ec4ad3720234ac6ae7e90343809a67c0fab27
[ "MIT" ]
null
null
null
#include "kx/view/context.hpp" namespace kx::view { Context::~Context() {} }
10.75
30
0.604651
kod-kristoff
1d492b9ab4cdad486d4dfc27fa0e9bcfc991a622
2,222
hpp
C++
src/dsp/BiquadFilter.hpp
flyingLowSounds/LRTRack
20121c1232e29a26d527134de13a0a3d3d065f52
[ "BSD-3-Clause" ]
null
null
null
src/dsp/BiquadFilter.hpp
flyingLowSounds/LRTRack
20121c1232e29a26d527134de13a0a3d3d065f52
[ "BSD-3-Clause" ]
null
null
null
src/dsp/BiquadFilter.hpp
flyingLowSounds/LRTRack
20121c1232e29a26d527134de13a0a3d3d065f52
[ "BSD-3-Clause" ]
null
null
null
/* *\ ** __ ___ ______ ** ** / / / _ \/_ __/ ** ** / /__/ , _/ / / Lindenberg ** ** /____/_/|_| /_/ Research Tec. ** ** ** ** ** ** https://github.com/lindenbergresearch/LRTRack ** ** heapdump@icloud.com ** ** ** ** Sound Modules for VCV Rack ** ** Copyright 2017/2018 by Patrick Lindenberg / LRT ** ** ** ** For Redistribution and use in source and binary forms, ** ** with or without modification please see LICENSE. ** ** ** \* */ #pragma once #include "DSPEffect.hpp" namespace lrt { enum BiquadType { LOWPASS = 0, HIGHPASS, BANDPASS, NOTCH, PEAK, LOWSHELF, HIGHSHELF }; /** * @brief Common Biquad filters * based on: https://www.earlevel.com/main/2012/11/26/biquad-c-source-code/ */ struct Biquad : DSPEffect { public: Biquad(BiquadType type, double Fc, double Q, double peakGainDB, float sr); ~Biquad(); void setType(BiquadType type); void setQ(double Q); void setFc(double Fc); void setPeakGain(double peakGainDB); void setBiquad(BiquadType type, double Fc, double Q, double peakGain); void process() override; void invalidate() override; void init() override; double in, out; protected: int type; double a0, a1, a2, b1, b2; double Fc, Q, peakGain; double z1, z2; }; inline void Biquad::process() { out = in * a0 + z1; z1 = in * a1 + z2 - b1 * out; z2 = in * a2 - b2 * out; } }
30.027027
78
0.382988
flyingLowSounds
1d4bdcda798508cf8f851ae57a9380c58fa916c3
1,324
cc
C++
src/Molecule_Lib/rxnfile_test.cc
IanAWatson/LillyMol-4.0-Bazel
f38f23a919c622c31280222f8a90e6ab7d871b93
[ "Apache-2.0" ]
6
2020-08-17T15:02:14.000Z
2022-01-21T19:27:56.000Z
src/Molecule_Lib/rxnfile_test.cc
IanAWatson/LillyMol-4.0-Bazel
f38f23a919c622c31280222f8a90e6ab7d871b93
[ "Apache-2.0" ]
null
null
null
src/Molecule_Lib/rxnfile_test.cc
IanAWatson/LillyMol-4.0-Bazel
f38f23a919c622c31280222f8a90e6ab7d871b93
[ "Apache-2.0" ]
null
null
null
// Tests for some of the functions in rxnfile.cc #include "rxn_file.h" #include "googlemock/include/gmock/gmock.h" #include "googletest/include/gtest/gtest.h" #include "google/protobuf/text_format.h" namespace { class TestRxnFile : public testing::Test { protected: void SetUp() override; protected: RXN_File _rxn; }; void TestRxnFile::SetUp() { _rxn.set_do_automatic_atom_mapping(0); return; } TEST_F(TestRxnFile, TestremoveNonParticipatingFragmentsMapped) { const_IWSubstring buffer = "[C:1][C:2](=[O:3])[O:4]+[N:5][C:6]>>[C:1][C:2](=[O:3])[N:5][C:6].[C:8][C:9]"; EXPECT_TRUE(_rxn.build_from_reaction_smiles(buffer, 1)); EXPECT_EQ(_rxn.number_reagents(), 2); EXPECT_EQ(_rxn.number_products(), 1); const int removed = _rxn.remove_non_participating_fragments(); EXPECT_EQ(removed, 1); EXPECT_EQ(_rxn.product(0).natoms(), 5); } TEST_F(TestRxnFile, TestremoveNonParticipatingFragmentsUnMapped) { const_IWSubstring buffer = "[C:1][C:2](=[O:3])[O:4]+[N:5][C:6]>>CC.[C:1][C:2](=[O:3])[N:5][C:6]"; EXPECT_TRUE(_rxn.build_from_reaction_smiles(buffer, 1)); EXPECT_EQ(_rxn.number_reagents(), 2); EXPECT_EQ(_rxn.number_products(), 1); const int removed = _rxn.remove_non_participating_fragments(); EXPECT_EQ(removed, 1); EXPECT_EQ(_rxn.product(0).natoms(), 5); } } // namespace
24.981132
107
0.706949
IanAWatson
1d4caef2dc2b43daf6badc5fd9ae4982ae8d78df
1,063
cpp
C++
BashuOJ-Code/2919.cpp
magicgh/algorithm-contest-code
c21a90b11f73535c61e6363a4305b74cff24a85b
[ "MIT" ]
null
null
null
BashuOJ-Code/2919.cpp
magicgh/algorithm-contest-code
c21a90b11f73535c61e6363a4305b74cff24a85b
[ "MIT" ]
null
null
null
BashuOJ-Code/2919.cpp
magicgh/algorithm-contest-code
c21a90b11f73535c61e6363a4305b74cff24a85b
[ "MIT" ]
null
null
null
#include<cstdio> #include<cmath> #include<algorithm> #define ri register int using namespace std; const double Pi=3.1415926535; const double Max=0x7fffffff; struct marisa{int x,y,val,mul;}mao[2005]; int n;double k,sv[2005],sm[2005],f[2005]; inline int getint() { int num=0,bj=1; char c=getchar(); while(c<'0'||c>'9')bj=(c=='-'||bj==-1)?-1:1,c=getchar(); while(c>='0'&&c<='9')num=num*10+c-'0',c=getchar(); return num*bj; } inline double getslope(const int &alpha){return tan(Pi/180*alpha);} inline bool cmp(const marisa &t1,const marisa &t2){return double(t1.y-t1.x*k)<(t2.y-t2.x*k);} inline int max(const int &t1,const int &t2){return t1>t2?t1:t2;} int main() { n=getint(); for(ri i=1;i<=n;++i) { int x=getint(),y=getint(),v=getint(),m=getint(); mao[i]=(marisa){x,y,v,m}; } k=getslope(getint()); sort(mao+1,mao+n+1,cmp); for(ri i=1;i<=n;++i)sv[i]=sv[i-1]+mao[i].val,sm[i]=sm[i-1]+mao[i].mul; for(ri i=1;i<=n;++i) { f[i]=-Max; for(ri j=0;j<i;++j)f[i]=max(f[i],f[j]+((sv[i]-sv[j])/(i-j))*(sm[i]-sm[j])); } printf("%.3lf",f[n]); return 0; }
26.575
93
0.611477
magicgh
1d4ea267cd38a2d37d671d2ce4935bb6689c5848
196
cpp
C++
tournaments/eyeRhyme/eyeRhyme.cpp
gurfinkel/codeSignal
114817947ac6311bd53a48f0f0e17c0614bf7911
[ "MIT" ]
5
2020-02-06T09:51:22.000Z
2021-03-19T00:18:44.000Z
tournaments/eyeRhyme/eyeRhyme.cpp
gurfinkel/codeSignal
114817947ac6311bd53a48f0f0e17c0614bf7911
[ "MIT" ]
null
null
null
tournaments/eyeRhyme/eyeRhyme.cpp
gurfinkel/codeSignal
114817947ac6311bd53a48f0f0e17c0614bf7911
[ "MIT" ]
3
2019-09-27T13:06:21.000Z
2021-04-20T23:13:17.000Z
bool eyeRhyme(std::string pairOfLines) { std::regex pattern(".*(...)\\t.*(...)"); std::smatch match; std::regex_search(pairOfLines, match, pattern); return match.str(1) == match.str(2); }
28
49
0.632653
gurfinkel
1d502c84566f650a6fe8a0de58978cd3e924c014
261
cc
C++
Chapter01/1.22.cc
bhshp/Cpp-Primer-5E
dbae02971354e5d66088ab7144cb843fc06822f2
[ "MIT" ]
null
null
null
Chapter01/1.22.cc
bhshp/Cpp-Primer-5E
dbae02971354e5d66088ab7144cb843fc06822f2
[ "MIT" ]
null
null
null
Chapter01/1.22.cc
bhshp/Cpp-Primer-5E
dbae02971354e5d66088ab7144cb843fc06822f2
[ "MIT" ]
null
null
null
#include <iostream> #include "Sales_item.h" int main() { Sales_item sum; if (std::cin >> sum) { Sales_item temp; while (std::cin >> temp) { sum += temp; } std::cout << sum << std::endl; } return 0; }
17.4
38
0.475096
bhshp
1d50570bdd4f505da1ecebc6b593004fda53c85f
7,968
cpp
C++
logdevice/common/StickyCopySetManager.cpp
YangKian/LogDevice
e5c2168c11e9de867a1bcf519f95016e1c879b5c
[ "BSD-3-Clause" ]
1,831
2018-09-12T15:41:52.000Z
2022-01-05T02:38:03.000Z
logdevice/common/StickyCopySetManager.cpp
YangKian/LogDevice
e5c2168c11e9de867a1bcf519f95016e1c879b5c
[ "BSD-3-Clause" ]
183
2018-09-12T16:14:59.000Z
2021-12-07T15:49:43.000Z
logdevice/common/StickyCopySetManager.cpp
YangKian/LogDevice
e5c2168c11e9de867a1bcf519f95016e1c879b5c
[ "BSD-3-Clause" ]
228
2018-09-12T15:41:51.000Z
2022-01-05T08:12:09.000Z
/** * Copyright (c) 2017-present, Facebook, Inc. and its affiliates. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. */ #include "logdevice/common/StickyCopySetManager.h" #include <shared_mutex> #include <folly/Memory.h> #include "logdevice/common/debug.h" namespace facebook { namespace logdevice { using NodeStatus = NodeAvailabilityChecker::NodeStatus; CopySetSelector::Result StickyCopySetManager::getCopySet(StoreChainLink copyset_out[], copyset_size_t* copyset_size_out, bool* chain_out, const AppendContext& append_ctx, folly::Optional<lsn_t>& block_starting_lsn_out, CopySetManager::State& csm_state) { ld_check(copyset_out != nullptr); ld_check(copyset_size_out != nullptr); State& state = checked_downcast<State&>(csm_state); std::shared_lock<folly::SharedMutex> lock(mutex_); size_t invalid_block_seq_no = 0; // returns true if we have to change the copyset auto block_invalid = [&, this]() { return (invalid_block_seq_no == block_seq_no_) || shouldStartNewBlock(state); }; do { // For out-of-block records, we use the current block's copyset anyway. We // will store these as single records though. It's OK for old records to // cause us to start new blocks, as this will only happen if the current // copyset is gone bad. if (block_invalid()) { lock.unlock(); std::unique_lock<folly::SharedMutex> u_lock(mutex_); // Re-checking the state after relock if (block_invalid()) { // trying to start a new block if (!startNewBlock(state, append_ctx, chain_out)) { return CopySetSelector::Result::FAILED; } } u_lock.unlock(); lock.lock(); } ld_check(copyset_.size() > 0); // We assume that the underlying copyset selector checks node availability // on the copyset too, before issuing it to use with a positive result. // Thus, the following check is only here to detect changes between calls // to the copyset selector and should not turn this into an endless loop. if (!checkAndOutputNodes(copyset_out, copyset_size_out, chain_out)) { invalid_block_seq_no = block_seq_no_; } } while (invalid_block_seq_no == block_seq_no_); if (send_block_records_ && append_ctx.lsn >= current_block_starting_lsn_) { // This record is part of a block with this starting LSN block_starting_lsn_out.assign(current_block_starting_lsn_); } else { // This is a single (out-of-block) record block_starting_lsn_out.assign(LSN_INVALID); } onCopySetAssigned(state, append_ctx); ld_check(current_block_css_result_ == CopySetSelector::Result::SUCCESS); return current_block_css_result_; } CopySetSelector::Result StickyCopySetManager::getCopysetUsingUnderlyingSelector( logid_t log_id, StoreChainLink copyset_out[], copyset_size_t* copyset_size_out) { ld_check(copyset_out != nullptr); ld_check(copyset_size_out != nullptr); std::shared_lock<folly::SharedMutex> lock(mutex_); auto result = underlying_selector_->select(copyset_out, copyset_size_out); lock.unlock(); if (result == CopySetSelector::Result::FAILED) { RATELIMIT_ERROR( std::chrono::seconds(1), 1, "Underlying copyset selector failed to pick a copyset for log:%lu", log_id.val_); return result; } ld_check(*copyset_size_out > 0); return result; } bool StickyCopySetManager::checkAndOutputNodes(StoreChainLink copyset_out[], copyset_size_t* copyset_size_out, bool* chain_out) const { bool local_chain_out = (chain_out ? *chain_out : false); copyset_size_t offset = 0; for (auto shard : copyset_) { StoreChainLink destination; auto node_status = deps_->getNodeAvailability()->checkNode( nodeset_state_.get(), shard, &destination); switch (node_status) { case NodeStatus::AVAILABLE_NOCHAIN: local_chain_out = false; break; case NodeStatus::AVAILABLE: break; case NodeStatus::NOT_AVAILABLE: return false; } // we might write an incomplete copyset here, but that's okay, as we won't // set copyset_size_out if we fail copyset_out[offset++] = destination; } *copyset_size_out = offset; if (chain_out) { *chain_out = local_chain_out; } return true; }; bool StickyCopySetManager::shouldStartNewBlock(const State& state) const { if (current_block_starting_lsn_ == LSN_INVALID) { // we should start a new block if we don't have a copyset return true; } // In a single-copyset scenario we are changing the copyset with every // block. // TODO: consider not doing that for a multiple-copyset scenario? if (current_block_bytes_written_ >= block_size_threshold_) { return true; } // Start a new block if the current one has expired if (current_block_expiration_ < std::chrono::steady_clock::now()) { return true; } if (state.last_tried_block_seq_no == block_seq_no_) { // We tried this copyset already, it failed. // TODO: should we retry to any of the copysets we already tried before // breaking the block? return true; } return false; } bool StickyCopySetManager::startNewBlock(State& csm_state, const AppendContext& /*append_ctx*/, bool* chain_out) { StoreChainLink copyset[COPYSET_SIZE_MAX]; copyset_size_t size = 0; auto result = underlying_selector_->select( copyset, &size, chain_out, csm_state.css_state.get()); if (result == CopySetSelector::Result::FAILED) { return false; } shuffleCopySet(copyset, size, chain_out ? *chain_out : false); copyset_.clear(); for (size_t i = 0; i < size; ++i) { copyset_.push_back(copyset[i].destination); } ++block_seq_no_; lsn_t max_lsn = max_lsn_seen_.load(); // Since this is happening under a lock, // no one will modify this while we are // here. current_block_starting_lsn_ = max_lsn + 1; current_block_bytes_written_ = 0; current_block_expiration_ = std::chrono::steady_clock::now() + block_time_threshold_; current_block_css_result_ = result; return true; } void StickyCopySetManager::onCopySetAssigned(State& state, const AppendContext& append_ctx) { // Lots of records being written in parallel might lead to the block // extending past the threshold, but we are not too concerned about that. current_block_bytes_written_ += append_ctx.payload_size; // storing the current LSN as the max if it's larger than what we've seen // already atomic_fetch_max(max_lsn_seen_, append_ctx.lsn); // Updating the state so we know whether to change to a new block if this // wave fails state.last_tried_block_seq_no = block_seq_no_; } // see docblock in CopySetSelector::createState() std::unique_ptr<CopySetManager::State> StickyCopySetManager::createState() const { return std::make_unique<StickyCopySetManager::State>( underlying_selector_->createState()); } StickyCopySetManager::StickyCopySetManager( std::unique_ptr<CopySetSelector> selector, std::shared_ptr<NodeSetState> nodeset_state, size_t sticky_copysets_block_size, std::chrono::milliseconds sticky_copysets_block_max_time, const CopySetSelectorDependencies* deps) : CopySetManager(std::move(selector), nodeset_state), block_size_threshold_(sticky_copysets_block_size), block_time_threshold_(sticky_copysets_block_max_time), deps_(deps) {} }} // namespace facebook::logdevice
34.344828
80
0.67997
YangKian
1d51ef4c6743a3b4b85dd73552808e70a1b04c75
8,437
cpp
C++
TAO/tests/Bug_2319_Regression/server.cpp
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
36
2015-01-10T07:27:33.000Z
2022-03-07T03:32:08.000Z
TAO/tests/Bug_2319_Regression/server.cpp
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
2
2018-08-13T07:30:51.000Z
2019-02-25T03:04:31.000Z
TAO/tests/Bug_2319_Regression/server.cpp
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
38
2015-01-08T14:12:06.000Z
2022-01-19T08:33:00.000Z
// $Id: server.cpp 84563 2009-02-23 08:13:54Z johnnyw $ #include "ace/Thread_Manager.h" #include "ace/OS_NS_stdio.h" #include "ace/OS_NS_unistd.h" #include "ace/Get_Opt.h" #include "TestS.h" #include "TestC.h" int num_calls = 10; // total calls client is going to make const int sleep_time = 1; // sleep for 1 sec on each call // This should equal num_calls within 'sleep * num_calls' seconds int calls_received = 0; const ACE_TCHAR *ior = ACE_TEXT("file://test.ior"); const ACE_TCHAR *ior_file = ACE_TEXT("test.ior"); /***************************/ /*** Servant Declaration ***/ /***************************/ class ST_AMH_Servant : public virtual POA_Test::AMH_Roundtrip { public: ST_AMH_Servant (CORBA::ORB_ptr orb); void test_method (Test::AMH_RoundtripResponseHandler_ptr _tao_rh, Test::Timestamp send_time); protected: CORBA::ORB_ptr orb_; }; /****************************/ /**** Server Declaration ****/ /****************************/ /** Class that performs all 'dirty' initialisation work that is common to all the AMH servers and 'hides' all the common ORB functions. */ class ST_AMH_Server { public: ST_AMH_Server (void); virtual ~ST_AMH_Server (); /// ORB inititalisation stuff int start_orb_and_poa (const CORBA::ORB_var &_orb); /// register the servant with the poa virtual void register_servant (ST_AMH_Servant *servant); /// orb-perform_work () abstraction virtual void run_event_loop (); public: protected: CORBA::ORB_ptr orb_; PortableServer::POA_var root_poa_; private: /// Write servant IOR to file specified with the '-o' option int write_ior_to_file (CORBA::String_var ior); }; // ------------------------------------------------------------------------ // ------------------------------------------------------------------------ // ------------------------------------------------------------------------ // ------------------------------------------------------------------------ // int parse_args (int argc, ACE_TCHAR *argv[]) { ACE_Get_Opt get_opts (argc, argv, ACE_TEXT("n:o:k:")); int c; while ((c = get_opts ()) != -1) switch (c) { case 'n': num_calls = ACE_OS::atoi (get_opts.opt_arg ()); break; case 'o': ior_file = get_opts.opt_arg (); break; case 'k': ior = get_opts.opt_arg (); break; default: break; } return 0; } /***************************/ /*** Servant Definition ***/ /***************************/ // ------------------------------------------------------------------------ // ST_AMH_Servant::ST_AMH_Servant (CORBA::ORB_ptr orb) : orb_(CORBA::ORB::_duplicate(orb)) { } // ------------------------------------------------------------------------ // void ST_AMH_Servant::test_method (Test::AMH_RoundtripResponseHandler_ptr, Test::Timestamp) { ACE_OS::printf("Recieved Timestamp # %d\n", calls_received); ACE_OS::sleep(1); ++calls_received; // When _tao_rh destructor is called, it shouldn't send anything to // the client as well } /*** Server Declaration ***/ // ------------------------------------------------------------------------ // ST_AMH_Server::ST_AMH_Server (void) { } // ------------------------------------------------------------------------ // ST_AMH_Server::~ST_AMH_Server () { try { this->root_poa_->destroy (1, 1); } catch (const CORBA::Exception& ex) { ex._tao_print_exception ("Exception caught:"); } } // ------------------------------------------------------------------------ // int ST_AMH_Server::start_orb_and_poa (const CORBA::ORB_var &_orb) { try { this->orb_ = CORBA::ORB::_duplicate(_orb.in ()); CORBA::Object_var poa_object = this->orb_->resolve_initial_references("RootPOA"); if (CORBA::is_nil (poa_object.in ())) ACE_ERROR_RETURN ((LM_ERROR, " (%P|%t) Unable to initialize the POA.\n"), 1); this->root_poa_ = PortableServer::POA::_narrow (poa_object.in ()); PortableServer::POAManager_var poa_manager = this->root_poa_->the_POAManager (); poa_manager->activate (); } catch (const CORBA::Exception& ex) { ex._tao_print_exception ("Exception caught:"); return -1; } return 0; } // ------------------------------------------------------------------------ // void ST_AMH_Server::register_servant (ST_AMH_Servant *servant) { try { CORBA::Object_var poa_object = this->orb_->resolve_initial_references("RootPOA"); PortableServer::POA_var root_poa = PortableServer::POA::_narrow (poa_object.in ()); PortableServer::ObjectId_var id = root_poa->activate_object (servant); CORBA::Object_var object = root_poa->id_to_reference (id.in ()); Test::Roundtrip_var roundtrip = Test::Roundtrip::_narrow (object.in ()); CORBA::String_var iorstr = this->orb_->object_to_string(roundtrip.in ()); (void) this->write_ior_to_file(iorstr); } catch (const CORBA::Exception& ex) { ex._tao_print_exception ("Exception caught:"); } } // ------------------------------------------------------------------------ // void ST_AMH_Server::run_event_loop () { try { ACE_Time_Value period (1, 0); while (1) { this->orb_->perform_work (&period); // when all calls from client have been recieved, exit if (calls_received == num_calls ) return; } } catch (const CORBA::Exception&) { } } // ------------------------------------------------------------------------ // int ST_AMH_Server::write_ior_to_file (CORBA::String_var iorstr) { // If the ior_output_file exists, output the ior to it FILE *output_file= ACE_OS::fopen (ior_file, "w"); if (output_file == 0) { ACE_ERROR ((LM_ERROR, "Cannot open output file for writing IOR: %s", ior_file)); return -1; } ACE_OS::fprintf (output_file, "%s", iorstr.in ()); ACE_OS::fclose (output_file); return 0; } // ------------------------------------------------------------------------ // static ACE_THR_FUNC_RETURN start_server(void* _arg) { ST_AMH_Server *amh_server = static_cast<ST_AMH_Server*>(_arg); amh_server->run_event_loop(); return 0; } // ------------------------------------------------------------------------ // static ACE_THR_FUNC_RETURN start_client(void* _arg) { Test::Roundtrip_var roundtrip(static_cast<Test::Roundtrip_ptr>(_arg)); // Do a couple of calls on the server. If the sever is trying to // do something stupid like sending an exception to us, then it // won't be able to handle more than 1 request from us. Test::Timestamp time = 10; for (int i = 0; i < num_calls; i++) { roundtrip->test_method(time); ACE_DEBUG ((LM_DEBUG, "Sent call # %d\n", i)); } return 0; } // ------------------------------------------------------------------------ // int ACE_TMAIN (int argc, ACE_TCHAR *argv[]) { if (parse_args (argc, argv) != 0) return 1; ST_AMH_Server amh_server; CORBA::ORB_var orb = CORBA::ORB_init (argc, argv); amh_server.start_orb_and_poa(orb); ST_AMH_Servant servant(orb.in()); amh_server.register_servant(&servant); CORBA::Object_var object = orb->string_to_object(ior); Test::Roundtrip_var roundtrip = Test::Roundtrip::_narrow(object.in ()); if (CORBA::is_nil(roundtrip.in())) { ACE_ERROR_RETURN ((LM_ERROR, "Nil Test::Roundtrip reference <%s>\n", ior), 1); } ACE_thread_t serverThr; ACE_thread_t clientThr; ACE_Thread_Manager::instance()->spawn(start_server, (void*)&amh_server, THR_NEW_LWP | THR_JOINABLE, &serverThr); ACE_Thread_Manager::instance()->spawn(start_client, (void*)roundtrip.in (), THR_NEW_LWP | THR_JOINABLE, &clientThr); ACE_Thread_Manager::instance()->join(clientThr); ACE_OS::printf("End client\n"); ACE_Thread_Manager::instance()->join(serverThr); ACE_OS::printf("End server\n"); orb->destroy(); return 0; }
25.566667
79
0.521986
cflowe
1d562b46272d0fc9fb6a4bbfea79f335292e5daa
10,045
cc
C++
google_apis/gcm/engine/checkin_request_unittest.cc
google-ar/chromium
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2,151
2020-04-18T07:31:17.000Z
2022-03-31T08:39:18.000Z
google_apis/gcm/engine/checkin_request_unittest.cc
harrymarkovskiy/WebARonARCore
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
395
2020-04-18T08:22:18.000Z
2021-12-08T13:04:49.000Z
google_apis/gcm/engine/checkin_request_unittest.cc
harrymarkovskiy/WebARonARCore
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
338
2020-04-18T08:03:10.000Z
2022-03-29T12:33:22.000Z
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <stdint.h> #include <string> #include "google_apis/gcm/engine/checkin_request.h" #include "google_apis/gcm/engine/gcm_request_test_base.h" #include "google_apis/gcm/monitoring/fake_gcm_stats_recorder.h" #include "google_apis/gcm/protocol/checkin.pb.h" namespace gcm { const uint64_t kAndroidId = 42UL; const uint64_t kBlankAndroidId = 999999UL; const uint64_t kBlankSecurityToken = 999999UL; const char kCheckinURL[] = "http://foo.bar/checkin"; const char kChromeVersion[] = "Version String"; const uint64_t kSecurityToken = 77; const char kSettingsDigest[] = "settings_digest"; const char kEmailAddress[] = "test_user@gmail.com"; const char kTokenValue[] = "token_value"; class CheckinRequestTest : public GCMRequestTestBase { public: enum ResponseScenario { VALID_RESPONSE, // Both android_id and security_token set in response. MISSING_ANDROID_ID, // android_id is missing. MISSING_SECURITY_TOKEN, // security_token is missing. ANDROID_ID_IS_ZER0, // android_id is 0. SECURITY_TOKEN_IS_ZERO // security_token is 0. }; CheckinRequestTest(); ~CheckinRequestTest() override; void FetcherCallback(net::HttpStatusCode response_code, const checkin_proto::AndroidCheckinResponse& response); void CreateRequest(uint64_t android_id, uint64_t security_token); void SetResponseScenario(ResponseScenario response_scenario); protected: bool callback_called_; net::HttpStatusCode response_code_ = net::HTTP_CONTINUE; // Something that's not used in tests. uint64_t android_id_; uint64_t security_token_; int checkin_device_type_; checkin_proto::ChromeBuildProto chrome_build_proto_; std::unique_ptr<CheckinRequest> request_; FakeGCMStatsRecorder recorder_; }; CheckinRequestTest::CheckinRequestTest() : callback_called_(false), android_id_(kBlankAndroidId), security_token_(kBlankSecurityToken), checkin_device_type_(0) { } CheckinRequestTest::~CheckinRequestTest() {} void CheckinRequestTest::FetcherCallback( net::HttpStatusCode response_code, const checkin_proto::AndroidCheckinResponse& checkin_response) { callback_called_ = true; response_code_ = response_code; if (checkin_response.has_android_id()) android_id_ = checkin_response.android_id(); if (checkin_response.has_security_token()) security_token_ = checkin_response.security_token(); } void CheckinRequestTest::CreateRequest(uint64_t android_id, uint64_t security_token) { // First setup a chrome_build protobuf. chrome_build_proto_.set_platform( checkin_proto::ChromeBuildProto::PLATFORM_LINUX); chrome_build_proto_.set_channel( checkin_proto::ChromeBuildProto::CHANNEL_CANARY); chrome_build_proto_.set_chrome_version(kChromeVersion); std::map<std::string, std::string> account_tokens; account_tokens[kEmailAddress] = kTokenValue; CheckinRequest::RequestInfo request_info(android_id, security_token, account_tokens, kSettingsDigest, chrome_build_proto_); // Then create a request with that protobuf and specified android_id, // security_token. request_.reset(new CheckinRequest( GURL(kCheckinURL), request_info, GetBackoffPolicy(), base::Bind(&CheckinRequestTest::FetcherCallback, base::Unretained(this)), url_request_context_getter(), &recorder_)); // Setting android_id_ and security_token_ to blank value, not used elsewhere // in the tests. callback_called_ = false; android_id_ = kBlankAndroidId; security_token_ = kBlankSecurityToken; } void CheckinRequestTest::SetResponseScenario( ResponseScenario response_scenario) { checkin_proto::AndroidCheckinResponse response; response.set_stats_ok(true); uint64_t android_id = response_scenario == ANDROID_ID_IS_ZER0 ? 0 : kAndroidId; uint64_t security_token = response_scenario == SECURITY_TOKEN_IS_ZERO ? 0 : kSecurityToken; if (response_scenario != MISSING_ANDROID_ID) response.set_android_id(android_id); if (response_scenario != MISSING_SECURITY_TOKEN) response.set_security_token(security_token); std::string response_string; response.SerializeToString(&response_string); SetResponse(net::HTTP_OK, response_string); } TEST_F(CheckinRequestTest, FetcherDataAndURL) { CreateRequest(kAndroidId, kSecurityToken); request_->Start(); // Get data sent by request. net::TestURLFetcher* fetcher = GetFetcher(); ASSERT_TRUE(fetcher); EXPECT_EQ(GURL(kCheckinURL), fetcher->GetOriginalURL()); checkin_proto::AndroidCheckinRequest request_proto; request_proto.ParseFromString(fetcher->upload_data()); EXPECT_EQ(kAndroidId, static_cast<uint64_t>(request_proto.id())); EXPECT_EQ(kSecurityToken, request_proto.security_token()); EXPECT_EQ(chrome_build_proto_.platform(), request_proto.checkin().chrome_build().platform()); EXPECT_EQ(chrome_build_proto_.chrome_version(), request_proto.checkin().chrome_build().chrome_version()); EXPECT_EQ(chrome_build_proto_.channel(), request_proto.checkin().chrome_build().channel()); EXPECT_EQ(2, request_proto.account_cookie_size()); EXPECT_EQ(kEmailAddress, request_proto.account_cookie(0)); EXPECT_EQ(kTokenValue, request_proto.account_cookie(1)); #if defined(CHROME_OS) EXPECT_EQ(checkin_proto::DEVICE_CHROME_OS, request_proto.checkin().type()); #else EXPECT_EQ(checkin_proto::DEVICE_CHROME_BROWSER, request_proto.checkin().type()); #endif EXPECT_EQ(kSettingsDigest, request_proto.digest()); } TEST_F(CheckinRequestTest, ResponseBodyEmpty) { CreateRequest(0u, 0u); request_->Start(); SetResponse(net::HTTP_OK, std::string()); CompleteFetch(); EXPECT_FALSE(callback_called_); SetResponseScenario(VALID_RESPONSE); CompleteFetch(); EXPECT_TRUE(callback_called_); EXPECT_EQ(net::HTTP_OK, response_code_); EXPECT_EQ(kAndroidId, android_id_); EXPECT_EQ(kSecurityToken, security_token_); } TEST_F(CheckinRequestTest, ResponseBodyCorrupted) { CreateRequest(0u, 0u); request_->Start(); SetResponse(net::HTTP_OK, "Corrupted response body"); CompleteFetch(); EXPECT_FALSE(callback_called_); SetResponseScenario(VALID_RESPONSE); CompleteFetch(); EXPECT_TRUE(callback_called_); EXPECT_EQ(net::HTTP_OK, response_code_); EXPECT_EQ(kAndroidId, android_id_); EXPECT_EQ(kSecurityToken, security_token_); } TEST_F(CheckinRequestTest, ResponseHttpStatusUnauthorized) { CreateRequest(0u, 0u); request_->Start(); SetResponse(net::HTTP_UNAUTHORIZED, std::string()); CompleteFetch(); EXPECT_TRUE(callback_called_); EXPECT_EQ(net::HTTP_UNAUTHORIZED, response_code_); EXPECT_EQ(kBlankAndroidId, android_id_); EXPECT_EQ(kBlankSecurityToken, security_token_); } TEST_F(CheckinRequestTest, ResponseHttpStatusBadRequest) { CreateRequest(0u, 0u); request_->Start(); SetResponse(net::HTTP_BAD_REQUEST, std::string()); CompleteFetch(); EXPECT_TRUE(callback_called_); EXPECT_EQ(net::HTTP_BAD_REQUEST, response_code_); EXPECT_EQ(kBlankAndroidId, android_id_); EXPECT_EQ(kBlankSecurityToken, security_token_); } TEST_F(CheckinRequestTest, ResponseHttpStatusNotOK) { CreateRequest(0u, 0u); request_->Start(); SetResponse(net::HTTP_INTERNAL_SERVER_ERROR, std::string()); CompleteFetch(); EXPECT_FALSE(callback_called_); SetResponseScenario(VALID_RESPONSE); CompleteFetch(); EXPECT_TRUE(callback_called_); EXPECT_EQ(net::HTTP_OK, response_code_); EXPECT_EQ(kAndroidId, android_id_); EXPECT_EQ(kSecurityToken, security_token_); } TEST_F(CheckinRequestTest, ResponseMissingAndroidId) { CreateRequest(0u, 0u); request_->Start(); SetResponseScenario(MISSING_ANDROID_ID); CompleteFetch(); EXPECT_FALSE(callback_called_); SetResponseScenario(VALID_RESPONSE); CompleteFetch(); EXPECT_TRUE(callback_called_); EXPECT_EQ(kAndroidId, android_id_); EXPECT_EQ(kSecurityToken, security_token_); } TEST_F(CheckinRequestTest, ResponseMissingSecurityToken) { CreateRequest(0u, 0u); request_->Start(); SetResponseScenario(MISSING_SECURITY_TOKEN); CompleteFetch(); EXPECT_FALSE(callback_called_); SetResponseScenario(VALID_RESPONSE); CompleteFetch(); EXPECT_TRUE(callback_called_); EXPECT_EQ(kAndroidId, android_id_); EXPECT_EQ(kSecurityToken, security_token_); } TEST_F(CheckinRequestTest, AndroidIdEqualsZeroInResponse) { CreateRequest(0u, 0u); request_->Start(); SetResponseScenario(ANDROID_ID_IS_ZER0); CompleteFetch(); EXPECT_FALSE(callback_called_); SetResponseScenario(VALID_RESPONSE); CompleteFetch(); EXPECT_TRUE(callback_called_); EXPECT_EQ(kAndroidId, android_id_); EXPECT_EQ(kSecurityToken, security_token_); } TEST_F(CheckinRequestTest, SecurityTokenEqualsZeroInResponse) { CreateRequest(0u, 0u); request_->Start(); SetResponseScenario(SECURITY_TOKEN_IS_ZERO); CompleteFetch(); EXPECT_FALSE(callback_called_); SetResponseScenario(VALID_RESPONSE); CompleteFetch(); EXPECT_TRUE(callback_called_); EXPECT_EQ(kAndroidId, android_id_); EXPECT_EQ(kSecurityToken, security_token_); } TEST_F(CheckinRequestTest, SuccessfulFirstTimeCheckin) { CreateRequest(0u, 0u); request_->Start(); SetResponseScenario(VALID_RESPONSE); CompleteFetch(); EXPECT_TRUE(callback_called_); EXPECT_EQ(kAndroidId, android_id_); EXPECT_EQ(kSecurityToken, security_token_); } TEST_F(CheckinRequestTest, SuccessfulSubsequentCheckin) { CreateRequest(kAndroidId, kSecurityToken); request_->Start(); SetResponseScenario(VALID_RESPONSE); CompleteFetch(); EXPECT_TRUE(callback_called_); EXPECT_EQ(kAndroidId, android_id_); EXPECT_EQ(kSecurityToken, security_token_); } } // namespace gcm
29.631268
79
0.757889
google-ar
1d57552649962a2385765a987376e50840a60437
6,617
cpp
C++
src/Math/Vector4d.cpp
bodguy/CrossPlatform
c8fb740456f8c9b0e6af495958d6b5d6c2d7946f
[ "Apache-2.0" ]
6
2018-07-20T00:59:54.000Z
2021-08-21T15:55:48.000Z
src/Math/Vector4d.cpp
bodguy/CrossPlatform
c8fb740456f8c9b0e6af495958d6b5d6c2d7946f
[ "Apache-2.0" ]
9
2018-07-17T15:03:22.000Z
2019-10-05T01:02:31.000Z
src/Math/Vector4d.cpp
bodguy/CrossPlatform
c8fb740456f8c9b0e6af495958d6b5d6c2d7946f
[ "Apache-2.0" ]
1
2019-10-27T01:54:38.000Z
2019-10-27T01:54:38.000Z
// Copyright (C) 2017 by bodguy // This code is licensed under Apache 2.0 license (see LICENSE.md for details) #include "Vector4d.h" #include <algorithm> // until c++11 for std::swap #include <cmath> #include <utility> // since c++11 for std::swap #include "Math.h" #include "Vector2d.h" #include "Vector3d.h" namespace Theodore { Vector4d::Vector4d() : x(0.f), y(0.f), z(0.f), w(1.f) {} Vector4d::Vector4d(float tx, float ty, float tz, float tw) : x(tx), y(ty), z(tz), w(tw) {} Vector4d::Vector4d(const Vector2d& other) { x = other.x; y = other.y; z = 0.0f; w = 0.0f; } Vector4d::Vector4d(const Vector3d& other) { x = other.x; y = other.y; z = other.z; w = 0.0f; } Vector4d::Vector4d(const Vector2d& other, float tz, float tw) { x = other.x; y = other.y; z = tz; w = tw; } Vector4d::Vector4d(const Vector3d& other, float tw) { x = other.x; y = other.y; z = other.z; w = tw; } Vector4d::Vector4d(const Vector4d& other) { x = other.x; y = other.y; z = other.z; w = other.w; } Vector4d& Vector4d::operator=(Vector4d other) { Swap(*this, other); return *this; } float Vector4d::operator[](unsigned int i) const { switch (i) { case 0: return x; case 1: return y; case 2: return z; case 3: return w; default: return x; } } Vector4d Vector4d::operator+(const Vector4d& other) const { // using op= (more effective c++ section 22) return Vector4d(*this) += other; } Vector4d& Vector4d::operator+=(const Vector4d& other) { x += other.x; y += other.y; z += other.z; w += other.w; return *this; } Vector4d Vector4d::operator-(const Vector4d& other) const { // using op= (more effective c++ section 22) return Vector4d(*this) -= other; } Vector4d& Vector4d::operator-=(const Vector4d& other) { x -= other.x; y -= other.y; z -= other.z; w -= other.w; return *this; } Vector4d Vector4d::operator*(const Vector4d& other) const { // using op= (more effective c++ section 22) return Vector4d(*this) *= other; } Vector4d& Vector4d::operator*=(const Vector4d& other) { x *= other.x; y *= other.y; z *= other.z; w *= other.w; return *this; } Vector4d Vector4d::operator/(const Vector4d& other) const { // using op= (more effective c++ section 22) return Vector4d(*this) /= other; } Vector4d& Vector4d::operator/=(const Vector4d& other) { x /= other.x; y /= other.y; z /= other.z; w /= other.w; return *this; } float Vector4d::DotProduct(const Vector4d& a, const Vector4d& b) { return a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w; } Vector4d Vector4d::operator+(const float scalar) const { return Vector4d(*this) += scalar; } Vector4d& Vector4d::operator+=(const float scalar) { x += scalar; y += scalar; z += scalar; w += scalar; return *this; } Vector4d Vector4d::operator-(const float scalar) const { return Vector4d(*this) -= scalar; } Vector4d& Vector4d::operator-=(const float scalar) { x -= scalar; y -= scalar; z -= scalar; w -= scalar; return *this; } Vector4d Vector4d::operator*(const float scalar) const { return Vector4d(*this) *= scalar; } Vector4d& Vector4d::operator*=(const float scalar) { x *= scalar; y *= scalar; z *= scalar; w *= scalar; return *this; } Vector4d Vector4d::operator/(const float scalar) const { return Vector4d(*this) /= scalar; } Vector4d& Vector4d::operator/=(const float scalar) { x /= scalar; y /= scalar; z /= scalar; w /= scalar; return *this; } bool Vector4d::operator<(const Vector4d& other) const { return x < other.x && y < other.y && z < other.z && w < other.w; } bool Vector4d::operator>(const Vector4d& other) const { return x > other.x && y > other.y && z > other.z && w > other.w; } bool Vector4d::operator<=(const Vector4d& other) const { return x <= other.x && y <= other.y && z <= other.z && w <= other.w; } bool Vector4d::operator>=(const Vector4d& other) const { return x >= other.x && y >= other.y && z >= other.z && w >= other.w; } bool Vector4d::operator==(const Vector4d& other) const { return (Math::IsEqual(x, other.x) && Math::IsEqual(y, other.y) && Math::IsEqual(z, other.z) && Math::IsEqual(w, other.w)); } bool Vector4d::operator!=(const Vector4d& other) const { return !(*this == other); } bool Vector4d::operator<(const float scalar) const { return x < scalar && y < scalar && z < scalar; } bool Vector4d::operator>(const float scalar) const { return x > scalar && y > scalar && z > scalar; } bool Vector4d::operator<=(const float scalar) const { return x <= scalar && y <= scalar && z <= scalar; } bool Vector4d::operator>=(const float scalar) const { return x >= scalar && y >= scalar && z >= scalar; } bool Vector4d::operator==(const float scalar) const { // scalar only equal with vector components. return (Math::IsEqual(x, scalar) && Math::IsEqual(y, scalar) && Math::IsEqual(z, scalar)); } bool Vector4d::operator!=(const float scalar) const { return !(*this == scalar); } Vector4d& Vector4d::Normalize() { float len = std::sqrt(x * x + y * y + z * z + w * w); if (Math::IsZero(len) || Math::IsEqual(len, 1.f)) return *this; float inv = 1 / len; x = x * inv; y = y * inv; z = z * inv; return *this; } float Vector4d::Length() { return std::sqrt(x * x + y * y + z * z + w * w); } Vector3d Vector4d::ToVector3d(const Vector4d& other) { return Vector3d(other.x, other.y, other.z); } Vector4d Vector4d::Absolute(const Vector4d& other) { return Vector4d(std::fabsf(other.x), std::fabsf(other.y), std::fabsf(other.z), std::fabsf(other.w)); } void Vector4d::Swap(Vector4d& first, Vector4d& second) { using std::swap; swap(first.x, second.x); swap(first.y, second.y); swap(first.z, second.z); swap(first.w, second.w); } const Vector4d Vector4d::up = Vector4d(0.f, 1.f, 0.f, 1.f); const Vector4d Vector4d::down = Vector4d(0.f, -1.f, 0.f, 1.f); const Vector4d Vector4d::left = Vector4d(-1.f, 0.f, 0.f, 1.f); const Vector4d Vector4d::right = Vector4d(1.f, 0.f, 0.f, 1.f); const Vector4d Vector4d::forward = Vector4d(0.f, 0.f, -1.f, 1.f); const Vector4d Vector4d::backward = Vector4d(0.f, 0.f, 1.f, 1.f); const Vector4d Vector4d::one = Vector4d(1.f, 1.f, 1.f, 1.f); const Vector4d Vector4d::zero = Vector4d(0.f, 0.f, 0.f, 0.f); } // namespace Theodore
27.686192
183
0.598156
bodguy
1d58a0e2d444eca04f97fa660467b8921a3386aa
13,606
cpp
C++
android-31/android/provider/DocumentsProvider.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
12
2020-03-26T02:38:56.000Z
2022-03-14T08:17:26.000Z
android-31/android/provider/DocumentsProvider.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
1
2021-01-27T06:07:45.000Z
2021-11-13T19:19:43.000Z
android-29/android/provider/DocumentsProvider.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
3
2021-02-02T12:34:55.000Z
2022-03-08T07:45:57.000Z
#include "../../JArray.hpp" #include "../content/ContentValues.hpp" #include "../content/Context.hpp" #include "../content/IntentSender.hpp" #include "../content/pm/ProviderInfo.hpp" #include "../content/res/AssetFileDescriptor.hpp" #include "../graphics/Point.hpp" #include "../net/Uri.hpp" #include "../os/Bundle.hpp" #include "../os/CancellationSignal.hpp" #include "../os/ParcelFileDescriptor.hpp" #include "./DocumentsContract_Path.hpp" #include "../../JString.hpp" #include "./DocumentsProvider.hpp" namespace android::provider { // Fields // QJniObject forward DocumentsProvider::DocumentsProvider(QJniObject obj) : android::content::ContentProvider(obj) {} // Constructors DocumentsProvider::DocumentsProvider() : android::content::ContentProvider( "android.provider.DocumentsProvider", "()V" ) {} // Methods void DocumentsProvider::attachInfo(android::content::Context arg0, android::content::pm::ProviderInfo arg1) const { callMethod<void>( "attachInfo", "(Landroid/content/Context;Landroid/content/pm/ProviderInfo;)V", arg0.object(), arg1.object() ); } android::os::Bundle DocumentsProvider::call(JString arg0, JString arg1, android::os::Bundle arg2) const { return callObjectMethod( "call", "(Ljava/lang/String;Ljava/lang/String;Landroid/os/Bundle;)Landroid/os/Bundle;", arg0.object<jstring>(), arg1.object<jstring>(), arg2.object() ); } android::net::Uri DocumentsProvider::canonicalize(android::net::Uri arg0) const { return callObjectMethod( "canonicalize", "(Landroid/net/Uri;)Landroid/net/Uri;", arg0.object() ); } JString DocumentsProvider::copyDocument(JString arg0, JString arg1) const { return callObjectMethod( "copyDocument", "(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;", arg0.object<jstring>(), arg1.object<jstring>() ); } JString DocumentsProvider::createDocument(JString arg0, JString arg1, JString arg2) const { return callObjectMethod( "createDocument", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;", arg0.object<jstring>(), arg1.object<jstring>(), arg2.object<jstring>() ); } android::content::IntentSender DocumentsProvider::createWebLinkIntent(JString arg0, android::os::Bundle arg1) const { return callObjectMethod( "createWebLinkIntent", "(Ljava/lang/String;Landroid/os/Bundle;)Landroid/content/IntentSender;", arg0.object<jstring>(), arg1.object() ); } jint DocumentsProvider::delete_(android::net::Uri arg0, JString arg1, JArray arg2) const { return callMethod<jint>( "delete", "(Landroid/net/Uri;Ljava/lang/String;[Ljava/lang/String;)I", arg0.object(), arg1.object<jstring>(), arg2.object<jarray>() ); } void DocumentsProvider::deleteDocument(JString arg0) const { callMethod<void>( "deleteDocument", "(Ljava/lang/String;)V", arg0.object<jstring>() ); } void DocumentsProvider::ejectRoot(JString arg0) const { callMethod<void>( "ejectRoot", "(Ljava/lang/String;)V", arg0.object<jstring>() ); } android::provider::DocumentsContract_Path DocumentsProvider::findDocumentPath(JString arg0, JString arg1) const { return callObjectMethod( "findDocumentPath", "(Ljava/lang/String;Ljava/lang/String;)Landroid/provider/DocumentsContract$Path;", arg0.object<jstring>(), arg1.object<jstring>() ); } android::os::Bundle DocumentsProvider::getDocumentMetadata(JString arg0) const { return callObjectMethod( "getDocumentMetadata", "(Ljava/lang/String;)Landroid/os/Bundle;", arg0.object<jstring>() ); } JArray DocumentsProvider::getDocumentStreamTypes(JString arg0, JString arg1) const { return callObjectMethod( "getDocumentStreamTypes", "(Ljava/lang/String;Ljava/lang/String;)[Ljava/lang/String;", arg0.object<jstring>(), arg1.object<jstring>() ); } JString DocumentsProvider::getDocumentType(JString arg0) const { return callObjectMethod( "getDocumentType", "(Ljava/lang/String;)Ljava/lang/String;", arg0.object<jstring>() ); } JArray DocumentsProvider::getStreamTypes(android::net::Uri arg0, JString arg1) const { return callObjectMethod( "getStreamTypes", "(Landroid/net/Uri;Ljava/lang/String;)[Ljava/lang/String;", arg0.object(), arg1.object<jstring>() ); } JString DocumentsProvider::getType(android::net::Uri arg0) const { return callObjectMethod( "getType", "(Landroid/net/Uri;)Ljava/lang/String;", arg0.object() ); } android::net::Uri DocumentsProvider::insert(android::net::Uri arg0, android::content::ContentValues arg1) const { return callObjectMethod( "insert", "(Landroid/net/Uri;Landroid/content/ContentValues;)Landroid/net/Uri;", arg0.object(), arg1.object() ); } jboolean DocumentsProvider::isChildDocument(JString arg0, JString arg1) const { return callMethod<jboolean>( "isChildDocument", "(Ljava/lang/String;Ljava/lang/String;)Z", arg0.object<jstring>(), arg1.object<jstring>() ); } JString DocumentsProvider::moveDocument(JString arg0, JString arg1, JString arg2) const { return callObjectMethod( "moveDocument", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;", arg0.object<jstring>(), arg1.object<jstring>(), arg2.object<jstring>() ); } android::content::res::AssetFileDescriptor DocumentsProvider::openAssetFile(android::net::Uri arg0, JString arg1) const { return callObjectMethod( "openAssetFile", "(Landroid/net/Uri;Ljava/lang/String;)Landroid/content/res/AssetFileDescriptor;", arg0.object(), arg1.object<jstring>() ); } android::content::res::AssetFileDescriptor DocumentsProvider::openAssetFile(android::net::Uri arg0, JString arg1, android::os::CancellationSignal arg2) const { return callObjectMethod( "openAssetFile", "(Landroid/net/Uri;Ljava/lang/String;Landroid/os/CancellationSignal;)Landroid/content/res/AssetFileDescriptor;", arg0.object(), arg1.object<jstring>(), arg2.object() ); } android::os::ParcelFileDescriptor DocumentsProvider::openDocument(JString arg0, JString arg1, android::os::CancellationSignal arg2) const { return callObjectMethod( "openDocument", "(Ljava/lang/String;Ljava/lang/String;Landroid/os/CancellationSignal;)Landroid/os/ParcelFileDescriptor;", arg0.object<jstring>(), arg1.object<jstring>(), arg2.object() ); } android::content::res::AssetFileDescriptor DocumentsProvider::openDocumentThumbnail(JString arg0, android::graphics::Point arg1, android::os::CancellationSignal arg2) const { return callObjectMethod( "openDocumentThumbnail", "(Ljava/lang/String;Landroid/graphics/Point;Landroid/os/CancellationSignal;)Landroid/content/res/AssetFileDescriptor;", arg0.object<jstring>(), arg1.object(), arg2.object() ); } android::os::ParcelFileDescriptor DocumentsProvider::openFile(android::net::Uri arg0, JString arg1) const { return callObjectMethod( "openFile", "(Landroid/net/Uri;Ljava/lang/String;)Landroid/os/ParcelFileDescriptor;", arg0.object(), arg1.object<jstring>() ); } android::os::ParcelFileDescriptor DocumentsProvider::openFile(android::net::Uri arg0, JString arg1, android::os::CancellationSignal arg2) const { return callObjectMethod( "openFile", "(Landroid/net/Uri;Ljava/lang/String;Landroid/os/CancellationSignal;)Landroid/os/ParcelFileDescriptor;", arg0.object(), arg1.object<jstring>(), arg2.object() ); } android::content::res::AssetFileDescriptor DocumentsProvider::openTypedAssetFile(android::net::Uri arg0, JString arg1, android::os::Bundle arg2) const { return callObjectMethod( "openTypedAssetFile", "(Landroid/net/Uri;Ljava/lang/String;Landroid/os/Bundle;)Landroid/content/res/AssetFileDescriptor;", arg0.object(), arg1.object<jstring>(), arg2.object() ); } android::content::res::AssetFileDescriptor DocumentsProvider::openTypedAssetFile(android::net::Uri arg0, JString arg1, android::os::Bundle arg2, android::os::CancellationSignal arg3) const { return callObjectMethod( "openTypedAssetFile", "(Landroid/net/Uri;Ljava/lang/String;Landroid/os/Bundle;Landroid/os/CancellationSignal;)Landroid/content/res/AssetFileDescriptor;", arg0.object(), arg1.object<jstring>(), arg2.object(), arg3.object() ); } android::content::res::AssetFileDescriptor DocumentsProvider::openTypedDocument(JString arg0, JString arg1, android::os::Bundle arg2, android::os::CancellationSignal arg3) const { return callObjectMethod( "openTypedDocument", "(Ljava/lang/String;Ljava/lang/String;Landroid/os/Bundle;Landroid/os/CancellationSignal;)Landroid/content/res/AssetFileDescriptor;", arg0.object<jstring>(), arg1.object<jstring>(), arg2.object(), arg3.object() ); } JObject DocumentsProvider::query(android::net::Uri arg0, JArray arg1, android::os::Bundle arg2, android::os::CancellationSignal arg3) const { return callObjectMethod( "query", "(Landroid/net/Uri;[Ljava/lang/String;Landroid/os/Bundle;Landroid/os/CancellationSignal;)Landroid/database/Cursor;", arg0.object(), arg1.object<jarray>(), arg2.object(), arg3.object() ); } JObject DocumentsProvider::query(android::net::Uri arg0, JArray arg1, JString arg2, JArray arg3, JString arg4) const { return callObjectMethod( "query", "(Landroid/net/Uri;[Ljava/lang/String;Ljava/lang/String;[Ljava/lang/String;Ljava/lang/String;)Landroid/database/Cursor;", arg0.object(), arg1.object<jarray>(), arg2.object<jstring>(), arg3.object<jarray>(), arg4.object<jstring>() ); } JObject DocumentsProvider::query(android::net::Uri arg0, JArray arg1, JString arg2, JArray arg3, JString arg4, android::os::CancellationSignal arg5) const { return callObjectMethod( "query", "(Landroid/net/Uri;[Ljava/lang/String;Ljava/lang/String;[Ljava/lang/String;Ljava/lang/String;Landroid/os/CancellationSignal;)Landroid/database/Cursor;", arg0.object(), arg1.object<jarray>(), arg2.object<jstring>(), arg3.object<jarray>(), arg4.object<jstring>(), arg5.object() ); } JObject DocumentsProvider::queryChildDocuments(JString arg0, JArray arg1, android::os::Bundle arg2) const { return callObjectMethod( "queryChildDocuments", "(Ljava/lang/String;[Ljava/lang/String;Landroid/os/Bundle;)Landroid/database/Cursor;", arg0.object<jstring>(), arg1.object<jarray>(), arg2.object() ); } JObject DocumentsProvider::queryChildDocuments(JString arg0, JArray arg1, JString arg2) const { return callObjectMethod( "queryChildDocuments", "(Ljava/lang/String;[Ljava/lang/String;Ljava/lang/String;)Landroid/database/Cursor;", arg0.object<jstring>(), arg1.object<jarray>(), arg2.object<jstring>() ); } JObject DocumentsProvider::queryDocument(JString arg0, JArray arg1) const { return callObjectMethod( "queryDocument", "(Ljava/lang/String;[Ljava/lang/String;)Landroid/database/Cursor;", arg0.object<jstring>(), arg1.object<jarray>() ); } JObject DocumentsProvider::queryRecentDocuments(JString arg0, JArray arg1) const { return callObjectMethod( "queryRecentDocuments", "(Ljava/lang/String;[Ljava/lang/String;)Landroid/database/Cursor;", arg0.object<jstring>(), arg1.object<jarray>() ); } JObject DocumentsProvider::queryRecentDocuments(JString arg0, JArray arg1, android::os::Bundle arg2, android::os::CancellationSignal arg3) const { return callObjectMethod( "queryRecentDocuments", "(Ljava/lang/String;[Ljava/lang/String;Landroid/os/Bundle;Landroid/os/CancellationSignal;)Landroid/database/Cursor;", arg0.object<jstring>(), arg1.object<jarray>(), arg2.object(), arg3.object() ); } JObject DocumentsProvider::queryRoots(JArray arg0) const { return callObjectMethod( "queryRoots", "([Ljava/lang/String;)Landroid/database/Cursor;", arg0.object<jarray>() ); } JObject DocumentsProvider::querySearchDocuments(JString arg0, JArray arg1, android::os::Bundle arg2) const { return callObjectMethod( "querySearchDocuments", "(Ljava/lang/String;[Ljava/lang/String;Landroid/os/Bundle;)Landroid/database/Cursor;", arg0.object<jstring>(), arg1.object<jarray>(), arg2.object() ); } JObject DocumentsProvider::querySearchDocuments(JString arg0, JString arg1, JArray arg2) const { return callObjectMethod( "querySearchDocuments", "(Ljava/lang/String;Ljava/lang/String;[Ljava/lang/String;)Landroid/database/Cursor;", arg0.object<jstring>(), arg1.object<jstring>(), arg2.object<jarray>() ); } void DocumentsProvider::removeDocument(JString arg0, JString arg1) const { callMethod<void>( "removeDocument", "(Ljava/lang/String;Ljava/lang/String;)V", arg0.object<jstring>(), arg1.object<jstring>() ); } JString DocumentsProvider::renameDocument(JString arg0, JString arg1) const { return callObjectMethod( "renameDocument", "(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;", arg0.object<jstring>(), arg1.object<jstring>() ); } void DocumentsProvider::revokeDocumentPermission(JString arg0) const { callMethod<void>( "revokeDocumentPermission", "(Ljava/lang/String;)V", arg0.object<jstring>() ); } jint DocumentsProvider::update(android::net::Uri arg0, android::content::ContentValues arg1, JString arg2, JArray arg3) const { return callMethod<jint>( "update", "(Landroid/net/Uri;Landroid/content/ContentValues;Ljava/lang/String;[Ljava/lang/String;)I", arg0.object(), arg1.object(), arg2.object<jstring>(), arg3.object<jarray>() ); } } // namespace android::provider
31.422633
189
0.721961
YJBeetle
1d5d9cede9f7f9bf6df2da82d35587b759010128
836
cpp
C++
Array/stock.cpp
RYzen-009/DSA
0f7f9d2c7f7452667329f7a43b3eb4110d5c174c
[ "MIT" ]
null
null
null
Array/stock.cpp
RYzen-009/DSA
0f7f9d2c7f7452667329f7a43b3eb4110d5c174c
[ "MIT" ]
null
null
null
Array/stock.cpp
RYzen-009/DSA
0f7f9d2c7f7452667329f7a43b3eb4110d5c174c
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; //This is a O(N*N) Solution int stock(int price[],int start , int end) { if(start >= end) return 0; int profit=0,curr_profit=0; for(int i=start;i<=end;i++) { for(int j=i+1;j<=end;j++) { if(price[j]>price[i]) { curr_profit = (price[j]-price[i]) + stock(price,start,i-1) + stock(price,j+1,end); profit=max(profit,curr_profit); } } } return profit; } int max_profit( int arr[], int n ) { int profit = 0; for(int i=1;i<n;i++) { if(arr[i]>arr[i-1]) profit += arr[i]-arr[i-1]; } return profit; } int main() { int n; cin>>n; int price[n]; for(int i=0;i<n;i++) cin>>price[i]; cout<<max_profit(price,n); // cout << stock(price, 0, n-1); return 0; }
18.173913
92
0.511962
RYzen-009
1d5e5894b13b332ef7c8190174dcd6ed61f24b5a
8,694
cpp
C++
SimCenterUQInputSurrogate.cpp
bhajay/quoFEM
23e57fd85d28468379906eed59aaa54b77604a0c
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
SimCenterUQInputSurrogate.cpp
bhajay/quoFEM
23e57fd85d28468379906eed59aaa54b77604a0c
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
SimCenterUQInputSurrogate.cpp
bhajay/quoFEM
23e57fd85d28468379906eed59aaa54b77604a0c
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
/* ***************************************************************************** Copyright (c) 2016-2017, The Regents of the University of California (Regents). All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of the FreeBSD Project. REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE AND ACCOMPANYING DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. *************************************************************************** */ #include "SimCenterUQInputSurrogate.h" #include "SimCenterUQResultsSurrogate.h" #include <RandomVariablesContainer.h> #include <QPushButton> #include <QScrollArea> #include <QJsonArray> #include <QJsonObject> #include <QLabel> #include <QLineEdit> #include <QDebug> #include <QFileDialog> #include <QPushButton> #include <sectiontitle.h> #include <iostream> #include <sstream> #include <fstream> #include <time.h> #include <QStackedWidget> #include <SurrogateDoEInputWidget.h> #include <SurrogateNoDoEInputWidget.h> #include <SurrogateMFInputWidget.h> #include <InputWidgetFEM.h> #include <InputWidgetParameters.h> #include <InputWidgetEDP.h> SimCenterUQInputSurrogate::SimCenterUQInputSurrogate(InputWidgetParameters *param,InputWidgetFEM *femwidget,InputWidgetEDP *edpwidget, QWidget *parent) : UQ_Engine(parent),uqSpecific(0), theParameters(param), theEdpWidget(edpwidget), theFemWidget(femwidget) { layout = new QVBoxLayout(); mLayout = new QVBoxLayout(); // // create layout for input selection box // QHBoxLayout *methodLayout1= new QHBoxLayout; inpMethod = new QComboBox(); inpMethod->addItem(tr("Sampling and Simulation")); inpMethod->addItem(tr("Import Data File")); inpMethod->addItem(tr("Import Multi-fidelity Data File")); inpMethod->setMaximumWidth(250); inpMethod->setMinimumWidth(250); methodLayout1->addWidget(new QLabel("Training Dataset")); methodLayout1->addWidget(inpMethod,2); methodLayout1->addStretch(); mLayout->addLayout(methodLayout1); // // input selection widgets // theStackedWidget = new QStackedWidget(); theDoE = new SurrogateDoEInputWidget(); theStackedWidget->addWidget(theDoE); theData = new SurrogateNoDoEInputWidget(theParameters,theFemWidget,theEdpWidget); theStackedWidget->addWidget(theData); theMultiFidelity = new SurrogateMFInputWidget(theParameters,theFemWidget,theEdpWidget); theStackedWidget->addWidget(theMultiFidelity); theStackedWidget->setCurrentIndex(0); theInpCurrentMethod = theDoE; mLayout->addWidget(theStackedWidget); // // // layout->addLayout(mLayout); this->setLayout(layout); connect(inpMethod, SIGNAL(currentIndexChanged(QString)), this, SLOT(onIndexChanged(QString))); } void SimCenterUQInputSurrogate::onIndexChanged(const QString &text) { if (text=="Sampling and Simulation") { theStackedWidget->setCurrentIndex(0); theInpCurrentMethod = theDoE; theFemWidget->setFEMforGP("GPmodel"); // reset FEM } else if (text=="Import Data File") { delete theData; theData = new SurrogateNoDoEInputWidget(theParameters,theFemWidget,theEdpWidget); theStackedWidget->insertWidget(1,theData); theStackedWidget->setCurrentIndex(1); theInpCurrentMethod = theData; } else if (text=="Import Multi-fidelity Data File") { delete theMultiFidelity; theMultiFidelity = new SurrogateMFInputWidget(theParameters,theFemWidget,theEdpWidget); theStackedWidget->insertWidget(2,theMultiFidelity); theStackedWidget->setCurrentIndex(2); theInpCurrentMethod = theMultiFidelity; theFemWidget->setFEMforGP("GPdata"); } //theParameters->setGPVarNamesAndValues(QStringList({}));// remove GP RVs } SimCenterUQInputSurrogate::~SimCenterUQInputSurrogate() { } int SimCenterUQInputSurrogate::getMaxNumParallelTasks(void){ return theInpCurrentMethod->getNumberTasks(); } void SimCenterUQInputSurrogate::clear(void) { } void SimCenterUQInputSurrogate::numModelsChanged(int numModels) { emit onNumModelsChanged(numModels); } bool SimCenterUQInputSurrogate::outputToJSON(QJsonObject &jsonObject) { bool result = true; QJsonObject uq; uq["method"]=inpMethod->currentText(); theInpCurrentMethod->outputToJSON(uq); jsonObject["surrogateMethodInfo"]=uq; return result; } bool SimCenterUQInputSurrogate::inputFromJSON(QJsonObject &jsonObject) { bool result = false; this->clear(); // // get sampleingMethodData, if not present it's an error // if (jsonObject.contains("surrogateMethodInfo")) { QJsonObject uq = jsonObject["surrogateMethodInfo"].toObject(); if (uq.contains("method")) { QString method =uq["method"].toString(); int index = inpMethod->findText(method); if (index == -1) { return false; } inpMethod->setCurrentIndex(index); result = theInpCurrentMethod->inputFromJSON(uq); if (result == false) return result; } } return result; } bool SimCenterUQInputSurrogate::outputAppDataToJSON(QJsonObject &jsonObject) { bool result = true; jsonObject["Application"] = "SimCenterUQ-UQ"; QJsonObject uq; uq["method"]=inpMethod->currentText(); theInpCurrentMethod->outputToJSON(uq); jsonObject["ApplicationData"] = uq; return result; } bool SimCenterUQInputSurrogate::inputAppDataFromJSON(QJsonObject &jsonObject) { bool result = false; this->clear(); // // get sampleingMethodData, if not present it's an error if (jsonObject.contains("ApplicationData")) { QJsonObject uq = jsonObject["ApplicationData"].toObject(); if (uq.contains("method")) { QString method = uq["method"].toString(); int index = inpMethod->findText(method); if (index == -1) { errorMessage(QString("ERROR: Unknown Method") + method); return false; } inpMethod->setCurrentIndex(index); return theInpCurrentMethod->inputFromJSON(uq); } } else { errorMessage("ERROR: Surrogate Input Widget - no \"surrogateMethodData\" input"); return false; } return result; } int SimCenterUQInputSurrogate::processResults(QString &filenameResults, QString &filenameTab) { return 0; } UQ_Results * SimCenterUQInputSurrogate::getResults(void) { qDebug() << "RETURNED SimCenterUQRESULTSSURROGATE"; return new SimCenterUQResultsSurrogate(theRandomVariables); } RandomVariablesContainer * SimCenterUQInputSurrogate::getParameters(void) { QString classType("Uncertain"); theRandomVariables = new RandomVariablesContainer(classType,tr("SimCenterUQ")); return theRandomVariables; } QString SimCenterUQInputSurrogate::getMethodName(void){ //if (inpMethod->currentIndex()==0){ // return QString("surrogateModel"); //} else if (inpMethod->currentIndex()==1){ // return QString("surrogateData"); //} return QString("surrogate"); }
29.773973
151
0.714286
bhajay
1d5f5217cdb36694f29d57aca3ea8659f6edb5c7
6,620
cpp
C++
src/daat.cpp
elshize/irkit_top-k_query_processing
210a357e4763ab51deda23669629b3395636f2ca
[ "MIT" ]
null
null
null
src/daat.cpp
elshize/irkit_top-k_query_processing
210a357e4763ab51deda23669629b3395636f2ca
[ "MIT" ]
null
null
null
src/daat.cpp
elshize/irkit_top-k_query_processing
210a357e4763ab51deda23669629b3395636f2ca
[ "MIT" ]
1
2020-10-28T07:22:35.000Z
2020-10-28T07:22:35.000Z
#include <iostream> #include <chrono> #include <string> #include <sstream> #include <irkit/coding/stream_vbyte.hpp> #include <irkit/index.hpp> #include <irkit/io.hpp> #include <irkit/memoryview.hpp> #include <irkit/index/source.hpp> #include <irkit/index/types.hpp> #include <irkit/index/posting_list.hpp> // #define private public using std::uint32_t; using irk::index::document_t; using doc_list_t = irk::index::block_document_list_view< irk::stream_vbyte_codec<document_t>>; using payload_list_t = irk::index::block_payload_list_view<uint32_t, irk::stream_vbyte_codec<uint32_t>>; using post_list_t = irk::posting_list_view<doc_list_t, payload_list_t>; template<class Document, class Score> struct Posting { Document document; Score score; }; bool order(const Posting<long, long>& lhs, const Posting<long, long>& rhs) { return lhs.score > rhs.score; } // auto taat(int k, const std::vector<post_list_t>& query, // long collection_size){ // std::vector<long> acc(collection_size, 0); // std::vector<Posting<long, long> > topk; // long threshold = 0; // for(size_t i = 0; i < query.size(); ++i){ // for(auto posting : query[i]){ // acc[posting.document()] += posting.payload(); // } // } // for(size_t i = 0; i < acc.size(); ++i){ // if(acc[i] > threshold){ // Posting<long, long> p {long(i), acc[i]}; // topk.push_back(p); // if(topk.size() <= k) std::push_heap(topk.begin(), topk.end(), order); // else{ // std::pop_heap(topk.begin(), topk.end(), order); // topk.pop_back(); // } // threshold = topk.size() == k ? topk[0].score : threshold; // } // } // std::sort(topk.begin(), topk.end(), order); // return topk; // } auto daat(int k, const std::vector<post_list_t>& query, long collection_size){ std::vector<post_list_t::iterator> pointers; auto cur_posting = query[0].begin().document(); std::vector<Posting<long, long> > topk; long threshold = 0; // for(auto plist : query){ // for(auto p : plist){ // std::cout << p.document() << "\t" // << p.payload() << std::endl; // } // std::cout << std::endl; // } for(const auto& plist : query){ pointers.push_back(plist.begin()); if(plist.begin().document() < cur_posting){ cur_posting = plist.begin().document(); } } // for(const auto& plist : query){ // auto p = plist.begin().nextgeq(document_t(60000)); // std::cout << p.document_iterator_.block() << " " // << p.document_iterator_.pos() << "\t"; // std::cout << plist.end().document_iterator_.block()<< " " // << plist.end().document_iterator_.pos() << "\n"; // } // std::cout << cur_posting << std::endl; // std::cout << pointers[0].document() << "\t" // << query[0].begin().document() << std::endl; int flag = 0; long cur_score = 0; int debug = 0; while(flag < pointers.size()){ flag = 0; cur_score = 0; document_t min = document_t(collection_size); // std::cout << debug++ << std::endl; // std::cout << "hey "; for(size_t i = 0; i < pointers.size(); ++i){ // std::cout << i << " "; if(pointers[i] != query[i].end()){ //std::cout << pointers[i].document() << '\t'; if(pointers[i].document() == cur_posting){ //std::cout << "debug" << "\t"; cur_score += pointers[i].payload(); pointers[i].moveto(cur_posting + 1); } // std::cout << pointers[i].document_iterator_.block() << " " // << pointers[i].document_iterator_.pos() << " "; if(pointers[i] != query[i].end()){ min = std::min(min, pointers[i].document()); // std::cout << pointers[i].document() << "\t"; } } else{ ++flag; } } if(cur_score > threshold){ Posting<long, long> p {long(cur_posting), cur_score}; topk.push_back(p); if(topk.size() <= k){ std::push_heap(topk.begin(), topk.end(), order); } else{ std::pop_heap(topk.begin(), topk.end(), order); topk.pop_back(); } threshold = topk.size() == k ? topk[0].score : threshold; } cur_posting = min; // std::cout << flag << "\t"; // std::cout << cur_posting << std::endl; } std::sort(topk.begin(), topk.end(), order); return topk; } int main(int argc, char** argv){ assert(argc == 3); irk::fs::path index_dir(argv[1]); std::ifstream term_in(irk::index::term_map_path(index_dir).c_str()); std::ifstream title_in(irk::index::title_map_path(index_dir).c_str()); irk::inverted_index_mapped_data_source data(index_dir, "bm25"); irk::inverted_index_view index_view(&data); std::ifstream query_in(argv[2]); if (!query_in) { std::cerr << "Failed to open query.txt\n"; exit(1); } std::string line; int k = 1000; int num = 1; while(getline(query_in, line)){ std::stringstream aQuery(line); std::string term; std::vector<post_list_t> query_postings; while(aQuery >> term){ auto id = index_view.term_id(term); if (id.has_value()) { query_postings.push_back( index_view.scored_postings(id.value())); } } if(query_postings.size() == 0){ std::cout << "Can't find any result for query '" << line << "'\n"; continue; } auto result = daat(k, query_postings, index_view.collection_size()); // auto check = taat(k, query_postings, index_view.collection_size()); // for(size_t i = 0; i < result.size(); ++i){ // assert(result[i].document == check[i].document); // assert(result[i].score == check[i].score); // } std::cout << "Query " << num << ": " << line << "\nDID\t" << "Score\n"; for(auto posting : result){ std::cout << posting.document << "\t" << posting.score << std::endl; } std::cout << std::endl; ++num; } }
35.026455
84
0.513746
elshize
1d612ac6828828b43ba4d4d62f797163f66801c6
20,916
cpp
C++
tools/indextool.cpp
Arnaud-de-Grandmaison-ARM/tarmac-trace-utilities
5428f72485531be0c4482768b4923640e7ada397
[ "Apache-2.0" ]
1
2021-07-03T23:54:51.000Z
2021-07-03T23:54:51.000Z
tools/indextool.cpp
Arnaud-de-Grandmaison-ARM/tarmac-trace-utilities
5428f72485531be0c4482768b4923640e7ada397
[ "Apache-2.0" ]
null
null
null
tools/indextool.cpp
Arnaud-de-Grandmaison-ARM/tarmac-trace-utilities
5428f72485531be0c4482768b4923640e7ada397
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2016-2021 Arm Limited. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * This file is part of Tarmac Trace Utilities */ #include "libtarmac/argparse.hh" #include "libtarmac/index.hh" #include "libtarmac/tarmacutil.hh" #include <stdio.h> #include <string.h> #include <algorithm> #include <climits> #include <functional> #include <iostream> #include <stack> #include <string> #include <vector> using std::cerr; using std::cout; using std::dec; using std::endl; using std::hex; using std::min; using std::showbase; using std::stack; using std::string; using std::vector; static bool omit_index_offsets; static void dump_memory_at_line(const IndexNavigator &IN, unsigned trace_line, const std::string &prefix); template <typename Payload, typename Annotation> class TreeDumper { struct StackEntry { bool first_of_two; bool right_child; string prefix; }; string prefix; stack<StackEntry> stk; virtual void dump_payload(const string &prefix, const Payload &) = 0; virtual void dump_annotation(const string &prefix, const Payload &, const Annotation &) { } virtual void node_header(off_t offset) { cout << prefix << "Node"; if (!omit_index_offsets) cout << prefix << " at file offset " << offset; cout << ":" << endl; } void visit(const Payload &payload, off_t offset) { node_header(offset); dump_payload(prefix + " ", payload); } void walk(const Payload &payload, const Annotation &annotation, off_t leftoff, const Annotation *, off_t rightoff, const Annotation *, off_t offset) { string firstlineprefix, finalprefix, node_type; if (!stk.empty()) { StackEntry &pop = stk.top(); prefix = pop.prefix; if (pop.first_of_two) { firstlineprefix = prefix + "├── "; prefix += "│ "; finalprefix = prefix; } else { firstlineprefix = prefix + "└── "; finalprefix = prefix; prefix += " "; } node_type = pop.right_child ? "Right child node" : "Left child node"; stk.pop(); } else { node_type = "Root node"; firstlineprefix = finalprefix = prefix; } cout << firstlineprefix << hex << node_type << " at file offset " << offset << ":" << endl; if (rightoff) { stk.push({false, true, prefix}); if (leftoff) stk.push({true, false, prefix}); } else if (leftoff) { stk.push({false, false, prefix}); } if (rightoff || leftoff) prefix += "│ "; else prefix += " "; cout << prefix << "Child offsets = { "; if (leftoff) cout << leftoff; else cout << "null"; cout << ", "; if (rightoff) cout << rightoff; else cout << "null"; cout << " }" << endl << dec; dump_payload(prefix, payload); dump_annotation(prefix, payload, annotation); if (!stk.empty()) { // Leave a blank line before the next node, if we're expecting one. size_t useful_prefix_len = min((size_t)1, prefix.find_last_not_of(" ")) - 1; cout << prefix.substr(0, useful_prefix_len - 1) << endl; } prefix = finalprefix; } protected: const IndexNavigator &IN; public: class Visitor { TreeDumper *parent; public: Visitor(TreeDumper *parent) : parent(parent) {} void operator()(const Payload &payload, off_t offset) { parent->visit(payload, offset); } } visitor; class Walker { TreeDumper *parent; public: Walker(TreeDumper *parent) : parent(parent) {} void operator()(const Payload &payload, const Annotation &annotation, off_t lo, const Annotation *la, off_t ro, const Annotation *ra, off_t offset) { parent->walk(payload, annotation, lo, la, ro, ra, offset); } } walker; TreeDumper(const IndexNavigator &IN) : IN(IN), visitor(this), walker(this) { } }; class SeqTreeDumper : public TreeDumper<SeqOrderPayload, SeqOrderAnnotation> { using TreeDumper::TreeDumper; virtual void dump_payload(const string &prefix, const SeqOrderPayload &node) override { cout << prefix << "Line range: start " << node.trace_file_firstline << ", extent " << node.trace_file_lines << endl; cout << prefix << "Byte range: start " << hex << node.trace_file_pos << ", extent " << node.trace_file_len << dec << endl; cout << prefix << "Modification time: " << node.mod_time << endl; cout << prefix << "PC: "; if (node.pc == KNOWN_INVALID_PC) cout << "invalid"; else cout << hex << node.pc << dec; cout << endl; if (!omit_index_offsets) { cout << prefix << "Root of memory tree: " << hex << node.memory_root << dec << endl; } cout << prefix << "Call depth: " << node.call_depth << endl; if (dump_memory) { dump_memory_at_line(IN, node.trace_file_firstline, prefix + " "); } } virtual void dump_annotation(const string &prefix, const SeqOrderPayload &node, const SeqOrderAnnotation &annotation) override { auto *array = (const CallDepthArrayEntry *)IN.index.index_offset( annotation.call_depth_array); for (unsigned i = 0, e = annotation.call_depth_arraylen; i < e; i++) { const CallDepthArrayEntry &ent = array[i]; cout << prefix << "LRT[" << i << "] = { "; if (ent.call_depth == SENTINEL_DEPTH) cout << "sentinel"; else cout << "depth " << ent.call_depth; cout << ", " << ent.cumulative_lines << " lines, " << ent.cumulative_insns << " insns, " << "left-crosslink " << ent.leftlink << ", " << "right-crosslink " << ent.rightlink << "}" << endl; } } public: bool dump_memory; }; class MemTreeDumper : public TreeDumper<MemoryPayload, MemoryAnnotation> { using TreeDumper::TreeDumper; virtual void dump_payload(const string &prefix, const MemoryPayload &node) override { cout << prefix << "Range: "; // FIXME: to make diagnostic dumps less opaque, it would be // nice here to translate reg addresses back into some // meaningful identification involving a register number. if (node.type == 'r') cout << "register-space"; else cout << "memory"; cout << " [" << hex << node.lo << "-" << node.hi << dec << "]" << endl; cout << prefix << "Contents: "; if (node.raw) { cout << (node.hi + 1 - node.lo) << " bytes"; if (!omit_index_offsets) cout << " at file offset " << hex << node.contents << dec; } else { cout << "memory subtree"; if (!omit_index_offsets) cout << " with root pointer at " << hex << node.contents << ", actual root is " << IN.index.index_subtree_root(node.contents) << dec; } cout << endl; cout << prefix << "Last modification: "; if (node.trace_file_firstline == 0) cout << "never"; else cout << "line " << node.trace_file_firstline; cout << endl; } virtual void dump_annotation(const string &prefix, const MemoryPayload &node, const MemoryAnnotation &annotation) override { cout << prefix << "Latest modification time in whole subtree: " << annotation.latest << endl; } }; class MemSubtreeDumper : public TreeDumper<MemorySubPayload, EmptyAnnotation<MemorySubPayload>> { using TreeDumper::TreeDumper; virtual void dump_payload(const string &prefix, const MemorySubPayload &node) override { // Here we _can't_ translate register-space addresses back // into registers, even if we wanted to, because we haven't // been told whether this subtree even refers to register or // memory space. cout << prefix << "Range: [" << hex << node.lo << "-" << node.hi << dec << "]" << endl; cout << prefix << "Contents: " << (node.hi + 1 - node.lo) << " bytes"; if (!omit_index_offsets) cout << " at file offset " << hex << node.contents << dec; cout << endl; } }; class ByPCTreeDumper : public TreeDumper<ByPCPayload, EmptyAnnotation<ByPCPayload>> { using TreeDumper::TreeDumper; virtual void dump_payload(const string &prefix, const ByPCPayload &node) override { cout << prefix << "PC: " << hex << node.pc << dec << endl; cout << prefix << "Line: " << node.trace_file_firstline << endl; } }; static const struct { const char *pname; RegPrefix prefix; unsigned nregs; } reg_families[] = { #define WRITE_ENTRY(prefix, ignore1, ignore2, nregs) \ {#prefix, RegPrefix::prefix, nregs}, REGPREFIXLIST(WRITE_ENTRY, WRITE_ENTRY) #undef WRITE_ENTRY }; static void dump_registers(bool got_iflags, unsigned iflags) { for (const auto &fam : reg_families) { for (unsigned i = 0; i < fam.nregs; i++) { RegisterId r{fam.prefix, i}; cout << reg_name(r); if (!got_iflags && reg_needs_iflags(r)) { cout << " - dependent on iflags\n"; } else { cout << " offset=" << hex << reg_offset(r, iflags) << " size=" << hex << reg_size(r) << "\n"; } } } } static unsigned long long parseint(const string &s) { try { size_t pos; unsigned long long toret = stoull(s, &pos, 0); if (pos < s.size()) throw ArgparseError("'" + s + "': unable to parse numeric value"); return toret; } catch (std::invalid_argument) { throw ArgparseError("'" + s + "': unable to parse numeric value"); } catch (std::out_of_range) { throw ArgparseError("'" + s + "': numeric value out of range"); } } static void hexdump(const void *vdata, size_t size, Addr startaddr, const std::string &prefix) { const unsigned char *data = (const unsigned char *)vdata; char linebuf[100], fmtbuf[32]; constexpr Addr linelen = 16, mask = ~(linelen - 1); while (size > 0) { Addr lineaddr = startaddr & mask; size_t linesize = min(size, (size_t)(lineaddr + linelen - startaddr)); memset(linebuf, ' ', 83); snprintf(fmtbuf, sizeof(fmtbuf), "%016llx", (unsigned long long)lineaddr); memcpy(linebuf, fmtbuf, 16); size_t outlinelen = 16; for (size_t i = 0; i < linesize; i++) { size_t lineoff = i + (startaddr - lineaddr); size_t hexoff = 16 + 1 + 3 * lineoff; snprintf(fmtbuf, sizeof(fmtbuf), "%02x", (unsigned)data[i]); memcpy(linebuf + hexoff, fmtbuf, 2); size_t chroff = 16 + 1 + 3 * 16 + 1 + lineoff; linebuf[chroff] = (0x20 <= data[i] && data[i] < 0x7F ? data[i] : '.'); outlinelen = chroff + 1; } linebuf[outlinelen] = '\0'; cout << prefix << linebuf << endl; startaddr += linesize; size -= linesize; } } static void regdump(const std::vector<unsigned char> &val, const std::vector<unsigned char> &def) { for (size_t i = 0, e = min(val.size(), def.size()); i < e; i++) { if (i) cout << " "; if (def[i]) { char fmtbuf[3]; snprintf(fmtbuf, sizeof(fmtbuf), "%02x", (unsigned)val[i]); cout << fmtbuf; } else { cout << ".."; } } } static void dump_memory_at_line(const IndexNavigator &IN, unsigned trace_line, const std::string &prefix) { SeqOrderPayload node; if (!IN.node_at_line(trace_line, &node)) { cerr << "Unable to find a node at line " << trace_line << "\n"; exit(1); } off_t memroot = node.memory_root; unsigned iflags = IN.get_iflags(memroot); const void *outdata; Addr outaddr; size_t outsize; unsigned outline; Addr readaddr = 0; size_t readsize = 0; while (IN.getmem_next(memroot, 'm', readaddr, readsize, &outdata, &outaddr, &outsize, &outline)) { cout << prefix << "Memory last modified at line " << outline << ":" << endl; hexdump(outdata, outsize, outaddr, prefix); readsize -= outaddr + outsize - readaddr; readaddr = outaddr + outsize; if (!readaddr) break; } for (const auto &regfam : reg_families) { for (unsigned i = 0; i < regfam.nregs; i++) { RegisterId reg{regfam.prefix, i}; size_t size = reg_size(reg); vector<unsigned char> val(size), def(size); unsigned mod_line = IN.getmem(memroot, 'r', reg_offset(reg, iflags), size, &val[0], &def[0]); bool print = false; for (auto c : def) { if (c) { print = true; break; } } if (print) { cout << prefix << reg_name(reg) << ", last modified at line " << mod_line << ": "; regdump(val, def); cout << endl; } } } } int main(int argc, char **argv) { enum class Mode { None, Header, SeqVisit, SeqVisitWithMem, SeqWalk, MemVisit, MemWalk, MemSubVisit, MemSubWalk, ByPCVisit, ByPCWalk, RegMap, FullMemByLine, } mode = Mode::None; off_t root; unsigned trace_line; unsigned iflags = 0; bool got_iflags = false; Argparse ap("tarmac-indextool", argc, argv); TarmacUtility tu(ap, false, false); ap.optnoval({"--header"}, "dump file header", [&]() { mode = Mode::Header; }); ap.optnoval({"--seq"}, "dump logical content of the sequential order tree", [&]() { mode = Mode::SeqVisit; }); ap.optnoval({"--seq-with-mem"}, "dump logical content of the sequential " "order tree, and memory contents at each node", [&]() { mode = Mode::SeqVisitWithMem; }); ap.optnoval({"--seqtree"}, "dump physical structure of the sequential " "order tree", [&]() { mode = Mode::SeqWalk; }); ap.optval({"--mem"}, "OFFSET", "dump logical content of memory tree with " "root at OFFSET", [&](const string &s) { mode = Mode::MemVisit; root = parseint(s); }); ap.optval({"--memtree"}, "OFFSET", "dump physical structure of a memory " "tree with root at OFFSET", [&](const string &s) { mode = Mode::MemWalk; root = parseint(s); }); ap.optval({"--memsub"}, "OFFSET", "dump logical content of a memory " "subtree with root at OFFSET", [&](const string &s) { mode = Mode::MemSubVisit; root = parseint(s); }); ap.optval({"--memsubtree"}, "OFFSET", "dump physical structure of a memory" " subtree with root at OFFSET", [&](const string &s) { mode = Mode::MemSubWalk; root = parseint(s); }); ap.optnoval({"--bypc"}, "dump logical content of the by-PC tree", [&]() { mode = Mode::ByPCVisit; }); ap.optnoval({"--bypctree"}, "dump physical structure of the by-PC tree", [&]() { mode = Mode::ByPCWalk; }); ap.optnoval({"--regmap"}, "write a memory map of the register space", [&]() { mode = Mode::RegMap; }); ap.optval({"--iflags"}, "FLAGS", "(for --regmap) specify iflags context " "to retrieve registers", [&](const string &s) { got_iflags = true; iflags = parseint(s); }); ap.optnoval({"--omit-index-offsets"}, "do not dump offsets in index file " "(so that output is more stable when index format changes)", [&]() { omit_index_offsets = true; }); ap.optval({"--full-mem-at-line"}, "OFFSET", "dump full content of memory " "tree corresponding to a particular line of the trace file", [&](const string &s) { mode = Mode::FullMemByLine; trace_line = parseint(s); }); ap.parse([&]() { if (mode == Mode::None && !tu.only_index()) throw ArgparseError("expected an option describing a query"); if (mode != Mode::RegMap && tu.trace.tarmac_filename.empty()) throw ArgparseError("expected a trace file name"); }); cout << showbase; // ensure all hex values have a leading 0x // Modes that don't need a trace file switch (mode) { case Mode::RegMap: { dump_registers(got_iflags, iflags); return 0; } default: // Exit this switch and go on to load the trace file break; } tu.setup(); const IndexNavigator IN(tu.trace); switch (mode) { case Mode::None: case Mode::RegMap: assert(false && "This should have been ruled out above"); case Mode::Header: { cout << "Endianness: " << (IN.index.isBigEndian() ? "big" : "little") << endl; cout << "Architecture: " << (IN.index.isAArch64() ? "AArch64" : "AArch32") << endl; cout << "Root of sequential order tree: " << IN.index.seqroot << endl; cout << "Root of by-PC tree: " << IN.index.bypcroot << endl; cout << "Line number adjustment for file header: " << IN.index.lineno_offset << endl; break; } case Mode::SeqVisit: case Mode::SeqVisitWithMem: { SeqTreeDumper d(IN); d.dump_memory = (mode == Mode::SeqVisitWithMem); IN.index.seqtree.visit(IN.index.seqroot, d.visitor); break; } case Mode::SeqWalk: { SeqTreeDumper d(IN); IN.index.seqtree.walk(IN.index.seqroot, WalkOrder::Preorder, d.walker); break; } case Mode::MemVisit: { MemTreeDumper d(IN); IN.index.memtree.visit(root, d.visitor); break; } case Mode::MemWalk: { MemTreeDumper d(IN); IN.index.memtree.walk(root, WalkOrder::Preorder, d.walker); break; } case Mode::MemSubVisit: { MemSubtreeDumper d(IN); IN.index.memsubtree.visit(root, d.visitor); break; } case Mode::MemSubWalk: { MemSubtreeDumper d(IN); IN.index.memsubtree.walk(root, WalkOrder::Preorder, d.walker); break; } case Mode::ByPCVisit: { ByPCTreeDumper d(IN); IN.index.bypctree.visit(IN.index.bypcroot, d.visitor); break; } case Mode::ByPCWalk: { ByPCTreeDumper d(IN); IN.index.bypctree.walk(IN.index.bypcroot, WalkOrder::Preorder, d.walker); break; } case Mode::FullMemByLine: { dump_memory_at_line(IN, trace_line, ""); break; } } return 0; }
32.129032
80
0.525961
Arnaud-de-Grandmaison-ARM
1d649dac6a42226fa94ae240b8186b2955d1311a
313
cpp
C++
srcgen/readme_gen.t.cpp
oleg-rabaev/cppa2z
f6ca795f5817901b075bf5b7fb43bd0f5b85f702
[ "BSL-1.0" ]
62
2016-10-05T11:31:50.000Z
2021-09-07T06:20:40.000Z
srcgen/readme_gen.t.cpp
oleg-rabaev/cppa2z
f6ca795f5817901b075bf5b7fb43bd0f5b85f702
[ "BSL-1.0" ]
29
2021-02-14T20:12:46.000Z
2021-05-09T17:56:27.000Z
srcgen/readme_gen.t.cpp
oleg-rabaev/cppa2z
f6ca795f5817901b075bf5b7fb43bd0f5b85f702
[ "BSL-1.0" ]
1
2021-01-31T13:40:39.000Z
2021-01-31T13:40:39.000Z
#include <catch.hpp> #include <readme_gen.h> #include <iostream> #include <fstream> using namespace std; namespace srcgen { TEST_CASE( "readme_gen.generate" ) { ofstream fout("README.md"); auto& out = fout; //auto& out = cout; readme_gen gen(out); gen.generate(); } } // namespace srcgen
15.65
36
0.654952
oleg-rabaev
1d68103ce4511c1b958913c200f8ae26f60f6791
2,212
cpp
C++
raygame/Grain.cpp
DynashEtvala/SandGame
16b286533c2f8f6a20ebead2475e2c70d7d7cd56
[ "MIT" ]
null
null
null
raygame/Grain.cpp
DynashEtvala/SandGame
16b286533c2f8f6a20ebead2475e2c70d7d7cd56
[ "MIT" ]
null
null
null
raygame/Grain.cpp
DynashEtvala/SandGame
16b286533c2f8f6a20ebead2475e2c70d7d7cd56
[ "MIT" ]
null
null
null
#include "Grain.h" #include "MatManager.h" Grain::Grain(int X, int Y) : GMaterial(X, Y) { grain = true; density = 9; } Grain::~Grain() {} void Grain::Update(GMaterial*** matList, int bottom, int side, MatManager& m) { if (CanUpdate()) { if (posY == bottom - 1) { m.PrepChange(posX, posY, AIR); } else if ((matList[posY + 1][posX]->liquid ? matList[posY + 1][posX]->CanUpdate() : true) && matList[posY + 1][posX]->density < density) { m.PrepChange(posX, posY, matList[posY + 1][posX]->type); updatedFrame = true; m.PrepChange(posX, posY + 1, type); } else if ((matList[posY + 1][posX + 1]->density < density && matList[posY][posX + 1]->density < density) || (matList[posY + 1][posX - 1]->density < density && matList[posY][posX - 1]->density < density)) { if (((matList[posY + 1][posX + 1]->liquid ? matList[posY + 1][posX + 1]->CanUpdate() : true) && matList[posY + 1][posX + 1]->density < density && matList[posY][posX + 1]->density < density) && ((matList[posY + 1][posX - 1]->liquid ? matList[posY + 1][posX - 1]->CanUpdate() : true) && matList[posY + 1][posX - 1]->density < density && matList[posY][posX - 1]->density < density)) { if (GetRandomValue(0, 1)) { m.PrepChange(posX, posY, matList[posY + 1][posX + 1]->type); updatedFrame = true; m.PrepChange(posX + 1, posY + 1, type); } else { m.PrepChange(posX, posY, matList[posY + 1][posX - 1]->type); updatedFrame = true; m.PrepChange(posX - 1, posY + 1, type); } } else if ((matList[posY + 1][posX + 1]->liquid ? matList[posY + 1][posX + 1]->CanUpdate() : true) && matList[posY + 1][posX + 1]->density < density && matList[posY][posX + 1]->density < density) { m.PrepChange(posX, posY, matList[posY + 1][posX + 1]->type); updatedFrame = true; m.PrepChange(posX + 1, posY + 1, type); } else if ((matList[posY + 1][posX - 1]->liquid ? matList[posY + 1][posX - 1]->CanUpdate() : true) && matList[posY + 1][posX - 1]->density < density && matList[posY][posX - 1]->density < density) { m.PrepChange(posX, posY, matList[posY + 1][posX - 1]->type); updatedFrame = true; m.PrepChange(posX - 1, posY + 1, type); } } } }
36.866667
382
0.588156
DynashEtvala
1d69613537efd25d9bc893cf161343529d7c5984
5,409
cpp
C++
test/entity_system/aggregation_test.cpp
sheiny/ophidian
037ae44357e0093d60b379513615b467c1f841cf
[ "Apache-2.0" ]
40
2016-04-22T14:42:42.000Z
2021-05-25T23:14:23.000Z
test/entity_system/aggregation_test.cpp
sheiny/ophidian
037ae44357e0093d60b379513615b467c1f841cf
[ "Apache-2.0" ]
64
2016-04-28T21:10:47.000Z
2017-11-07T11:33:17.000Z
test/entity_system/aggregation_test.cpp
eclufsc/openeda
037ae44357e0093d60b379513615b467c1f841cf
[ "Apache-2.0" ]
25
2016-04-18T19:31:48.000Z
2021-05-05T15:50:41.000Z
#include <catch.hpp> #include <ophidian/entity_system/Aggregation.h> using namespace ophidian::entity_system; class EntityA : public EntityBase { public: using EntityBase::EntityBase; }; class EntityB : public EntityBase { public: using EntityBase::EntityBase; }; TEST_CASE("Aggregation: no parts", "[entity_system][Property][Aggregation][EntitySystem]") { EntitySystem<EntityA> sys1; EntitySystem<EntityB> sys2; Aggregation<EntityA, EntityB> aggregation(sys1, sys2); auto en1 = sys1.add(); auto parts = aggregation.parts(en1); REQUIRE(parts.begin() == parts.end()); REQUIRE(parts.empty()); REQUIRE(parts.size() == 0); REQUIRE(aggregation.firstPart(en1) == EntityB()); } TEST_CASE("Aggregation: add part", "[entity_system][Property][Aggregation][EntitySystem]") { EntitySystem<EntityA> sys1; EntitySystem<EntityB> sys2; Aggregation<EntityA, EntityB> aggregation(sys1, sys2); auto en1 = sys1.add(); auto en2 = sys2.add(); REQUIRE(aggregation.whole(en2) == EntityA()); aggregation.addAssociation(en1, en2); REQUIRE(aggregation.whole(en2) == en1); auto parts = aggregation.parts(en1); REQUIRE(parts.begin() != parts.end()); REQUIRE(!parts.empty()); REQUIRE(parts.size() == 1); REQUIRE(std::count(parts.begin(), parts.end(), en2) == 1); } TEST_CASE("Aggregation: erase part", "[entity_system][Property][Aggregation][EntitySystem]") { EntitySystem<EntityA> sys1; EntitySystem<EntityB> sys2; Aggregation<EntityA, EntityB> aggregation(sys1, sys2); auto en1 = sys1.add(); auto en2 = sys2.add(); aggregation.addAssociation(en1, en2); sys2.erase(en2); auto parts = aggregation.parts(en1); REQUIRE(std::count(parts.begin(), parts.end(), en2) == 0); } TEST_CASE("Aggregation: erase whole", "[entity_system][Property][Aggregation][EntitySystem]") { EntitySystem<EntityA> sys1; EntitySystem<EntityB> sys2; Aggregation<EntityA, EntityB> aggregation(sys1, sys2); auto en1 = sys1.add(); auto en2 = sys2.add(); aggregation.addAssociation(en1, en2); sys1.erase(en1); REQUIRE(aggregation.whole(en2) == EntityA()); } TEST_CASE("Aggregation: add parts, erase one, keep others", "[entity_system][Property][Aggregation][EntitySystem]") { EntitySystem<EntityA> sys1; EntitySystem<EntityB> sys2; Aggregation<EntityA, EntityB> aggregation(sys1, sys2); auto en1 = sys1.add(); auto part1 = sys2.add(); auto part2 = sys2.add(); auto part3 = sys2.add(); auto part4 = sys2.add(); auto part5 = sys2.add(); aggregation.addAssociation(en1, part1); aggregation.addAssociation(en1, part2); aggregation.addAssociation(en1, part3); aggregation.addAssociation(en1, part4); aggregation.addAssociation(en1, part5); sys2.erase(part4); REQUIRE(aggregation.whole(part1) == en1); REQUIRE(aggregation.whole(part2) == en1); REQUIRE(aggregation.whole(part3) == en1); REQUIRE(aggregation.whole(part5) == en1); REQUIRE(aggregation.parts(en1).size() == 4); } TEST_CASE("Aggregation: clear()", "[entity_system][Property][Aggregation][EntitySystem]") { INFO("Given an aggregation with 5 wholes and some parts"); EntitySystem<EntityA> sys1; EntitySystem<EntityB> sys2; Aggregation<EntityA, EntityB> aggregation(sys1, sys2); std::vector<EntityA> wholes{ sys1.add(), sys1.add(), sys1.add(), sys1.add(), sys1.add() }; aggregation.addAssociation(wholes[0], sys2.add()); aggregation.addAssociation(wholes[0], sys2.add()); aggregation.addAssociation(wholes[1], sys2.add()); aggregation.addAssociation(wholes[1], sys2.add()); aggregation.addAssociation(wholes[1], sys2.add()); aggregation.addAssociation(wholes[2], sys2.add()); aggregation.addAssociation(wholes[3], sys2.add()); aggregation.addAssociation(wholes[3], sys2.add()); aggregation.addAssociation(wholes[3], sys2.add()); aggregation.addAssociation(wholes[3], sys2.add()); aggregation.addAssociation(wholes[4], sys2.add()); aggregation.addAssociation(wholes[4], sys2.add()); INFO("When the wholes system is cleared"); sys1.clear(); INFO("Then parts must be kept valid") REQUIRE(sys2.size() == 12); INFO("Then all parts must have nextPart == NIL") { std::list<EntityB> partsWithNextPart; std::copy_if(sys2.begin(), sys2.end(), std::back_inserter(partsWithNextPart), [&aggregation](const EntityB & en)->bool { return aggregation.nextPart(en) != EntityB(); }); REQUIRE(partsWithNextPart.empty()); } INFO("Then all parts must have whole == NIL") { std::list<EntityB> partsWithWhole; std::copy_if(sys2.begin(), sys2.end(), std::back_inserter(partsWithWhole), [&aggregation](const EntityB & en)->bool { return aggregation.whole(en) != EntityA(); }); REQUIRE(partsWithWhole.empty()); } } TEST_CASE("Aggregation: lifetime managment", "[entity_system][Property][Aggregation][EntitySystem]") { std::unique_ptr<Aggregation<EntityA, EntityB> > agg; EntitySystem<EntityA> sys1; EntitySystem<EntityB> sys2; REQUIRE_NOTHROW(sys1.add()); agg = std::move(std::make_unique<Aggregation<EntityA, EntityB> >(sys1, sys2)); REQUIRE_NOTHROW(sys1.add()); agg.reset(); REQUIRE_NOTHROW(sys1.add()); }
30.908571
126
0.66944
sheiny
1d6a07e49752b88b77db346cfba7d1581b49a24c
7,486
cpp
C++
redis-cpp-test/writer_test.cpp
summerlight/redis-cpp
6b3b044e4c9e91a97b871379027d28f2d1a61769
[ "MIT" ]
null
null
null
redis-cpp-test/writer_test.cpp
summerlight/redis-cpp
6b3b044e4c9e91a97b871379027d28f2d1a61769
[ "MIT" ]
null
null
null
redis-cpp-test/writer_test.cpp
summerlight/redis-cpp
6b3b044e4c9e91a97b871379027d28f2d1a61769
[ "MIT" ]
null
null
null
#include "redis_test.h" #include "writer_type_traits.h" #include <vector> #include <list> #include <string> #include <iterator> #include <utility> #include <cassert> #include <cstdio> #include <cinttypes> #include <catch.hpp> namespace redis_test { using std::begin; using std::end; // element count function test TEST_CASE("element_count", "[writer]") { // scalar type test int a = 0; std::string b = "test"; std::wstring c = L"test"; char* d = ""; REQUIRE(redis::count_element(a) == 1); REQUIRE(redis::count_element(b) == 1); REQUIRE(redis::count_element(c) == 1); REQUIRE(redis::count_element(d) == 1); REQUIRE(redis::count_element(0) == 1); REQUIRE(redis::count_element(std::string("")) == 1); REQUIRE(redis::count_element(std::wstring(L"")) == 1); REQUIRE(redis::count_element("") == 1); // pair type test std::pair<int, std::wstring> e; REQUIRE(redis::count_element(e) == 2); REQUIRE(redis::count_element(std::make_pair(0, "")) == 2); // optional type test REQUIRE(redis::count_element(redis::optional(true, a, "test", std::make_pair(10, 10))) == 4); REQUIRE(redis::count_element(redis::optional(false, b, "test", std::make_pair(10, 10))) == 0); REQUIRE(!b.empty()); // variadic argument test REQUIRE(redis::count_element(0) == 1); REQUIRE(redis::count_element(0, 0) == 2); REQUIRE(redis::count_element(0, 0, 0) == 3); REQUIRE(redis::count_element(0, 0, 0, 0) == 4); REQUIRE(redis::count_element(0, 0, 0, 0, 0) == 5); REQUIRE(redis::count_element(0, 0, 0, 0, 0, 0) == 6); REQUIRE(redis::count_element(0, 0, 0, 0, 0, 0, 0) == 7); REQUIRE(redis::count_element(0, 0, 0, 0, 0, 0, 0, 0) == 8); REQUIRE(redis::count_element(0, 0, 0, 0, 0, 0, 0, 0, 0) == 9); REQUIRE(redis::count_element(0, 0, 0, 0, 0, 0, 0, 0, 0, 0) == 10); } TEST_CASE("container_count", "[writer]") { { // empty std::vector<int> vec; REQUIRE(redis::count_element(vec) == 0); } { // l-value std::vector<int> vec; vec.push_back(1); vec.push_back(2); vec.push_back(3); REQUIRE(redis::count_element(vec) == 3); } { // const l-value const std::vector<std::string> vec(3); REQUIRE(redis::count_element(vec) == 3); } { // r-value REQUIRE(redis::count_element(std::vector<std::wstring>(3)) == 3u); } { // pair vector std::vector<std::pair<int, std::string>> vec; vec.push_back(std::make_pair(0, "0")); vec.push_back(std::make_pair(1, "1")); vec.push_back(std::make_pair(2, "2")); REQUIRE(redis::count_element(vec) == 6u); } { // list std::list<int> list; list.push_back(0); list.push_back(1); list.push_back(2); list.push_back(3); REQUIRE(redis::count_element(list) == 4u); } { // optional type with container test std::vector<int> vec; vec.push_back(1); vec.push_back(2); REQUIRE(redis::count_element(redis::optional(true, vec)) == 2); REQUIRE(vec.size() == 2); // optional value for l-value should not move container - only for r-value } } void write_integer_test(int64_t value) { mock_stream output; redis::detail::write_integer(output, value); char buffer[24]; snprintf(buffer, 24, "%" PRId64, value); REQUIRE(check_equal(buffer, output)); } TEST_CASE("writer_helper_function", "[writer]") { for (int i = 0; i < 100; i++) { write_integer_test(uniform_random<int64_t>()); } write_integer_test(std::numeric_limits<int64_t>::max()); write_integer_test(std::numeric_limits<int64_t>::min()); write_integer_test(0); { mock_stream output; redis::detail::write_newline(output); REQUIRE(check_equal("\r\n", output)); } { mock_stream output; const char test_data[] = "this is test"; redis::detail::write_bulk_element(output, redis::const_buffer_view(begin(test_data), end(test_data)-1)); REQUIRE(check_equal("$12\r\nthis is test\r\n", output)); } { mock_stream output; redis::write_header(output, 10); REQUIRE(check_equal("*10\r\n", output)); } } template<typename T> void write_element_test(T&& value, const char expected[]) { mock_stream output; redis::write_element(output, std::forward<T>(value)); REQUIRE(check_equal(expected, output)); } TEST_CASE("write_element_for_each_type", "[writer]") { write_element_test(10, "$2\r\n10\r\n"); write_element_test("test", "$4\r\ntest\r\n"); write_element_test(std::make_pair(1, 2), "$1\r\n1\r\n$1\r\n2\r\n"); write_element_test(std::string("test"), "$4\r\ntest\r\n"); { std::vector<char> vec; vec.push_back('a'); vec.push_back('b'); vec.push_back('c'); write_element_test(vec, "$3\r\nabc\r\n"); } { std::vector<int> vec; vec.push_back(1); vec.push_back(2); vec.push_back(3); write_element_test(vec, "$1\r\n1\r\n$1\r\n2\r\n$1\r\n3\r\n"); } write_element_test(redis::optional(true, 1, "test"), "$1\r\n1\r\n$4\r\ntest\r\n"); { const char data[] = "1234"; write_element_test(redis::const_buffer_view(begin(data), end(data)-1), "$4\r\n1234\r\n"); } } TEST_CASE("write_variadic_element", "[writer]") { { mock_stream output; redis::write_element(output, 0); REQUIRE(check_equal("$1\r\n0\r\n", output)); } { mock_stream output; redis::write_element(output, 0, 0); REQUIRE(check_equal("$1\r\n0\r\n$1\r\n0\r\n", output)); } { mock_stream output; redis::write_element(output, 0, 0, 0); REQUIRE(check_equal("$1\r\n0\r\n$1\r\n0\r\n$1\r\n0\r\n", output)); } { mock_stream output; redis::write_element(output, 0, 0, 0, 0); REQUIRE(check_equal("$1\r\n0\r\n$1\r\n0\r\n$1\r\n0\r\n$1\r\n0\r\n", output)); } { mock_stream output; redis::write_element(output, 0, 0, 0, 0, 0); REQUIRE(check_equal("$1\r\n0\r\n$1\r\n0\r\n$1\r\n0\r\n$1\r\n0\r\n$1\r\n0\r\n", output)); } { mock_stream output; redis::write_element(output, 0, 0, 0, 0, 0, 0); REQUIRE(check_equal("$1\r\n0\r\n$1\r\n0\r\n$1\r\n0\r\n$1\r\n0\r\n$1\r\n0\r\n$1\r\n0\r\n", output)); } { mock_stream output; redis::write_element(output, 0, 0, 0, 0, 0, 0, 0); REQUIRE(check_equal("$1\r\n0\r\n$1\r\n0\r\n$1\r\n0\r\n$1\r\n0\r\n$1\r\n0\r\n$1\r\n0\r\n$1\r\n0\r\n", output)); } { mock_stream output; redis::write_element(output, 0, 0, 0, 0, 0, 0, 0, 0); REQUIRE(check_equal("$1\r\n0\r\n$1\r\n0\r\n$1\r\n0\r\n$1\r\n0\r\n$1\r\n0\r\n$1\r\n0\r\n$1\r\n0\r\n$1\r\n0\r\n", output)); } { mock_stream output; redis::write_element(output, 0, 0, 0, 0, 0, 0, 0, 0, 0); REQUIRE(check_equal("$1\r\n0\r\n$1\r\n0\r\n$1\r\n0\r\n$1\r\n0\r\n$1\r\n0\r\n$1\r\n0\r\n$1\r\n0\r\n$1\r\n0\r\n$1\r\n0\r\n", output)); } { mock_stream output; redis::write_element(output, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); REQUIRE(check_equal("$1\r\n0\r\n$1\r\n0\r\n$1\r\n0\r\n$1\r\n0\r\n$1\r\n0\r\n$1\r\n0\r\n$1\r\n0\r\n$1\r\n0\r\n$1\r\n0\r\n$1\r\n0\r\n", output)); } } } // namespace "redis_test"
29.128405
151
0.5716
summerlight
1d6ae8ad2074a9081568cf84ed3510effc7914a0
4,759
cpp
C++
qtmultimedia/src/multimedia/controls/qmediagaplessplaybackcontrol.cpp
wgnet/wds_qt
8db722fd367d2d0744decf99ac7bafaba8b8a3d3
[ "Apache-2.0" ]
1
2020-04-30T15:47:35.000Z
2020-04-30T15:47:35.000Z
qtmultimedia/src/multimedia/controls/qmediagaplessplaybackcontrol.cpp
wgnet/wds_qt
8db722fd367d2d0744decf99ac7bafaba8b8a3d3
[ "Apache-2.0" ]
null
null
null
qtmultimedia/src/multimedia/controls/qmediagaplessplaybackcontrol.cpp
wgnet/wds_qt
8db722fd367d2d0744decf99ac7bafaba8b8a3d3
[ "Apache-2.0" ]
null
null
null
/**************************************************************************** ** ** Copyright (C) 2015 The Qt Company Ltd. ** Contact: http://www.qt.io/licensing/ ** ** This file is part of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL21$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see http://www.qt.io/terms-conditions. For further ** information use the contact form at http://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** As a special exception, The Qt Company gives you certain additional ** rights. These rights are described in The Qt Company LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qmediagaplessplaybackcontrol.h" #include "qmediacontrol_p.h" /*! \class QMediaGaplessPlaybackControl \inmodule QtMultimedia \ingroup multimedia_control \brief The QMediaGaplessPlaybackControl class provides access to the gapless playback related control of a QMediaService. If a QMediaService supports gapless playback it will implement QMediaGaplessPlaybackControl. This control provides a means to set the \l {setNextMedia()}{next media} or \l {setCrossfadeTime()}{crossfade time} for smooth transitions between tracks. The functionality provided by this control is exposed to application code through the QMediaPlayer class. The interface name of QMediaGaplessPlaybackControl is \c org.qt-project.qt.mediagaplessplaybackcontrol/5.0 as defined in QMediaGaplessPlaybackControl_iid. \sa QMediaService::requestControl(), QMediaPlayer */ /*! \macro QMediaGaplessPlaybackControl_iid \c org.qt-project.qt.mediagaplessplaybackcontrol/5.0 Defines the interface name of the QMediaGaplessPlaybackControl class. \relates QMediaGaplessPlaybackControl */ /*! Destroys a gapless playback control. */ QMediaGaplessPlaybackControl::~QMediaGaplessPlaybackControl() { } /*! Constructs a new gapless playback control with the given \a parent. */ QMediaGaplessPlaybackControl::QMediaGaplessPlaybackControl(QObject *parent): QMediaControl(*new QMediaControlPrivate, parent) { } /*! \fn QMediaGaplessPlaybackControl::nextMedia() const Returns the content of the next media */ /*! \fn QMediaGaplessPlaybackControl::setNextMedia(const QMediaContent& media) Sets the next \a media for smooth transition. */ /*! \fn QMediaGaplessPlaybackControl::nextMediaChanged(const QMediaContent& media) Signals that the next \a media has changed (either explicitly via \l setNextMedia() or when the player clears the next media while advancing to it). \sa nextMedia() */ /*! \fn QMediaGaplessPlaybackControl::advancedToNextMedia() Signals when the player advances to the next media (the content of next media will be cleared). \sa nextMedia() */ /*! \fn QMediaGaplessPlaybackControl::isCrossfadeSupported() const Indicates whether crossfading is supported or not. If crossfading is not supported, \l setCrossfadeTime() will be ignored and \l crossfadeTime() will always return 0. */ /*! \fn QMediaGaplessPlaybackControl::setCrossfadeTime(qreal crossfadeTime) Sets the \a crossfadeTime in seconds for smooth transition. Positive value means how much time it will take for the next media to transit from silent to full volume and vice versa for current one. So both current and the next one will be playing during this period of time. A crossfade time of zero or negative will result in gapless playback (suitable for some continuous media). */ /*! \fn QMediaGaplessPlaybackControl::crossfadeTime() const Returns current crossfade time in seconds. */ /*! \fn QMediaGaplessPlaybackControl::crossfadeTimeChanged(qreal crossfadeTime) Signals that the \a crossfadeTime has changed. \sa crossfadeTime() */
31.516556
104
0.731246
wgnet
1d6d9c273d5f7d9846b20218c85c3fc9f4fc1cda
116
cc
C++
code/cmake_gtest/hello_test.cc
iusyu/c_practic
7428b8d37df09cb27bc9d66d1e34c81a973b6119
[ "MIT" ]
null
null
null
code/cmake_gtest/hello_test.cc
iusyu/c_practic
7428b8d37df09cb27bc9d66d1e34c81a973b6119
[ "MIT" ]
null
null
null
code/cmake_gtest/hello_test.cc
iusyu/c_practic
7428b8d37df09cb27bc9d66d1e34c81a973b6119
[ "MIT" ]
null
null
null
#include<gtest/gtest.h> TEST(HelloTest, BaseAssertions) { EXPECT_STRNE("Hello", "World"); EXPECT_EQ(4*7, 28); }
14.5
33
0.689655
iusyu
1d6f00d0db2a9d242e151aace57d04d195111936
855
cxx
C++
Plugins/Mipf_Plugin_ModelExporter/Mipf_Plugin_ModelExporterActivator.cxx
linson7017/MIPF
adf982ae5de69fca9d6599fbbbd4ca30f4ae9767
[ "ECL-2.0", "Apache-2.0" ]
4
2017-04-13T06:01:49.000Z
2019-12-04T07:23:53.000Z
Plugins/Mipf_Plugin_ModelExporter/Mipf_Plugin_ModelExporterActivator.cxx
linson7017/MIPF
adf982ae5de69fca9d6599fbbbd4ca30f4ae9767
[ "ECL-2.0", "Apache-2.0" ]
1
2017-10-27T02:00:44.000Z
2017-10-27T02:00:44.000Z
Plugins/Mipf_Plugin_ModelExporter/Mipf_Plugin_ModelExporterActivator.cxx
linson7017/MIPF
adf982ae5de69fca9d6599fbbbd4ca30f4ae9767
[ "ECL-2.0", "Apache-2.0" ]
2
2017-09-06T01:59:07.000Z
2019-12-04T07:23:54.000Z
#include "Mipf_Plugin_ModelExporterActivator.h" #include "ModelExporterView.h" #include "Utils/PluginFactory.h" QF_API QF::IQF_Activator* QF::QF_CreatePluginActivator(QF::IQF_Main* pMain) { QF::IQF_Activator* pActivator = new Mipf_Plugin_ModelExporter_Activator(pMain); //assert(pActivator); return pActivator; } const char Mipf_Plugin_ModelExporter_Activator_ID[] = "Mipf_Plugin_ModelExporter_Activator_ID"; Mipf_Plugin_ModelExporter_Activator::Mipf_Plugin_ModelExporter_Activator(QF::IQF_Main* pMain):ActivatorBase(pMain) { } bool Mipf_Plugin_ModelExporter_Activator::Init() { return true; } const char* Mipf_Plugin_ModelExporter_Activator::GetID() { return Mipf_Plugin_ModelExporter_Activator_ID; } void Mipf_Plugin_ModelExporter_Activator::Register() { REGISTER_PLUGIN("ModelExporterWidget", ModelExporterView); }
26.71875
114
0.803509
linson7017
1d6fce8cf7939bb40cdcd85982d240f6be366064
32,156
cxx
C++
panda/src/pgraph/lightAttrib.cxx
cmarshall108/panda3d-python3
8bea2c0c120b03ec1c9fd179701fdeb7510bb97b
[ "PHP-3.0", "PHP-3.01" ]
null
null
null
panda/src/pgraph/lightAttrib.cxx
cmarshall108/panda3d-python3
8bea2c0c120b03ec1c9fd179701fdeb7510bb97b
[ "PHP-3.0", "PHP-3.01" ]
null
null
null
panda/src/pgraph/lightAttrib.cxx
cmarshall108/panda3d-python3
8bea2c0c120b03ec1c9fd179701fdeb7510bb97b
[ "PHP-3.0", "PHP-3.01" ]
null
null
null
/** * PANDA 3D SOFTWARE * Copyright (c) Carnegie Mellon University. All rights reserved. * * All use of this software is subject to the terms of the revised BSD * license. You should have received a copy of this license along * with this source code in a file named "LICENSE." * * @file lightAttrib.cxx * @author drose * @date 2002-03-26 */ #include "lightAttrib.h" #include "pandaNode.h" #include "nodePath.h" #include "graphicsStateGuardianBase.h" #include "bamReader.h" #include "bamWriter.h" #include "datagram.h" #include "datagramIterator.h" #include "config_pgraph.h" #include "attribNodeRegistry.h" #include "indent.h" #include <iterator> CPT(RenderAttrib) LightAttrib::_empty_attrib; int LightAttrib::_attrib_slot; CPT(RenderAttrib) LightAttrib::_all_off_attrib; TypeHandle LightAttrib::_type_handle; // This STL Function object is used in sort_on_lights(), below, to sort a list // of Lights in reverse order by priority. In the case of two lights with // equal priority, the class priority is compared. class CompareLightPriorities { public: bool operator ()(const NodePath &a, const NodePath &b) const { nassertr(!a.is_empty() && !b.is_empty(), a < b); Light *la = a.node()->as_light(); Light *lb = b.node()->as_light(); nassertr(la != nullptr && lb != nullptr, a < b); if (la->get_priority() != lb->get_priority()) { return la->get_priority() > lb->get_priority(); } return la->get_class_priority() > lb->get_class_priority(); } }; /** * Use LightAttrib::make() to construct a new LightAttrib object. The copy * constructor is only defined to facilitate methods like add_on_light(). */ LightAttrib:: LightAttrib(const LightAttrib &copy) : _on_lights(copy._on_lights), _off_lights(copy._off_lights), _off_all_lights(copy._off_all_lights), _sort_seq(UpdateSeq::old()) { // Increase the attrib_ref of all the lights in this attribute. Lights::const_iterator it; for (it = _on_lights.begin(); it != _on_lights.end(); ++it) { Light *lobj = (*it).node()->as_light(); nassertd(lobj != nullptr) continue; lobj->attrib_ref(); } } /** * Destructor. */ LightAttrib:: ~LightAttrib() { // Call attrib_unref() on all on lights. Lights::const_iterator it; for (it = _on_lights.begin(); it != _on_lights.end(); ++it) { const NodePath &np = *it; if (!np.is_empty()) { Light *lobj = np.node()->as_light(); if (lobj != nullptr) { lobj->attrib_unref(); } } } } /** * Constructs a new LightAttrib object that turns on (or off, according to op) * the indicated light(s). * * This method is now deprecated. Use add_on_light() or add_off_light() * instead. */ CPT(RenderAttrib) LightAttrib:: make(LightAttrib::Operation op, Light *light) { pgraph_cat.warning() << "Using deprecated LightAttrib interface.\n"; CPT(RenderAttrib) attrib; switch (op) { case O_set: attrib = make_all_off(); attrib = DCAST(LightAttrib, attrib)->add_on_light(NodePath(light->as_node())); return attrib; case O_add: attrib = make(); attrib = DCAST(LightAttrib, attrib)->add_on_light(NodePath(light->as_node())); return attrib; case O_remove: attrib = make(); attrib = DCAST(LightAttrib, attrib)->add_off_light(NodePath(light->as_node())); return attrib; } nassertr(false, make()); return make(); } /** * Constructs a new LightAttrib object that turns on (or off, according to op) * the indicate light(s). * * This method is now deprecated. Use add_on_light() or add_off_light() * instead. */ CPT(RenderAttrib) LightAttrib:: make(LightAttrib::Operation op, Light *light1, Light *light2) { pgraph_cat.warning() << "Using deprecated LightAttrib interface.\n"; CPT(RenderAttrib) attrib; switch (op) { case O_set: attrib = make_all_off(); attrib = DCAST(LightAttrib, attrib)->add_on_light(NodePath(light1->as_node())); attrib = DCAST(LightAttrib, attrib)->add_on_light(NodePath(light2->as_node())); return attrib; case O_add: attrib = make(); attrib = DCAST(LightAttrib, attrib)->add_on_light(NodePath(light1->as_node())); attrib = DCAST(LightAttrib, attrib)->add_on_light(NodePath(light2->as_node())); return attrib; case O_remove: attrib = make(); attrib = DCAST(LightAttrib, attrib)->add_off_light(NodePath(light1->as_node())); attrib = DCAST(LightAttrib, attrib)->add_off_light(NodePath(light2->as_node())); return attrib; } nassertr(false, make()); return make(); } /** * Constructs a new LightAttrib object that turns on (or off, according to op) * the indicate light(s). * * This method is now deprecated. Use add_on_light() or add_off_light() * instead. */ CPT(RenderAttrib) LightAttrib:: make(LightAttrib::Operation op, Light *light1, Light *light2, Light *light3) { pgraph_cat.warning() << "Using deprecated LightAttrib interface.\n"; CPT(RenderAttrib) attrib; switch (op) { case O_set: attrib = make_all_off(); attrib = DCAST(LightAttrib, attrib)->add_on_light(NodePath(light1->as_node())); attrib = DCAST(LightAttrib, attrib)->add_on_light(NodePath(light2->as_node())); attrib = DCAST(LightAttrib, attrib)->add_on_light(NodePath(light3->as_node())); return attrib; case O_add: attrib = make(); attrib = DCAST(LightAttrib, attrib)->add_on_light(NodePath(light1->as_node())); attrib = DCAST(LightAttrib, attrib)->add_on_light(NodePath(light2->as_node())); attrib = DCAST(LightAttrib, attrib)->add_on_light(NodePath(light3->as_node())); return attrib; case O_remove: attrib = make(); attrib = DCAST(LightAttrib, attrib)->add_off_light(NodePath(light1->as_node())); attrib = DCAST(LightAttrib, attrib)->add_off_light(NodePath(light2->as_node())); attrib = DCAST(LightAttrib, attrib)->add_off_light(NodePath(light3->as_node())); return attrib; } nassertr(false, make()); return make(); } /** * Constructs a new LightAttrib object that turns on (or off, according to op) * the indicate light(s). * * This method is now deprecated. Use add_on_light() or add_off_light() * instead. */ CPT(RenderAttrib) LightAttrib:: make(LightAttrib::Operation op, Light *light1, Light *light2, Light *light3, Light *light4) { pgraph_cat.warning() << "Using deprecated LightAttrib interface.\n"; CPT(RenderAttrib) attrib; switch (op) { case O_set: attrib = make_all_off(); attrib = DCAST(LightAttrib, attrib)->add_on_light(NodePath(light1->as_node())); attrib = DCAST(LightAttrib, attrib)->add_on_light(NodePath(light2->as_node())); attrib = DCAST(LightAttrib, attrib)->add_on_light(NodePath(light3->as_node())); attrib = DCAST(LightAttrib, attrib)->add_on_light(NodePath(light4->as_node())); return attrib; case O_add: attrib = make(); attrib = DCAST(LightAttrib, attrib)->add_on_light(NodePath(light1->as_node())); attrib = DCAST(LightAttrib, attrib)->add_on_light(NodePath(light2->as_node())); attrib = DCAST(LightAttrib, attrib)->add_on_light(NodePath(light3->as_node())); attrib = DCAST(LightAttrib, attrib)->add_on_light(NodePath(light4->as_node())); return attrib; case O_remove: attrib = make(); attrib = DCAST(LightAttrib, attrib)->add_off_light(NodePath(light1->as_node())); attrib = DCAST(LightAttrib, attrib)->add_off_light(NodePath(light2->as_node())); attrib = DCAST(LightAttrib, attrib)->add_off_light(NodePath(light3->as_node())); attrib = DCAST(LightAttrib, attrib)->add_off_light(NodePath(light4->as_node())); return attrib; } nassertr(false, make()); return make(); } /** * Returns a RenderAttrib that corresponds to whatever the standard default * properties for render attributes of this type ought to be. */ CPT(RenderAttrib) LightAttrib:: make_default() { return return_new(new LightAttrib); } /** * Returns the basic operation type of the LightAttrib. If this is O_set, the * lights listed here completely replace any lights that were already on. If * this is O_add, the lights here are added to the set of lights that were * already on, and if O_remove, the lights here are removed from the set of * lights that were on. * * This method is now deprecated. LightAttribs nowadays have a separate list * of on_lights and off_lights, so this method doesn't make sense. Query the * lists independently. */ LightAttrib::Operation LightAttrib:: get_operation() const { pgraph_cat.warning() << "Using deprecated LightAttrib interface.\n"; if (has_all_off()) { return O_set; } else if (get_num_off_lights() == 0) { return O_add; } else { return O_remove; } } /** * Returns the number of lights listed in the attribute. * * This method is now deprecated. LightAttribs nowadays have a separate list * of on_lights and off_lights, so this method doesn't make sense. Query the * lists independently. */ int LightAttrib:: get_num_lights() const { pgraph_cat.warning() << "Using deprecated LightAttrib interface.\n"; if (get_num_off_lights() == 0) { return get_num_on_lights(); } else { return get_num_off_lights(); } } /** * Returns the nth light listed in the attribute. * * This method is now deprecated. LightAttribs nowadays have a separate list * of on_lights and off_lights, so this method doesn't make sense. Query the * lists independently. */ Light *LightAttrib:: get_light(int n) const { pgraph_cat.warning() << "Using deprecated LightAttrib interface.\n"; if (get_num_off_lights() == 0) { return get_on_light(n).node()->as_light(); } else { return get_off_light(n).node()->as_light(); } } /** * Returns true if the indicated light is listed in the attrib, false * otherwise. * * This method is now deprecated. LightAttribs nowadays have a separate list * of on_lights and off_lights, so this method doesn't make sense. Query the * lists independently. */ bool LightAttrib:: has_light(Light *light) const { pgraph_cat.warning() << "Using deprecated LightAttrib interface.\n"; if (get_num_off_lights() == 0) { return has_on_light(NodePath(light->as_node())); } else { return has_off_light(NodePath(light->as_node())); } } /** * Returns a new LightAttrib, just like this one, but with the indicated light * added to the list of lights. * * This method is now deprecated. Use add_on_light() or add_off_light() * instead. */ CPT(RenderAttrib) LightAttrib:: add_light(Light *light) const { pgraph_cat.warning() << "Using deprecated LightAttrib interface.\n"; if (get_num_off_lights() == 0) { return add_on_light(NodePath(light->as_node())); } else { return add_off_light(NodePath(light->as_node())); } } /** * Returns a new LightAttrib, just like this one, but with the indicated light * removed from the list of lights. * * This method is now deprecated. Use remove_on_light() or remove_off_light() * instead. */ CPT(RenderAttrib) LightAttrib:: remove_light(Light *light) const { pgraph_cat.warning() << "Using deprecated LightAttrib interface.\n"; if (get_num_off_lights() == 0) { return remove_on_light(NodePath(light->as_node())); } else { return remove_off_light(NodePath(light->as_node())); } } /** * Constructs a new LightAttrib object that does nothing. */ CPT(RenderAttrib) LightAttrib:: make() { // We make it a special case and store a pointer to the empty attrib forever // once we find it the first time, as an optimization. if (_empty_attrib == nullptr) { _empty_attrib = return_new(new LightAttrib); } return _empty_attrib; } /** * Constructs a new LightAttrib object that turns off all lights (and hence * disables lighting). */ CPT(RenderAttrib) LightAttrib:: make_all_off() { // We make it a special case and store a pointer to the off attrib forever // once we find it the first time, as an optimization. if (_all_off_attrib == nullptr) { LightAttrib *attrib = new LightAttrib; attrib->_off_all_lights = true; _all_off_attrib = return_new(attrib); } return _all_off_attrib; } /** * Returns a new LightAttrib, just like this one, but with the indicated light * added to the list of lights turned on by this attrib. */ CPT(RenderAttrib) LightAttrib:: add_on_light(const NodePath &light) const { nassertr(!light.is_empty(), this); Light *lobj = light.node()->as_light(); nassertr(lobj != nullptr, this); LightAttrib *attrib = new LightAttrib(*this); std::pair<Lights::iterator, bool> insert_result = attrib->_on_lights.insert(Lights::value_type(light)); if (insert_result.second) { lobj->attrib_ref(); // Also ensure it is removed from the off_lights list. attrib->_off_lights.erase(light); } return return_new(attrib); } /** * Returns a new LightAttrib, just like this one, but with the indicated light * removed from the list of lights turned on by this attrib. */ CPT(RenderAttrib) LightAttrib:: remove_on_light(const NodePath &light) const { nassertr(!light.is_empty(), this); Light *lobj = light.node()->as_light(); nassertr(lobj != nullptr, this); LightAttrib *attrib = new LightAttrib(*this); if (attrib->_on_lights.erase(light)) { lobj->attrib_unref(); } return return_new(attrib); } /** * Returns a new LightAttrib, just like this one, but with the indicated light * added to the list of lights turned off by this attrib. */ CPT(RenderAttrib) LightAttrib:: add_off_light(const NodePath &light) const { nassertr(!light.is_empty(), this); Light *lobj = light.node()->as_light(); nassertr(lobj != nullptr, this); LightAttrib *attrib = new LightAttrib(*this); if (!_off_all_lights) { attrib->_off_lights.insert(light); } if (attrib->_on_lights.erase(light)) { lobj->attrib_unref(); } return return_new(attrib); } /** * Returns a new LightAttrib, just like this one, but with the indicated light * removed from the list of lights turned off by this attrib. */ CPT(RenderAttrib) LightAttrib:: remove_off_light(const NodePath &light) const { nassertr(!light.is_empty() && light.node()->as_light() != nullptr, this); LightAttrib *attrib = new LightAttrib(*this); attrib->_off_lights.erase(light); return return_new(attrib); } /** * Returns the most important light (that is, the light with the highest * priority) in the LightAttrib, excluding any ambient lights. Returns an * empty NodePath if no non-ambient lights are found. */ NodePath LightAttrib:: get_most_important_light() const { check_sorted(); if (_num_non_ambient_lights > 0) { return _sorted_on_lights[0]; } else { return NodePath(); } } /** * Returns the total contribution of all the ambient lights. */ LColor LightAttrib:: get_ambient_contribution() const { check_sorted(); LVecBase4 total(0); Lights::const_iterator li; li = _sorted_on_lights.begin() + _num_non_ambient_lights; for (; li != _sorted_on_lights.end(); ++li) { const NodePath &np = (*li); Light *light = np.node()->as_light(); nassertd(light != nullptr && light->is_ambient_light()) continue; total += light->get_color(); } return total; } /** * */ void LightAttrib:: output(std::ostream &out) const { out << get_type() << ":"; if (_off_lights.empty()) { if (_on_lights.empty()) { if (_off_all_lights) { out << "all off"; } else { out << "identity"; } } else { if (_off_all_lights) { out << "set"; } else { out << "on"; } } } else { out << "off"; Lights::const_iterator fi; for (fi = _off_lights.begin(); fi != _off_lights.end(); ++fi) { NodePath light = (*fi); if (light.is_empty()) { out << " " << light; } else { out << " " << light.get_name(); } } if (!_on_lights.empty()) { out << " on"; } } Lights::const_iterator li; for (li = _on_lights.begin(); li != _on_lights.end(); ++li) { NodePath light = (*li); if (light.is_empty()) { out << " " << light; } else { out << " " << light.get_name(); } } } /** * */ void LightAttrib:: write(std::ostream &out, int indent_level) const { indent(out, indent_level) << get_type() << ":"; if (_off_lights.empty()) { if (_on_lights.empty()) { if (_off_all_lights) { out << "all off\n"; } else { out << "identity\n"; } } else { if (_off_all_lights) { out << "set\n"; } else { out << "on\n"; } } } else { out << "off\n"; Lights::const_iterator fi; for (fi = _off_lights.begin(); fi != _off_lights.end(); ++fi) { NodePath light = (*fi); indent(out, indent_level + 2) << light << "\n"; } if (!_on_lights.empty()) { indent(out, indent_level) << "on\n"; } } Lights::const_iterator li; for (li = _on_lights.begin(); li != _on_lights.end(); ++li) { NodePath light = (*li); indent(out, indent_level + 2) << light << "\n"; } } /** * Intended to be overridden by derived LightAttrib types to return a unique * number indicating whether this LightAttrib is equivalent to the other one. * * This should return 0 if the two LightAttrib objects are equivalent, a * number less than zero if this one should be sorted before the other one, * and a number greater than zero otherwise. * * This will only be called with two LightAttrib objects whose get_type() * functions return the same. */ int LightAttrib:: compare_to_impl(const RenderAttrib *other) const { const LightAttrib *ta = (const LightAttrib *)other; if (_off_all_lights != ta->_off_all_lights) { return (int)_off_all_lights - (int)ta->_off_all_lights; } Lights::const_iterator li = _on_lights.begin(); Lights::const_iterator oli = ta->_on_lights.begin(); while (li != _on_lights.end() && oli != ta->_on_lights.end()) { NodePath light = (*li); NodePath other_light = (*oli); int compare = light.compare_to(other_light); if (compare != 0) { return compare; } ++li; ++oli; } if (li != _on_lights.end()) { return 1; } if (oli != ta->_on_lights.end()) { return -1; } Lights::const_iterator fi = _off_lights.begin(); Lights::const_iterator ofi = ta->_off_lights.begin(); while (fi != _off_lights.end() && ofi != ta->_off_lights.end()) { NodePath light = (*fi); NodePath other_light = (*ofi); int compare = light.compare_to(other_light); if (compare != 0) { return compare; } ++fi; ++ofi; } if (fi != _off_lights.end()) { return 1; } if (ofi != ta->_off_lights.end()) { return -1; } return 0; } /** * Intended to be overridden by derived RenderAttrib types to return a unique * hash for these particular properties. RenderAttribs that compare the same * with compare_to_impl(), above, should return the same hash; RenderAttribs * that compare differently should return a different hash. */ size_t LightAttrib:: get_hash_impl() const { size_t hash = 0; Lights::const_iterator li; for (li = _on_lights.begin(); li != _on_lights.end(); ++li) { NodePath light = (*li); hash = light.add_hash(hash); } // This bool value goes here, between the two lists, to differentiate // between the two. hash = int_hash::add_hash(hash, (int)_off_all_lights); for (li = _off_lights.begin(); li != _off_lights.end(); ++li) { NodePath light = (*li); hash = light.add_hash(hash); } return hash; } /** * Intended to be overridden by derived RenderAttrib types to specify how two * consecutive RenderAttrib objects of the same type interact. * * This should return the result of applying the other RenderAttrib to a node * in the scene graph below this RenderAttrib, which was already applied. In * most cases, the result is the same as the other RenderAttrib (that is, a * subsequent RenderAttrib completely replaces the preceding one). On the * other hand, some kinds of RenderAttrib (for instance, ColorTransformAttrib) * might combine in meaningful ways. */ CPT(RenderAttrib) LightAttrib:: compose_impl(const RenderAttrib *other) const { const LightAttrib *ta = (const LightAttrib *)other; if (ta->_off_all_lights) { // If the other type turns off all lights, it doesn't matter what we are. return ta; } // This is a three-way merge between ai, bi, and ci, except that bi and ci // should have no intersection and therefore needn't be compared to each // other. Lights::const_iterator ai = _on_lights.begin(); Lights::const_iterator bi = ta->_on_lights.begin(); Lights::const_iterator ci = ta->_off_lights.begin(); // Create a new LightAttrib that will hold the result. LightAttrib *new_attrib = new LightAttrib; std::back_insert_iterator<Lights> result = std::back_inserter(new_attrib->_on_lights); while (ai != _on_lights.end() && bi != ta->_on_lights.end() && ci != ta->_off_lights.end()) { if ((*ai) < (*bi)) { if ((*ai) < (*ci)) { // Here is a light that we have in the original, which is not present // in the secondary. *result = *ai; ++ai; ++result; } else if ((*ci) < (*ai)) { // Here is a light that is turned off in the secondary, but was not // present in the original. ++ci; } else { // (*ci) == (*ai) // Here is a light that is turned off in the secondary, and was // present in the original. ++ai; ++ci; } } else if ((*bi) < (*ai)) { // Here is a new light we have in the secondary, that was not present in // the original. *result = *bi; ++bi; ++result; } else { // (*bi) == (*ai) // Here is a light we have in both. *result = *bi; ++ai; ++bi; ++result; } } while (ai != _on_lights.end() && bi != ta->_on_lights.end()) { if ((*ai) < (*bi)) { // Here is a light that we have in the original, which is not present in // the secondary. *result = *ai; ++ai; ++result; } else if ((*bi) < (*ai)) { // Here is a new light we have in the secondary, that was not present in // the original. *result = *bi; ++bi; ++result; } else { // Here is a light we have in both. *result = *bi; ++ai; ++bi; ++result; } } while (ai != _on_lights.end() && ci != ta->_off_lights.end()) { if ((*ai) < (*ci)) { // Here is a light that we have in the original, which is not present in // the secondary. *result = *ai; ++ai; ++result; } else if ((*ci) < (*ai)) { // Here is a light that is turned off in the secondary, but was not // present in the original. ++ci; } else { // (*ci) == (*ai) // Here is a light that is turned off in the secondary, and was present // in the original. ++ai; ++ci; } } while (ai != _on_lights.end()) { *result = *ai; ++ai; ++result; } while (bi != ta->_on_lights.end()) { *result = *bi; ++bi; ++result; } // Increase the attrib_ref of all the lights in this new attribute. Lights::const_iterator it; for (it = new_attrib->_on_lights.begin(); it != new_attrib->_on_lights.end(); ++it) { Light *lobj = (*it).node()->as_light(); nassertd(lobj != nullptr) continue; lobj->attrib_ref(); } // This is needed since _sorted_on_lights is not yet populated. new_attrib->_sort_seq = UpdateSeq::old(); return return_new(new_attrib); } /** * Intended to be overridden by derived RenderAttrib types to specify how two * consecutive RenderAttrib objects of the same type interact. * * See invert_compose() and compose_impl(). */ CPT(RenderAttrib) LightAttrib:: invert_compose_impl(const RenderAttrib *other) const { // I think in this case the other attrib always wins. Maybe this needs a // bit more thought. It's hard to imagine that it's even important to // compute this properly. return other; } /** * Makes sure the lights are sorted in order of priority. Also counts the * number of non-ambient lights. */ void LightAttrib:: sort_on_lights() { _sort_seq = Light::get_sort_seq(); // Separate the list of lights into ambient lights and other lights. _sorted_on_lights.clear(); OrderedLights ambient_lights; Lights::const_iterator li; for (li = _on_lights.begin(); li != _on_lights.end(); ++li) { const NodePath &np = (*li); nassertd(!np.is_empty() && np.node()->as_light() != nullptr) continue; if (!np.node()->is_ambient_light()) { _sorted_on_lights.push_back(np); } else { ambient_lights.push_back(np); } } // Remember how many lights were non-ambient lights, which makes it easier // to traverse through the list of non-ambient lights. _num_non_ambient_lights = _sorted_on_lights.size(); // This sort function uses the STL function object defined above. sort(_sorted_on_lights.begin(), _sorted_on_lights.end(), CompareLightPriorities()); // Now insert the ambient lights back at the end. We don't really care // about their relative priorities, because their contribution will simply // be summed up in the end anyway. _sorted_on_lights.insert(_sorted_on_lights.end(), ambient_lights.begin(), ambient_lights.end()); } /** * Tells the BamReader how to create objects of type LightAttrib. */ void LightAttrib:: register_with_read_factory() { BamReader::get_factory()->register_factory(get_class_type(), make_from_bam); } /** * Writes the contents of this object to the datagram for shipping out to a * Bam file. */ void LightAttrib:: write_datagram(BamWriter *manager, Datagram &dg) { RenderAttrib::write_datagram(manager, dg); dg.add_bool(_off_all_lights); // write the number of off_lights dg.add_uint16(get_num_off_lights()); // write the off lights pointers if any Lights::const_iterator fi; if (manager->get_file_minor_ver() < 40) { for (fi = _off_lights.begin(); fi != _off_lights.end(); ++fi) { manager->write_pointer(dg, fi->node()); } } else { for (fi = _off_lights.begin(); fi != _off_lights.end(); ++fi) { (*fi).write_datagram(manager, dg); } } // write the number of on lights dg.add_uint16(get_num_on_lights()); // write the on lights pointers if any Lights::const_iterator nti; if (manager->get_file_minor_ver() < 40) { for (nti = _on_lights.begin(); nti != _on_lights.end(); ++nti) { manager->write_pointer(dg, nti->node()); } } else { for (nti = _on_lights.begin(); nti != _on_lights.end(); ++nti) { (*nti).write_datagram(manager, dg); } } } /** * Receives an array of pointers, one for each time manager->read_pointer() * was called in fillin(). Returns the number of pointers processed. */ int LightAttrib:: complete_pointers(TypedWritable **p_list, BamReader *manager) { int pi = RenderAttrib::complete_pointers(p_list, manager); if (manager->get_file_minor_ver() >= 40) { for (size_t i = 0; i < _off_lights.size(); ++i) { pi += _off_lights[i].complete_pointers(p_list + pi, manager); } for (size_t i = 0; i < _on_lights.size(); ++i) { pi += _on_lights[i].complete_pointers(p_list + pi, manager); } } else { BamAuxData *aux = (BamAuxData *)manager->get_aux_data(this, "lights"); nassertr(aux != nullptr, pi); int i; aux->_off_list.reserve(aux->_num_off_lights); for (i = 0; i < aux->_num_off_lights; ++i) { PandaNode *node; DCAST_INTO_R(node, p_list[pi++], pi); aux->_off_list.push_back(node); } aux->_on_list.reserve(aux->_num_on_lights); for (i = 0; i < aux->_num_on_lights; ++i) { PandaNode *node; DCAST_INTO_R(node, p_list[pi++], pi); aux->_on_list.push_back(node); } } return pi; } /** * Called by the BamReader to perform any final actions needed for setting up * the object after all objects have been read and all pointers have been * completed. */ void LightAttrib:: finalize(BamReader *manager) { if (manager->get_file_minor_ver() >= 40) { AttribNodeRegistry *areg = AttribNodeRegistry::get_global_ptr(); // Check if any of the nodes we loaded are mentioned in the // AttribNodeRegistry. If so, replace them. for (size_t i = 0; i < _off_lights.size(); ++i) { int n = areg->find_node(_off_lights[i]); if (n != -1) { // If it's in the registry, replace it. _off_lights[i] = areg->get_node(n); } } for (size_t i = 0; i < _on_lights.size(); ++i) { int n = areg->find_node(_on_lights[i]); if (n != -1) { // If it's in the registry, replace it. _on_lights[i] = areg->get_node(n); } Light *lobj = _on_lights[i].node()->as_light(); nassertd(lobj != nullptr) continue; lobj->attrib_ref(); } } else { // Now it's safe to convert our saved PandaNodes into NodePaths. BamAuxData *aux = (BamAuxData *)manager->get_aux_data(this, "lights"); nassertv(aux != nullptr); nassertv(aux->_num_off_lights == (int)aux->_off_list.size()); nassertv(aux->_num_on_lights == (int)aux->_on_list.size()); AttribNodeRegistry *areg = AttribNodeRegistry::get_global_ptr(); _off_lights.reserve(aux->_off_list.size()); NodeList::iterator ni; for (ni = aux->_off_list.begin(); ni != aux->_off_list.end(); ++ni) { PandaNode *node = (*ni); int n = areg->find_node(node->get_type(), node->get_name()); if (n != -1) { // If it's in the registry, add that NodePath. _off_lights.push_back(areg->get_node(n)); } else { // Otherwise, add any arbitrary NodePath. Complain if it's ambiguous. _off_lights.push_back(NodePath(node)); } } _on_lights.reserve(aux->_on_list.size()); for (ni = aux->_on_list.begin(); ni != aux->_on_list.end(); ++ni) { PandaNode *node = (*ni); int n = areg->find_node(node->get_type(), node->get_name()); if (n != -1) { // If it's in the registry, add that NodePath. _on_lights.push_back(areg->get_node(n)); node = _on_lights.back().node(); } else { // Otherwise, add any arbitrary NodePath. Complain if it's ambiguous. _on_lights.push_back(NodePath(node)); } Light *lobj = node->as_light(); nassertd(lobj != nullptr) continue; lobj->attrib_ref(); } } // Now that the NodePaths have been filled in, we can sort the list. _off_lights.sort(); _on_lights.sort(); } /** * This function is called by the BamReader's factory when a new object of * type LightAttrib is encountered in the Bam file. It should create the * LightAttrib and extract its information from the file. */ TypedWritable *LightAttrib:: make_from_bam(const FactoryParams &params) { LightAttrib *attrib = new LightAttrib; DatagramIterator scan; BamReader *manager; parse_params(params, scan, manager); attrib->fillin(scan, manager); manager->register_finalize(attrib); return attrib; } /** * This internal function is called by make_from_bam to read in all of the * relevant data from the BamFile for the new LightAttrib. */ void LightAttrib:: fillin(DatagramIterator &scan, BamReader *manager) { RenderAttrib::fillin(scan, manager); _off_all_lights = scan.get_bool(); if (manager->get_file_minor_ver() >= 40) { _off_lights.resize(scan.get_uint16()); for (size_t i = 0; i < _off_lights.size(); ++i) { _off_lights[i].fillin(scan, manager); } _on_lights.resize(scan.get_uint16()); for (size_t i = 0; i < _on_lights.size(); ++i) { _on_lights[i].fillin(scan, manager); } } else { BamAuxData *aux = new BamAuxData; manager->set_aux_data(this, "lights", aux); aux->_num_off_lights = scan.get_uint16(); manager->read_pointers(scan, aux->_num_off_lights); aux->_num_on_lights = scan.get_uint16(); manager->read_pointers(scan, aux->_num_on_lights); } _sorted_on_lights.clear(); _sort_seq = UpdateSeq::old(); }
28.634016
87
0.655119
cmarshall108
1d700e704746fe72855cd291bcb6c139df468253
15,418
cpp
C++
src/BossBallos.cpp
haya3218/cse2-tweaks
48bccbd58240942ed5f5b288a90ef092820698c0
[ "MIT" ]
null
null
null
src/BossBallos.cpp
haya3218/cse2-tweaks
48bccbd58240942ed5f5b288a90ef092820698c0
[ "MIT" ]
null
null
null
src/BossBallos.cpp
haya3218/cse2-tweaks
48bccbd58240942ed5f5b288a90ef092820698c0
[ "MIT" ]
null
null
null
// THIS IS DECOMPILED PROPRIETARY CODE - USE AT YOUR OWN RISK. // // The original code belongs to Daisuke "Pixel" Amaya. // // Modifications and custom code are under the MIT licence. // See LICENCE.txt for details. #include "BossBallos.h" #include <stddef.h> #include "WindowsWrapper.h" #include "Boss.h" #include "Flash.h" #include "Frame.h" #include "Game.h" #include "MyChar.h" #include "MycHit.h" #include "MycParam.h" #include "NpChar.h" #include "Sound.h" static void ActBossChar_Eye(NPCHAR *npc) { RECT rcLeft[5] = { {272, 0, 296, 16}, {272, 16, 296, 32}, {272, 32, 296, 48}, {0, 0, 0, 0}, {240, 16, 264, 32}, }; RECT rcRight[5] = { {296, 0, 320, 16}, {296, 16, 320, 32}, {296, 32, 320, 48}, {0, 0, 0, 0}, {240, 32, 264, 48}, }; switch (npc->act_no) { case 100: npc->act_no = 101; npc->ani_no = 0; npc->ani_wait = 0; // Fallthrough case 101: ++npc->ani_wait; if (npc->ani_wait > 2) { npc->ani_wait = 0; ++npc->ani_no; } if (npc->ani_no > 2) npc->act_no = 102; break; case 102: npc->ani_no = 3; break; case 200: npc->act_no = 201; npc->ani_no = 3; npc->ani_wait = 0; // Fallthrough case 201: ++npc->ani_wait; if (npc->ani_wait > 2) { npc->ani_wait = 0; --npc->ani_no; } if (npc->ani_no <= 0) npc->act_no = 202; break; case 300: npc->act_no = 301; npc->ani_no = 4; if (npc->direct == 0) SetDestroyNpChar(npc->x - (4 * 0x200), npc->y, 0x800, 10); else SetDestroyNpChar(npc->x + (4 * 0x200), npc->y, 0x800, 10); break; } if (npc->direct == 0) npc->x = gBoss[0].x - (24 * 0x200); else npc->x = gBoss[0].x + (24 * 0x200); npc->y = gBoss[0].y - (36 * 0x200); if (npc->act_no >= 0 && npc->act_no < 300) { if (npc->ani_no != 3) npc->bits &= ~NPC_SHOOTABLE; else npc->bits |= NPC_SHOOTABLE; } if (npc->direct == 0) npc->rect = rcLeft[npc->ani_no]; else npc->rect = rcRight[npc->ani_no]; } static void ActBossChar_Body(NPCHAR *npc) { RECT rc[4] = { {0, 0, 120, 120}, {120, 0, 240, 120}, {0, 120, 120, 240}, {120, 120, 240, 240}, }; npc->x = gBoss[0].x; npc->y = gBoss[0].y; npc->rect = rc[npc->ani_no]; } static void ActBossChar_HITAI(NPCHAR *npc) // "Hitai" = "forehead" or "brow" (according to Google Translate, anyway) { npc->x = gBoss[0].x; npc->y = gBoss[0].y - (44 * 0x200); } static void ActBossChar_HARA(NPCHAR *npc) // "Hara" = "belly" or "stomach" (according to Google Translate, anyway) { npc->x = gBoss[0].x; npc->y = gBoss[0].y; } void ActBossChar_Ballos(void) { NPCHAR *npc = gBoss; static unsigned char flash; int i; int x, y; switch (npc->act_no) { case 0: // Initialize main boss npc->act_no = 1; npc->cond = 0x80; npc->exp = 1; npc->direct = gMirrorMode? 2:0; npc->x = 320 * 0x200; npc->y = -64 * 0x200; npc->hit_voice = 54; npc->hit.front = 32 * 0x200; npc->hit.top = 48 * 0x200; npc->hit.back = 32 * 0x200; npc->hit.bottom = 48 * 0x200; npc->bits = (NPC_IGNORE_SOLIDITY | NPC_SOLID_HARD | NPC_EVENT_WHEN_KILLED | NPC_SHOW_DAMAGE); npc->size = 3; npc->damage = 0; npc->code_event = 1000; npc->life = 800; // Initialize eyes gBoss[1].cond = 0x90; gBoss[1].direct = 0; gBoss[1].bits = NPC_IGNORE_SOLIDITY; gBoss[1].life = 10000; gBoss[1].view.front = 12 * 0x200; gBoss[1].view.top = 0; gBoss[1].view.back = 12 * 0x200; gBoss[1].view.bottom = 16 * 0x200; gBoss[1].hit.front = 12 * 0x200; gBoss[1].hit.top = 0; gBoss[1].hit.back = 12 * 0x200; gBoss[1].hit.bottom = 16 * 0x200; gBoss[2] = gBoss[1]; gBoss[2].direct = 2; // Initialize the body gBoss[3].cond = 0x90; gBoss[3].bits = (NPC_SOLID_SOFT | NPC_INVULNERABLE | NPC_IGNORE_SOLIDITY); gBoss[3].view.front = 60 * 0x200; gBoss[3].view.top = 60 * 0x200; gBoss[3].view.back = 60 * 0x200; gBoss[3].view.bottom = 60 * 0x200; gBoss[3].hit.front = 48 * 0x200; gBoss[3].hit.top = 24 * 0x200; gBoss[3].hit.back = 48 * 0x200; gBoss[3].hit.bottom = 32 * 0x200; gBoss[4].cond = 0x90; gBoss[4].bits = (NPC_SOLID_SOFT | NPC_INVULNERABLE | NPC_IGNORE_SOLIDITY); gBoss[4].hit.front = 32 * 0x200; gBoss[4].hit.top = 8 * 0x200; gBoss[4].hit.back = 32 * 0x200; gBoss[4].hit.bottom = 8 * 0x200; gBoss[5].cond = 0x90; gBoss[5].bits = (NPC_INVULNERABLE | NPC_IGNORE_SOLIDITY | NPC_SOLID_HARD); gBoss[5].hit.front = 32 * 0x200; gBoss[5].hit.top = 0; gBoss[5].hit.back = 32 * 0x200; gBoss[5].hit.bottom = 48 * 0x200; break; case 100: npc->act_no = 101; npc->ani_no = 0; npc->x = gMC.x; SetNpChar(333, gMC.x, 304 * 0x200, 0, 0, 2, NULL, 0x100); npc->act_wait = 0; // Fallthrough case 101: ++npc->act_wait; if (npc->act_wait > 30) npc->act_no = 102; break; case 102: npc->ym += 0x40; if (npc->ym > 0xC00) npc->ym = 0xC00; npc->y += npc->ym; if (npc->y > (304 * 0x200) - npc->hit.bottom) { npc->y = (304 * 0x200) - npc->hit.bottom; npc->ym = 0; npc->act_no = 103; npc->act_wait = 0; SetQuake2(30); PlaySoundObject(44, SOUND_MODE_PLAY); if (gMC.y > npc->y + (48 * 0x200) && gMC.x < npc->x + (24 * 0x200) && gMC.x > npc->x - (24 * 0x200)){ int damage = 16; if (damage == 1 && gbDamageModifier == 0.5){ damage = 1; } else if (gbDamageModifier == -1 ){ damage = 127; } else{ damage = damage * gbDamageModifier; } DamageMyChar(damage); } for (i = 0; i < 0x10; ++i) { x = npc->x + (Random(-40, 40) * 0x200); SetNpChar(4, x, npc->y + (40 * 0x200), 0, 0, 0, NULL, 0x100); } if (gMC.flag & 8) gMC.ym = -0x200; } break; case 103: ++npc->act_wait; if (npc->act_wait == 50) { npc->act_no = 104; gBoss[1].act_no = 100; gBoss[2].act_no = 100; } break; case 200: npc->act_no = 201; npc->count1 = 0; // Fallthrough case 201: npc->act_no = 203; npc->xm = 0; ++npc->count1; npc->hit.bottom = 48 * 0x200; npc->damage = 0; if (npc->count1 % 3 == 0) npc->act_wait = 150; else npc->act_wait = 50; // Fallthrough case 203: --npc->act_wait; if (npc->act_wait <= 0) { npc->act_no = 204; npc->ym = -0xC00; if (npc->x < gMC.x) npc->xm = 0x200; else npc->xm = -0x200; } break; case 204: if (npc->x < 80 * 0x200) npc->xm = 0x200; if (npc->x > 544 * 0x200) npc->xm = -0x200; npc->ym += 0x55; if (npc->ym > 0xC00) npc->ym = 0xC00; npc->x += npc->xm; npc->y += npc->ym; if (npc->y > (304 * 0x200) - npc->hit.bottom) { npc->y = (304 * 0x200) - npc->hit.bottom; npc->ym = 0; npc->act_no = 201; npc->act_wait = 0; if (gMC.y > npc->y + (56 * 0x200)){ int damage = 16; if (damage == 1 && gbDamageModifier == 0.5){ damage = 1; } else if (gbDamageModifier == -1 ){ damage = 127; } else{ damage = damage * gbDamageModifier; } DamageMyChar(damage); } if (gMC.flag & 8) gMC.ym = -0x200; SetQuake2(30); PlaySoundObject(26, SOUND_MODE_PLAY); SetNpChar(332, npc->x - (12 * 0x200), npc->y + (52 * 0x200), 0, 0, 0, NULL, 0x100); SetNpChar(332, npc->x + (12 * 0x200), npc->y + (52 * 0x200), 0, 0, 2, NULL, 0x100); PlaySoundObject(44, SOUND_MODE_PLAY); for (i = 0; i < 0x10; ++i) { x = npc->x + (Random(-40, 40) * 0x200); SetNpChar(4, x, npc->y + (40 * 0x200), 0, 0, 0, NULL, 0x100); } } break; case 220: npc->act_no = 221; npc->life = 1200; gBoss[1].act_no = 200; gBoss[2].act_no = 200; npc->xm = 0; npc->ani_no = 0; npc->shock = 0; flash = 0; // Fallthrough case 221: npc->ym += 0x40; if (npc->ym > 0xC00) npc->ym = 0xC00; npc->y += npc->ym; if (npc->y > (304 * 0x200) - npc->hit.bottom) { npc->y = (304 * 0x200) - npc->hit.bottom; npc->ym = 0; npc->act_no = 222; npc->act_wait = 0; SetQuake2(30); PlaySoundObject(26, SOUND_MODE_PLAY); for (i = 0; i < 0x10; ++i) { x = npc->x + (Random(-40, 40) * 0x200); SetNpChar(4, x, npc->y + (40 * 0x200), 0, 0, 0, NULL, 0x100); } if (gMC.flag & 8) gMC.ym = -0x200; } break; case 300: npc->act_no = 301; npc->act_wait = 0; for (i = 0; i < 0x100; i += 0x40) { SetNpChar(342, npc->x, npc->y, 0, 0, i, npc, 90); SetNpChar(342, npc->x, npc->y, 0, 0, i + 0x220, npc, 90); } SetNpChar(343, npc->x, npc->y, 0, 0, 0, npc, 0x18); SetNpChar(344, npc->x - (24 * 0x200), npc->y - (36 * 0x200), 0, 0, 0, npc, 0x20); SetNpChar(344, npc->x + (24 * 0x200), npc->y - (36 * 0x200), 0, 0, 2, npc, 0x20); // Fallthrough case 301: npc->y += ((225 * 0x200) - npc->y) / 8; ++npc->act_wait; if (npc->act_wait > 50) { npc->act_no = 310; npc->act_wait = 0; } break; case 311: npc->direct = gMirrorMode? 2:0; npc->xm = -0x3AA; npc->ym = 0; npc->x += npc->xm; if (npc->x < 111 * 0x200) { npc->x = 111 * 0x200; npc->act_no = 312; } break; case 312: npc->direct = 1; npc->ym = -0x3AA; npc->xm = 0; npc->y += npc->ym; if (npc->y < 111 * 0x200) { npc->y = 111 * 0x200; npc->act_no = 313; } break; case 313: npc->direct = gMirrorMode? 0:2; npc->xm = 0x3AA; npc->ym = 0; npc->x += npc->xm; if (npc->x > 513 * 0x200) { npc->x = 513 * 0x200; npc->act_no = 314; } if (npc->count1 != 0) --npc->count1; if (npc->count1 == 0 && npc->x > 304 * 0x200 && npc->x < 336 * 0x200) npc->act_no = 400; break; case 314: npc->direct = 3; npc->ym = 0x3AA; npc->xm = 0; npc->y += npc->ym; if (npc->y > 225 * 0x200) { npc->y = 225 * 0x200; npc->act_no = 311; } break; case 400: npc->act_no = 401; npc->act_wait = 0; npc->xm = 0; npc->ym = 0; DeleteNpCharCode(339, FALSE); // Fallthrough case 401: npc->y += ((159 * 0x200) - npc->y) / 8; ++npc->act_wait; if (npc->act_wait > 50) { npc->act_wait = 0; npc->act_no = 410; for (i = 0; i < 0x100; i += 0x20) SetNpChar(346, npc->x, npc->y, 0, 0, i, npc, 0x50); SetNpChar(343, npc->x, npc->y, 0, 0, 0, npc, 0x18); SetNpChar(344, npc->x - (24 * 0x200), npc->y - (36 * 0x200), 0, 0, 0, npc, 0x20); SetNpChar(344, npc->x + (24 * 0x200), npc->y - (36 * 0x200), 0, 0, 2, npc, 0x20); } break; case 410: ++npc->act_wait; if (npc->act_wait > 50) { npc->act_wait = 0; npc->act_no = 411; } break; case 411: ++npc->act_wait; if (npc->act_wait % 30 == 1) { x = (((npc->act_wait / 30) * 2) + 2) * 0x10 * 0x200; SetNpChar(348, x, 336 * 0x200, 0, 0, 0, NULL, 0x180); } if (npc->act_wait / 3 % 2) PlaySoundObject(26, SOUND_MODE_PLAY); if (npc->act_wait > 540) npc->act_no = 420; break; case 420: npc->act_no = 421; npc->act_wait = 0; npc->ani_wait = 0; SetQuake2(30); PlaySoundObject(35, SOUND_MODE_PLAY); gBoss[1].act_no = 102; gBoss[2].act_no = 102; for (i = 0; i < 0x100; ++i) { x = npc->x + (Random(-60, 60) * 0x200); y = npc->y + (Random(-60, 60) * 0x200); SetNpChar(4, x, y, 0, 0, 0, NULL, 0); } // Fallthrough case 421: ++npc->ani_wait; if (npc->ani_wait > 500) { npc->ani_wait = 0; npc->act_no = 422; } break; case 422: ++npc->ani_wait; if (npc->ani_wait > 200) { npc->ani_wait = 0; npc->act_no = 423; } break; case 423: ++npc->ani_wait; if (npc->ani_wait > 20) { npc->ani_wait = 0; npc->act_no = 424; } break; case 424: ++npc->ani_wait; if (npc->ani_wait > 200) { npc->ani_wait = 0; npc->act_no = 425; } break; case 425: ++npc->ani_wait; if (npc->ani_wait > 500) { npc->ani_wait = 0; npc->act_no = 426; } break; case 426: ++npc->ani_wait; if (npc->ani_wait > 200) { npc->ani_wait = 0; npc->act_no = 427; } break; case 427: ++npc->ani_wait; if (npc->ani_wait > 20) { npc->ani_wait = 0; npc->act_no = 428; } break; case 428: ++npc->ani_wait; if (npc->ani_wait > 200) { npc->ani_wait = 0; npc->act_no = 421; } break; case 1000: npc->act_no = 1001; npc->act_wait = 0; gBoss[1].act_no = 300; gBoss[2].act_no = 300; #ifndef FIX_BUGS // This code makes absolutely no sense. // Luckily, it doesn't cause any bugs. gBoss[1].act_no &= ~(NPC_SOLID_SOFT | NPC_SOLID_HARD); gBoss[2].act_no &= ~(NPC_SOLID_SOFT | NPC_SOLID_HARD); #endif gBoss[0].bits &= ~(NPC_SOLID_SOFT | NPC_SOLID_HARD); gBoss[3].bits &= ~(NPC_SOLID_SOFT | NPC_SOLID_HARD); gBoss[4].bits &= ~(NPC_SOLID_SOFT | NPC_SOLID_HARD); gBoss[5].bits &= ~(NPC_SOLID_SOFT | NPC_SOLID_HARD); // Fallthrough case 1001: ++gBoss[0].act_wait; if (gBoss[0].act_wait % 12 == 0) PlaySoundObject(44, SOUND_MODE_PLAY); SetDestroyNpChar(gBoss[0].x + (Random(-60, 60) * 0x200), gBoss[0].y + (Random(-60, 60) * 0x200), 1, 1); if (gBoss[0].act_wait > 150) { gBoss[0].act_wait = 0; gBoss[0].act_no = 1002; SetFlash(gBoss[0].x, gBoss[0].y, FLASH_MODE_EXPLOSION); PlaySoundObject(35, SOUND_MODE_PLAY); } break; case 1002: SetQuake2(40); ++gBoss[0].act_wait; if (gBoss[0].act_wait == 50) { gBoss[0].cond = 0; gBoss[1].cond = 0; gBoss[2].cond = 0; gBoss[3].cond = 0; gBoss[4].cond = 0; gBoss[5].cond = 0; DeleteNpCharCode(350, TRUE); DeleteNpCharCode(348, TRUE); } break; } if (npc->act_no > 420 && npc->act_no < 500) { gBoss[3].bits |= NPC_SHOOTABLE; gBoss[4].bits |= NPC_SHOOTABLE; gBoss[5].bits |= NPC_SHOOTABLE; ++npc->act_wait; if (npc->act_wait > 300) { npc->act_wait = 0; if (gMC.x > npc->x) { for (i = 0; i < 8; ++i) { x = ((156 + Random(-4, 4)) * 0x200 * 0x10) / 4; y = (Random(8, 68) * 0x200 * 0x10) / 4; SetNpChar(350, x, y, 0, 0, 0, NULL, 0x100); } } else { for (i = 0; i < 8; ++i) { x = (Random(-4, 4) * 0x200 * 0x10) / 4; y = (Random(8, 68) * 0x200 * 0x10) / 4; SetNpChar(350, x, y, 0, 0, 2, NULL, 0x100); } } } if (npc->act_wait == 270 || npc->act_wait == 280 || npc->act_wait == 290) { SetNpChar(353, npc->x, npc->y - (52 * 0x200), 0, 0, 1, NULL, 0x100); PlaySoundObject(39, SOUND_MODE_PLAY); for (i = 0; i < 4; ++i) SetNpChar(4, npc->x, npc->y - (52 * 0x200), 0, 0, 0, NULL, 0x100); } if (npc->life > 500) { if (Random(0, 10) == 2) { x = npc->x + (Random(-40, 40) * 0x200); y = npc->y + (Random(0, 40) * 0x200); SetNpChar(270, x, y, 0, 0, 3, NULL, 0); } } else { if (Random(0, 4) == 2) { x = npc->x + (Random(-40, 40) * 0x200); y = npc->y + (Random(0, 40) * 0x200); SetNpChar(270, x, y, 0, 0, 3, NULL, 0); } } } if (npc->shock != 0) { if (++flash / 2 % 2) gBoss[3].ani_no = 1; else gBoss[3].ani_no = 0; } else { gBoss[3].ani_no = 0; } if (npc->act_no > 420) gBoss[3].ani_no += 2; ActBossChar_Eye(&gBoss[1]); ActBossChar_Eye(&gBoss[2]); ActBossChar_Body(&gBoss[3]); ActBossChar_HITAI(&gBoss[4]); ActBossChar_HARA(&gBoss[5]); }
19.248439
116
0.530354
haya3218
1d75d52fa51962008828179d04899833ebe4f7d2
13,646
cpp
C++
nlsCppSdk/jni/jniSpeechRecognizer.cpp
kaimingguo/alibabacloud-nls-cpp-sdk
e624eefd2f87c56e4340c35a834ebd14b96bb19c
[ "Apache-2.0" ]
26
2019-06-02T15:22:01.000Z
2022-03-11T06:54:23.000Z
nlsCppSdk/jni/jniSpeechRecognizer.cpp
kaimingguo/alibabacloud-nls-cpp-sdk
e624eefd2f87c56e4340c35a834ebd14b96bb19c
[ "Apache-2.0" ]
8
2019-06-02T15:47:11.000Z
2022-01-19T06:51:55.000Z
nlsCppSdk/jni/jniSpeechRecognizer.cpp
kaimingguo/alibabacloud-nls-cpp-sdk
e624eefd2f87c56e4340c35a834ebd14b96bb19c
[ "Apache-2.0" ]
18
2019-06-02T13:00:17.000Z
2022-01-21T13:12:29.000Z
#include <jni.h> #include <string> #include <cstdlib> #include <vector> #include "nlsClient.h" #include "nlsEvent.h" #include "sr/speechRecognizerRequest.h" #include "log.h" #include "NlsRequestWarpper.h" #include "native-lib.h" using namespace AlibabaNls; using namespace AlibabaNls::utility; extern "C" { JNIEXPORT jlong JNICALL Java_com_alibaba_idst_util_SpeechRecognizer_createRecognizerCallback(JNIEnv *env, jobject instance, jobject _callback); //JNIEXPORT jlong JNICALL //Java_com_alibaba_idst_util_SpeechRecognizer_createRecognizerCallback(JNIEnv *env, jobject instance); JNIEXPORT jlong JNICALL Java_com_alibaba_idst_util_SpeechRecognizer_buildRecognizerRequest(JNIEnv *env, jobject instance, jlong wrapper); //JNIEXPORT jlong JNICALL //Java_com_alibaba_idst_util_SpeechRecognizer_buildRecognizerRequest(JNIEnv *env, jobject instance, jobject _callback); JNIEXPORT jint JNICALL Java_com_alibaba_idst_util_SpeechRecognizer_start__J(JNIEnv *env, jobject instance, jlong id); JNIEXPORT jint JNICALL Java_com_alibaba_idst_util_SpeechRecognizer_stop__J(JNIEnv *env, jobject instance, jlong id); JNIEXPORT jint JNICALL Java_com_alibaba_idst_util_SpeechRecognizer_cancel__J(JNIEnv *env, jobject instance, jlong id); JNIEXPORT jint JNICALL Java_com_alibaba_idst_util_SpeechRecognizer_setToken__JLjava_lang_String_2(JNIEnv *env, jobject instance, jlong id, jstring token_); JNIEXPORT jint JNICALL Java_com_alibaba_idst_util_SpeechRecognizer_setUrl__JLjava_lang_String_2(JNIEnv *env, jobject instance, jlong id, jstring value); JNIEXPORT jint JNICALL Java_com_alibaba_idst_util_SpeechRecognizer_setAppKey__JLjava_lang_String_2(JNIEnv *env, jobject instance, jlong id, jstring value); JNIEXPORT jint JNICALL Java_com_alibaba_idst_util_SpeechRecognizer_setFormat__JLjava_lang_String_2(JNIEnv *env, jobject instance, jlong id, jstring value); JNIEXPORT jint JNICALL Java_com_alibaba_idst_util_SpeechRecognizer_setIntermediateResult(JNIEnv *env, jobject instance, jlong id, jboolean value); JNIEXPORT jint JNICALL Java_com_alibaba_idst_util_SpeechRecognizer_setInverseTextNormalization(JNIEnv *env, jobject instance, jlong id, jboolean value); JNIEXPORT jint JNICALL Java_com_alibaba_idst_util_SpeechRecognizer_setPunctuationPrediction(JNIEnv *env, jobject instance, jlong id, jboolean value); JNIEXPORT jint JNICALL Java_com_alibaba_idst_util_SpeechRecognizer_enableVoiceDetection(JNIEnv *env, jobject instance, jlong id, jboolean value); JNIEXPORT jint JNICALL Java_com_alibaba_idst_util_SpeechRecognizer_setMaxStartSilence(JNIEnv *env, jobject instance, jlong id, jint _value); JNIEXPORT jint JNICALL Java_com_alibaba_idst_util_SpeechRecognizer_setMaxEndSilence(JNIEnv *env, jobject instance, jlong id, jint _value); JNIEXPORT jint JNICALL Java_com_alibaba_idst_util_SpeechRecognizer_setSampleRate__JI(JNIEnv *env, jobject instance, jlong id, jint _value); JNIEXPORT jint JNICALL Java_com_alibaba_idst_util_SpeechRecognizer_setParams__JLjava_lang_String_2(JNIEnv *env, jobject instance, jlong id, jstring value_); JNIEXPORT jint JNICALL Java_com_alibaba_idst_util_SpeechRecognizer_setContext__JLjava_lang_String_2(JNIEnv *env, jobject instance, jlong id, jstring value_); JNIEXPORT jint JNICALL Java_com_alibaba_idst_util_SpeechRecognizer_addHttpHeader(JNIEnv *env, jobject instance, jlong id, jstring key_, jstring value_); JNIEXPORT jint JNICALL Java_com_alibaba_idst_util_SpeechRecognizer_setCustomizationId__JLjava_lang_String_2(JNIEnv *env, jobject instance, jlong id, jstring customizationId_); JNIEXPORT jint JNICALL Java_com_alibaba_idst_util_SpeechRecognizer_setVocabularyId__JLjava_lang_String_2(JNIEnv *env, jobject instance, jlong id, jstring vocabularyId_); JNIEXPORT jint JNICALL Java_com_alibaba_idst_util_SpeechRecognizer_sendAudio(JNIEnv *env, jobject instance, jlong id, jbyteArray data_, jint num_byte); JNIEXPORT void JNICALL Java_com_alibaba_idst_util_SpeechRecognizer_releaseCallback(JNIEnv *env, jobject instance, jlong id); } JNIEXPORT jlong JNICALL Java_com_alibaba_idst_util_SpeechRecognizer_createRecognizerCallback(JNIEnv *env, jobject instance, jobject _callback){ jobject callback = env->NewGlobalRef(_callback); // NlsRequestWarpper* wrapper = new NlsRequestWarpper(callback, &NlsRequestWarpper::_global_mtx); NlsRequestWarpper* wrapper = new NlsRequestWarpper(callback); env->GetJavaVM(&wrapper->_jvm); pthread_mutex_lock(&NlsRequestWarpper::_global_mtx); NlsRequestWarpper::_requestMap.insert(std::make_pair(wrapper, true)); LOG_DEBUG("Set request: %p true, size: %d", wrapper, NlsRequestWarpper::_requestMap.size()); pthread_mutex_unlock(&NlsRequestWarpper::_global_mtx); return (jlong) wrapper; } JNIEXPORT jlong JNICALL Java_com_alibaba_idst_util_SpeechRecognizer_buildRecognizerRequest(JNIEnv *env, jobject instance, jlong wrapper) { NlsRequestWarpper* pWrapper = (NlsRequestWarpper*)wrapper; SpeechRecognizerRequest* request = gnlsClient->createRecognizerRequest(); request->setOnTaskFailed(OnTaskFailed, pWrapper); request->setOnRecognitionStarted(OnRecognizerStarted, pWrapper); request->setOnRecognitionCompleted(OnRecognizerCompleted, pWrapper); request->setOnRecognitionResultChanged(OnRecognizedResultChanged, pWrapper); request->setOnChannelClosed(OnChannelClosed, pWrapper); return (jlong) request; } JNIEXPORT jint JNICALL Java_com_alibaba_idst_util_SpeechRecognizer_start__J(JNIEnv *env, jobject instance, jlong id) { SpeechRecognizerRequest* request = (SpeechRecognizerRequest*) id; int ret = request->start(); return ret; } JNIEXPORT jint JNICALL Java_com_alibaba_idst_util_SpeechRecognizer_stop__J(JNIEnv *env, jobject instance, jlong id) { SpeechRecognizerRequest* request = (SpeechRecognizerRequest*) id; if (request != NULL) { int ret = request->stop(); gnlsClient->releaseRecognizerRequest(request); return ret; } return 0; } JNIEXPORT jint JNICALL Java_com_alibaba_idst_util_SpeechRecognizer_cancel__J(JNIEnv *env, jobject instance, jlong id) { SpeechRecognizerRequest* request = (SpeechRecognizerRequest*) id; if (request != NULL) { int ret = request->cancel(); gnlsClient->releaseRecognizerRequest(request); return ret; } return 0; } JNIEXPORT jint JNICALL Java_com_alibaba_idst_util_SpeechRecognizer_setToken__JLjava_lang_String_2(JNIEnv *env, jobject instance, jlong id, jstring token_) { if (token_ == NULL) { return -1; } const char *token = env->GetStringUTFChars(token_, 0); SpeechRecognizerRequest* request = (SpeechRecognizerRequest*) id; int ret = request->setToken(token); env->ReleaseStringUTFChars(token_, token); return ret; } JNIEXPORT jint JNICALL Java_com_alibaba_idst_util_SpeechRecognizer_setCustomizationId__JLjava_lang_String_2(JNIEnv *env, jobject instance, jlong id, jstring customizationId_) { if (customizationId_ == NULL) { return -1; } const char *customizationId = env->GetStringUTFChars(customizationId_, 0); SpeechRecognizerRequest* request = (SpeechRecognizerRequest*) id; int ret = request->setCustomizationId(customizationId); env->ReleaseStringUTFChars(customizationId_, customizationId); return ret; } JNIEXPORT jint JNICALL Java_com_alibaba_idst_util_SpeechRecognizer_setVocabularyId__JLjava_lang_String_2(JNIEnv *env, jobject instance, jlong id, jstring vocabularyId_) { if (vocabularyId_ == NULL) { return -1; } const char *vocabularyId = env->GetStringUTFChars(vocabularyId_, 0); SpeechRecognizerRequest* request = (SpeechRecognizerRequest*) id; int ret = request->setVocabularyId(vocabularyId); env->ReleaseStringUTFChars(vocabularyId_, vocabularyId); return ret; } JNIEXPORT jint JNICALL Java_com_alibaba_idst_util_SpeechRecognizer_setUrl__JLjava_lang_String_2(JNIEnv *env, jobject instance, jlong id, jstring _value) { if (_value == NULL) { return -1; } const char *value = env->GetStringUTFChars(_value, 0); SpeechRecognizerRequest* request = (SpeechRecognizerRequest*) id; int ret = request->setUrl(value); env->ReleaseStringUTFChars(_value, value); return ret; } JNIEXPORT jint JNICALL Java_com_alibaba_idst_util_SpeechRecognizer_setAppKey__JLjava_lang_String_2(JNIEnv *env, jobject instance, jlong id, jstring _value) { if (_value == NULL) { return -1; } const char *value = env->GetStringUTFChars(_value, 0); SpeechRecognizerRequest* request = (SpeechRecognizerRequest*) id; int ret = request->setAppKey(value); env->ReleaseStringUTFChars(_value, value); return ret; } JNIEXPORT jint JNICALL Java_com_alibaba_idst_util_SpeechRecognizer_setFormat__JLjava_lang_String_2(JNIEnv *env, jobject instance, jlong id, jstring _value) { if (_value == NULL) { return -1; } const char *value = env->GetStringUTFChars(_value, 0); SpeechRecognizerRequest* request = (SpeechRecognizerRequest*) id; int ret = request->setFormat(value); env->ReleaseStringUTFChars(_value, value); return ret; } JNIEXPORT jint JNICALL Java_com_alibaba_idst_util_SpeechRecognizer_setSampleRate__JI(JNIEnv *env, jobject instance, jlong id, jint _value) { SpeechRecognizerRequest* request = (SpeechRecognizerRequest*) id; return request->setSampleRate(_value); } JNIEXPORT jint JNICALL Java_com_alibaba_idst_util_SpeechRecognizer_setIntermediateResult(JNIEnv *env, jobject instance, jlong id, jboolean _value) { SpeechRecognizerRequest* request = (SpeechRecognizerRequest*) id; return request->setIntermediateResult(_value); } JNIEXPORT jint JNICALL Java_com_alibaba_idst_util_SpeechRecognizer_setPunctuationPrediction(JNIEnv *env, jobject instance, jlong id, jboolean _value) { SpeechRecognizerRequest* request = (SpeechRecognizerRequest*) id; return request->setPunctuationPrediction(_value); } JNIEXPORT jint JNICALL Java_com_alibaba_idst_util_SpeechRecognizer_setInverseTextNormalization(JNIEnv *env, jobject instance, jlong id, jboolean _value) { SpeechRecognizerRequest* request = (SpeechRecognizerRequest*) id; return request->setInverseTextNormalization(_value); } JNIEXPORT jint JNICALL Java_com_alibaba_idst_util_SpeechRecognizer_enableVoiceDetection(JNIEnv *env, jobject instance, jlong id, jboolean value) { SpeechRecognizerRequest* request = (SpeechRecognizerRequest*) id; return request->setEnableVoiceDetection(value); } JNIEXPORT jint JNICALL Java_com_alibaba_idst_util_SpeechRecognizer_setMaxStartSilence(JNIEnv *env, jobject instance, jlong id, jint value) { SpeechRecognizerRequest* request = (SpeechRecognizerRequest*) id; return request->setMaxStartSilence(value); } JNIEXPORT jint JNICALL Java_com_alibaba_idst_util_SpeechRecognizer_setMaxEndSilence(JNIEnv *env, jobject instance, jlong id, jint value) { SpeechRecognizerRequest* request = (SpeechRecognizerRequest*) id; return request->setMaxEndSilence(value); } JNIEXPORT jint JNICALL Java_com_alibaba_idst_util_SpeechRecognizer_setParams__JLjava_lang_String_2(JNIEnv *env, jobject instance, jlong id, jstring value_) { if (value_ == NULL) { return -1; } const char *value = env->GetStringUTFChars(value_, 0); SpeechRecognizerRequest* request = (SpeechRecognizerRequest*) id; int ret = request->setPayloadParam(value); env->ReleaseStringUTFChars(value_, value); return ret; } JNIEXPORT jint JNICALL Java_com_alibaba_idst_util_SpeechRecognizer_setContext__JLjava_lang_String_2(JNIEnv *env, jobject instance, jlong id, jstring value_) { if (value_ == NULL) { return -1; } const char *value = env->GetStringUTFChars(value_, 0); SpeechRecognizerRequest* request = (SpeechRecognizerRequest*) id; int ret = request->setContextParam(value); env->ReleaseStringUTFChars(value_, value); return ret; } JNIEXPORT jint JNICALL Java_com_alibaba_idst_util_SpeechRecognizer_addHttpHeader(JNIEnv *env, jobject instance, jlong id, jstring key_, jstring value_) { if (key_ == NULL || value_ == NULL) { return -1; } const char *key = env->GetStringUTFChars(key_, 0); const char *value = env->GetStringUTFChars(value_, 0); SpeechRecognizerRequest* request = (SpeechRecognizerRequest*) id; int ret = request->AppendHttpHeaderParam(key, value); env->ReleaseStringUTFChars(value_, value); env->ReleaseStringUTFChars(key_, key); return ret; } JNIEXPORT jint JNICALL Java_com_alibaba_idst_util_SpeechRecognizer_sendAudio(JNIEnv *env, jobject instance, jlong id, jbyteArray data_, jint num_byte) { jbyte *data = env->GetByteArrayElements(data_, NULL); SpeechRecognizerRequest* request = (SpeechRecognizerRequest*) id; int ret = request->sendAudio((uint8_t*)data, num_byte); env->ReleaseByteArrayElements(data_, data, 0); return ret; } JNIEXPORT void JNICALL Java_com_alibaba_idst_util_SpeechRecognizer_releaseCallback(JNIEnv *env, jobject instance, jlong id) { NlsRequestWarpper* wrapper = (NlsRequestWarpper*) id; pthread_mutex_lock(&NlsRequestWarpper::_global_mtx); if (NlsRequestWarpper::_requestMap.find(wrapper) != NlsRequestWarpper::_requestMap.end()) { NlsRequestWarpper::_requestMap.erase(wrapper); LOG_DEBUG("Set request: %p false, size: %d", wrapper, NlsRequestWarpper::_requestMap.size()); } if (wrapper != NULL) { LOG_DEBUG("Notify release sr callback."); delete wrapper; wrapper = NULL; } pthread_mutex_unlock(&NlsRequestWarpper::_global_mtx); }
40.135294
153
0.785798
kaimingguo
1d75f9f0228674e6a665780321daf37f8f4b8afd
1,983
cpp
C++
reverse_pair_leetcode.cpp
shivamkrs89/Sorting_problems
4451103f52545df752b567fcbb575eb7e29947a6
[ "MIT" ]
1
2021-05-27T14:56:48.000Z
2021-05-27T14:56:48.000Z
reverse_pair_leetcode.cpp
shivamkrs89/Sorting_problems
4451103f52545df752b567fcbb575eb7e29947a6
[ "MIT" ]
null
null
null
reverse_pair_leetcode.cpp
shivamkrs89/Sorting_problems
4451103f52545df752b567fcbb575eb7e29947a6
[ "MIT" ]
null
null
null
Given an integer array nums, return the number of reverse pairs in the array. A reverse pair is a pair (i, j) where 0 <= i < j < nums.length and nums[i] > 2 * nums[j]. Example 1: Input: nums = [1,3,2,3,1] Output: 2 Example 2: Input: nums = [2,4,3,5,1] Output: 3 Constraints: 1 <= nums.length <= 5 * 104 -231 <= nums[i] <= 231 - 1 //code starts class Solution { public: void merge(vector<int> &arr,int l,int m, int r,int& count) { // Your code here int sz1=m-l+1; int sz2=r-m; int larr[sz1]; int rarr[sz2]; int i,j,k; for(i=0;i<sz1;i++) larr[i]=arr[l+i]; for(j=0;j<sz2;j++) rarr[j]=arr[l+sz1+j]; j=0; while(j<sz2){//checking for both subarray for number of reverse pairs long long int sm=rarr[j]; sm*=2; if(larr[sz1-1]<sm){ j++;continue; } for(i=0;i<sz1;i++) { // cout<<sz1<<' '<<sz2<<' '<<sm/2<<' '<<larr[i]<<'\n'; if(larr[i]>sm) { count+=(sz1-i); break; } } j++; } i=0,j=0,k=l; while(i<sz1 && j<sz2) { if(larr[i]<rarr[j]) { arr[k]=larr[i]; i++; } else { arr[k]=rarr[j]; j++; } k++; } while(i<sz1) { arr[k]=larr[i]; i++;k++; } while(j<sz2) { arr[k]=rarr[j]; j++;k++; } } void mergeSort(vector<int> &arr, int l,int r,int& count) { if (l < r) { long long int m = l+(r-l)/2; mergeSort(arr, l, m,count); mergeSort(arr, m+1, r,count); merge(arr, l, m, r,count); } } int reversePairs(vector<int>& nums) { int count=0; mergeSort(nums,0,nums.size()-1,count); return count; } };
18.192661
89
0.413011
shivamkrs89
1d76ce7ac832293400bad337f5761086931d2f35
736
cpp
C++
Recursion/ReverseAstackusingRecursion.cpp
saurav-prakash/CB_DS_ALGO
3f3133b31dbbda7d5229cd6c72c378ed08e35e6f
[ "MIT" ]
null
null
null
Recursion/ReverseAstackusingRecursion.cpp
saurav-prakash/CB_DS_ALGO
3f3133b31dbbda7d5229cd6c72c378ed08e35e6f
[ "MIT" ]
null
null
null
Recursion/ReverseAstackusingRecursion.cpp
saurav-prakash/CB_DS_ALGO
3f3133b31dbbda7d5229cd6c72c378ed08e35e6f
[ "MIT" ]
2
2018-10-28T13:31:41.000Z
2018-10-31T02:37:42.000Z
https://www.quora.com/How-can-we-reverse-a-stack-by-using-only-push-and-pop-operations-without-using-any-secondary-DS #include<iostream> #include<stack> using namespace std; stack<int> s; int BottomInsert(int x){ if(s.size()==0) s.push(x); else{ int a = s.top(); s.pop(); BottomInsert(x); s.push(a); } } int reverse(){ if(s.size()>0){ int x = s.top(); s.pop(); reverse(); BottomInsert(x); } } int main() { int n,a; cin>>n; for(int i=0;i<n;i++){ cin>>a; s.push(a); } reverse(); while(!s.empty()){for(int i=0;i<n;i++){ cout << s.top() <<endl; s.pop();} return 0;} }
18.4
117
0.480978
saurav-prakash
1d798bfcd952ec393825f1afa2423c455c5143bf
5,533
hh
C++
dune/xt/grid/functors/interfaces.hh
dune-community/dune-xt
da921524c6fff8d60c715cb4849a0bdd5f020d2b
[ "BSD-2-Clause" ]
2
2020-02-08T04:08:52.000Z
2020-08-01T18:54:14.000Z
dune/xt/grid/functors/interfaces.hh
dune-community/dune-xt
da921524c6fff8d60c715cb4849a0bdd5f020d2b
[ "BSD-2-Clause" ]
35
2019-08-19T12:06:35.000Z
2020-03-27T08:20:39.000Z
dune/xt/grid/functors/interfaces.hh
dune-community/dune-xt
da921524c6fff8d60c715cb4849a0bdd5f020d2b
[ "BSD-2-Clause" ]
1
2020-02-08T04:09:34.000Z
2020-02-08T04:09:34.000Z
// This file is part of the dune-xt project: // https://zivgitlab.uni-muenster.de/ag-ohlberger/dune-community/dune-xt // Copyright 2009-2021 dune-xt developers and contributors. All rights reserved. // License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) // or GPL-2.0+ (http://opensource.org/licenses/gpl-license) // with "runtime exception" (http://www.dune-project.org/license.html) // Authors: // Felix Schindler (2014, 2016 - 2018, 2020) // René Fritze (2014 - 2020) // Tobias Leibner (2020) #ifndef DUNE_XT_GRID_FUNCTORS_INTERFACES_HH #define DUNE_XT_GRID_FUNCTORS_INTERFACES_HH #include <dune/xt/common/timedlogging.hh> #include <dune/xt/grid/boundaryinfo.hh> #include <dune/xt/grid/entity.hh> #include <dune/xt/grid/intersection.hh> #include <dune/xt/grid/type_traits.hh> namespace Dune::XT::Grid { template <class GL> class ElementFunctor; /** * \brief Interface for functors which are applied to elements (codim 0 entities) of a grid layer by the Walker. * * \sa Walker * \sa IntersectionFunctor * \sa ElementAndIntersectionFunctor */ template <class GL> class ElementFunctor : public Common::WithLogger<ElementFunctor<GL>> { static_assert(is_layer<GL>::value); protected: //! force implementors to use copy() method public: using GridViewType = GL; using ElementType = extract_entity_t<GridViewType>; using GV = GridViewType; using E = ElementType; ElementFunctor(const std::string& log_prefix = "", const std::array<bool, 3>& logging_state = Common::default_logger_state()) : Common::WithLogger<ElementFunctor<GL>>(log_prefix.empty() ? "ElementFunctor" : log_prefix, logging_state) {} ElementFunctor(const ElementFunctor<GL>&) = default; virtual ~ElementFunctor() = default; virtual ElementFunctor<GridViewType>* copy() = 0; virtual void prepare() {} virtual void apply_local(const ElementType& /*element*/) {} virtual void finalize() {} }; // class ElementFunctor template <class GL> class IntersectionFunctor; /** * \brief Interface for functors which are applied to intersections (codim 1 entities) of a grid layer by the Walker. * * \sa Walker * \sa ElementFunctor * \sa ElementAndIntersectionFunctor */ template <class GL> class IntersectionFunctor : public Common::WithLogger<IntersectionFunctor<GL>> { static_assert(is_layer<GL>::value); protected: //! force implementors to use copy() method IntersectionFunctor(const IntersectionFunctor<GL>&) = default; public: using GridViewType = GL; using ElementType = extract_entity_t<GridViewType>; using IntersectionType = extract_intersection_t<GridViewType>; using GV = GridViewType; using E = ElementType; using I = IntersectionType; IntersectionFunctor(const std::string& log_prefix = "", const std::array<bool, 3>& logging_state = Common::default_logger_state()) : Common::WithLogger<IntersectionFunctor<GL>>(log_prefix.empty() ? "IntersectionFunctor" : log_prefix, logging_state) {} virtual ~IntersectionFunctor() = default; virtual IntersectionFunctor<GridViewType>* copy() = 0; virtual void prepare() {} /** * \note The meaning of outside_element depends on the circumstances. If intersection.neighbor() is true, the result * of intersection.outside() is given (the meaning of which is different on inner, periodic or process boundary * intersections). If intersection.neighbor() is false, intersection.inside() is given. */ virtual void apply_local(const IntersectionType& /*intersection*/, const ElementType& /*inside_element*/, const ElementType& /*outside_element*/) {} virtual void finalize() {} }; // class IntersectionFunctor template <class GL> class ElementAndIntersectionFunctor; /** * \brief Interface for functors which are applied to entities and intersections of a grid layer by the Walker. * * \sa Walker * \sa ElementFunctor * \sa IntersectionFunctor */ template <class GL> class ElementAndIntersectionFunctor : public Common::WithLogger<ElementAndIntersectionFunctor<GL>> { static_assert(is_layer<GL>::value); protected: //! force implementors to use copy() method ElementAndIntersectionFunctor(const ElementAndIntersectionFunctor<GL>&) = default; public: using GridViewType = GL; using ElementType = extract_entity_t<GridViewType>; using IntersectionType = extract_intersection_t<GridViewType>; using GV = GridViewType; using E = ElementType; using I = IntersectionType; ElementAndIntersectionFunctor(const std::string& log_prefix = "", const std::array<bool, 3>& logging_state = Common::default_logger_state()) : Common::WithLogger<ElementAndIntersectionFunctor<GL>>( log_prefix.empty() ? "ElementAndIntersectionFunctor" : log_prefix, logging_state) {} virtual ~ElementAndIntersectionFunctor() = default; virtual ElementAndIntersectionFunctor<GL>* copy() = 0; virtual void prepare() {} virtual void apply_local(const ElementType& /*element*/) {} virtual void apply_local(const IntersectionType& /*intersection*/, const ElementType& /*inside_element*/, const ElementType& /*outside_element*/) {} virtual void finalize() {} }; // class ElementAndIntersectionFunctor } // namespace Dune::XT::Grid #endif // DUNE_XT_GRID_FUNCTORS_INTERFACES_HH
31.259887
119
0.711007
dune-community
1d7b92d30ae02e61f242523442784963f4e61ca4
2,999
cpp
C++
src/net/ip4/icmpv4.cpp
pidEins/IncludeOS
b92339164a2ba61f03ca9a940b1e9a0907c08bea
[ "Apache-2.0" ]
2
2017-04-28T17:29:25.000Z
2017-05-03T07:36:22.000Z
src/net/ip4/icmpv4.cpp
lefticus/IncludeOS
b92339164a2ba61f03ca9a940b1e9a0907c08bea
[ "Apache-2.0" ]
null
null
null
src/net/ip4/icmpv4.cpp
lefticus/IncludeOS
b92339164a2ba61f03ca9a940b1e9a0907c08bea
[ "Apache-2.0" ]
2
2017-05-01T18:16:28.000Z
2019-11-15T19:48:01.000Z
// This file is a part of the IncludeOS unikernel - www.includeos.org // // Copyright 2015 Oslo and Akershus University College of Applied Sciences // and Alfred Bratterud // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "../../api/net/ip4/icmpv4.hpp" #include <os> #include <net/inet_common.hpp> #include <net/ip4/packet_ip4.hpp> #include <net/util.hpp> namespace net { ICMPv4::ICMPv4(Inet<LinkLayer,IP4>& inet) : inet_{inet} {} void ICMPv4::bottom(Packet_ptr pckt) { if (pckt->size() < sizeof(full_header)) // Drop if not a full header return; full_header* full_hdr = reinterpret_cast<full_header*>(pckt->buffer()); icmp_header* hdr = &full_hdr->icmp_hdr; #ifdef DEBUG auto ip_address = full_hdr->ip_hdr.saddr.str().c_str(); #endif switch(hdr->type) { case (ICMP_ECHO): debug("<ICMP> PING from %s\n", ip_address); ping_reply(full_hdr, pckt->size()); break; case (ICMP_ECHO_REPLY): debug("<ICMP> PING Reply from %s\n", ip_address); break; } } void ICMPv4::ping_reply(full_header* full_hdr, uint16_t size) { auto packet_ptr = inet_.create_packet(size); auto buf = packet_ptr->buffer(); icmp_header* hdr = &reinterpret_cast<full_header*>(buf)->icmp_hdr; hdr->type = ICMP_ECHO_REPLY; hdr->code = 0; hdr->identifier = full_hdr->icmp_hdr.identifier; hdr->sequence = full_hdr->icmp_hdr.sequence; debug("<ICMP> Rest of header IN: 0x%lx OUT: 0x%lx\n", full_hdr->icmp_hdr.rest, hdr->rest); debug("<ICMP> Transmitting answer\n"); // Populate response IP header auto ip4_pckt = std::static_pointer_cast<PacketIP4>(packet_ptr); ip4_pckt->init(); ip4_pckt->set_src(full_hdr->ip_hdr.daddr); ip4_pckt->set_dst(full_hdr->ip_hdr.saddr); ip4_pckt->set_protocol(IP4::IP4_ICMP); ip4_pckt->set_ip_data_length(size); // Copy payload from old to new packet uint8_t* payload = reinterpret_cast<uint8_t*>(hdr) + sizeof(icmp_header); uint8_t* source = reinterpret_cast<uint8_t*>(&full_hdr->icmp_hdr) + sizeof(icmp_header); memcpy(payload, source, size - sizeof(full_header)); hdr->checksum = 0; hdr->checksum = net::checksum(reinterpret_cast<uint16_t*>(hdr), size - sizeof(full_header) + sizeof(icmp_header)); network_layer_out_(packet_ptr); } void icmp_default_out(Packet_ptr UNUSED(pckt)) { debug("<ICMP IGNORE> No handler. DROP!\n"); } } //< namespace net
32.247312
93
0.683228
pidEins
1d7c8b9bbaa1f388cd7f2a92ad602a41af2f28ea
1,825
cpp
C++
UVA/vol-114/11487.cpp
arash16/prays
0fe6bb2fa008b8fc46c80b01729f68308114020d
[ "MIT" ]
3
2017-05-12T14:45:37.000Z
2020-01-18T16:51:25.000Z
UVA/vol-114/11487.cpp
arash16/prays
0fe6bb2fa008b8fc46c80b01729f68308114020d
[ "MIT" ]
null
null
null
UVA/vol-114/11487.cpp
arash16/prays
0fe6bb2fa008b8fc46c80b01729f68308114020d
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; struct State { int i, j, d; State(int i, int j, int d):i(i),j(j),d(d){} }; #define MODUL 20437 char M[17][17]; int Pi[26], Pj[26], C[11][11], n, di[] = {1,-1,0,0}, dj[] = {0,0,1,-1}; int bfs(int sid, int &c) { memset(C, 0, sizeof(C)); char sch = 'A' + sid, dch = 'A' + sid + 1; queue<State> q; C[Pi[sid]][Pj[sid]] = 1; q.push(State(Pi[sid], Pj[sid], 0)); while (!q.empty()) { State s = q.front(); q.pop(); if (M[s.i][s.j] == dch) { c = C[s.i][s.j]; return s.d; } for (int k=0; k<4; ++k) { State t(s.i+di[k], s.j+dj[k], s.d+1); if (M[t.i][t.j]=='.' || (M[t.i][t.j]>='A' && M[t.i][t.j]<=dch)) { if (!C[t.i][t.j]) q.push(t); C[t.i][t.j] += C[s.i][s.j]; C[t.i][t.j] %= MODUL; } } } return c = 0; } int main() { ios_base::sync_with_stdio(0);cin.tie(0); memset(M, '#', sizeof(M)); for (int cse=1; cin >> n && n; ++cse) { int m = 0; for (int i=1; i<=n; ++i) { cin >> (M[i]+1); M[i][n+1] = '#'; M[i][n+2] = 0; for (int j=1; j<=n; ++j) if (M[i][j]>='A') { int id = M[i][j] - 'A'; m = max(m, id); Pi[id] = i; Pj[id] = j; } } memset(M[n+1], '#', 17); int sum=0, cnt=1; for (int i=0, c; cnt && i<m; ++i) { sum += bfs(i, c); cnt = ((long long) cnt * c) % MODUL; } cout << "Case " << cse << ": "; if (!cnt) cout << "Impossible\n"; else cout << sum << ' ' << cnt << "\n"; } }
23.397436
77
0.339178
arash16
1d7f74ad7e40faa7a119dd70081c07dfd0ec00d4
11,275
cpp
C++
contrib/groff/src/utils/addftinfo/guess.cpp
ivadasz/DragonFlyBSD
460227f342554313be3c7728ff679dd4a556cce9
[ "BSD-3-Clause" ]
3
2017-03-06T14:12:57.000Z
2019-11-23T09:35:10.000Z
contrib/groff/src/utils/addftinfo/guess.cpp
jorisgio/DragonFlyBSD
d37cc9027d161f3e36bf2667d32f41f87606b2ac
[ "BSD-3-Clause" ]
null
null
null
contrib/groff/src/utils/addftinfo/guess.cpp
jorisgio/DragonFlyBSD
d37cc9027d161f3e36bf2667d32f41f87606b2ac
[ "BSD-3-Clause" ]
null
null
null
// -*- C++ -*- /* Copyright (C) 1989, 1990, 1991, 1992, 2009 Free Software Foundation, Inc. Written by James Clark (jjc@jclark.com) This file is part of groff. groff is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. groff is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "guess.h" void guess(const char *s, const font_params &param, char_metric *metric) { int &height = metric->height; int &depth = metric->depth; metric->ic = 0; metric->left_ic = 0; metric->sk = 0; height = 0; depth = 0; if (s[0] == '\0' || (s[1] != '\0' && s[2] != '\0')) goto do_default; #define HASH(c1, c2) (((unsigned char)(c1) << 8) | (unsigned char)(c2)) switch (HASH(s[0], s[1])) { default: do_default: if (metric->type & 01) depth = param.desc_depth; if (metric->type & 02) height = param.asc_height; else height = param.x_height; break; case HASH('\\', '|'): case HASH('\\', '^'): case HASH('\\', '&'): // these have zero height and depth break; case HASH('f', 0): height = param.asc_height; if (param.italic) depth = param.desc_depth; break; case HASH('a', 0): case HASH('c', 0): case HASH('e', 0): case HASH('m', 0): case HASH('n', 0): case HASH('o', 0): case HASH('r', 0): case HASH('s', 0): case HASH('u', 0): case HASH('v', 0): case HASH('w', 0): case HASH('x', 0): case HASH('z', 0): height = param.x_height; break; case HASH('i', 0): height = param.x_height; break; case HASH('b', 0): case HASH('d', 0): case HASH('h', 0): case HASH('k', 0): case HASH('l', 0): case HASH('F', 'i'): case HASH('F', 'l'): case HASH('f', 'f'): case HASH('f', 'i'): case HASH('f', 'l'): height = param.asc_height; break; case HASH('t', 0): height = param.asc_height; break; case HASH('g', 0): case HASH('p', 0): case HASH('q', 0): case HASH('y', 0): height = param.x_height; depth = param.desc_depth; break; case HASH('j', 0): height = param.x_height; depth = param.desc_depth; break; case HASH('A', 0): case HASH('B', 0): case HASH('C', 0): case HASH('D', 0): case HASH('E', 0): case HASH('F', 0): case HASH('G', 0): case HASH('H', 0): case HASH('I', 0): case HASH('J', 0): case HASH('K', 0): case HASH('L', 0): case HASH('M', 0): case HASH('N', 0): case HASH('O', 0): case HASH('P', 0): case HASH('Q', 0): case HASH('R', 0): case HASH('S', 0): case HASH('T', 0): case HASH('U', 0): case HASH('V', 0): case HASH('W', 0): case HASH('X', 0): case HASH('Y', 0): case HASH('Z', 0): height = param.cap_height; break; case HASH('*', 'A'): case HASH('*', 'B'): case HASH('*', 'C'): case HASH('*', 'D'): case HASH('*', 'E'): case HASH('*', 'F'): case HASH('*', 'G'): case HASH('*', 'H'): case HASH('*', 'I'): case HASH('*', 'K'): case HASH('*', 'L'): case HASH('*', 'M'): case HASH('*', 'N'): case HASH('*', 'O'): case HASH('*', 'P'): case HASH('*', 'Q'): case HASH('*', 'R'): case HASH('*', 'S'): case HASH('*', 'T'): case HASH('*', 'U'): case HASH('*', 'W'): case HASH('*', 'X'): case HASH('*', 'Y'): case HASH('*', 'Z'): height = param.cap_height; break; case HASH('0', 0): case HASH('1', 0): case HASH('2', 0): case HASH('3', 0): case HASH('4', 0): case HASH('5', 0): case HASH('6', 0): case HASH('7', 0): case HASH('8', 0): case HASH('9', 0): case HASH('1', '2'): case HASH('1', '4'): case HASH('3', '4'): height = param.fig_height; break; case HASH('(', 0): case HASH(')', 0): case HASH('[', 0): case HASH(']', 0): case HASH('{', 0): case HASH('}', 0): height = param.body_height; depth = param.body_depth; break; case HASH('i', 's'): height = (param.em*3)/4; depth = param.em/4; break; case HASH('*', 'a'): case HASH('*', 'e'): case HASH('*', 'i'): case HASH('*', 'k'): case HASH('*', 'n'): case HASH('*', 'o'): case HASH('*', 'p'): case HASH('*', 's'): case HASH('*', 't'): case HASH('*', 'u'): case HASH('*', 'w'): height = param.x_height; break; case HASH('*', 'd'): case HASH('*', 'l'): height = param.asc_height; break; case HASH('*', 'g'): case HASH('*', 'h'): case HASH('*', 'm'): case HASH('*', 'r'): case HASH('*', 'x'): case HASH('*', 'y'): height = param.x_height; depth = param.desc_depth; break; case HASH('*', 'b'): case HASH('*', 'c'): case HASH('*', 'f'): case HASH('*', 'q'): case HASH('*', 'z'): height = param.asc_height; depth = param.desc_depth; break; case HASH('t', 's'): height = param.x_height; depth = param.desc_depth; break; case HASH('!', 0): case HASH('?', 0): case HASH('"', 0): case HASH('#', 0): case HASH('$', 0): case HASH('%', 0): case HASH('&', 0): case HASH('*', 0): case HASH('+', 0): height = param.asc_height; break; case HASH('`', 0): case HASH('\'', 0): height = param.asc_height; break; case HASH('~', 0): case HASH('^', 0): case HASH('a', 'a'): case HASH('g', 'a'): height = param.asc_height; break; case HASH('r', 'u'): case HASH('.', 0): break; case HASH(',', 0): depth = param.comma_depth; break; case HASH('m', 'i'): case HASH('-', 0): case HASH('h', 'y'): case HASH('e', 'm'): height = param.x_height; break; case HASH(':', 0): height = param.x_height; break; case HASH(';', 0): height = param.x_height; depth = param.comma_depth; break; case HASH('=', 0): case HASH('e', 'q'): height = param.x_height; break; case HASH('<', 0): case HASH('>', 0): case HASH('>', '='): case HASH('<', '='): case HASH('@', 0): case HASH('/', 0): case HASH('|', 0): case HASH('\\', 0): height = param.asc_height; break; case HASH('_', 0): case HASH('u', 'l'): case HASH('\\', '_'): depth = param.em/4; break; case HASH('r', 'n'): height = (param.em*3)/4; break; case HASH('s', 'r'): height = (param.em*3)/4; depth = param.em/4; break; case HASH('b', 'u'): case HASH('s', 'q'): case HASH('d', 'e'): case HASH('d', 'g'): case HASH('f', 'm'): case HASH('c', 't'): case HASH('r', 'g'): case HASH('c', 'o'): case HASH('p', 'l'): case HASH('*', '*'): case HASH('s', 'c'): case HASH('s', 'l'): case HASH('=', '='): case HASH('~', '='): case HASH('a', 'p'): case HASH('!', '='): case HASH('-', '>'): case HASH('<', '-'): case HASH('u', 'a'): case HASH('d', 'a'): case HASH('m', 'u'): case HASH('d', 'i'): case HASH('+', '-'): case HASH('c', 'u'): case HASH('c', 'a'): case HASH('s', 'b'): case HASH('s', 'p'): case HASH('i', 'b'): case HASH('i', 'p'): case HASH('i', 'f'): case HASH('p', 'd'): case HASH('g', 'r'): case HASH('n', 'o'): case HASH('p', 't'): case HASH('e', 's'): case HASH('m', 'o'): case HASH('b', 'r'): case HASH('d', 'd'): case HASH('r', 'h'): case HASH('l', 'h'): case HASH('o', 'r'): case HASH('c', 'i'): height = param.asc_height; break; case HASH('l', 't'): case HASH('l', 'b'): case HASH('r', 't'): case HASH('r', 'b'): case HASH('l', 'k'): case HASH('r', 'k'): case HASH('b', 'v'): case HASH('l', 'f'): case HASH('r', 'f'): case HASH('l', 'c'): case HASH('r', 'c'): height = (param.em*3)/4; depth = param.em/4; break; #if 0 case HASH('%', '0'): case HASH('-', '+'): case HASH('-', 'D'): case HASH('-', 'd'): case HASH('-', 'd'): case HASH('-', 'h'): case HASH('.', 'i'): case HASH('.', 'j'): case HASH('/', 'L'): case HASH('/', 'O'): case HASH('/', 'l'): case HASH('/', 'o'): case HASH('=', '~'): case HASH('A', 'E'): case HASH('A', 'h'): case HASH('A', 'N'): case HASH('C', 's'): case HASH('D', 'o'): case HASH('F', 'c'): case HASH('F', 'o'): case HASH('I', 'J'): case HASH('I', 'm'): case HASH('O', 'E'): case HASH('O', 'f'): case HASH('O', 'K'): case HASH('O', 'm'): case HASH('O', 'R'): case HASH('P', 'o'): case HASH('R', 'e'): case HASH('S', '1'): case HASH('S', '2'): case HASH('S', '3'): case HASH('T', 'P'): case HASH('T', 'p'): case HASH('Y', 'e'): case HASH('\\', '-'): case HASH('a', '"'): case HASH('a', '-'): case HASH('a', '.'): case HASH('a', '^'): case HASH('a', 'b'): case HASH('a', 'c'): case HASH('a', 'd'): case HASH('a', 'e'): case HASH('a', 'h'): case HASH('a', 'o'): case HASH('a', 't'): case HASH('a', '~'): case HASH('b', 'a'): case HASH('b', 'b'): case HASH('b', 's'): case HASH('c', '*'): case HASH('c', '+'): case HASH('f', '/'): case HASH('f', 'a'): case HASH('f', 'c'): case HASH('f', 'o'): case HASH('h', 'a'): case HASH('h', 'o'): case HASH('i', 'j'): case HASH('l', 'A'): case HASH('l', 'B'): case HASH('l', 'C'): case HASH('m', 'd'): case HASH('n', 'c'): case HASH('n', 'e'): case HASH('n', 'm'): case HASH('o', 'A'): case HASH('o', 'a'): case HASH('o', 'e'): case HASH('o', 'q'): case HASH('p', 'l'): case HASH('p', 'p'): case HASH('p', 's'): case HASH('r', '!'): case HASH('r', '?'): case HASH('r', 'A'): case HASH('r', 'B'): case HASH('r', 'C'): case HASH('r', 's'): case HASH('s', 'h'): case HASH('s', 's'): case HASH('t', 'e'): case HASH('t', 'f'): case HASH('t', 'i'): case HASH('t', 'm'): case HASH('~', '~'): case HASH('v', 'S'): case HASH('v', 'Z'): case HASH('v', 's'): case HASH('v', 'z'): case HASH('^', 'A'): case HASH('^', 'E'): case HASH('^', 'I'): case HASH('^', 'O'): case HASH('^', 'U'): case HASH('^', 'a'): case HASH('^', 'e'): case HASH('^', 'i'): case HASH('^', 'o'): case HASH('^', 'u'): case HASH('`', 'A'): case HASH('`', 'E'): case HASH('`', 'I'): case HASH('`', 'O'): case HASH('`', 'U'): case HASH('`', 'a'): case HASH('`', 'e'): case HASH('`', 'i'): case HASH('`', 'o'): case HASH('`', 'u'): case HASH('~', 'A'): case HASH('~', 'N'): case HASH('~', 'O'): case HASH('~', 'a'): case HASH('~', 'n'): case HASH('~', 'o'): case HASH('\'', 'A'): case HASH('\'', 'C'): case HASH('\'', 'E'): case HASH('\'', 'I'): case HASH('\'', 'O'): case HASH('\'', 'U'): case HASH('\'', 'a'): case HASH('\'', 'c'): case HASH('\'', 'e'): case HASH('\'', 'i'): case HASH('\'', 'o'): case HASH('\'', 'u') case HASH(':', 'A'): case HASH(':', 'E'): case HASH(':', 'I'): case HASH(':', 'O'): case HASH(':', 'U'): case HASH(':', 'Y'): case HASH(':', 'a'): case HASH(':', 'e'): case HASH(':', 'i'): case HASH(':', 'o'): case HASH(':', 'u'): case HASH(':', 'y'): case HASH(',', 'C'): case HASH(',', 'c'): #endif } }
22.96334
72
0.478847
ivadasz
1d7f7d015cd3ec939392650f78f504b0c234e3de
9,302
cpp
C++
wxMsOptionsDialog/wxMsOptionsDialog.cpp
tester0077/wxMS
da7b8aaefa7107f51b7ecab05c07c109d09f933f
[ "Zlib", "MIT" ]
null
null
null
wxMsOptionsDialog/wxMsOptionsDialog.cpp
tester0077/wxMS
da7b8aaefa7107f51b7ecab05c07c109d09f933f
[ "Zlib", "MIT" ]
null
null
null
wxMsOptionsDialog/wxMsOptionsDialog.cpp
tester0077/wxMS
da7b8aaefa7107f51b7ecab05c07c109d09f933f
[ "Zlib", "MIT" ]
null
null
null
/*----------------------------------------------------------------- * Name: wxMsOptionsDialog.cpp * Purpose: * Author: A. Wiegert * * Copyright: * Licence: wxWidgets license *---------------------------------------------------------------- */ /*---------------------------------------------------------------- * Standard wxWidgets headers *---------------------------------------------------------------- */ // Note __VISUALC__ is defined by wxWidgets, not by MSVC IDE // and thus won't be defined until some wxWidgets headers are included #if defined( _MSC_VER ) # if defined ( _DEBUG ) // this statement NEEDS to go BEFORE all headers # define _CRTDBG_MAP_ALLOC # endif #endif #include "wxMsPreProcDefsh.h" // needs to be first // For compilers that support precompilation, includes "wx/wx.h". #include "wx/wxprec.h" #ifdef __BORLANDC__ #pragma hdrstop #endif /* For all others, include the necessary headers * (this file is usually all you need because it * includes almost all "standard" wxWidgets headers) */ #ifndef WX_PRECOMP #include "wx/wx.h" #endif // ----------------------------------------------------------------- #include "wxMsh.h" #include "wxMsOptionsDialogh.h" #include "wxMsFilterDialogh.h" // ------------------------------------------------------------------ // Note __VISUALC__ is defined by wxWidgets, not by MSVC IDE // and thus won't be defined until some wxWidgets headers are included #if defined( _MSC_VER ) // only good for MSVC // this block needs to AFTER all headers #include <stdlib.h> #include <crtdbg.h> #ifdef _DEBUG #ifndef DBG_NEW #define DBG_NEW new ( _NORMAL_BLOCK , __FILE__ , __LINE__ ) #define new DBG_NEW #endif #endif #endif // ------------------------------------------------------------------ // Note: Check box update code is in the file for each page // Constructor wxMsOptionsDialog::wxMsOptionsDialog( wxWindow* parent ) : MyDialogOptionsBase( parent ) { m_pParent = parent; } // ------------------------------------------------------------------ bool wxMsOptionsDialog::TransferDataToWindow() { wxString wsT; bool b; // 'General' tab // launch mail client after processing mail b = m_iniPrefs.data[IE_LAUNCH_MAIL_CLIENT].dataCurrent.bVal; m_checkBoxOptLaunchMailClient->SetValue( b ); // e-mail client path m_textCtrlEmailClient->AppendText( m_iniPrefs.data[IE_MAIL_CLIENT_PATH].dataCurrent.wsVal ); // check for new mail at startup b = m_iniPrefs.data[IE_CHECK_MAIL_STARTUP].dataCurrent.bVal; m_checkBoxOptCheckMailAtStart->SetValue( b ); // play sound when new mail arrives b = m_iniPrefs.data[IE_SOUND_4_NEW_MAIL].dataCurrent.bVal; m_checkBoxOptPlaySound->SetValue( b ); // schedule mail check b = m_iniPrefs.data[IE_SCHEDULE_MAIL_CHECK].dataCurrent.bVal; m_checkBoxScheduleMailCheck->SetValue( b ); // schedule mail check interval - minutes m_spinCtrlMailCheckInterval->SetValue( m_iniPrefs.data[IE_MAIL_CHECK_INTERVAL].dataCurrent.lVal ); // schedule mail srerver connection check b = m_iniPrefs.data[IE_SCHEDULE_SERVER_CHECK].dataCurrent.bVal; m_checkBoxScheduleMailCheck->SetValue( b ); // schedule mail server connection check interval - minutes m_spinCtrlMailServerConectCheckInterval->SetValue( m_iniPrefs.data[IE_SERVER_CHECK_INTERVAL].dataCurrent.lVal ); // check for updates at startup m_checkBoxAutoUpdateCheck->SetValue( m_iniPrefs.data[IE_OPT_AUTO_UPDATE_CHECK].dataCurrent.bVal ); // number of message lines to get with TOP request m_spinCtrlMaxTopLines->SetValue( m_iniPrefs.data[IE_OPT_MAX_TOP_LINES].dataCurrent.lVal ); // ------------------------------------------------------------------ // same for the 'Log' tab b = m_iniPrefs.data[IE_LOG_FILE_WANTED].dataCurrent.bVal; m_cbOptLogToFile->SetValue( b ); if ( b ) { b = m_iniPrefs.data[IE_USE_LOG_DEF_DIR].dataCurrent.bVal; m_cbOptLogUseDefaultPath->SetValue( b ); if ( b ) { m_btnOptLogSelLogFilesDir->Enable( false ); m_tcOptLogFilesDestDir->Disable(); } else { m_btnOptLogSelLogFilesDir->Enable(); m_tcOptLogFilesDestDir->Enable(); } } else { m_cbOptLogUseDefaultPath->Disable(); m_btnOptLogSelLogFilesDir->Enable( false ); m_tcOptLogFilesDestDir->Disable(); } // the status has been set, just show the values b = m_cbOptLogUseDefaultPath->GetValue(); if( b ) { m_tcOptLogFilesDestDir->SetValue( wxStandardPaths::Get().GetDataDir() ); } else { m_tcOptLogFilesDestDir->SetValue( m_iniPrefs.data[IE_LOG_DIR_PATH].dataCurrent.wsVal ); } m_tcOptLogFilesDestDir->SetValue( m_iniPrefs.data[IE_LOG_DIR_PATH].dataCurrent.wsVal ); m_sliderOptLogVerbosity->SetValue( m_iniPrefs.data[IE_LOG_VERBOSITY].dataCurrent.lVal ); // ------------------------------------------------------------------ // and the Filter tab // list all of the current filters in m_checkListBoxFilter UpDateFilterList(); // set the default status color m_colourPickerStatusDefColor->SetColour( m_iniPrefs.data[IE_STATUS_DEFAULT_COLOR].dataCurrent.wsVal ); return true; } // ------------------------------------------------------------------ /** * Break out this code so we can update the list after modifying the * filter list because of either additions, deletion or name changes. */ void wxMsOptionsDialog::UpDateFilterList() { wxArrayString wasChoices; for ( std::vector<MyFilterListEl>::iterator it = wxGetApp().m_FilterList.begin(); it != wxGetApp().m_FilterList.end(); ++it ) { // need to add them to the front to keep them in // the same sequence as they are in the list. wasChoices.Add( it->m_wsName ); } // insert the filter names m_checkListBoxFilter->Clear(); if( wasChoices.GetCount() ) // any contents?? { m_checkListBoxFilter->InsertItems( wasChoices, 0); // set the checkboxes as needed int i = 0; for ( std::vector<MyFilterListEl>::iterator it = wxGetApp().m_FilterList.begin(); it != wxGetApp().m_FilterList.end(); ++it, i++ ) { m_checkListBoxFilter->Check( i, it->m_bState ); } // just in case the filter file was fiddled with int iNFilters = std::min( (long)(wxGetApp().m_FilterList.size() - 1), m_iniPrefs.data[IE_FILTER_LAST_SEL].dataCurrent.lVal ); m_checkListBoxFilter->SetSelection( iNFilters ); ExplainFilter( iNFilters ); } } // ------------------------------------------------------------------ bool wxMsOptionsDialog::TransferDataFromWindow() { // 'General' tab // Launch mail client after processing mail m_iniPrefs.data[IE_LAUNCH_MAIL_CLIENT].dataCurrent.bVal = m_checkBoxOptLaunchMailClient->GetValue(); // e-mail client path m_iniPrefs.data[IE_MAIL_CLIENT_PATH].dataCurrent.wsVal = m_textCtrlEmailClient->GetValue(); // check for new mail at startup m_iniPrefs.data[IE_CHECK_MAIL_STARTUP].dataCurrent.bVal = m_checkBoxOptCheckMailAtStart->GetValue(); // play sound when new mail arrives m_iniPrefs.data[IE_SOUND_4_NEW_MAIL].dataCurrent.bVal = m_checkBoxOptPlaySound->GetValue(); // schedule mail check m_iniPrefs.data[IE_SCHEDULE_MAIL_CHECK].dataCurrent.bVal = m_checkBoxScheduleMailCheck->GetValue(); // schedule mail check interval - minutes m_iniPrefs.data[IE_MAIL_CHECK_INTERVAL].dataCurrent.lVal = m_spinCtrlMailCheckInterval->GetValue(); // schedule mail srerver connection check m_iniPrefs.data[IE_SCHEDULE_SERVER_CHECK].dataCurrent.bVal = m_checkBoxScheduleMailCheck->GetValue(); // schedule mail server connection check interval - minutes m_iniPrefs.data[IE_SERVER_CHECK_INTERVAL].dataCurrent.lVal = m_spinCtrlMailServerConectCheckInterval->GetValue(); // schedule mail server connection check interval - minutes m_iniPrefs.data[IE_SERVER_CHECK_INTERVAL].dataCurrent.lVal = m_checkBoxScheduleConnectCheck->GetValue(); // check for updates at startup m_iniPrefs.data[IE_OPT_AUTO_UPDATE_CHECK].dataCurrent.bVal = m_checkBoxAutoUpdateCheck->GetValue(); // number of message lines to get with TOP request m_iniPrefs.data[IE_OPT_MAX_TOP_LINES].dataCurrent.lVal = m_spinCtrlMaxTopLines->GetValue(); // ------------------------------------------------------- // 'Log' tab m_iniPrefs.data[IE_LOG_FILE_WANTED].dataCurrent.bVal = m_cbOptLogToFile->GetValue(); m_iniPrefs.data[IE_USE_LOG_DEF_DIR].dataCurrent.bVal = m_cbOptLogUseDefaultPath->GetValue(); m_iniPrefs.data[IE_LOG_DIR_PATH].dataCurrent.wsVal = m_tcOptLogFilesDestDir->GetValue(); m_iniPrefs.data[IE_LOG_VERBOSITY].dataCurrent.lVal = m_sliderOptLogVerbosity->GetValue(); // update the filter enabled/disabled status int i = 0; for ( std::vector<MyFilterListEl>::iterator it = wxGetApp().m_FilterList.begin(); it != wxGetApp().m_FilterList.end(); ++it, i++ ) { it->m_bState = m_checkListBoxFilter->IsChecked( i ); } m_iniPrefs.data[IE_FILTER_LAST_SEL].dataCurrent.lVal = m_checkListBoxFilter->GetSelection(); // save the default status color m_iniPrefs.data[IE_STATUS_DEFAULT_COLOR].dataCurrent.wsVal = m_colourPickerStatusDefColor->GetColour().GetAsString(); return true; } // ------------------------------- eof ------------------------------
34.579926
85
0.659966
tester0077
1d7faf120dc4e5c475204d06d6392bd6ce62deb2
10,590
cc
C++
src/compiler/objective_c_generator.cc
duanwujie/grpc-hacking
4275e60eb686ceb202c042fe578c9cf992e590d0
[ "BSD-3-Clause" ]
9
2017-01-18T02:28:31.000Z
2021-04-12T13:59:18.000Z
src/compiler/objective_c_generator.cc
duanwujie/grpc-hacking
4275e60eb686ceb202c042fe578c9cf992e590d0
[ "BSD-3-Clause" ]
null
null
null
src/compiler/objective_c_generator.cc
duanwujie/grpc-hacking
4275e60eb686ceb202c042fe578c9cf992e590d0
[ "BSD-3-Clause" ]
3
2017-06-15T14:03:56.000Z
2019-12-17T05:46:48.000Z
/* * * Copyright 2015, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include <map> #include <sstream> #include "src/compiler/config.h" #include "src/compiler/objective_c_generator.h" #include "src/compiler/objective_c_generator_helpers.h" #include <google/protobuf/compiler/objectivec/objectivec_helpers.h> using ::google::protobuf::compiler::objectivec::ClassName; using ::grpc::protobuf::io::Printer; using ::grpc::protobuf::MethodDescriptor; using ::grpc::protobuf::ServiceDescriptor; using ::std::map; namespace grpc_objective_c_generator { namespace { void PrintProtoRpcDeclarationAsPragma( Printer *printer, const MethodDescriptor *method, map< ::grpc::string, ::grpc::string> vars) { vars["client_stream"] = method->client_streaming() ? "stream " : ""; vars["server_stream"] = method->server_streaming() ? "stream " : ""; printer->Print(vars, "#pragma mark $method_name$($client_stream$$request_type$)" " returns ($server_stream$$response_type$)\n\n"); } template <typename DescriptorType> static void PrintAllComments(const DescriptorType *desc, Printer *printer) { std::vector<grpc::string> comments; grpc_generator::GetComment(desc, grpc_generator::COMMENTTYPE_LEADING_DETACHED, &comments); grpc_generator::GetComment(desc, grpc_generator::COMMENTTYPE_LEADING, &comments); grpc_generator::GetComment(desc, grpc_generator::COMMENTTYPE_TRAILING, &comments); if (comments.empty()) { return; } printer->Print("/**\n"); for (auto it = comments.begin(); it != comments.end(); ++it) { printer->Print(" * "); size_t start_pos = it->find_first_not_of(' '); if (start_pos != grpc::string::npos) { printer->Print(it->c_str() + start_pos); } printer->Print("\n"); } printer->Print(" */\n"); } void PrintMethodSignature(Printer *printer, const MethodDescriptor *method, const map< ::grpc::string, ::grpc::string> &vars) { // Print comment PrintAllComments(method, printer); printer->Print(vars, "- ($return_type$)$method_name$With"); if (method->client_streaming()) { printer->Print("RequestsWriter:(GRXWriter *)requestWriter"); } else { printer->Print(vars, "Request:($request_class$ *)request"); } // TODO(jcanizales): Put this on a new line and align colons. if (method->server_streaming()) { printer->Print(vars, " eventHandler:(void(^)(BOOL done, " "$response_class$ *_Nullable response, NSError *_Nullable " "error))eventHandler"); } else { printer->Print(vars, " handler:(void(^)($response_class$ *_Nullable response, " "NSError *_Nullable error))handler"); } } void PrintSimpleSignature(Printer *printer, const MethodDescriptor *method, map< ::grpc::string, ::grpc::string> vars) { vars["method_name"] = grpc_generator::LowercaseFirstLetter(vars["method_name"]); vars["return_type"] = "void"; PrintMethodSignature(printer, method, vars); } void PrintAdvancedSignature(Printer *printer, const MethodDescriptor *method, map< ::grpc::string, ::grpc::string> vars) { vars["method_name"] = "RPCTo" + vars["method_name"]; vars["return_type"] = "GRPCProtoCall *"; PrintMethodSignature(printer, method, vars); } inline map< ::grpc::string, ::grpc::string> GetMethodVars( const MethodDescriptor *method) { map< ::grpc::string, ::grpc::string> res; res["method_name"] = method->name(); res["request_type"] = method->input_type()->name(); res["response_type"] = method->output_type()->name(); res["request_class"] = ClassName(method->input_type()); res["response_class"] = ClassName(method->output_type()); return res; } void PrintMethodDeclarations(Printer *printer, const MethodDescriptor *method) { map< ::grpc::string, ::grpc::string> vars = GetMethodVars(method); PrintProtoRpcDeclarationAsPragma(printer, method, vars); PrintSimpleSignature(printer, method, vars); printer->Print(";\n\n"); PrintAdvancedSignature(printer, method, vars); printer->Print(";\n\n\n"); } void PrintSimpleImplementation(Printer *printer, const MethodDescriptor *method, map< ::grpc::string, ::grpc::string> vars) { printer->Print("{\n"); printer->Print(vars, " [[self RPCTo$method_name$With"); if (method->client_streaming()) { printer->Print("RequestsWriter:requestWriter"); } else { printer->Print("Request:request"); } if (method->server_streaming()) { printer->Print(" eventHandler:eventHandler] start];\n"); } else { printer->Print(" handler:handler] start];\n"); } printer->Print("}\n"); } void PrintAdvancedImplementation(Printer *printer, const MethodDescriptor *method, map< ::grpc::string, ::grpc::string> vars) { printer->Print("{\n"); printer->Print(vars, " return [self RPCToMethod:@\"$method_name$\"\n"); printer->Print(" requestsWriter:"); if (method->client_streaming()) { printer->Print("requestWriter\n"); } else { printer->Print("[GRXWriter writerWithValue:request]\n"); } printer->Print(vars, " responseClass:[$response_class$ class]\n"); printer->Print(" responsesWriteable:[GRXWriteable "); if (method->server_streaming()) { printer->Print("writeableWithEventHandler:eventHandler]];\n"); } else { printer->Print("writeableWithSingleHandler:handler]];\n"); } printer->Print("}\n"); } void PrintMethodImplementations(Printer *printer, const MethodDescriptor *method) { map< ::grpc::string, ::grpc::string> vars = GetMethodVars(method); PrintProtoRpcDeclarationAsPragma(printer, method, vars); // TODO(jcanizales): Print documentation from the method. PrintSimpleSignature(printer, method, vars); PrintSimpleImplementation(printer, method, vars); printer->Print("// Returns a not-yet-started RPC object.\n"); PrintAdvancedSignature(printer, method, vars); PrintAdvancedImplementation(printer, method, vars); } } // namespace ::grpc::string GetHeader(const ServiceDescriptor *service) { ::grpc::string output; { // Scope the output stream so it closes and finalizes output to the string. grpc::protobuf::io::StringOutputStream output_stream(&output); Printer printer(&output_stream, '$'); map< ::grpc::string, ::grpc::string> vars = { {"service_class", ServiceClassName(service)}}; printer.Print(vars, "@protocol $service_class$ <NSObject>\n\n"); for (int i = 0; i < service->method_count(); i++) { PrintMethodDeclarations(&printer, service->method(i)); } printer.Print("@end\n\n"); printer.Print( "/**\n" " * Basic service implementation, over gRPC, that only does\n" " * marshalling and parsing.\n" " */\n"); printer.Print(vars, "@interface $service_class$ :" " GRPCProtoService<$service_class$>\n"); printer.Print( "- (instancetype)initWithHost:(NSString *)host" " NS_DESIGNATED_INITIALIZER;\n"); printer.Print("+ (instancetype)serviceWithHost:(NSString *)host;\n"); printer.Print("@end\n"); } return output; } ::grpc::string GetSource(const ServiceDescriptor *service) { ::grpc::string output; { // Scope the output stream so it closes and finalizes output to the string. grpc::protobuf::io::StringOutputStream output_stream(&output); Printer printer(&output_stream, '$'); map< ::grpc::string, ::grpc::string> vars = { {"service_name", service->name()}, {"service_class", ServiceClassName(service)}, {"package", service->file()->package()}}; printer.Print(vars, "@implementation $service_class$\n\n"); printer.Print("// Designated initializer\n"); printer.Print("- (instancetype)initWithHost:(NSString *)host {\n"); printer.Print( vars, " return (self = [super initWithHost:host" " packageName:@\"$package$\" serviceName:@\"$service_name$\"]);\n"); printer.Print("}\n\n"); printer.Print( "// Override superclass initializer to disallow different" " package and service names.\n"); printer.Print("- (instancetype)initWithHost:(NSString *)host\n"); printer.Print(" packageName:(NSString *)packageName\n"); printer.Print(" serviceName:(NSString *)serviceName {\n"); printer.Print(" return [self initWithHost:host];\n"); printer.Print("}\n\n"); printer.Print("+ (instancetype)serviceWithHost:(NSString *)host {\n"); printer.Print(" return [[self alloc] initWithHost:host];\n"); printer.Print("}\n\n\n"); for (int i = 0; i < service->method_count(); i++) { PrintMethodImplementations(&printer, service->method(i)); } printer.Print("@end\n"); } return output; } } // namespace grpc_objective_c_generator
37.157895
80
0.660529
duanwujie
1d83f15f2aa24f6eb63ee0484c3f2848236484a5
5,505
cxx
C++
3rd/fltk/src/list_fonts.cxx
MarioHenze/cgv
bacb2d270b1eecbea1e933b8caad8d7e11d807c2
[ "BSD-3-Clause" ]
11
2017-09-30T12:21:55.000Z
2021-04-29T21:31:57.000Z
3rd/fltk/src/list_fonts.cxx
MarioHenze/cgv
bacb2d270b1eecbea1e933b8caad8d7e11d807c2
[ "BSD-3-Clause" ]
2
2017-07-11T11:20:08.000Z
2018-03-27T12:09:02.000Z
3rd/fltk/src/list_fonts.cxx
MarioHenze/cgv
bacb2d270b1eecbea1e933b8caad8d7e11d807c2
[ "BSD-3-Clause" ]
24
2018-03-27T11:46:16.000Z
2021-05-01T20:28:34.000Z
// // "$Id: list_fonts.cxx 5556 2006-12-13 00:55:45Z spitzak $" // // Copyright 1998-2006 by Bill Spitzak and others. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Library General Public // License as published by the Free Software Foundation; either // version 2 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Library General Public License for more details. // // You should have received a copy of the GNU Library General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 // USA. // // Please report all bugs and problems to "fltk-bugs@fltk.org". // // This file is seperate from Font.cxx due the historical reasons in // that on X11 significant code was saved by only using the fltk // built-in fonts and not doing anything with named fonts. This // is probably irrelevant now and they could be merged. #include <config.h> #include <fltk/Font.h> #include <fltk/string.h> #if USE_X11 # include "x11/list_fonts.cxx" #elif defined(_WIN32) # include "win32/list_fonts.cxx" #elif USE_QUARTZ # include "osx/list_fonts.cxx" #endif using namespace fltk; /*! \fn int fltk::list_fonts(fltk::Font**& arrayp); \relates fltk::Font Generate an array containing every font on the server. \a arrayp is set to a pointer to this array, and the length of the array is the return value. Each entry is a "base" font, there may be bold, italic, and bold+italic version of each font pointed to by bold() or italic(). Subsequent calls will usually return the same array quickly, but if a signal comes in indicating a change it will probably delete the old array and return a new one. */ /*! \relates fltk::Font Find a font with the given "nice" name. You can get bold and italic by adding a space and "bold" or "italic" (or both) to the name, or by passing them as the attributes. Case is ignored and fltk will accept some variations in the font name. The current implementation calls fltk::list_fonts() and then does a binary search of the returned list. This can make the first call pretty slow, especially on X. Directly calling the system has a problem in that we want the same structure returned for any call that names the same font. This is sufficiently painful that I have not done this yet. */ fltk::Font* fltk::font(const char* name, int attributes /* = 0 */) { if (!name || !*name) return 0; // find out if the " bold" or " italic" are on the end: int length = strlen(name); // also accept "italics" because old Nuke saved scripts used that: if (length > 8 && !strncasecmp(name+length-8, " italics", 8)) { length -= 8; attributes |= ITALIC; } if (length > 7 && !strncasecmp(name+length-7, " italic", 7)) { length -= 7; attributes |= ITALIC; } if (length > 5 && !strncasecmp(name+length-5, " bold", 5)) { length -= 5; attributes |= BOLD; } Font* font = 0; // always try the built-in fonts first, because list_fonts is *slow*... int i; for (i = 0; i <= 12; i += 4) { font = fltk::font(i); const char* fontname = font->name(); if (!strncasecmp(name, fontname, length) && !fontname[length]) goto GOTIT; } // now try all the fonts on the server, using a binary search: #if defined(WIN32) && !defined(__CYGWIN__) // this function is in win32/list_fonts.cxx: name = GetFontSubstitutes(name,length); #endif font = 0; {Font** list; int b = list_fonts(list); int a = 0; while (a < b) { int c = (a+b)/2; Font* testfont = list[c]; const char* fontname = testfont->name(); int d = strncasecmp(name, fontname, length); if (!d) { // If we match a prefix of the font return it unless a better match found font = testfont; if (!fontname[length]) goto GOTIT; } if (d > 0) a = c+1; else b = c; }} if (!font) return 0; GOTIT: return font->plus(attributes); } /*! \fn fltk::Font* fltk::font(int i) \relates fltk::Font Turn an fltk1 integer font id into a font. */ /*! \fn int fltk::Font::sizes(int*& sizep); Sets array to point at a list of sizes. The return value is the length of this array. The sizes are sorted from smallest to largest and indicate what sizes can be given to fltk::setfont() that will be matched exactly (fltk::setfont() will pick the closest size for other sizes). A zero in the first location of the array indicates a scalable font, where any size works, although the array may still list sizes that work "better" than others. The returned array points at a static buffer that is overwritten each call, so you want to copy it if you plan to keep it. The return value is the length of the list. The argument \a arrayp is set to point at the array, which is in static memory reused each time this call is done. */ /*! \fn int fltk::Font::encodings(const char**& arrayp); Return all the encodings for this font. These strings may be sent to fltk::set_encoding() before using the font. The return value is the length of the list. The argument \a arrayp is set to point at the array, which is in static memory reused each time this call is done. */ // // End of "$Id: list_fonts.cxx 5556 2006-12-13 00:55:45Z spitzak $". //
35.980392
79
0.695186
MarioHenze
1d84b662da08c3b1d258fc98fda3dfe608edc490
10,450
cc
C++
B2G/ndk/sources/host-tools/ndk-stack/elff/dwarf_utils.cc
wilebeast/FireFox-OS
43067f28711d78c429a1d6d58c77130f6899135f
[ "Apache-2.0" ]
3
2015-08-31T15:24:31.000Z
2020-04-24T20:31:29.000Z
B2G/ndk/sources/host-tools/ndk-stack/elff/dwarf_utils.cc
wilebeast/FireFox-OS
43067f28711d78c429a1d6d58c77130f6899135f
[ "Apache-2.0" ]
null
null
null
B2G/ndk/sources/host-tools/ndk-stack/elff/dwarf_utils.cc
wilebeast/FireFox-OS
43067f28711d78c429a1d6d58c77130f6899135f
[ "Apache-2.0" ]
3
2015-07-29T07:17:15.000Z
2020-11-04T06:55:37.000Z
/* Copyright (C) 2007-2010 The Android Open Source Project ** ** This software is licensed under the terms of the GNU General Public ** License version 2, as published by the Free Software Foundation, and ** may be copied, distributed, and modified under those terms. ** ** This program is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** GNU General Public License for more details. */ /* * Contains implementation of misc. DWARF utility routines. */ #include "stdio.h" #include "dwarf_utils.h" /* "Stringifies" the parameter. */ #define DWARF_NAMEFY(val) case val: return "" #val "" /* "Stringifies" two parameters. */ #define DWARF_NAMEFY2(val1, val2) case val1: return "" #val1 " | " #val2 "" const char* dwarf_at_name(Dwarf_At at) { switch (at) { DWARF_NAMEFY(DW_AT_sibling); DWARF_NAMEFY(DW_AT_location); DWARF_NAMEFY(DW_AT_name); DWARF_NAMEFY(DW_AT_ordering); DWARF_NAMEFY(DW_AT_subscr_data); DWARF_NAMEFY(DW_AT_byte_size); DWARF_NAMEFY(DW_AT_bit_offset); DWARF_NAMEFY(DW_AT_bit_size); DWARF_NAMEFY(DW_AT_element_list); DWARF_NAMEFY(DW_AT_stmt_list); DWARF_NAMEFY(DW_AT_low_pc); DWARF_NAMEFY(DW_AT_high_pc); DWARF_NAMEFY(DW_AT_language); DWARF_NAMEFY(DW_AT_member); DWARF_NAMEFY(DW_AT_discr); DWARF_NAMEFY(DW_AT_discr_value); DWARF_NAMEFY(DW_AT_visibility); DWARF_NAMEFY(DW_AT_import); DWARF_NAMEFY(DW_AT_string_length); DWARF_NAMEFY(DW_AT_common_reference); DWARF_NAMEFY(DW_AT_comp_dir); DWARF_NAMEFY(DW_AT_const_value); DWARF_NAMEFY(DW_AT_containing_type); DWARF_NAMEFY(DW_AT_default_value); DWARF_NAMEFY(DW_AT_inline); DWARF_NAMEFY(DW_AT_is_optional); DWARF_NAMEFY(DW_AT_lower_bound); DWARF_NAMEFY(DW_AT_producer); DWARF_NAMEFY(DW_AT_prototyped); DWARF_NAMEFY(DW_AT_return_addr); DWARF_NAMEFY(DW_AT_start_scope); DWARF_NAMEFY2(DW_AT_bit_stride, DW_AT_stride_size); DWARF_NAMEFY(DW_AT_upper_bound); DWARF_NAMEFY(DW_AT_abstract_origin); DWARF_NAMEFY(DW_AT_accessibility); DWARF_NAMEFY(DW_AT_address_class); DWARF_NAMEFY(DW_AT_artificial); DWARF_NAMEFY(DW_AT_base_types); DWARF_NAMEFY(DW_AT_calling_convention); DWARF_NAMEFY(DW_AT_count); DWARF_NAMEFY(DW_AT_data_member_location); DWARF_NAMEFY(DW_AT_decl_column); DWARF_NAMEFY(DW_AT_decl_file); DWARF_NAMEFY(DW_AT_decl_line); DWARF_NAMEFY(DW_AT_declaration); DWARF_NAMEFY(DW_AT_discr_list); DWARF_NAMEFY(DW_AT_encoding); DWARF_NAMEFY(DW_AT_external); DWARF_NAMEFY(DW_AT_frame_base); DWARF_NAMEFY(DW_AT_friend); DWARF_NAMEFY(DW_AT_identifier_case); DWARF_NAMEFY(DW_AT_macro_info); DWARF_NAMEFY(DW_AT_namelist_item); DWARF_NAMEFY(DW_AT_priority); DWARF_NAMEFY(DW_AT_segment); DWARF_NAMEFY(DW_AT_specification); DWARF_NAMEFY(DW_AT_static_link); DWARF_NAMEFY(DW_AT_type); DWARF_NAMEFY(DW_AT_use_location); DWARF_NAMEFY(DW_AT_variable_parameter); DWARF_NAMEFY(DW_AT_virtuality); DWARF_NAMEFY(DW_AT_vtable_elem_location); DWARF_NAMEFY(DW_AT_allocated); DWARF_NAMEFY(DW_AT_associated); DWARF_NAMEFY(DW_AT_data_location); DWARF_NAMEFY2(DW_AT_byte_stride, DW_AT_stride); DWARF_NAMEFY(DW_AT_entry_pc); DWARF_NAMEFY(DW_AT_use_UTF8); DWARF_NAMEFY(DW_AT_extension); DWARF_NAMEFY(DW_AT_ranges); DWARF_NAMEFY(DW_AT_trampoline); DWARF_NAMEFY(DW_AT_call_column); DWARF_NAMEFY(DW_AT_call_file); DWARF_NAMEFY(DW_AT_call_line); DWARF_NAMEFY(DW_AT_description); DWARF_NAMEFY(DW_AT_binary_scale); DWARF_NAMEFY(DW_AT_decimal_scale); DWARF_NAMEFY(DW_AT_small); DWARF_NAMEFY(DW_AT_decimal_sign); DWARF_NAMEFY(DW_AT_digit_count); DWARF_NAMEFY(DW_AT_picture_string); DWARF_NAMEFY(DW_AT_mutable); DWARF_NAMEFY(DW_AT_threads_scaled); DWARF_NAMEFY(DW_AT_explicit); DWARF_NAMEFY(DW_AT_object_pointer); DWARF_NAMEFY(DW_AT_endianity); DWARF_NAMEFY(DW_AT_elemental); DWARF_NAMEFY(DW_AT_pure); DWARF_NAMEFY(DW_AT_recursive); DWARF_NAMEFY(DW_AT_signature); DWARF_NAMEFY(DW_AT_main_subprogram); DWARF_NAMEFY(DW_AT_data_bit_offset); DWARF_NAMEFY(DW_AT_const_expr); DWARF_NAMEFY(DW_AT_enum_class); DWARF_NAMEFY(DW_AT_linkage_name); default: return "DW_AT_Unknown"; } } const char* dwarf_form_name(Dwarf_Form form) { switch (form) { DWARF_NAMEFY(DW_FORM_addr); DWARF_NAMEFY(DW_FORM_block2); DWARF_NAMEFY(DW_FORM_block4); DWARF_NAMEFY(DW_FORM_data2); DWARF_NAMEFY(DW_FORM_data4); DWARF_NAMEFY(DW_FORM_data8); DWARF_NAMEFY(DW_FORM_string); DWARF_NAMEFY(DW_FORM_block); DWARF_NAMEFY(DW_FORM_block1); DWARF_NAMEFY(DW_FORM_data1); DWARF_NAMEFY(DW_FORM_flag); DWARF_NAMEFY(DW_FORM_sdata); DWARF_NAMEFY(DW_FORM_strp); DWARF_NAMEFY(DW_FORM_udata); DWARF_NAMEFY(DW_FORM_ref_addr); DWARF_NAMEFY(DW_FORM_ref1); DWARF_NAMEFY(DW_FORM_ref2); DWARF_NAMEFY(DW_FORM_ref4); DWARF_NAMEFY(DW_FORM_ref8); DWARF_NAMEFY(DW_FORM_ref_udata); DWARF_NAMEFY(DW_FORM_indirect); DWARF_NAMEFY(DW_FORM_sec_offset); DWARF_NAMEFY(DW_FORM_exprloc); DWARF_NAMEFY(DW_FORM_flag_present); DWARF_NAMEFY(DW_FORM_ref_sig8); default: return "DW_FORM_Unknown"; } } const char* dwarf_tag_name(Dwarf_Tag tag) { switch (tag) { DWARF_NAMEFY(DW_TAG_array_type); DWARF_NAMEFY(DW_TAG_class_type); DWARF_NAMEFY(DW_TAG_entry_point); DWARF_NAMEFY(DW_TAG_enumeration_type); DWARF_NAMEFY(DW_TAG_formal_parameter); DWARF_NAMEFY(DW_TAG_imported_declaration); DWARF_NAMEFY(DW_TAG_label); DWARF_NAMEFY(DW_TAG_lexical_block); DWARF_NAMEFY(DW_TAG_member); DWARF_NAMEFY(DW_TAG_pointer_type); DWARF_NAMEFY(DW_TAG_reference_type); DWARF_NAMEFY(DW_TAG_compile_unit); DWARF_NAMEFY(DW_TAG_string_type); DWARF_NAMEFY(DW_TAG_structure_type); DWARF_NAMEFY(DW_TAG_subroutine_type); DWARF_NAMEFY(DW_TAG_typedef); DWARF_NAMEFY(DW_TAG_union_type); DWARF_NAMEFY(DW_TAG_unspecified_parameters); DWARF_NAMEFY(DW_TAG_variant); DWARF_NAMEFY(DW_TAG_common_block); DWARF_NAMEFY(DW_TAG_common_inclusion); DWARF_NAMEFY(DW_TAG_inheritance); DWARF_NAMEFY(DW_TAG_inlined_subroutine); DWARF_NAMEFY(DW_TAG_module); DWARF_NAMEFY(DW_TAG_ptr_to_member_type); DWARF_NAMEFY(DW_TAG_set_type); DWARF_NAMEFY(DW_TAG_subrange_type); DWARF_NAMEFY(DW_TAG_with_stmt); DWARF_NAMEFY(DW_TAG_access_declaration); DWARF_NAMEFY(DW_TAG_base_type); DWARF_NAMEFY(DW_TAG_catch_block); DWARF_NAMEFY(DW_TAG_const_type); DWARF_NAMEFY(DW_TAG_constant); DWARF_NAMEFY(DW_TAG_enumerator); DWARF_NAMEFY(DW_TAG_file_type); DWARF_NAMEFY(DW_TAG_friend); DWARF_NAMEFY(DW_TAG_namelist); DWARF_NAMEFY2(DW_TAG_namelist_item, DW_TAG_namelist_items); DWARF_NAMEFY(DW_TAG_packed_type); DWARF_NAMEFY(DW_TAG_subprogram); DWARF_NAMEFY2(DW_TAG_template_type_parameter, DW_TAG_template_type_param); DWARF_NAMEFY2(DW_TAG_template_value_parameter, DW_TAG_template_value_param); DWARF_NAMEFY(DW_TAG_thrown_type); DWARF_NAMEFY(DW_TAG_try_block); DWARF_NAMEFY(DW_TAG_variant_part); DWARF_NAMEFY(DW_TAG_variable); DWARF_NAMEFY(DW_TAG_volatile_type); DWARF_NAMEFY(DW_TAG_dwarf_procedure); DWARF_NAMEFY(DW_TAG_restrict_type); DWARF_NAMEFY(DW_TAG_interface_type); DWARF_NAMEFY(DW_TAG_namespace); DWARF_NAMEFY(DW_TAG_imported_module); DWARF_NAMEFY(DW_TAG_unspecified_type); DWARF_NAMEFY(DW_TAG_partial_unit); DWARF_NAMEFY(DW_TAG_imported_unit); DWARF_NAMEFY(DW_TAG_mutable_type); DWARF_NAMEFY(DW_TAG_condition); DWARF_NAMEFY(DW_TAG_shared_type); DWARF_NAMEFY(DW_TAG_type_unit); DWARF_NAMEFY(DW_TAG_rvalue_reference_type); DWARF_NAMEFY(DW_TAG_template_alias); default: return "DW_TAG_Unknown"; } } void dump_attrib(Dwarf_At at, Dwarf_Form form, const Dwarf_Value* val) { if (form != 0) { printf(" +++ Attribute: %s [%s]\n", dwarf_at_name(at), dwarf_form_name(form)); } else { printf(" +++ Attribute: %s\n", dwarf_at_name(at)); } dump_value(val); } void dump_value(const Dwarf_Value* attr_value) { printf(" Data[%03u]: (", attr_value->encoded_size); switch (attr_value->type) { case DWARF_VALUE_U8: printf("BYTE) = %u (x%02X)\n", (Elf_Word)attr_value->u8, (Elf_Word)attr_value->u8); break; case DWARF_VALUE_S8: printf("SBYTE) = %d (x%02X)\n", (Elf_Sword)attr_value->s8, (Elf_Sword)attr_value->s8); break; case DWARF_VALUE_U16: printf("WORD) = %u (x%04X)\n", (Elf_Word)attr_value->u16, (Elf_Word)attr_value->u16); break; case DWARF_VALUE_S16: printf("SWORD) = %d (x%04X)\n", (Elf_Sword)attr_value->s16, (Elf_Sword)attr_value->s16); break; case DWARF_VALUE_U32: printf("DWORD) = %u (x%08X)\n", attr_value->u32, attr_value->u32); break; case DWARF_VALUE_S32: printf("SDWORD) = %d (x%08X)\n", attr_value->s32, attr_value->s32); break; case DWARF_VALUE_U64: printf("XWORD) = %" FMT_I64 "u (x%" FMT_I64 "X)\n", attr_value->u64, attr_value->u64); break; case DWARF_VALUE_S64: printf("SXWORD) = %" FMT_I64 "d (x%" FMT_I64 "X)\n", attr_value->s64, attr_value->s64); break; case DWARF_VALUE_STR: printf("STRING) = %s\n", attr_value->str); break; case DWARF_VALUE_PTR32: printf("PTR32) = x%08X\n", attr_value->ptr32); break; case DWARF_VALUE_PTR64: printf("PTR64) = x%08" FMT_I64 "X\n", attr_value->ptr64); break; case DWARF_VALUE_BLOCK: printf("BLOCK) = [%u]:", attr_value->block.block_size); for (Elf_Xword i = 0; i < attr_value->block.block_size; i++) { Elf_Byte prnt = *((const Elf_Byte*)attr_value->block.block_ptr + i); printf(" x%02X", prnt); } printf("\n"); break; case DWARF_VALUE_UNKNOWN: default: printf("UNKNOWN)"); break; } }
33.280255
78
0.712632
wilebeast
1d8704d46a68fa52d829c7de741f6033433ca6a2
29,017
cxx
C++
Plugins/PrismPlugins/vtkPrismFilter.cxx
cjh1/ParaView
b0eba067c87078d5fe56ec3cb21447f149e1f31a
[ "BSD-3-Clause" ]
null
null
null
Plugins/PrismPlugins/vtkPrismFilter.cxx
cjh1/ParaView
b0eba067c87078d5fe56ec3cb21447f149e1f31a
[ "BSD-3-Clause" ]
null
null
null
Plugins/PrismPlugins/vtkPrismFilter.cxx
cjh1/ParaView
b0eba067c87078d5fe56ec3cb21447f149e1f31a
[ "BSD-3-Clause" ]
null
null
null
/*========================================================================= Program: Visualization Toolkit Module: vtkPrismFilter.cxx =========================================================================*/ #include "vtkPrismFilter.h" #include "vtkPrismPrivate.h" #include "vtkDoubleArray.h" #include "vtkFloatArray.h" #include "vtkMath.h" #include "vtkInformation.h" #include "vtkInformationVector.h" #include "vtkObjectFactory.h" #include "vtkStreamingDemandDrivenPipeline.h" #include "vtkPolyData.h" #include "vtkCellArray.h" #include "vtkPointData.h" #include "vtkRectilinearGrid.h" #include "vtkCellData.h" #include "vtkPrismSurfaceReader.h" #include "vtkUnstructuredGrid.h" #include "vtkSmartPointer.h" #include "vtkPoints.h" #include "vtkMultiBlockDataSet.h" #include "vtkCompositeDataIterator.h" #include "vtkExtractGeometry.h" #include "vtkBox.h" #include "vtkDataObject.h" #include <math.h> vtkStandardNewMacro(vtkPrismFilter); class vtkPrismFilter::MyInternal { public: bool SimulationDataThreshold; vtkSmartPointer<vtkExtractGeometry > ExtractGeometry; vtkSmartPointer<vtkBox> Box; vtkPrismSurfaceReader *Reader; vtkSmartPointer<vtkDoubleArray> RangeArray; std::string AxisVarName[3]; MyInternal() { this->SimulationDataThreshold=false; this->RangeArray = vtkSmartPointer<vtkDoubleArray>::New(); this->RangeArray->Initialize(); this->RangeArray->SetNumberOfComponents(1); this->Reader = vtkPrismSurfaceReader::New(); this->AxisVarName[0] = "none"; this->AxisVarName[1] = "none"; this->AxisVarName[2] = "none"; this->ExtractGeometry=vtkSmartPointer<vtkExtractGeometry >::New(); this->Box= vtkSmartPointer<vtkBox>::New(); this->ExtractGeometry->SetImplicitFunction(this->Box); this->ExtractGeometry->ExtractInsideOn(); this->ExtractGeometry->ExtractBoundaryCellsOn(); } ~MyInternal() { if(this->Reader) { this->Reader->Delete(); } } }; //---------------------------------------------------------------------------- vtkPrismFilter::vtkPrismFilter() { this->Internal = new MyInternal(); this->SetNumberOfInputPorts(1); this->SetNumberOfOutputPorts(4); } //---------------------------------------------------------------------------- vtkPrismFilter::~vtkPrismFilter() { delete this->Internal; } //---------------------------------------------------------------------------- void vtkPrismFilter::SetSimulationDataThreshold(bool b) { this->Internal->SimulationDataThreshold=b; this->Modified(); } //---------------------------------------------------------------------------- bool vtkPrismFilter::GetSimulationDataThreshold() { return this->Internal->SimulationDataThreshold; } //---------------------------------------------------------------------------- unsigned long vtkPrismFilter::GetMTime() { unsigned long time = this->Superclass::GetMTime(); unsigned long readertime = this->Internal->Reader->GetMTime(); return time > readertime ? time : readertime; } //---------------------------------------------------------------------------- int vtkPrismFilter::IsValidFile() { if(!this->Internal->Reader) { return 0; } return this->Internal->Reader->IsValidFile(); } //---------------------------------------------------------------------------- void vtkPrismFilter::SetFileName(const char* file) { if(!this->Internal->Reader) { return; } this->Internal->Reader->SetFileName(file); } //---------------------------------------------------------------------------- const char* vtkPrismFilter::GetFileName() { if(!this->Internal->Reader) { return NULL; } return this->Internal->Reader->GetFileName(); } //---------------------------------------------------------------------------- int vtkPrismFilter::GetNumberOfTableIds() { if(!this->Internal->Reader) { return 0; } return this->Internal->Reader->GetNumberOfTableIds(); } //---------------------------------------------------------------------------- int* vtkPrismFilter::GetTableIds() { if(!this->Internal->Reader) { return NULL; } return this->Internal->Reader->GetTableIds(); } //---------------------------------------------------------------------------- vtkIntArray* vtkPrismFilter::GetTableIdsAsArray() { if(!this->Internal->Reader) { return NULL; } return this->Internal->Reader->GetTableIdsAsArray(); } //---------------------------------------------------------------------------- void vtkPrismFilter::SetTable(int tableId) { if(!this->Internal->Reader) { return ; } this->Internal->Reader->SetTable(tableId); } //---------------------------------------------------------------------------- int vtkPrismFilter::GetTable() { if(!this->Internal->Reader) { return 0; } return this->Internal->Reader->GetTable(); } //---------------------------------------------------------------------------- int vtkPrismFilter::GetNumberOfTableArrayNames() { if(!this->Internal->Reader) { return 0; } return this->Internal->Reader->GetNumberOfTableArrayNames(); } //---------------------------------------------------------------------------- const char* vtkPrismFilter::GetTableArrayName(int index) { if(!this->Internal->Reader) { return NULL; } return this->Internal->Reader->GetTableArrayName(index); } //---------------------------------------------------------------------------- void vtkPrismFilter::SetTableArrayToProcess(const char* name) { if(!this->Internal->Reader) { return ; } int numberOfArrays=this->Internal->Reader->GetNumberOfTableArrayNames(); for(int i=0;i<numberOfArrays;i++) { this->Internal->Reader->SetTableArrayStatus(this->Internal->Reader->GetTableArrayName(i), 0); } this->Internal->Reader->SetTableArrayStatus(name, 1); this->SetInputArrayToProcess( 0, 0, 0, vtkDataObject::FIELD_ASSOCIATION_POINTS, name ); } //---------------------------------------------------------------------------- const char* vtkPrismFilter::GetTableArrayNameToProcess() { int numberOfArrays; int i; numberOfArrays=this->Internal->Reader->GetNumberOfTableArrayNames(); for(i=0;i<numberOfArrays;i++) { if(this->Internal->Reader->GetTableArrayStatus(this->Internal->Reader->GetTableArrayName(i))) { return this->Internal->Reader->GetTableArrayName(i); } } return NULL; } //---------------------------------------------------------------------------- void vtkPrismFilter::SetTableArrayStatus(const char* name, int flag) { if(!this->Internal->Reader) { return ; } return this->Internal->Reader->SetTableArrayStatus(name , flag); } //---------------------------------------------------------------------------- int vtkPrismFilter::GetTableArrayStatus(const char* name) { if(!this->Internal->Reader) { return 0 ; } return this->Internal->Reader->GetTableArrayStatus(name); } //---------------------------------------------------------------------------- int vtkPrismFilter::RequestData( vtkInformation *request, vtkInformationVector **inputVector, vtkInformationVector *outputVector) { this->RequestSESAMEData(request, inputVector,outputVector); this->RequestGeometryData(request, inputVector,outputVector); return 1; } //---------------------------------------------------------------------------- int vtkPrismFilter::RequestSESAMEData( vtkInformation *vtkNotUsed(request), vtkInformationVector **vtkNotUsed(inputVector), vtkInformationVector *outputVector) { std::string filename=this->Internal->Reader->GetFileName(); if(filename.empty()) { return 1; } this->Internal->Reader->Update(); vtkInformation *outInfo = outputVector->GetInformationObject(0); vtkPointSet *output = vtkPointSet::SafeDownCast( outInfo->Get(vtkDataObject::DATA_OBJECT())); vtkPointSet *input= this->Internal->Reader->GetOutput(0); output->ShallowCopy(input); vtkInformation *curveOutInfo = outputVector->GetInformationObject(1); vtkPointSet *curveOutput = vtkPointSet::SafeDownCast( curveOutInfo->Get(vtkDataObject::DATA_OBJECT())); vtkPointSet *curveInput= this->Internal->Reader->GetOutput(1); curveOutput->ShallowCopy(curveInput); vtkInformation *contourOutInfo = outputVector->GetInformationObject(2); vtkPointSet *contourOutput = vtkPointSet::SafeDownCast( contourOutInfo->Get(vtkDataObject::DATA_OBJECT())); contourOutput->ShallowCopy(this->Internal->Reader->GetOutput(2)); //Copy the PRISM_GEOMETRY_BOUNDS and PRISM_THRESHOLD_BOUNDS field data //from output data 1 to 3. This way the points have the same bounds key //as the surface vtkInformation *geomInfo = outputVector->GetInformationObject(3); vtkMultiBlockDataSet *geomOutput = vtkMultiBlockDataSet::SafeDownCast( geomInfo->Get(vtkDataObject::DATA_OBJECT())); //give it the same prism world bounds as the surface //this way we don't scale the world with the points which will cause //the reference surface to change size on each time step. //we want to copy from the input port 1 so we get if the points have any scaling geomOutput->GetFieldData()->PassData(output->GetFieldData()); return 1; } //---------------------------------------------------------------------------- int vtkPrismFilter::CreateGeometry(vtkDataSet *inputData, unsigned int index, vtkMultiBlockDataSet *output) { double weight = 0.0; double *weights = NULL; vtkIdType cellId, ptId; vtkIdType numCells, numPts; vtkIdList *cellPts = NULL; vtkDataArray *inputScalars[3]; vtkSmartPointer<vtkPolyData> polydata = vtkSmartPointer<vtkPolyData>::New(); // construct new points at the centers of the cells vtkPoints *newPoints = vtkPoints::New(); vtkPointData *outPD = polydata->GetPointData(); vtkCellData *outCD = polydata->GetCellData(); vtkPointData *inPD = inputData->GetPointData(); vtkCellData *inCD = inputData->GetCellData(); int maxCellSize = inputData->GetMaxCellSize(); vtkDebugMacro( << "Mapping point data to new cell center point..." ); bool isCellData[3]={true,true,true}; inputScalars[0] = inCD->GetScalars( this->GetXAxisVarName() ); if(!inputScalars[0]) { inputScalars[0] = inPD->GetScalars( this->GetXAxisVarName() ); if(inputScalars[0]) { isCellData[0]=false; } } inputScalars[1] = inCD->GetScalars( this->GetYAxisVarName() ); if(!inputScalars[1]) { inputScalars[1] = inPD->GetScalars( this->GetYAxisVarName() ); if(inputScalars[1]) { isCellData[1]=false; } } inputScalars[2] = inCD->GetScalars( this->GetZAxisVarName() ); if(!inputScalars[2]) { inputScalars[2] = inPD->GetScalars( this->GetZAxisVarName() ); if(inputScalars[2]) { isCellData[2]=false; } } vtkIdType newIDs[1] = {0}; if ( (numCells=inputData->GetNumberOfCells()) < 1 ) { vtkDebugMacro(<< "No input cells, nothing to do." ); return 0; } bool scalingEnabled[3] = {this->GetSESAMEXLogScaling(), this->GetSESAMEYLogScaling(), this->GetSESAMEZLogScaling()}; if(!isCellData[0] && !isCellData[1] && !isCellData[2]) { //All Point Data. weights = new double[maxCellSize]; cellPts = vtkIdList::New(); cellPts->Allocate( maxCellSize ); // Pass cell data (note that this passes current cell data through to the // new points that will be created at the cell centers) outCD->PassData( inCD ); // create space for the newly interpolated values outPD->CopyAllocate( inPD,numCells ); int abort=0; //double funcArgs[3] = { 0.0, 0.0, 0.0 }; double newPt[3] = {0.0, 0.0, 0.0}; vtkIdType progressInterval=numCells/20 + 1; polydata->Allocate( numCells ); for ( cellId=0; cellId < numCells && !abort; cellId++ ) { if ( !(cellId % progressInterval) ) { this->UpdateProgress( (double)cellId/numCells ); abort = GetAbortExecute(); } inputData->GetCellPoints( cellId, cellPts ); numPts = cellPts->GetNumberOfIds(); if ( numPts > 0 ) { weight = 1.0 / numPts; for (ptId=0; ptId < numPts; ptId++) { weights[ptId] = weight; } outPD->InterpolatePoint(inPD, cellId, cellPts, weights); } inputScalars[0] = outPD->GetScalars( this->GetXAxisVarName() ); inputScalars[1] = outPD->GetScalars( this->GetYAxisVarName() ); inputScalars[2] = outPD->GetScalars( this->GetZAxisVarName() ); newPt[0] = inputScalars[0]->GetTuple( cellId )[0]; newPt[1] = inputScalars[1]->GetTuple( cellId )[0]; newPt[2] = inputScalars[2]->GetTuple( cellId )[0]; vtkPrismCommon::logScale(newPt,scalingEnabled); newIDs[0] = newPoints->InsertNextPoint( newPt ); polydata->InsertNextCell( VTK_VERTEX, 1, newIDs ); } } else if(isCellData[0] && isCellData[1] && isCellData[2]) { //All Cell Data. weights = new double[maxCellSize]; cellPts = vtkIdList::New(); cellPts->Allocate( maxCellSize ); // Pass cell data (note that this passes current cell data through to the // new points that will be created at the cell centers) outCD->PassData( inCD ); // create space for the newly interpolated values outPD->CopyAllocate( inPD,numCells ); int abort=0; //double funcArgs[3] = { 0.0, 0.0, 0.0 }; double newPt[3] = {0.0, 0.0, 0.0}; vtkIdType progressInterval=numCells/20 + 1; polydata->Allocate( numCells ); for ( cellId=0; cellId < numCells && !abort; cellId++ ) { if ( !(cellId % progressInterval) ) { this->UpdateProgress( (double)cellId/numCells ); abort = GetAbortExecute(); } inputData->GetCellPoints( cellId, cellPts ); numPts = cellPts->GetNumberOfIds(); if ( numPts > 0 ) { weight = 1.0 / numPts; for (ptId=0; ptId < numPts; ptId++) { weights[ptId] = weight; } outPD->InterpolatePoint(inPD, cellId, cellPts, weights); } newPt[0] = inputScalars[0]->GetTuple( cellId )[0]; newPt[1] = inputScalars[1]->GetTuple( cellId )[0]; newPt[2] = inputScalars[2]->GetTuple( cellId )[0]; vtkPrismCommon::logScale(newPt,scalingEnabled); newIDs[0] = newPoints->InsertNextPoint( newPt ); polydata->InsertNextCell( VTK_VERTEX, 1, newIDs ); } } else { //Mixed input array types between cell and point. We can't handle this right now. vtkDebugMacro(<< "Error: Prism can't handle mixed cell and point data" ); return 0; } polydata->SetPoints( newPoints ); newPoints->Delete(); polydata->Squeeze(); cellPts->Delete(); delete [] weights; output->SetBlock(index,polydata); return 1; } //---------------------------------------------------------------------------- int vtkPrismFilter::RequestGeometryData( vtkInformation *vtkNotUsed(request), vtkInformationVector **inputVector, vtkInformationVector *outputVector) { if( strcmp(this->GetXAxisVarName(), "none") == 0) { return 1; } vtkInformation *info = outputVector->GetInformationObject(3); vtkMultiBlockDataSet *output = vtkMultiBlockDataSet::SafeDownCast( info->Get(vtkDataObject::DATA_OBJECT())); if ( !output ) { vtkDebugMacro( << "No output found." ); return 0; } vtkInformation *inInfo = inputVector[0]->GetInformationObject(0); vtkMultiBlockDataSet *inputMB = vtkMultiBlockDataSet::SafeDownCast( inInfo->Get(vtkDataObject::DATA_OBJECT())); if (inputMB ) { unsigned int j=0; vtkCompositeDataIterator* iter= inputMB->NewIterator(); iter->SkipEmptyNodesOn(); iter->TraverseSubTreeOn(); iter->VisitOnlyLeavesOn(); iter->GoToFirstItem(); while(!iter->IsDoneWithTraversal()) { vtkDataSet *inputData=NULL; inputData=vtkDataSet::SafeDownCast(iter->GetCurrentDataObject()); iter->GoToNextItem(); if(inputData) { this->CreateGeometry(inputData,j,output); j++; } } iter->Delete(); return 1; } vtkDataSet *inputDS = vtkDataSet::SafeDownCast( inInfo->Get(vtkDataObject::DATA_OBJECT())); if(inputDS) { this->CreateGeometry(inputDS,0,output); return 1; } else { vtkDebugMacro( << "Incorrect input type." ); return 0; } return 1; } //---------------------------------------------------------------------------- vtkDoubleArray* vtkPrismFilter::GetRanges() { this->Internal->Reader->GetRanges(this->Internal->RangeArray); return this->Internal->RangeArray; } //---------------------------------------------------------------------------- void vtkPrismFilter::SetXAxisVarName( const char *name ) { this->Internal->AxisVarName[0]=name; this->Modified(); } //---------------------------------------------------------------------------- void vtkPrismFilter::SetYAxisVarName( const char *name ) { this->Internal->AxisVarName[1]=name; this->Modified(); } //---------------------------------------------------------------------------- void vtkPrismFilter::SetZAxisVarName( const char *name ) { this->Internal->AxisVarName[2]=name; this->Modified(); } //---------------------------------------------------------------------------- const char * vtkPrismFilter::GetXAxisVarName() { return this->Internal->AxisVarName[0].c_str(); } //---------------------------------------------------------------------------- const char * vtkPrismFilter::GetYAxisVarName() { return this->Internal->AxisVarName[1].c_str(); } //---------------------------------------------------------------------------- const char * vtkPrismFilter::GetZAxisVarName() { return this->Internal->AxisVarName[2].c_str(); } //---------------------------------------------------------------------------- int vtkPrismFilter::FillOutputPortInformation( int port, vtkInformation* info) { if(port==0) { // now add our info info->Set(vtkDataObject::DATA_TYPE_NAME(), "vtkPolyData"); } if(port==1) { // now add our info info->Set(vtkDataObject::DATA_TYPE_NAME(), "vtkPolyData"); } if(port==2) { // now add our info info->Set(vtkDataObject::DATA_TYPE_NAME(), "vtkPolyData"); } if(port==3) { info->Set(vtkDataObject::DATA_TYPE_NAME(), "vtkMultiBlockDataSet"); } return 1; } //---------------------------------------------------------------------------- int vtkPrismFilter::FillInputPortInformation( int vtkNotUsed(port), vtkInformation* info) { // now add our info info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkDataObject"); return 1; } //---------------------------------------------------------------------------- void vtkPrismFilter::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); os << indent << "Not Implemented: " << "\n"; } //---------------------------------------------------------------------------- void vtkPrismFilter::SetSESAMEXAxisVarName( const char *name ) { this->Internal->Reader->SetXAxisVarName(name); } //---------------------------------------------------------------------------- void vtkPrismFilter::SetSESAMEYAxisVarName( const char *name ) { this->Internal->Reader->SetYAxisVarName(name); } //---------------------------------------------------------------------------- void vtkPrismFilter::SetSESAMEZAxisVarName( const char *name ) { this->Internal->Reader->SetZAxisVarName(name); } //---------------------------------------------------------------------------- const char* vtkPrismFilter::GetSESAMEXAxisVarName() { return this->Internal->Reader->GetXAxisVarName(); } //---------------------------------------------------------------------------- const char* vtkPrismFilter::GetSESAMEYAxisVarName() { return this->Internal->Reader->GetYAxisVarName(); } //---------------------------------------------------------------------------- const char* vtkPrismFilter::GetSESAMEZAxisVarName() { return this->Internal->Reader->GetZAxisVarName(); } //---------------------------------------------------------------------------- void vtkPrismFilter::SetShowCold(bool b) { this->Internal->Reader->SetShowCold(b); this->Modified(); } //---------------------------------------------------------------------------- void vtkPrismFilter::SetShowVaporization(bool b) { this->Internal->Reader->SetShowVaporization(b); this->Modified(); } //---------------------------------------------------------------------------- void vtkPrismFilter::SetShowSolidMelt(bool b) { this->Internal->Reader->SetShowSolidMelt(b); this->Modified(); } //---------------------------------------------------------------------------- void vtkPrismFilter::SetShowLiquidMelt(bool b) { this->Internal->Reader->SetShowLiquidMelt(b); this->Modified(); } //---------------------------------------------------------------------------- bool vtkPrismFilter::GetShowCold() { return this->Internal->Reader->GetShowCold(); } //---------------------------------------------------------------------------- bool vtkPrismFilter::GetShowVaporization() { return this->Internal->Reader->GetShowVaporization(); } //---------------------------------------------------------------------------- bool vtkPrismFilter::GetShowSolidMelt() { return this->Internal->Reader->GetShowSolidMelt(); } //---------------------------------------------------------------------------- bool vtkPrismFilter::GetShowLiquidMelt() { return this->Internal->Reader->GetShowLiquidMelt(); } //---------------------------------------------------------------------------- void vtkPrismFilter::SetSESAMEXLogScaling(bool b) { this->Internal->Reader->SetXLogScaling(b); } //---------------------------------------------------------------------------- void vtkPrismFilter::SetSESAMEYLogScaling(bool b) { this->Internal->Reader->SetYLogScaling(b); } //---------------------------------------------------------------------------- void vtkPrismFilter::SetSESAMEZLogScaling(bool b) { this->Internal->Reader->SetZLogScaling(b); } //---------------------------------------------------------------------------- bool vtkPrismFilter::GetSESAMEXLogScaling() { return this->Internal->Reader->GetXLogScaling(); } //---------------------------------------------------------------------------- bool vtkPrismFilter::GetSESAMEYLogScaling() { return this->Internal->Reader->GetYLogScaling(); } //---------------------------------------------------------------------------- bool vtkPrismFilter::GetSESAMEZLogScaling() { return this->Internal->Reader->GetZLogScaling(); } //---------------------------------------------------------------------------- void vtkPrismFilter::SetSESAMEVariableConversionValues(int i, double value) { this->Internal->Reader->SetVariableConversionValues(i,value); this->Modified(); } //---------------------------------------------------------------------------- void vtkPrismFilter::SetNumberOfSESAMEVariableConversionValues(int v) { this->Internal->Reader->SetNumberOfVariableConversionValues(v); } //---------------------------------------------------------------------------- double vtkPrismFilter::GetSESAMEVariableConversionValue(int i) { return this->Internal->Reader->GetVariableConversionValue(i); } //---------------------------------------------------------------------------- void vtkPrismFilter::AddSESAMEVariableConversionNames(char* value) { this->Internal->Reader->AddVariableConversionNames(value); this->Modified(); } //---------------------------------------------------------------------------- void vtkPrismFilter::RemoveAllSESAMEVariableConversionNames() { this->Internal->Reader->RemoveAllVariableConversionNames(); this->Modified(); } //---------------------------------------------------------------------------- const char * vtkPrismFilter::GetSESAMEVariableConversionName(int i) { return this->Internal->Reader->GetVariableConversionName(i); } //---------------------------------------------------------------------------- vtkDoubleArray* vtkPrismFilter:: GetSESAMEXRange() { return this->Internal->Reader->GetXRange(); } //---------------------------------------------------------------------------- vtkDoubleArray* vtkPrismFilter:: GetSESAMEYRange() { return this->Internal->Reader->GetYRange(); } //---------------------------------------------------------------------------- void vtkPrismFilter::SetThresholdSESAMEXBetween(double lower, double upper) { this->Internal->Reader->SetThresholdXBetween(lower,upper); } //---------------------------------------------------------------------------- void vtkPrismFilter::SetThresholdSESAMEYBetween(double lower, double upper) { this->Internal->Reader->SetThresholdYBetween(lower,upper); } //---------------------------------------------------------------------------- double* vtkPrismFilter::GetSESAMEXThresholdBetween() { return this->Internal->Reader->GetXThresholdBetween(); } //---------------------------------------------------------------------------- void vtkPrismFilter::GetSESAMEXThresholdBetween (double &_arg1, double &_arg2) { return this->Internal->Reader->GetXThresholdBetween(_arg1,_arg2); } //---------------------------------------------------------------------------- void vtkPrismFilter::GetSESAMEXThresholdBetween (double _arg[2]) { this->Internal->Reader->GetXThresholdBetween(_arg); } //---------------------------------------------------------------------------- double* vtkPrismFilter::GetSESAMEYThresholdBetween() { return this->Internal->Reader->GetYThresholdBetween(); } //---------------------------------------------------------------------------- void vtkPrismFilter::GetSESAMEYThresholdBetween (double &_arg1, double &_arg2) { return this->Internal->Reader->GetYThresholdBetween(_arg1,_arg2); } //---------------------------------------------------------------------------- void vtkPrismFilter::GetSESAMEYThresholdBetween (double _arg[2]) { this->Internal->Reader->GetYThresholdBetween(_arg); } //---------------------------------------------------------------------------- void vtkPrismFilter::SetWarpSESAMESurface(bool b) { this->Internal->Reader->SetWarpSurface(b); } //---------------------------------------------------------------------------- void vtkPrismFilter::SetDisplaySESAMEContours(bool b) { this->Internal->Reader->SetDisplayContours(b); } //---------------------------------------------------------------------------- void vtkPrismFilter::SetSESAMEContourVarName( const char *name ) { this->Internal->Reader->SetContourVarName(name); } //---------------------------------------------------------------------------- const char* vtkPrismFilter::GetSESAMEContourVarName() { return this->Internal->Reader->GetContourVarName(); } //---------------------------------------------------------------------------- vtkDoubleArray* vtkPrismFilter:: GetSESAMEContourVarRange() { return this->Internal->Reader->GetContourVarRange(); } //---------------------------------------------------------------------------- void vtkPrismFilter::SetSESAMEContourValue(int i, double value) { this->Internal->Reader->SetContourValue(i,value); } //---------------------------------------------------------------------------- double vtkPrismFilter::GetSESAMEContourValue(int i) { return this->Internal->Reader->GetContourValue(i); } //---------------------------------------------------------------------------- double* vtkPrismFilter::GetSESAMEContourValues() { return this->Internal->Reader->GetContourValues(); } //---------------------------------------------------------------------------- void vtkPrismFilter::GetSESAMEContourValues(double *contourValues) { this->Internal->Reader->GetContourValues(contourValues); } //---------------------------------------------------------------------------- void vtkPrismFilter::SetNumberOfSESAMEContours(int i) { this->Internal->Reader->SetNumberOfContours(i); } //---------------------------------------------------------------------------- vtkStringArray* vtkPrismFilter:: GetSESAMEAxisVarNames() { return this->Internal->Reader->GetAxisVarNames(); }
29.339737
101
0.524313
cjh1
1d8848ae58ddd94865c7ba6003358f0278906b9b
657
cc
C++
chrome/browser/ui/views/frame/immersive_mode_controller_factory_ash.cc
kjthegod/chromium
cf940f7f418436b77e15b1ea23e6fa100ca1c91a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2019-11-28T10:46:52.000Z
2019-11-28T10:46:52.000Z
chrome/browser/ui/views/frame/immersive_mode_controller_factory_ash.cc
kjthegod/chromium
cf940f7f418436b77e15b1ea23e6fa100ca1c91a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/browser/ui/views/frame/immersive_mode_controller_factory_ash.cc
kjthegod/chromium
cf940f7f418436b77e15b1ea23e6fa100ca1c91a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2015-03-27T11:15:39.000Z
2016-08-17T14:19:56.000Z
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/host_desktop.h" #include "chrome/browser/ui/views/frame/immersive_mode_controller_ash.h" #include "chrome/browser/ui/views/frame/immersive_mode_controller_stub.h" namespace chrome { ImmersiveModeController* CreateImmersiveModeController( chrome::HostDesktopType host_desktop_type) { if (host_desktop_type == chrome::HOST_DESKTOP_TYPE_ASH) return new ImmersiveModeControllerAsh(); return new ImmersiveModeControllerStub(); } } // namespace chrome
32.85
73
0.794521
kjthegod
1d8a781b17462e186cc72bd38c078f3fecca5161
2,085
cpp
C++
source/ashes/renderer/D3D11Renderer/Command/Commands/D3D11CopyImageCommand.cpp
DragonJoker/Ashes
a6ed950b3fd8fb9626c60b4291fbd52ea75ac66e
[ "MIT" ]
227
2018-09-17T16:03:35.000Z
2022-03-19T02:02:45.000Z
source/ashes/renderer/D3D11Renderer/Command/Commands/D3D11CopyImageCommand.cpp
DragonJoker/RendererLib
0f8ad8edec1b0929ebd10247d3dd0a9ee8f8c91a
[ "MIT" ]
39
2018-02-06T22:22:24.000Z
2018-08-29T07:11:06.000Z
source/ashes/renderer/D3D11Renderer/Command/Commands/D3D11CopyImageCommand.cpp
DragonJoker/Ashes
a6ed950b3fd8fb9626c60b4291fbd52ea75ac66e
[ "MIT" ]
8
2019-05-04T10:33:32.000Z
2021-04-05T13:19:27.000Z
/* This file belongs to Ashes. See LICENSE file in root folder. */ #include "Command/Commands/D3D11CopyImageCommand.hpp" #include "Image/D3D11Image.hpp" #include "Image/D3D11ImageView.hpp" #include "ashesd3d11_api.hpp" namespace ashes::d3d11 { namespace { D3D11_BOX doGetSrcBox( VkImageCopy const & copyInfo ) { return { UINT( copyInfo.srcOffset.x ), UINT( copyInfo.srcOffset.y ), UINT( copyInfo.srcOffset.z ), UINT( copyInfo.srcOffset.x ) + copyInfo.extent.width, UINT( copyInfo.srcOffset.y ) + copyInfo.extent.height, UINT( copyInfo.srcOffset.z ) + copyInfo.extent.depth, }; } } CopyImageCommand::CopyImageCommand( VkDevice device , VkImageCopy const & copyInfo , VkImage src , VkImage dst ) : CommandBase{ device } , m_src{ src } , m_dst{ dst } , m_copyInfo{ copyInfo } , m_srcBox{ doGetSrcBox( m_copyInfo ) } , m_srcSubresource{ D3D11CalcSubresource( m_copyInfo.srcSubresource.mipLevel , m_copyInfo.srcSubresource.baseArrayLayer , get( m_src )->getMipmapLevels() ) } , m_dstSubresource{ D3D11CalcSubresource( m_copyInfo.dstSubresource.mipLevel , m_copyInfo.dstSubresource.baseArrayLayer , get( m_dst )->getMipmapLevels() ) } { } void CopyImageCommand::apply( Context const & context )const { if ( isDepthOrStencilFormat( get( m_src )->getFormat() ) ) { context.context->CopySubresourceRegion( get( m_dst )->getResource() , m_dstSubresource , 0 , 0 , 0 , get( m_src )->getResource() , m_srcSubresource , nullptr ); } else { context.context->CopySubresourceRegion( get( m_dst )->getResource() , m_dstSubresource , UINT( m_copyInfo.dstOffset.x ) , UINT( m_copyInfo.dstOffset.y ) , UINT( m_copyInfo.dstOffset.z ) , get( m_src )->getResource() , m_srcSubresource , &m_srcBox ); } auto dstMemory = get( m_dst )->getMemory(); get( dstMemory )->updateDownload( 0u, get( m_dst )->getMemoryRequirements().size, 0u ); } CommandPtr CopyImageCommand::clone()const { return std::make_unique< CopyImageCommand >( *this ); } }
25.426829
89
0.686331
DragonJoker
1d91e4e76e434ac4473d937835788a3d1703d8f2
1,378
cpp
C++
038.cpp
LeeYiyuan/projecteuler
81a0b65f73b47fbb9bfe99cb5ff72da7e0ba0d74
[ "MIT" ]
null
null
null
038.cpp
LeeYiyuan/projecteuler
81a0b65f73b47fbb9bfe99cb5ff72da7e0ba0d74
[ "MIT" ]
null
null
null
038.cpp
LeeYiyuan/projecteuler
81a0b65f73b47fbb9bfe99cb5ff72da7e0ba0d74
[ "MIT" ]
null
null
null
/* We are considering the concatenated product of an integer a with (1, 2, ..., n) with n > 1, i.e. n >= 2. If a >= 10000, then 2a >= 20000. As such, the concatenated product will have at least 10 digits. By the pigeonhole principle, one of the digit will occur at least twice, making it non pandigital. As such we only need consider a < 10000. Also since all valid products are exactly 9 digits long, we can compare the strings directly instead of having to convert them into a numerical. */ #include <iostream> #include <string> #include <algorithm> #include <vector> int main() { std::string max_product_string = "000000000"; std::vector<char> pandigital_digits = { '1', '2', '3', '4', '5', '6', '7', '8', '9' }; for (int a = 1; a < 10000; a++) { std::string product_string = ""; int n = 1; while (product_string.length() < 8) // Extend to at least 9 digits long. { product_string += std::to_string(n * a); n++; } if (product_string.length() != 9) // If not possible to produce exactly 9 digits. continue; if (std::is_permutation(product_string.begin(), product_string.end(), pandigital_digits.begin())) max_product_string = std::max(max_product_string, product_string); } std::cout << max_product_string; }
32.809524
105
0.618287
LeeYiyuan
1d95ef6eb38128f0002cf42c70e45e230ba12aab
21,527
cc
C++
examples/uintTest/ffmpeg/ffmpeg_enc_mux_test.cc
rockchip-linux/rkmedia
992663e9069e8426f5a71f4045666786b3bd4bcf
[ "BSD-3-Clause" ]
23
2020-02-29T10:47:22.000Z
2022-01-20T01:52:21.000Z
examples/uintTest/ffmpeg/ffmpeg_enc_mux_test.cc
rockchip-linux/rkmedia
992663e9069e8426f5a71f4045666786b3bd4bcf
[ "BSD-3-Clause" ]
13
2020-05-12T15:11:04.000Z
2021-12-02T05:48:39.000Z
examples/uintTest/ffmpeg/ffmpeg_enc_mux_test.cc
rockchip-linux/rkmedia
992663e9069e8426f5a71f4045666786b3bd4bcf
[ "BSD-3-Clause" ]
19
2020-01-12T04:07:33.000Z
2022-02-18T08:43:19.000Z
// Copyright 2019 Fuzhou Rockchip Electronics Co., Ltd. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifdef NDEBUG #undef NDEBUG #endif #ifndef DEBUG #define DEBUG #endif #include <assert.h> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <cmath> #include <string> #include <unordered_map> extern "C" { #define __STDC_CONSTANT_MACROS #include <libavformat/avformat.h> } #include "buffer.h" #include "encoder.h" #include "key_string.h" #include "muxer.h" #include "media_type.h" #ifndef M_PI #define M_PI 3.14159265358979323846 /* pi */ #endif static const int aac_sample_rates[] = { 96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 0 }; static int free_memory(void *buffer) { assert(buffer); free(buffer); return 0; } std::shared_ptr<easymedia::MediaBuffer> adts_get_extradata(SampleInfo sample_info) { size_t dsi_size = 2; char *ptr = (char*)malloc(dsi_size); assert(ptr); uint32_t sample_rate_idx = 0; for (; aac_sample_rates[sample_rate_idx] != 0; sample_rate_idx++) if (sample_info.sample_rate == aac_sample_rates[sample_rate_idx]) break; uint32_t object_type = 2; // AAC LC by default ptr[0] = (object_type << 3) | (sample_rate_idx >> 1); ptr[1] = ((sample_rate_idx & 1) << 7) | (sample_info.channels << 3); std::shared_ptr<easymedia::MediaBuffer> extra_data = std::make_shared<easymedia::MediaBuffer>(ptr, dsi_size, -1, ptr, free_memory); extra_data->SetValidSize(dsi_size); return extra_data; } template <typename Encoder> int encode(std::shared_ptr<easymedia::Muxer> mux, std::shared_ptr<easymedia::Stream> file_write, std::shared_ptr<Encoder> encoder, std::shared_ptr<easymedia::MediaBuffer> src, int stream_no) { auto enc = encoder; int ret = enc->SendInput(src); if (ret < 0) { fprintf(stderr, "[%d]: frame encode failed, ret=%d\n", stream_no, ret); return -1; } while (ret >= 0) { auto out = enc->FetchOutput(); if (!out) { if (errno != EAGAIN) { fprintf(stderr, "[%d]: frame fetch failed, ret=%d\n", stream_no, errno); ret = errno; } break; } size_t out_len = out->GetValidSize(); if (out_len == 0) break; fprintf(stderr, "[%d]: frame encoded, out %zu bytes\n\n", stream_no, out_len); if (mux) mux->Write(out, stream_no); if (file_write) file_write->Write(out->GetPtr(), 1, out_len); } return ret; } std::shared_ptr<easymedia::AudioEncoder> initAudioEncoder(std::string EncoderName, std::string EncType, SampleInfo& sample) { std::string param; PARAM_STRING_APPEND(param, KEY_OUTPUTDATATYPE, EncType); auto aud_enc = easymedia::REFLECTOR(Encoder)::Create<easymedia::AudioEncoder>( EncoderName.c_str(), param.c_str()); if (!aud_enc) { fprintf(stderr, "Create %s encoder failed\n", EncoderName.c_str()); exit(EXIT_FAILURE); } MediaConfig aud_enc_config; auto &ac = aud_enc_config.aud_cfg; ac.sample_info = sample; ac.bit_rate = 64000; // 64kbps ac.codec_type = StringToCodecType(EncType.c_str()); aud_enc_config.type = Type::Audio; if (!aud_enc->InitConfig(aud_enc_config)) { fprintf(stderr, "Init config of ffmpeg_aud encoder failed\n"); exit(EXIT_FAILURE); } return aud_enc; } std::shared_ptr<easymedia::VideoEncoder> initVideoEncoder(std::string EncoderName, std::string SrcFormat, std::string OutFormat, int w, int h) { std::string param; PARAM_STRING_APPEND(param, KEY_OUTPUTDATATYPE, OutFormat); // If not rkmpp, then it is ffmpeg if (EncoderName == "ffmpeg_vid") { if (OutFormat == "video:h264") { PARAM_STRING_APPEND(param, KEY_NAME, "libx264"); } else if (OutFormat == "video:h265") { PARAM_STRING_APPEND(param, KEY_NAME, "libx265"); } else { exit(EXIT_FAILURE); } } auto vid_enc = easymedia::REFLECTOR(Encoder)::Create<easymedia::VideoEncoder>( EncoderName.c_str(), param.c_str()); if (!vid_enc) { fprintf(stderr, "Create encoder %s failed\n", EncoderName.c_str()); exit(EXIT_FAILURE); } PixelFormat fmt = PIX_FMT_NONE; if (SrcFormat == "nv12") { fmt = PIX_FMT_NV12; } else if (SrcFormat == "yuv420p") { fmt = PIX_FMT_YUV420P; } else { fprintf(stderr, "TO BE TESTED <%s:%s,%d>\n", __FILE__, __FUNCTION__, __LINE__); exit(EXIT_FAILURE); } // TODO SrcFormat and OutFormat use the same variable ImageInfo vid_info = {fmt, w, h, w, h}; if (EncoderName == "rkmpp") { vid_info.vir_width = UPALIGNTO16(w); vid_info.vir_height = UPALIGNTO16(h); } MediaConfig vid_enc_config; if (OutFormat == VIDEO_H264 || OutFormat == VIDEO_H265) { VideoConfig &vid_cfg = vid_enc_config.vid_cfg; ImageConfig &img_cfg = vid_cfg.image_cfg; img_cfg.image_info = vid_info; vid_cfg.qp_init = 24; vid_cfg.qp_step = 4; vid_cfg.qp_min = 12; vid_cfg.qp_max = 48; vid_cfg.bit_rate = w * h * 7; if (vid_cfg.bit_rate > 1000000) { vid_cfg.bit_rate /= 1000000; vid_cfg.bit_rate *= 1000000; } vid_cfg.frame_rate = 30; vid_cfg.level = 52; vid_cfg.gop_size = 10; // vid_cfg.frame_rate; vid_cfg.profile = 100; // vid_cfg.rc_quality = "aq_only"; vid_cfg.rc_mode = "vbr"; vid_cfg.rc_quality = KEY_HIGHEST; vid_cfg.rc_mode = KEY_CBR; vid_enc_config.type = Type::Video; } else { // TODO assert(0); } if (!vid_enc->InitConfig(vid_enc_config)) { fprintf(stderr, "Init config of encoder %s failed\n", EncoderName.c_str()); exit(EXIT_FAILURE); } return vid_enc; } std::shared_ptr<easymedia::SampleBuffer> initAudioBuffer(MediaConfig &cfg) { auto &audio_info = cfg.aud_cfg.sample_info; fprintf(stderr, "sample number=%d\n", audio_info.nb_samples); int aud_size = GetSampleSize(audio_info) * audio_info.nb_samples; auto aud_mb = easymedia::MediaBuffer::Alloc2(aud_size); auto aud_buffer = std::make_shared<easymedia::SampleBuffer>(aud_mb, audio_info); aud_buffer->SetValidSize(aud_size); assert(aud_buffer && (int)aud_buffer->GetSize() >= aud_size); return aud_buffer; } std::shared_ptr<easymedia::MediaBuffer> initVideoBuffer(std::string &EncoderName, ImageInfo &image_info) { // The vir_width/vir_height have aligned when init video encoder size_t len = CalPixFmtSize(image_info); fprintf(stderr, "video buffer len %zu\n", len); // Just treat all aligned memory to be hardware memory // need to know rkmpp needs DRM managed memory, // but ffmpeg software encoder doesn't need. easymedia::MediaBuffer::MemType MemType = EncoderName == "rkmpp" ? easymedia::MediaBuffer::MemType::MEM_HARD_WARE : easymedia::MediaBuffer::MemType::MEM_COMMON; auto &&src_mb = easymedia::MediaBuffer::Alloc2( len, MemType); assert(src_mb.GetSize() > 0); auto src_buffer = std::make_shared<easymedia::ImageBuffer>(src_mb, image_info); assert(src_buffer && src_buffer->GetSize() >= len); return src_buffer; } std::shared_ptr<easymedia::Muxer> initMuxer(std::string &output_path) { easymedia::REFLECTOR(Muxer)::DumpFactories(); std::string param; char* cut = strrchr((char*)output_path.c_str(), '.'); if (cut) { std::string output_data_type = cut + 1; if (output_data_type == "mp4") { PARAM_STRING_APPEND(param, KEY_OUTPUTDATATYPE, "mp4"); } else if (output_data_type == "aac") { PARAM_STRING_APPEND(param, KEY_OUTPUTDATATYPE, "adts"); } } PARAM_STRING_APPEND(param, KEY_PATH, output_path); return easymedia::REFLECTOR(Muxer)::Create<easymedia::Muxer>( "ffmpeg", param.c_str()); } std::shared_ptr<easymedia::Stream> initFileWrite(std::string &output_path) { std::string stream_name = "file_write_stream"; std::string params = ""; PARAM_STRING_APPEND(params, KEY_PATH, output_path.c_str()); PARAM_STRING_APPEND(params, KEY_OPEN_MODE, "we"); // write and close-on-exec return easymedia::REFLECTOR(Stream):: Create<easymedia::Stream>(stream_name.c_str(), params.c_str()); } std::shared_ptr<easymedia::Stream> initAudioCapture(std::string device, SampleInfo& sample_info) { std::string stream_name = "alsa_capture_stream"; std::string params; std::string fmt_str = SampleFmtToString(sample_info.fmt); std::string rule = "output_data_type=" + fmt_str + "\n"; if (!easymedia::REFLECTOR(Stream)::IsMatch(stream_name.c_str(), rule.c_str())) { fprintf(stderr, "unsupport data type\n"); return nullptr; } PARAM_STRING_APPEND(params, KEY_DEVICE, device.c_str()); PARAM_STRING_APPEND(params, KEY_SAMPLE_FMT, fmt_str); PARAM_STRING_APPEND_TO(params, KEY_CHANNELS, sample_info.channels); PARAM_STRING_APPEND_TO(params, KEY_SAMPLE_RATE, sample_info.sample_rate); printf("%s params:\n%s\n", stream_name.c_str(), params.c_str()); return easymedia::REFLECTOR(Stream)::Create<easymedia::Stream>( stream_name.c_str(), params.c_str()); } static char optstr[] = "?t:i:o:w:h:e:c:"; int main(int argc, char **argv) { int c; std::string input_path; std::string output_path; int w = 0, h = 0; std::string vid_input_format; std::string vid_enc_format; std::string vid_enc_codec_name = "rkmpp"; // rkmpp, ffmpeg_vid std::string aud_enc_format = AUDIO_AAC; // test mp2, aac std::string aud_input_format = AUDIO_PCM_FLTP; std::string aud_enc_codec_name = "ffmpeg_aud"; std::string stream_type; std::string device_name = "default"; opterr = 1; while ((c = getopt(argc, argv, optstr)) != -1) { switch (c) { case 't': stream_type = optarg; break; case 'i': { char *cut = strchr(optarg, ':'); if (cut) { cut[0] = 0; device_name = optarg; if (device_name == "alsa") device_name = cut + 1; } input_path = optarg; } break; case 'o': output_path = optarg; break; case 'w': w = atoi(optarg); break; case 'h': h = atoi(optarg); break; case 'e': { char *cut = strchr(optarg, ':'); if (cut) { cut[0] = 0; char *sub = optarg; if (!strcmp(sub,"aud")) { sub = cut + 1; char *subsub = strchr(sub, '_'); if (subsub) { subsub[0] = 0; aud_input_format = sub; aud_enc_format = subsub + 1; } break; } else if (!strcmp(sub,"vid")) { optarg = cut + 1; } else { exit(EXIT_FAILURE); } } cut = strchr(optarg, '_'); if (!cut) { fprintf(stderr, "input/output format must be cut by \'_\'\n"); exit(EXIT_FAILURE); } cut[0] = 0; vid_input_format = optarg; vid_enc_format = cut + 1; if (vid_enc_format == "h264") vid_enc_format = VIDEO_H264; else if (vid_enc_format == "h265") vid_enc_format = VIDEO_H265; } break; case 'c': { char *cut = strchr(optarg, ':'); if (cut) { cut[0] = 0; char *sub = optarg; if (!strcmp(sub, "aud")) { aud_enc_codec_name = cut + 1; break; } else if (!strcmp(sub, "vid")) { optarg = cut + 1; } else { exit(EXIT_FAILURE); } } cut = strchr(optarg, ':'); if (cut) { cut[0] = 0; std::string ff = optarg; if (ff == "ffmpeg") vid_enc_codec_name = cut + 1; } else { vid_enc_codec_name = optarg; } } break; case '?': default: printf("usage example: \n"); printf("ffmpeg_enc_mux_test -t video_audio -i input.yuv -o output.mp4 -w 320 -h 240 -e " "nv12_h264 -c rkmpp\n"); printf("ffmpeg_enc_mux_test -t audio -i alsa:default -o output.aac -e aud:fltp_aac " "-c aud:ffmpeg_aud\n"); printf("ffmpeg_enc_mux_test -t audio -i alsa:default -o output.mp2 -e aud:s16le_mp2 " "-c aud:ffmpeg_aud\n"); exit(0); } } if (aud_input_format == "u8") { aud_input_format = AUDIO_PCM_U8; } else if (aud_input_format == "s16le") { aud_input_format = AUDIO_PCM_S16; } else if (aud_input_format == "s32le") { aud_input_format = AUDIO_PCM_S32; } else if (aud_input_format == "fltp") { aud_input_format = AUDIO_PCM_FLTP; } if (aud_enc_format == "aac") { aud_enc_format = AUDIO_AAC; } else if (aud_enc_format == "mp2") { aud_enc_format = AUDIO_MP2; } printf("stream type: %s\n", stream_type.c_str()); printf("input file path: %s\n", input_path.c_str()); printf("output file path: %s\n", output_path.c_str()); if (!device_name.empty()) printf("device_name: %s\n", device_name.c_str()); if (stream_type.find("video") != stream_type.npos) { printf("vid_input_format format: %s\n", vid_input_format.c_str()); printf("vid_enc_format format: %s\n", vid_enc_format.c_str()); } if (stream_type.find("audio") != stream_type.npos) { printf("aud_input_format: %s\n", aud_input_format.c_str()); printf("aud_enc_format: %s\n", aud_enc_format.c_str()); } if (input_path.empty() || output_path.empty()) exit(EXIT_FAILURE); if (stream_type.find("video") != stream_type.npos && (!w || !h)) exit(EXIT_FAILURE); if (stream_type.find("video") != stream_type.npos && (vid_input_format.empty() || vid_enc_format.empty())) exit(EXIT_FAILURE); int vid_index = 0; int aud_index = 0; int64_t first_audio_time = 0; int64_t first_video_time = 0; int64_t vinterval_per_frame = 0; int64_t ainterval_per_frame = 0; size_t video_frame_len = 0; std::shared_ptr<easymedia::VideoEncoder> vid_enc = nullptr; std::shared_ptr<easymedia::MediaBuffer> src_buffer = nullptr; std::shared_ptr<easymedia::MediaBuffer> dst_buffer = nullptr; std::shared_ptr<easymedia::Stream> audio_capture = nullptr; std::shared_ptr<easymedia::AudioEncoder> aud_enc = nullptr; std::shared_ptr<easymedia::SampleBuffer> aud_buffer = nullptr; std::shared_ptr<easymedia::Stream> file_write = nullptr; // 0. muxer int vid_stream_no = -1; int aud_stream_no = -1; auto mux = initMuxer(output_path); if (!mux) { fprintf(stderr, "Init Muxer failed and then init file write stream." "output_path = %s\n", output_path.c_str()); file_write = initFileWrite(output_path); if (!file_write) { fprintf(stderr, "Init file write stream failed.\n"); exit(EXIT_FAILURE); } } easymedia::REFLECTOR(Encoder)::DumpFactories(); // 1.video stream int input_file_fd = -1; if (stream_type.find("video") != stream_type.npos) { input_file_fd = open(input_path.c_str(), O_RDONLY | O_CLOEXEC); assert(input_file_fd >= 0); unlink(output_path.c_str()); vid_enc = initVideoEncoder(vid_enc_codec_name, vid_input_format, vid_enc_format, w, h); src_buffer = initVideoBuffer(vid_enc_codec_name, vid_enc->GetConfig().img_cfg.image_info); if (vid_enc_codec_name == "rkmpp") { size_t dst_len = CalPixFmtSize(vid_enc->GetConfig().img_cfg.image_info); dst_buffer = easymedia::MediaBuffer::Alloc( dst_len, easymedia::MediaBuffer::MemType::MEM_HARD_WARE); assert(dst_buffer && dst_buffer->GetSize() >= dst_len); } // TODO SrcFormat and OutFormat use the same variable vid_enc->GetConfig().img_cfg.image_info.pix_fmt = StringToPixFmt(vid_enc_format.c_str()); if (mux && !mux->NewMuxerStream(vid_enc->GetConfig(), vid_enc->GetExtraData(), vid_stream_no)) { fprintf(stderr, "NewMuxerStream failed for video\n"); exit(EXIT_FAILURE); } vinterval_per_frame = 1000000LL /* us */ / vid_enc->GetConfig().vid_cfg.frame_rate; // TODO SrcFormat and OutFormat use the same variable vid_enc->GetConfig().vid_cfg.image_cfg.image_info.pix_fmt = StringToPixFmt(std::string("image:").append(vid_input_format).c_str()); // Since the input is packed yuv images, no padding buffer, // we want to read actual pixel size video_frame_len = CalPixFmtSize(vid_enc->GetConfig().vid_cfg.image_cfg.image_info.pix_fmt, w, h); } // 2. audio stream. SampleInfo sample_info = {SAMPLE_FMT_NONE, 2, 48000, 1024}; if (stream_type.find("audio") != stream_type.npos) { sample_info.fmt = StringToSampleFmt(aud_input_format.c_str()); audio_capture = initAudioCapture(device_name, sample_info); if (!audio_capture) { fprintf(stderr, "initAudioCapture failed.\n"); exit(EXIT_FAILURE); } aud_enc = initAudioEncoder(aud_enc_codec_name, aud_enc_format, sample_info); if (aud_enc_format == AUDIO_AAC) { auto extra_data = adts_get_extradata(sample_info); aud_enc->SetExtraData(extra_data); } aud_buffer = initAudioBuffer(aud_enc->GetConfig()); assert(aud_buffer && aud_buffer->GetValidSize() > 0); auto &audio_info = aud_enc->GetConfig().aud_cfg.sample_info; sample_info = audio_info; if (mux && !mux->NewMuxerStream(aud_enc->GetConfig(), aud_enc->GetExtraData(), aud_stream_no)) { fprintf(stderr, "NewMuxerStream failed for audio\n"); exit(EXIT_FAILURE); } ainterval_per_frame = 1000000LL /* us */ * aud_enc->GetConfig().aud_cfg.sample_info.nb_samples / aud_enc->GetConfig().aud_cfg.sample_info.sample_rate; } if (mux && !(mux->WriteHeader(aud_stream_no))) { fprintf(stderr, "WriteHeader on stream index %d return nullptr\n", aud_stream_no); exit(EXIT_FAILURE); } // for ffmpeg, WriteHeader once, this call only dump info //mux->WriteHeader(aud_stream_no); int64_t audio_duration = 10 * 1000 * 1000; while (true) { if (stream_type.find("video") != stream_type.npos && vid_index * vinterval_per_frame < aud_index * ainterval_per_frame) { // video ssize_t read_len = read(input_file_fd, src_buffer->GetPtr(), video_frame_len); if (read_len < 0) { // if 0 Continue to drain all encoded buffer fprintf(stderr, "%s read len %zu\n", vid_enc_codec_name.c_str(), read_len); break; } else if (read_len == 0 && vid_enc_codec_name == "rkmpp") { // rkmpp process does not accept empty buffer // it will treat the result of nullptr input as normal // though it is ugly, but we cannot change it by now fprintf(stderr, "%s read len 0\n", vid_enc_codec_name.c_str()); break; } if (first_video_time == 0) { first_video_time = easymedia::gettimeofday(); } // feed video buffer src_buffer->SetValidSize(read_len); // important src_buffer->SetUSTimeStamp(first_video_time + vid_index * vinterval_per_frame); // important vid_index++; if (vid_enc_codec_name == "rkmpp") { dst_buffer->SetValidSize(dst_buffer->GetSize()); if (0 != vid_enc->Process(src_buffer, dst_buffer, nullptr)) { continue; } size_t out_len = dst_buffer->GetValidSize(); fprintf(stderr, "vframe %d encoded, type %s, out %zu bytes\n", vid_index, dst_buffer->GetUserFlag() & easymedia::MediaBuffer::kIntra ? "I frame" : "P frame", out_len); if (mux) mux->Write(dst_buffer, vid_stream_no); } else if (vid_enc_codec_name == "ffmpeg_vid") { if (0 > encode<easymedia::VideoEncoder>(mux, file_write, vid_enc, src_buffer, vid_stream_no)) { fprintf(stderr, "Encode video frame %d failed\n", vid_index); break; } } } else { // audio if (first_audio_time == 0) first_audio_time = easymedia::gettimeofday(); if (first_audio_time > 0 && easymedia::gettimeofday() - first_audio_time > audio_duration) break; size_t read_samples = audio_capture->Read( aud_buffer->GetPtr(), aud_buffer->GetSampleSize(), sample_info.nb_samples); if (!read_samples && errno != EAGAIN) { exit(EXIT_FAILURE); // fatal error } aud_buffer->SetSamples(read_samples); aud_buffer->SetUSTimeStamp(first_audio_time + aud_index * ainterval_per_frame); aud_index++; if (0 > encode<easymedia::AudioEncoder>(mux, file_write, aud_enc, aud_buffer, aud_stream_no)) { fprintf(stderr, "Encode audio frame %d failed\n", aud_index); break; } } } if (stream_type.find("video") != stream_type.npos) { src_buffer->SetValidSize(0); if (0 > encode<easymedia::VideoEncoder>(mux, file_write, vid_enc, src_buffer, vid_stream_no)) { fprintf(stderr, "Drain video frame %d failed\n", vid_index); } aud_buffer->SetSamples(0); if (0 > encode<easymedia::AudioEncoder>(mux, file_write, aud_enc, aud_buffer, aud_stream_no)) { fprintf(stderr, "Drain audio frame %d failed\n", aud_index); } } if (mux) { auto buffer = easymedia::MediaBuffer::Alloc(1); buffer->SetEOF(true); buffer->SetValidSize(0); mux->Write(buffer, vid_stream_no); } close(input_file_fd); mux = nullptr; vid_enc = nullptr; aud_enc = nullptr; return 0; }
32.966309
101
0.638036
rockchip-linux
1d97027888e95e1cae4c4c88fa25316c0b7771cf
879
cpp
C++
src/as3/as3_object.cpp
sweetkristas/swiftly
0b5c2badc88637b8bdaa841a45d1babd8f12a703
[ "BSL-1.0", "Zlib", "BSD-3-Clause" ]
null
null
null
src/as3/as3_object.cpp
sweetkristas/swiftly
0b5c2badc88637b8bdaa841a45d1babd8f12a703
[ "BSL-1.0", "Zlib", "BSD-3-Clause" ]
null
null
null
src/as3/as3_object.cpp
sweetkristas/swiftly
0b5c2badc88637b8bdaa841a45d1babd8f12a703
[ "BSL-1.0", "Zlib", "BSD-3-Clause" ]
null
null
null
#include "../asserts.hpp" #include "as3_object.hpp" #include "as3_value.hpp" #include "../swf_player.hpp" namespace avm2 { as3_object::as3_object(swf::player_ptr player) : player_(player) { } double as3_object::to_number() { const char* str = to_string(); if(str) { return atof(str); } return 0; } void as3_object::builtin(const std::string& name, const as3_value& value) { auto it = members_.find(name); if(it != members_.end()) { std::cerr << "Replacing builtin: " << name << std::endl; } members_[name] = value; members_[name].set_flags(as3_value::DO_NOT_ENUM); } as3_value as3_object::default_value(HintType hint) { if(hint == NO_HINT || hint == HINT_NUMBER) { return as3_value(to_number()); } ASSERT_LOG(hint != HINT_STRING, "FATAL: hint value is unknown: " << hint); // string hint return as3_value(to_string()); } }
20.44186
76
0.660978
sweetkristas
1d98096eeac41cba2c00f7d2112f421b919d322b
3,121
cpp
C++
datasets/github_cpp_10/2/19.cpp
yijunyu/demo-fast
11c0c84081a3181494b9c469bda42a313c457ad2
[ "BSD-2-Clause" ]
1
2019-05-03T19:27:45.000Z
2019-05-03T19:27:45.000Z
datasets/github_cpp_10/2/19.cpp
yijunyu/demo-vscode-fast
11c0c84081a3181494b9c469bda42a313c457ad2
[ "BSD-2-Clause" ]
null
null
null
datasets/github_cpp_10/2/19.cpp
yijunyu/demo-vscode-fast
11c0c84081a3181494b9c469bda42a313c457ad2
[ "BSD-2-Clause" ]
null
null
null
#include <map> #include <iostream> #define DEBUG #ifdef DEBUG int newCount = 0; int deleteCount = 0; void *operator new(size_t size) { newCount++; return malloc(size); } void operator delete(void *data) { deleteCount++; free(data); return ; } #endif class LRUNode { public: LRUNode(int key, int value) : m_key(key), m_value(value), m_last(nullptr), m_next(nullptr) {} int m_key, m_value; LRUNode *m_last, *m_next; }; class LRUCache { public: LRUCache(int capacity) : m_size(0), m_max(capacity), m_head(new LRUNode(-1, -1)), m_end(new LRUNode(-1, -1)) { m_head->m_next = m_end; m_end->m_last = m_head; m_end->m_next = nullptr; } ~LRUCache() { auto temp = m_head; while(temp) { auto temp2 = temp; temp = temp->m_next; delete temp2; } } int get(int key) { auto it = m_map.find(key); if(it != m_map.end()) { auto temp =it->second; temp->m_last->m_next = temp->m_next; temp->m_next->m_last = temp->m_last; temp->m_next = m_head->m_next; temp->m_next->m_last = temp; m_head->m_next = temp; temp->m_last = m_head; return temp->m_value; } else { return -1; } } void put(int key, int value) { auto it = m_map.find(key); if(it != m_map.end()) { it->second->m_last->m_next = it->second->m_next; it->second->m_next->m_last = it->second->m_last; auto temp = it->second; temp->m_next = m_head->m_next; temp->m_next->m_last = temp; m_head->m_next = temp; temp->m_last = m_head; temp->m_value = value; return ; } if(m_size == m_max) { auto temp = m_end->m_last; temp->m_last->m_next = temp->m_next; temp->m_next->m_last = temp->m_last; m_map.erase(m_map.find(temp->m_key)); delete temp; m_size --; } auto temp = new LRUNode(key, value); m_map[key] = temp; temp->m_next = m_head->m_next; temp->m_next->m_last = temp; m_head->m_next = temp; temp->m_last = m_head; m_size ++; return ; } std::map<int, LRUNode *> m_map; LRUNode *m_head, *m_end; int m_size; int m_max; }; int main() { LRUCache *cache = new LRUCache(2); cache->put(1, 1); cache->put(2, 2); std::cout << cache->get(1) << std::endl; cache->put(3, 3); std::cout << cache->get(2) << std::endl; cache->put(4, 4); std::cout << cache->get(1) << std::endl; std::cout << cache->get(3) << std::endl; std::cout << cache->get(4) << std::endl; delete cache; #ifdef DEBUG std::cout << (newCount == deleteCount) << std::endl; #endif return 0; }
20.806667
93
0.485421
yijunyu
1d9a980328700b6f6d3254e7cad32ca740d33f3c
689
hpp
C++
gnet/include/net/connection.hpp
gapry/GNet
4d63540e1f532fae1a44a97f9b2d74a6754f2513
[ "MIT" ]
1
2021-05-19T03:56:47.000Z
2021-05-19T03:56:47.000Z
gnet/include/net/connection.hpp
gapry/GNet
4d63540e1f532fae1a44a97f9b2d74a6754f2513
[ "MIT" ]
null
null
null
gnet/include/net/connection.hpp
gapry/GNet
4d63540e1f532fae1a44a97f9b2d74a6754f2513
[ "MIT" ]
null
null
null
#pragma once #include "net/packet.hpp" #include "net/socket.hpp" #include "noncopyable.hpp" #include "platform/types.hpp" namespace gnet { class engine; class connection : public noncopyable<connection> { friend class engine; public: enum class status { none, listening, connecting, connected, }; connection() = default; ~connection() = default; auto set_user_data(void* const data) -> void; auto get_user_data(void) -> void*; auto close(void) -> void; protected: socket m_sock; status m_status = status::none; void* m_user_data = nullptr; u64 m_totoal_send_bytes = 0; u64 m_totoal_recv_bytes = 0; }; } // namespace gnet
16.404762
51
0.67344
gapry
1d9ccbc0ffe9b36993559d827bbd3d81a7c3dba8
2,023
cc
C++
chrome/browser/web_applications/components/web_app_constants.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/browser/web_applications/components/web_app_constants.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/browser/web_applications/components/web_app_constants.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/web_applications/components/web_app_constants.h" #include "base/compiler_specific.h" #include "components/services/app_service/public/mojom/types.mojom.h" namespace web_app { static_assert(Source::kMinValue == 0, "Source enum should be zero based"); bool IsSuccess(InstallResultCode code) { return code == InstallResultCode::kSuccessNewInstall || code == InstallResultCode::kSuccessAlreadyInstalled; } DisplayMode ResolveEffectiveDisplayMode(DisplayMode app_display_mode, DisplayMode user_display_mode) { switch (user_display_mode) { case DisplayMode::kBrowser: return user_display_mode; case DisplayMode::kUndefined: case DisplayMode::kMinimalUi: case DisplayMode::kFullscreen: NOTREACHED(); FALLTHROUGH; case DisplayMode::kStandalone: break; } switch (app_display_mode) { case DisplayMode::kBrowser: case DisplayMode::kMinimalUi: return DisplayMode::kMinimalUi; case DisplayMode::kUndefined: NOTREACHED(); FALLTHROUGH; case DisplayMode::kStandalone: case DisplayMode::kFullscreen: return DisplayMode::kStandalone; } } apps::mojom::LaunchContainer ConvertDisplayModeToAppLaunchContainer( DisplayMode display_mode) { switch (display_mode) { case DisplayMode::kBrowser: return apps::mojom::LaunchContainer::kLaunchContainerTab; case DisplayMode::kMinimalUi: return apps::mojom::LaunchContainer::kLaunchContainerWindow; case DisplayMode::kStandalone: return apps::mojom::LaunchContainer::kLaunchContainerWindow; case DisplayMode::kFullscreen: return apps::mojom::LaunchContainer::kLaunchContainerWindow; case DisplayMode::kUndefined: return apps::mojom::LaunchContainer::kLaunchContainerNone; } } } // namespace web_app
32.111111
74
0.733564
sarang-apps
1d9d30a945339fabdd63cd82a686a8c6d5c8614d
127
hpp
C++
src/main.hpp
Southclaws/pawn-bcrypt
c046c3dc5c65997ae92d0c83d87fd487b69eaf23
[ "MIT" ]
9
2019-01-02T21:13:26.000Z
2022-01-15T09:43:11.000Z
src/main.hpp
Southclaws/pawn-bcrypt
c046c3dc5c65997ae92d0c83d87fd487b69eaf23
[ "MIT" ]
null
null
null
src/main.hpp
Southclaws/pawn-bcrypt
c046c3dc5c65997ae92d0c83d87fd487b69eaf23
[ "MIT" ]
null
null
null
#ifndef MAIN_H #define MAIN_H #include "SDK/amx/amx.h" #include "SDK/plugincommon.h" #define BCRYPT_VERSION "v2.2.3" #endif
12.7
31
0.732283
Southclaws
1da1a863a316357d81a85c5e5da86b93ae9e3139
7,729
cpp
C++
IPhreeqcMMS/IPhreeqc/src/phreeqcpp/nvector.cpp
usgs-coupled/webmod
66419e3714f20a357a7db0abd84246d61c002b88
[ "DOC" ]
null
null
null
IPhreeqcMMS/IPhreeqc/src/phreeqcpp/nvector.cpp
usgs-coupled/webmod
66419e3714f20a357a7db0abd84246d61c002b88
[ "DOC" ]
null
null
null
IPhreeqcMMS/IPhreeqc/src/phreeqcpp/nvector.cpp
usgs-coupled/webmod
66419e3714f20a357a7db0abd84246d61c002b88
[ "DOC" ]
1
2020-06-04T23:27:02.000Z
2020-06-04T23:27:02.000Z
/************************************************************************** * * * File : nvector.c * * Programmers : Radu Serban, LLNL * * Version of : 26 June 2002 * *------------------------------------------------------------------------* * Copyright (c) 2002, The Regents of the University of California * * Produced at the Lawrence Livermore National Laboratory * * All rights reserved * * For details, see LICENSE below * *------------------------------------------------------------------------* * This is the implementation file for a generic NVECTOR * * package. It contains the implementation of the N_Vector * * kernels listed in nvector.h. * * * *------------------------------------------------------------------------* * LICENSE * *------------------------------------------------------------------------* * Copyright (c) 2002, The Regents of the University of California. * * Produced at the Lawrence Livermore National Laboratory. * * Written by S.D. Cohen, A.C. Hindmarsh, R. Serban, * * D. Shumaker, and A.G. Taylor. * * UCRL-CODE-155951 (CVODE) * * UCRL-CODE-155950 (CVODES) * * UCRL-CODE-155952 (IDA) * * UCRL-CODE-237203 (IDAS) * * UCRL-CODE-155953 (KINSOL) * * All rights reserved. * * * * This file is part of SUNDIALS. * * * * Redistribution and use in source and binary forms, with or without * * modification, are permitted provided that the following conditions * * are met: * * * * 1. Redistributions of source code must retain the above copyright * * notice, this list of conditions and the disclaimer below. * * * * 2. Redistributions in binary form must reproduce the above copyright * * notice, this list of conditions and the disclaimer (as noted below) * * in the documentation and/or other materials provided with the * * distribution. * * * * 3. Neither the name of the UC/LLNL nor the names of its contributors * * may be used to endorse or promote products derived from this software * * without specific prior written permission. * * * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * * REGENTS OF THE UNIVERSITY OF CALIFORNIA, THE U.S. DEPARTMENT OF ENERGY * * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * **************************************************************************/ #include "nvector.h" /* generic M_Env and N_Vector */ #if defined(PHREEQCI_GUI) #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #endif N_Vector N_VNew(integertype n, M_Env machEnv) { N_Vector v_new; v_new = machEnv->ops->nvnew(n, machEnv); return (v_new); } N_Vector_S N_VNew_S(integertype ns, integertype n, M_Env machEnv) { N_Vector_S vs_new; vs_new = machEnv->ops->nvnewS(ns, n, machEnv); return (vs_new); } void N_VFree(N_Vector v) { v->menv->ops->nvfree(v); } void N_VFree_S(integertype ns, N_Vector_S vs) { (*vs)->menv->ops->nvfreeS(ns, vs); } N_Vector N_VMake(integertype n, realtype * v_data, M_Env machEnv) { N_Vector v_new; v_new = machEnv->ops->nvmake(n, v_data, machEnv); return (v_new); } void N_VDispose(N_Vector v) { v->menv->ops->nvdispose(v); } realtype * N_VGetData(N_Vector v) { realtype *data; data = v->menv->ops->nvgetdata(v); return (data); } void N_VSetData(realtype * v_data, N_Vector v) { v->menv->ops->nvsetdata(v_data, v); } void N_VLinearSum(realtype a, N_Vector x, realtype b, N_Vector y, N_Vector z) { z->menv->ops->nvlinearsum(a, x, b, y, z); } void N_VConst(realtype c, N_Vector z) { z->menv->ops->nvconst(c, z); } void N_VProd(N_Vector x, N_Vector y, N_Vector z) { z->menv->ops->nvprod(x, y, z); } void N_VDiv(N_Vector x, N_Vector y, N_Vector z) { z->menv->ops->nvdiv(x, y, z); } void N_VScale(realtype c, N_Vector x, N_Vector z) { z->menv->ops->nvscale(c, x, z); } void N_VAbs(N_Vector x, N_Vector z) { z->menv->ops->nvabs(x, z); } void N_VInv(N_Vector x, N_Vector z) { z->menv->ops->nvinv(x, z); } void N_VAddConst(N_Vector x, realtype b, N_Vector z) { z->menv->ops->nvaddconst(x, b, z); } realtype N_VDotProd(N_Vector x, N_Vector y) { realtype prod; prod = y->menv->ops->nvdotprod(x, y); return (prod); } realtype N_VMaxNorm(N_Vector x) { realtype norm; norm = x->menv->ops->nvmaxnorm(x); return (norm); } realtype N_VWrmsNorm(N_Vector x, N_Vector w) { realtype norm; norm = x->menv->ops->nvwrmsnorm(x, w); return (norm); } realtype N_VMin(N_Vector x) { realtype minval; minval = x->menv->ops->nvmin(x); return (minval); } realtype N_VWL2Norm(N_Vector x, N_Vector w) { realtype norm; norm = x->menv->ops->nvwl2norm(x, w); return (norm); } realtype N_VL1Norm(N_Vector x) { realtype norm; norm = x->menv->ops->nvl1norm(x); return (norm); } void N_VOneMask(N_Vector x) { x->menv->ops->nvonemask(x); } void N_VCompare(realtype c, N_Vector x, N_Vector z) { z->menv->ops->nvcompare(c, x, z); } booleantype N_VInvTest(N_Vector x, N_Vector z) { booleantype flag; flag = z->menv->ops->nvinvtest(x, z); return (flag); } booleantype N_VConstrProdPos(N_Vector c, N_Vector x) { booleantype flag; flag = x->menv->ops->nvconstrprodpos(c, x); return (flag); } booleantype N_VConstrMask(N_Vector c, N_Vector x, N_Vector m) { booleantype flag; flag = x->menv->ops->nvconstrmask(c, x, m); return (flag); } realtype N_VMinQuotient(N_Vector num, N_Vector denom) { realtype quotient; quotient = num->menv->ops->nvminquotient(num, denom); return (quotient); } void N_VPrint(N_Vector x) { x->menv->ops->nvprint(x); }
28.311355
76
0.514167
usgs-coupled
1da20345aff80162281d51c350669235def7ffd9
6,597
cpp
C++
frameworks-ext/native/services/surfaceflinger/tests/internal/surface2_test/surface.cpp
touxiong88/92_mediatek
5e96a7bb778fd9d9b335825584664e0c8b5ff2c7
[ "Apache-2.0" ]
1
2022-01-07T01:53:19.000Z
2022-01-07T01:53:19.000Z
frameworks-ext/native/services/surfaceflinger/tests/internal/surface2_test/surface.cpp
touxiong88/92_mediatek
5e96a7bb778fd9d9b335825584664e0c8b5ff2c7
[ "Apache-2.0" ]
null
null
null
frameworks-ext/native/services/surfaceflinger/tests/internal/surface2_test/surface.cpp
touxiong88/92_mediatek
5e96a7bb778fd9d9b335825584664e0c8b5ff2c7
[ "Apache-2.0" ]
1
2020-02-28T02:48:42.000Z
2020-02-28T02:48:42.000Z
/* Copyright Statement: * * This software/firmware and related documentation ("MediaTek Software") are * protected under relevant copyright laws. The information contained herein is * confidential and proprietary to MediaTek Inc. and/or its licensors. Without * the prior written permission of MediaTek inc. and/or its licensors, any * reproduction, modification, use or disclosure of MediaTek Software, and * information contained herein, in whole or in part, shall be strictly * prohibited. * * MediaTek Inc. (C) 2010. All rights reserved. * * BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES * THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE") * RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO RECEIVER * ON AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR * NONINFRINGEMENT. NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY WHATSOEVER WITH * RESPECT TO THE SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, * INCORPORATED IN, OR SUPPLIED WITH THE MEDIATEK SOFTWARE, AND RECEIVER AGREES * TO LOOK ONLY TO SUCH THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. * RECEIVER EXPRESSLY ACKNOWLEDGES THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO * OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES CONTAINED IN MEDIATEK * SOFTWARE. MEDIATEK SHALL ALSO NOT BE RESPONSIBLE FOR ANY MEDIATEK SOFTWARE * RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR * STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S * ENTIRE AND CUMULATIVE LIABILITY WITH RESPECT TO THE MEDIATEK SOFTWARE * RELEASED HEREUNDER WILL BE, AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE * MEDIATEK SOFTWARE AT ISSUE, OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE * CHARGE PAID BY RECEIVER TO MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE. * * The following software/firmware and/or related documentation ("MediaTek * Software") have been modified by MediaTek Inc. All revisions are subject to * any receiver's applicable license agreements with MediaTek Inc. */ /* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "SurfaceUtils.h" using namespace android; // # of buffer (frame 0 for LayerDim) #define FRAME_COUNT 5 frame_t frames[FRAME_COUNT]; static void initFrames() { frame_t *f; block_t *b; const char img_name[] = "/data/android.png"; for (int i = 0; i < FRAME_COUNT; i++) { f = &frames[i]; f->api_type = NATIVE_WINDOW_API_MEDIA; strncpy(f->name, img_name, sizeof(img_name)); // blk 0 b = &f->blk[0]; b->rect = Rect(0, 220, 300, 300); b->alpha = 0.0f; // blk 1 b = &f->blk[1]; b->rect = Rect(100, 80, 200, 180); b->alpha = 0.3f; } } status_t main(int argc, char** argv) { // create our thread pool sp<ProcessState> proc = ProcessState::self(); ProcessState::self()->startThreadPool(); // one layer per client sp<SurfaceComposerClient> client[FRAME_COUNT]; for (int i = 0; i < FRAME_COUNT; i++) { client[i] = new SurfaceComposerClient(); } LOGD("end create client"); sp<SurfaceControl> surfaceControls[FRAME_COUNT]; // surface 1 (LayerDim) surfaceControls[0] = client[0]->createSurface( String8("test-surface2"), DISPLAY_HANDLE, DISPLAY_WIDTH, DISPLAY_HEIGHT, PIXEL_FORMAT_RGBA_8888, ISurfaceComposer::eFXSurfaceDim & ISurfaceComposer::eFXSurfaceMask); // surface 2 ~ for (int i = 1; i < FRAME_COUNT; i++) { surfaceControls[i] = client[i]->createSurface( String8("test-surface2"), DISPLAY_HANDLE, LAYER_WIDTH, LAYER_HEIGHT, PIXEL_FORMAT_RGBA_8888); } LOGD("end create surface"); SurfaceComposerClient::openGlobalTransaction(); // surface 1 (LayerDim) surfaceControls[0]->setLayer(100000); surfaceControls[0]->setPosition(0, 0); surfaceControls[0]->setAlpha(0.6f); // surace 2 ~ for (int i = 1; i < FRAME_COUNT; i++) { surfaceControls[i]->setLayer(101000 + i * 10); surfaceControls[i]->setPosition(i * 20, i * 50); } SurfaceComposerClient::closeGlobalTransaction(); LOGD("end transaction"); Parcel parcels[FRAME_COUNT]; // i = 1 means that we exclude LayerDim sp<Surface> surfaces[FRAME_COUNT]; // 1 = 1 means that exclude LayerDim // pretend it went cross-process // surface 2 ~ for (int i = 1; i < FRAME_COUNT; i++) { SurfaceControl::writeSurfaceToParcel(surfaceControls[i], &parcels[i]); parcels[i].setDataPosition(0); surfaces[i] = Surface::readFromParcel(parcels[i]); } LOGD("end IPC"); // surface 2 ~ SurfaceUtils surface_utils[FRAME_COUNT]; // i = 1 means that we exclude LayerDim ANativeWindow *windows[FRAME_COUNT]; // i = 1 means that we exclude LayerDim for (int i = 1; i < FRAME_COUNT; i++) { windows[i] = surfaces[i].get(); LOGD("window = %p\n", windows[i]); surface_utils[i].setWindow(windows[i]); } // set api connection type //native_window_api_connect(window, frame.api_type); // exclude LayerDim for (int i = 1; i < FRAME_COUNT; i++) { surface_utils[i].connectAPI(NATIVE_WINDOW_API_CPU); } // initialize input frames initFrames(); // display int loop = 0; while (true) { // surface 2 ~ for (int i = 1; i < FRAME_COUNT; i++) { // show frame surface_utils[i].showTestFrame(&frames[0], i % 4); } usleep(16667); // fsp = 60 loop = loop + 1; if (loop == FRAME_COUNT) { // printf("\nloop again...\n"); loop = 0; } }; IPCThreadState::self()->joinThreadPool(); return NO_ERROR; }
36.65
85
0.665302
touxiong88
1daaeab8f7c7325dbb5d2011e0070c0dbbb5391a
2,789
cpp
C++
distributions/univariate/continuous/InverseGaussianRand.cpp
aWeinzierl/RandLib
7af0237d1902aadbf2451b7dfab02c52cf98ae87
[ "MIT" ]
null
null
null
distributions/univariate/continuous/InverseGaussianRand.cpp
aWeinzierl/RandLib
7af0237d1902aadbf2451b7dfab02c52cf98ae87
[ "MIT" ]
null
null
null
distributions/univariate/continuous/InverseGaussianRand.cpp
aWeinzierl/RandLib
7af0237d1902aadbf2451b7dfab02c52cf98ae87
[ "MIT" ]
null
null
null
#include "InverseGaussianRand.h" #include "NormalRand.h" #include "UniformRand.h" InverseGaussianRand::InverseGaussianRand(double mean, double shape) { SetParameters(mean, shape); } String InverseGaussianRand::Name() const { return "Inverse-Gaussian(" + toStringWithPrecision(GetMean()) + ", " + toStringWithPrecision(GetShape()) + ")"; } void InverseGaussianRand::SetParameters(double mean, double shape) { if (mean <= 0.0) throw std::invalid_argument("Inverse-Gaussian distribution: mean should be positive"); if (shape <= 0.0) throw std::invalid_argument("Inverse-Gaussian distribution: shape should be positive"); mu = mean; lambda = shape; pdfCoef = 0.5 * std::log(0.5 * lambda * M_1_PI); cdfCoef = std::exp(2 * lambda / mu); } double InverseGaussianRand::f(const double & x) const { return (x > 0.0) ? std::exp(logf(x)) : 0.0; } double InverseGaussianRand::logf(const double & x) const { if (x <= 0.0) return -INFINITY; double y = -1.5 * std::log(x); double z = (x - mu); z *= z; z *= -0.5 * lambda / (x * mu * mu); z += pdfCoef; return y + z; } double InverseGaussianRand::F(const double & x) const { if (x <= 0.0) return 0.0; double b = std::sqrt(0.5 * lambda / x); double a = b * x / mu; double y = std::erfc(b - a); y += cdfCoef * std::erfc(a + b); return 0.5 * y; } double InverseGaussianRand::S(const double & x) const { if (x <= 0.0) return 1.0; double b = std::sqrt(0.5 * lambda / x); double a = b * x / mu; double y = std::erfc(a - b); y -= cdfCoef * std::erfc(a + b); return 0.5 * y; } double InverseGaussianRand::Variate() const { double X = NormalRand::StandardVariate(localRandGenerator); double U = UniformRand::StandardVariate(localRandGenerator); X *= X; double mupX = mu * X; double y = 4 * lambda + mupX; y = std::sqrt(y * mupX); y -= mupX; y *= -0.5 / lambda; ++y; if (U * (1 + y) > 1.0) y = 1.0 / y; return mu * y; } double InverseGaussianRand::Mean() const { return mu; } double InverseGaussianRand::Variance() const { return mu * mu * mu / lambda; } std::complex<double> InverseGaussianRand::CFImpl(double t) const { double im = mu * mu; im *= t / lambda; std::complex<double> y(1, -im - im); y = 1.0 - std::sqrt(y); y *= lambda / mu; return std::exp(y); } double InverseGaussianRand::Mode() const { double aux = 1.5 * mu / lambda; double mode = 1 + aux * aux; mode = std::sqrt(mode); mode -= aux; return mu * mode; } double InverseGaussianRand::Skewness() const { return 3 * std::sqrt(mu / lambda); } double InverseGaussianRand::ExcessKurtosis() const { return 15 * mu / lambda; }
23.049587
115
0.59663
aWeinzierl
1dacf41695c03099d5ee068786f3dda87b179bb3
16,234
cpp
C++
storage.cpp
uyjulian/krxp3file
f2ccee343b22645e44ec45f44acf565f5c061214
[ "MIT" ]
null
null
null
storage.cpp
uyjulian/krxp3file
f2ccee343b22645e44ec45f44acf565f5c061214
[ "MIT" ]
null
null
null
storage.cpp
uyjulian/krxp3file
f2ccee343b22645e44ec45f44acf565f5c061214
[ "MIT" ]
null
null
null
#include <stdio.h> #include <string.h> #include <windows.h> #include "ncbind/ncbind.hpp" #include <map> #include <vector> #include <stdio.h> #include <stdlib.h> #include "cxdec.h" #include "tp_stub.h" #include "XP3Archive.h" #undef tTJSBinaryStream class XP3Stream : public IStream { public: XP3Stream(CompatTJSBinaryStream *in_vfd) { ref_count = 1; vfd = in_vfd; } // IUnknown HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void **ppvObject) { if (riid == IID_IUnknown || riid == IID_ISequentialStream || riid == IID_IStream) { if (ppvObject == NULL) return E_POINTER; *ppvObject = this; AddRef(); return S_OK; } else { *ppvObject = 0; return E_NOINTERFACE; } } ULONG STDMETHODCALLTYPE AddRef(void) { ref_count++; return ref_count; } ULONG STDMETHODCALLTYPE Release(void) { int ret = --ref_count; if (ret <= 0) { delete this; ret = 0; } return ret; } // ISequentialStream HRESULT STDMETHODCALLTYPE Read(void *pv, ULONG cb, ULONG *pcbRead) { try { ULONG read; read = vfd->Read(pv, cb); if(pcbRead) *pcbRead = read; } catch(...) { return E_FAIL; } return S_OK; } HRESULT STDMETHODCALLTYPE Write(const void *pv, ULONG cb, ULONG *pcbWritten) { return E_NOTIMPL; } // IStream HRESULT STDMETHODCALLTYPE Seek(LARGE_INTEGER dlibMove, DWORD dwOrigin, ULARGE_INTEGER *plibNewPosition) { try { switch(dwOrigin) { case STREAM_SEEK_SET: if(plibNewPosition) (*plibNewPosition).QuadPart = vfd->Seek(dlibMove.QuadPart, TJS_BS_SEEK_SET); else vfd->Seek(dlibMove.QuadPart, TJS_BS_SEEK_SET); break; case STREAM_SEEK_CUR: if(plibNewPosition) (*plibNewPosition).QuadPart = vfd->Seek(dlibMove.QuadPart, TJS_BS_SEEK_CUR); else vfd->Seek(dlibMove.QuadPart, TJS_BS_SEEK_CUR); break; case STREAM_SEEK_END: if(plibNewPosition) (*plibNewPosition).QuadPart = vfd->Seek(dlibMove.QuadPart, TJS_BS_SEEK_END); else vfd->Seek(dlibMove.QuadPart, TJS_BS_SEEK_END); break; default: return E_FAIL; } } catch(...) { return E_FAIL; } return S_OK; } HRESULT STDMETHODCALLTYPE SetSize(ULARGE_INTEGER libNewSize) { return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE CopyTo(IStream *pstm, ULARGE_INTEGER cb, ULARGE_INTEGER *pcbRead, ULARGE_INTEGER *pcbWritten) { return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE Commit(DWORD grfCommitFlags) { return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE Revert(void) { return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE LockRegion(ULARGE_INTEGER libOffset, ULARGE_INTEGER cb, DWORD dwLockType) { return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE UnlockRegion(ULARGE_INTEGER libOffset, ULARGE_INTEGER cb, DWORD dwLockType) { return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE Stat(STATSTG *pstatstg, DWORD grfStatFlag) { // This method imcompletely fills the target structure, because some // informations like access mode or stream name are already lost // at this point. if(pstatstg) { ZeroMemory(pstatstg, sizeof(*pstatstg)); #if 0 // pwcsName // this object's storage pointer does not have a name ... if(!(grfStatFlag & STATFLAG_NONAME)) { // anyway returns an empty string LPWSTR str = (LPWSTR)CoTaskMemAlloc(sizeof(*str)); if(str == NULL) return E_OUTOFMEMORY; *str = TJS_W('\0'); pstatstg->pwcsName = str; } #endif // type pstatstg->type = STGTY_STREAM; // cbSize pstatstg->cbSize.QuadPart = vfd->GetSize(); // mtime, ctime, atime unknown // grfMode unknown pstatstg->grfMode = STGM_DIRECT | STGM_READWRITE | STGM_SHARE_DENY_WRITE ; // Note that this method always returns flags above, regardless of the // actual mode. // In the return value, the stream is to be indicated that the // stream can be written, but of cource, the Write method will fail // if the stream is read-only. // grfLockSuppoted pstatstg->grfLocksSupported = 0; // grfStatBits unknown } else { return E_INVALIDARG; } return S_OK; } HRESULT STDMETHODCALLTYPE Clone(IStream **ppstm) { return E_NOTIMPL; } protected: /** * デストラクタ */ virtual ~XP3Stream() { delete vfd; vfd = NULL; } private: int ref_count; CompatTJSBinaryStream *vfd; }; class XP3Storage : public iTVPStorageMedia { public: XP3Storage(tTVPXP3Archive *in_fs) { ref_count = 1; fs = in_fs; char buf[(sizeof(void *) * 2) + 1]; snprintf(buf, (sizeof(void *) * 2) + 1, "%p", this); // The hash function does not work properly with numbers, so change to letters. char *p = buf; while(*p) { if(*p >= '0' && *p <= '9') *p = 'g' + (*p - '0'); if(*p >= 'A' && *p <= 'Z') *p |= 32; p++; } name = ttstr(TJS_W("xpk")) + buf; } virtual ~XP3Storage() { if (fs) { delete fs; fs = NULL; } } public: // ----------------------------------- // iTVPStorageMedia Intefaces // ----------------------------------- virtual void TJS_INTF_METHOD AddRef() { ref_count++; }; virtual void TJS_INTF_METHOD Release() { if (ref_count == 1) { delete this; } else { ref_count--; } }; // returns media name like "file", "http" etc. virtual void TJS_INTF_METHOD GetName(ttstr &out_name) { out_name = name; } // virtual ttstr TJS_INTF_METHOD IsCaseSensitive() = 0; // returns whether this media is case sensitive or not // normalize domain name according with the media's rule virtual void TJS_INTF_METHOD NormalizeDomainName(ttstr &name) { // normalize domain name // make all characters small tjs_char *p = name.Independ(); while(*p) { if(*p >= TJS_W('A') && *p <= TJS_W('Z')) *p += TJS_W('a') - TJS_W('A'); p++; } } // normalize path name according with the media's rule virtual void TJS_INTF_METHOD NormalizePathName(ttstr &name) { // normalize path name // make all characters small tjs_char *p = name.Independ(); while(*p) { if(*p >= TJS_W('A') && *p <= TJS_W('Z')) *p += TJS_W('a') - TJS_W('A'); p++; } } // check file existence virtual bool TJS_INTF_METHOD CheckExistentStorage(const ttstr &name) { const tjs_char *ptr = name.c_str(); // The domain name needs to be "." if (!TJS_strncmp(ptr, TJS_W("./"), 2)) { ptr += 2; ttstr fname(ptr); tTVPArchive::NormalizeInArchiveStorageName(fname); return fs->IsExistent(fname); } return false; } // open a storage and return a tTJSBinaryStream instance. // name does not contain in-archive storage name but // is normalized. virtual tTJSBinaryStream * TJS_INTF_METHOD Open(const ttstr & name, tjs_uint32 flags) { if (flags == TJS_BS_READ) { const tjs_char *ptr = name.c_str(); // The domain name needs to be "." if (!TJS_strncmp(ptr, TJS_W("./"), 2)) { ptr += 2; ttstr fname(ptr); tTVPArchive::NormalizeInArchiveStorageName(fname); CompatTJSBinaryStream *stream = fs->CreateStream(fname); if (stream) { IStream *streamm = new XP3Stream(stream); if (streamm) { tTJSBinaryStream *ret = TVPCreateBinaryStreamAdapter(streamm); streamm->Release(); return ret; } } } } return NULL; } // list files at given place virtual void TJS_INTF_METHOD GetListAt(const ttstr &name, iTVPStorageLister * lister) { const tjs_char *ptr = name.c_str(); // The domain name needs to be "." if (!TJS_strncmp(ptr, TJS_W("./"), 2)) { ptr += 2; // Skip extra slashes while (*ptr) { if (!TJS_strncmp(ptr, TJS_W("/"), 1)) { ptr += 1; } else { break; } } ttstr fname(ptr); tTVPArchive::NormalizeInArchiveStorageName(fname); // TODO: handle directories correctly // Basic logic: trim leading name int count = fs->GetCount(); for (int i = 0; i < count; i += 1) { ttstr filename = fs->GetName(i); tTVPArchive::NormalizeInArchiveStorageName(filename); // Skip directory if (filename.StartsWith(fname)) { const tjs_char *ptr2 = filename.c_str() + fname.GetLen(); ttstr fname(ptr2); // Only add files directly in level if (!TJS_strstr(ptr2, TJS_W("/"))) { lister->Add(ptr2); } } } } else { TVPAddLog(ttstr("Unable to search in: '") + ttstr(name) + ttstr("'")); } } // basically the same as above, // check wether given name is easily accessible from local OS filesystem. // if true, returns local OS native name. otherwise returns an empty string. virtual void TJS_INTF_METHOD GetLocallyAccessibleName(ttstr &name) { name = ""; } virtual void TJS_INTF_METHOD SetArchiveExtractionFilter(tTVPXP3ArchiveExtractionFilterWithUserdata filter, void *filterdata) { fs->SetArchiveExtractionFilter(filter, filterdata); } private: tjs_uint ref_count; ttstr name; tTVPXP3Archive *fs; }; static std::vector<XP3Storage*> storage_media_vector; class XP3Encryption { public: XP3Encryption() { char buf[(sizeof(void *) * 2) + 1]; snprintf(buf, (sizeof(void *) * 2) + 1, "%p", this); // The hash function does not work properly with numbers, so change to letters. char *p = buf; while(*p) { if(*p >= '0' && *p <= '9') *p = 'g' + (*p - '0'); if(*p >= 'A' && *p <= 'Z') *p |= 32; p++; } name = ttstr(TJS_W("enc")) + buf; filter = NULL; } virtual ~XP3Encryption() { } virtual void TJS_INTF_METHOD GetName(ttstr &out_name) { out_name = name; } virtual void TJS_INTF_METHOD Filter(tTVPXP3ExtractionFilterInfo *info) { } static void TVP_tTVPXP3ArchiveExtractionFilter_CONVENTION FilterExec(tTVPXP3ExtractionFilterInfo *info, void *data) { if (info->SizeOfSelf != sizeof(tTVPXP3ExtractionFilterInfo)) { TVPThrowExceptionMessage(TJS_W("Incompatible tTVPXP3ExtractionFilterInfo size")); } ((XP3Encryption *)data)->Filter(info); } virtual void TJS_INTF_METHOD GetArchiveExtractionFilter(tTVPXP3ArchiveExtractionFilterWithUserdata &out_filter, void * &out_data) { out_filter = FilterExec; out_data = this; } private: ttstr name; tTVPXP3ArchiveExtractionFilterWithUserdata filter; }; static std::vector<XP3Encryption*> xp3_encryption_vector; class XP3CxdecEncryption : public XP3Encryption { public: XP3CxdecEncryption(cxdec_information *in_information) : XP3Encryption() { memcpy(&information, in_information, sizeof(*in_information)); memset(&state, 0, sizeof(state)); cxdec_init(&state, &information); } virtual ~XP3CxdecEncryption() { cxdec_release(&state); } virtual void TJS_INTF_METHOD Filter(tTVPXP3ExtractionFilterInfo *info) { cxdec_decode(&state, &information, info->FileHash, (DWORD)(info->Offset), (PBYTE)(info->Buffer), (DWORD)(info->BufferSize)); } private: cxdec_information information; cxdec_state state; }; class StoragesXP3File { public: static ttstr mountXP3(ttstr filename) { { { tTVPXP3Archive * arc = NULL; try { if (TVPIsXP3Archive(filename)) { arc = new tTVPXP3Archive(filename); if (arc) { XP3Storage * xp3storage = new XP3Storage(arc); TVPRegisterStorageMedia(xp3storage); storage_media_vector.push_back(xp3storage); ttstr xp3storage_name; xp3storage->GetName(xp3storage_name); return xp3storage_name; } } } catch(...) { return TJS_W(""); } } } return TJS_W(""); } static bool setEncryptionXP3(ttstr medianame, ttstr encryptionmethod) { for (auto i = storage_media_vector.begin(); i != storage_media_vector.end(); i += 1) { ttstr this_medianame; (*i)->GetName(this_medianame); if (medianame == this_medianame) { if (encryptionmethod.GetLen() == 0) { (*i)->SetArchiveExtractionFilter(NULL, NULL); return true; } else { for (auto j = xp3_encryption_vector.begin(); j != xp3_encryption_vector.end(); j += 1) { ttstr this_encryptionmethod; (*j)->GetName(this_encryptionmethod); if (encryptionmethod == this_encryptionmethod) { tTVPXP3ArchiveExtractionFilterWithUserdata this_encryptionfilter; void *this_encryptionfilterdata; (*j)->GetArchiveExtractionFilter(this_encryptionfilter, this_encryptionfilterdata); (*i)->SetArchiveExtractionFilter(this_encryptionfilter, this_encryptionfilterdata); return true; } } } return false; } } return false; } static ttstr loadEncryptionMethodCxdec(tTJSVariant encryption_var) { cxdec_information information_tmp; ncbPropAccessor encryption_accessor(encryption_var); int max_count = encryption_accessor.GetArrayCount(); if (max_count >= 6) { tTJSVariant tmp_var; if (encryption_accessor.checkVariant(0, tmp_var)) { ncbPropAccessor tmp_accessor(tmp_var); if (tmp_accessor.GetArrayCount() >= (int)sizeof(information_tmp.xcode_building_first_stage_order)) { for (int i = 0; i < (int)sizeof(information_tmp.xcode_building_first_stage_order); i += 1) { information_tmp.xcode_building_first_stage_order[i] = (uint8_t)tmp_accessor.getIntValue(i); } } else { return TJS_W(""); } } else { return TJS_W(""); } if (encryption_accessor.checkVariant(1, tmp_var)) { ncbPropAccessor tmp_accessor(tmp_var); if (tmp_accessor.GetArrayCount() >= (int)sizeof(information_tmp.xcode_building_stage_0_order)) { for (int i = 0; i < (int)sizeof(information_tmp.xcode_building_stage_0_order); i += 1) { information_tmp.xcode_building_stage_0_order[i] = (uint8_t)tmp_accessor.getIntValue(i); } } else { return TJS_W(""); } } else { return TJS_W(""); } if (encryption_accessor.checkVariant(2, tmp_var)) { ncbPropAccessor tmp_accessor(tmp_var); if (tmp_accessor.GetArrayCount() >= (int)sizeof(information_tmp.xcode_building_stage_1_order)) { for (int i = 0; i < (int)sizeof(information_tmp.xcode_building_stage_1_order); i += 1) { information_tmp.xcode_building_stage_1_order[i] = (uint8_t)tmp_accessor.getIntValue(i); } } else { return TJS_W(""); } } else { return TJS_W(""); } if (encryption_accessor.checkVariant(3, tmp_var)) { information_tmp.boundary_mask = (uint16_t)tmp_var.AsInteger(); } else { return TJS_W(""); } if (encryption_accessor.checkVariant(4, tmp_var)) { information_tmp.boundary_offset = (uint16_t)tmp_var.AsInteger(); } else { return TJS_W(""); } if (encryption_accessor.checkVariant(5, tmp_var)) { if (tmp_var.Type() == tvtOctet) { const tTJSVariantOctet *oct = tmp_var.AsOctetNoAddRef(); if (oct->GetLength() == (int)sizeof(information_tmp.encryption_control_block)) { memcpy(information_tmp.encryption_control_block, oct->GetData(), (int)sizeof(information_tmp.encryption_control_block)); } else { return TJS_W(""); } } else { return TJS_W(""); } } else { return TJS_W(""); } { XP3CxdecEncryption * xp3cxdecencryption = new XP3CxdecEncryption(&information_tmp); xp3_encryption_vector.push_back(xp3cxdecencryption); ttstr xp3cxdecencryption_name; xp3cxdecencryption->GetName(xp3cxdecencryption_name); return xp3cxdecencryption_name; } } return TJS_W(""); } static bool unmountXP3(ttstr medianame) { for (auto i = storage_media_vector.begin(); i != storage_media_vector.end(); i += 1) { ttstr this_medianame; (*i)->GetName(this_medianame); if (medianame == this_medianame) { TVPUnregisterStorageMedia(*i); (*i)->Release(); storage_media_vector.erase(i); return true; } } return false; } }; NCB_ATTACH_CLASS(StoragesXP3File, Storages) { NCB_METHOD(mountXP3); NCB_METHOD(loadEncryptionMethodCxdec); NCB_METHOD(setEncryptionXP3); NCB_METHOD(unmountXP3); }; static void PreRegistCallback() { } static void PostUnregistCallback() { for (auto i = storage_media_vector.begin(); i != storage_media_vector.end(); i += 1) { TVPUnregisterStorageMedia(*i); } } NCB_PRE_REGIST_CALLBACK(PreRegistCallback); NCB_POST_UNREGIST_CALLBACK(PostUnregistCallback);
21.937838
130
0.65985
uyjulian
1dade2debcc8231dc0676d580e1b76419631cd4f
2,192
cpp
C++
Functions/FunctionAVX.cpp
alisa-vernigor/MathForTypingAnalysis
28e72c8fbf116ddb379b1d823efbf3c5b99b3896
[ "MIT" ]
null
null
null
Functions/FunctionAVX.cpp
alisa-vernigor/MathForTypingAnalysis
28e72c8fbf116ddb379b1d823efbf3c5b99b3896
[ "MIT" ]
null
null
null
Functions/FunctionAVX.cpp
alisa-vernigor/MathForTypingAnalysis
28e72c8fbf116ddb379b1d823efbf3c5b99b3896
[ "MIT" ]
null
null
null
#include "Function.h" #include "vectorclass/vectorclass.h" #include "vectorclass/vectormath_exp.h" namespace NSMathModule { namespace NSFunctions { double CDensity0::compute0_AVX(const std::vector<double>& means, double arg) { double tmp_result = 0; size_t regular_part = means.size() & static_cast<size_t>(-4); for (size_t index = 0; index < regular_part; index += 4) { Vec4d means_block(means[index], means[index + 1], means[index + 2], means[index + 3]); tmp_result += find_derivative_0(means_block, arg); } for (size_t index = regular_part; index < means.size(); ++index) { double mean = means[regular_part]; tmp_result += find_derivative_0(mean, arg); } return tmp_result / static_cast<double>(means.size()); } double CDensity1::compute1_AVX(const std::vector<double>& means, double arg) { double tmp_result = 0; size_t regular_part = means.size() & static_cast<size_t>(-4); for (size_t index = 0; index < regular_part; index += 4) { Vec4d means_block(means[index], means[index + 1], means[index + 2], means[index + 3]); tmp_result += find_derivative_1(means_block, arg); } for (size_t index = regular_part; index < means.size(); ++index) { double mean = means[regular_part]; tmp_result += find_derivative_1(mean, arg); } return tmp_result / static_cast<double>(means.size()); } double CDensity2::compute2_AVX(const std::vector<double>& means, double arg) { double tmp_result = 0; size_t regular_part = means.size() & static_cast<size_t>(-4); for (size_t index = 0; index < regular_part; index += 4) { Vec4d means_block(means[index], means[index + 1], means[index + 2], means[index + 3]); tmp_result += find_derivative_2(means_block, arg); } for (size_t index = regular_part; index < means.size(); ++index) { double mean = means[regular_part]; tmp_result += find_derivative_2(mean, arg); } return tmp_result / static_cast<double>(means.size()); } } }
35.934426
82
0.614507
alisa-vernigor
1db08e9350390ee0af6d3a24c1e181f70bfb3f20
12,144
cpp
C++
trunk/libs/platform/source/win32/core_app.cpp
ChuyX3/angsys
89b2eaee866bcfd11e66efda49b38acc7468c780
[ "Apache-2.0" ]
null
null
null
trunk/libs/platform/source/win32/core_app.cpp
ChuyX3/angsys
89b2eaee866bcfd11e66efda49b38acc7468c780
[ "Apache-2.0" ]
null
null
null
trunk/libs/platform/source/win32/core_app.cpp
ChuyX3/angsys
89b2eaee866bcfd11e66efda49b38acc7468c780
[ "Apache-2.0" ]
null
null
null
#include "pch.h" #include <ang/platform/platform.h> #include <ang/core/time.h> #include "dispatcher.h" #include "core_app.h" #include <comdef.h> #include <windowsx.h> using namespace ang; using namespace ang::platform; using namespace ang::platform::events; using namespace ang::platform::windows; namespace ang::platform { extern icore_app* s_current_app; } LRESULT STDCALL core_app::wndproc(HWND hwnd, UINT m, WPARAM wprm, LPARAM lprm) { message msg((core_msg)m, wprm, lprm); core_app_t wnd = null; if ((core_msg::created == (core_msg)m) && (lprm != 0)) { LPCREATESTRUCT pcs = (LPCREATESTRUCT)lprm; if (pcs->lpCreateParams) { wnd = (core_app*)pcs->lpCreateParams; wnd->m_hwnd = hwnd; SetWindowLongPtrW(hwnd, GWLP_USERDATA, (LONG_PTR)pcs->lpCreateParams); } } else { wnd = reinterpret_cast<core_app*>(GetWindowLongPtrW(hwnd, GWLP_USERDATA)); } if (!wnd.is_empty()) { wnd->wndproc(msg); return msg.result(); } return DefWindowProcW(hwnd, m, wprm, lprm); } core_app::core_app() : m_hint(null) , m_hwnd(null) { s_current_app = this; m_thread = core::async::thread::this_thread(); m_timer.reset(); m_controllers = new input::controller_manager(); } core_app::~core_app() { m_controllers = null; s_current_app = null; } pointer core_app::core_app_handle()const { return m_hint; } icore_view_t core_app::core_view() { return this; } input::ikeyboard_t core_app::keyboard() { return null; } ivar core_app::property(astring name)const { return null; } void core_app::property(astring name, ivar var) { } pointer core_app::core_view_handle()const { return m_hwnd; } graphics::icore_context_t core_app::core_context()const { return new graphics::device_context(const_cast<core_app*>(this)); } graphics::size<float> core_app::core_view_size()const { if (IsWindow(m_hwnd)) { RECT rc; GetClientRect(m_hwnd, &rc); return { float(rc.right - rc.left), float(rc.bottom - rc.top) }; } return{ 0,0 }; } graphics::size<float> core_app::core_view_scale_factor()const { return{ 1.0f,1.0f }; } imessage_listener_t core_app::dispatcher()const { return const_cast<core_app*>(this); } error core_app::run(function<error(icore_app_t)> setup, app_args_t& args) { //m_frm = frm; m_thread = core::async::thread::this_thread(); error err = setup(this); wstring name = args.name->cstr(); wstring title = args.title->cstr(); if (err.code() != error_code::success) return err; setup = null;//releasing scope WNDCLASSEXW wcex; wcex.cbSize = sizeof(WNDCLASSEX); wcex.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC | CS_SAVEBITS; wcex.lpfnWndProc = &core_app::wndproc; wcex.cbClsExtra = 0; wcex.cbWndExtra = 0; wcex.hInstance = m_hint; wcex.hIcon = NULL; wcex.hCursor = LoadCursor(nullptr, IDC_ARROW); wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1); wcex.lpszMenuName = NULL; wcex.lpszClassName = name.cstr(); wcex.hIconSm = NULL; RegisterClassExW(&wcex);; HWND hwnd = CreateWindowExW(0, name.cstr(), title.cstr(), WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, nullptr, nullptr, m_hint, this); if (!hwnd) { _com_error err(GetLastError()); castr_t msg(err.ErrorMessage(), -1); return error(err.Error(), msg, error_code::system_error); } ShowWindow(hwnd, SW_SHOW); UpdateWindow(hwnd); core::time::step_timer timer; if (args.fps > 0) { timer.frames_per_second(args.fps); timer.fixed_time_step(true); } // Main message loop: MSG msg; while (true) { core::async::async_action_status_t status = m_thread->status(); if (status & core::async::async_action_status::canceled) PostQuitMessage(0); if (PeekMessageW(&msg, NULL, 0, 0, PM_REMOVE)) { TranslateMessage(&msg); DispatchMessageW(&msg); /*if (msg.hwnd == NULL) { events::message m{ (events::core_msg)msg.message, msg.wParam, msg.lParam }; wndproc(m); }*/ } if (msg.message == WM_QUIT) break; else timer.tick([&]() { m_controllers->update(timer.elapsed_time()); SendMessageW(m_hwnd, (UINT)core_msg::update, timer.elapsed_time(), timer.total_time()); }); } return error_code::success; } void core_app::wndproc(events::message& msg) { switch (msg.msg()) { case core_msg::created: { //auto cs = LPCREATESTRUCT((LPARAM)msg.lparam()); on_created(msg); }break; case core_msg::destroyed: { on_destroyed(msg); } break; case (core_msg)WM_ERASEBKGND: case core_msg::draw: { on_draw(msg); } break; case core_msg::update: { on_update(msg); } break; case core_msg::display_change: case core_msg::orientation: case core_msg::size: { on_display_event(msg); } break; case core_msg::system_reserved_event: { on_task_command(msg); } case core_msg::got_focus: case core_msg::lost_focus: { on_activate(msg); } break; case core_msg::pointer_entered: case core_msg::pointer_pressed: case core_msg::pointer_moved: case core_msg::pointer_released: case core_msg::pointer_leaved: { on_pointer_event(msg); } break; case core_msg::mouse_move: case core_msg::lbutton_down: case core_msg::rbutton_down: case (core_msg)WM_XBUTTONDOWN: case core_msg::lbutton_up: case core_msg::rbutton_up: case (core_msg)WM_XBUTTONUP: { on_mouse_event(msg); } break; case core_msg::key_down: case core_msg::put_char: case core_msg::key_up: { on_key_event(msg); break; } default: { def_wndproc(msg); } break; } } void core_app::def_wndproc(events::message& msg) { msg.result(DefWindowProcW(m_hwnd, (uint)(core_msg)msg.msg(), (WPARAM)msg.wparam(), (LPARAM)msg.lparam())); } dword core_app::on_created(events::message& m) { auto it = m_event_listeners.find(m.msg()); if (it.is_valid()) { icreated_event_args_t args = new created_event_args(m, this, null); try { it->value->invoke(args.get()); } catch (const exception & e) { } } def_wndproc(m); return m.result(); } dword core_app::on_destroyed(events::message& m) { auto it = m_event_listeners.find(m.msg()); if (it.is_valid()) { imsg_event_args_t args = new msg_event_args(m); try { it->value->invoke(args.get()); } catch (const exception & e) { } } m_event_listeners.clear(); def_wndproc(m); PostQuitMessage(m.lparam()); return m.result(); } dword core_app::on_draw(events::message& m) { auto it = m_event_listeners.find(m.msg()); if (it.is_valid()) { graphics::device_context_t dc = new graphics::paint_dc(this); if (dc->get_HDC() == null) dc = new graphics::device_context(this); idraw_event_args_t args = new draw_event_args(m, this, dc, core_view_size()); try { it->value->invoke(args.get()); } catch (const exception & e) { } } m.result(0); return m.result(); } dword core_app::on_update(events::message& m) { auto it = m_event_listeners.find(m.msg()); if (it.is_valid()) { imsg_event_args_t args = new msg_event_args(m); try { it->value->invoke(args.get()); } catch (const exception & e) { } } m.result(0); return m.result(); } dword core_app::on_activate(events::message& m) { int handled = 0; auto it = m_event_listeners.find(m.msg()); if (it.is_valid()) { activate_status_t status = m.msg() == core_msg::got_focus ? activate_status::activated : activate_status::deactivated; iactivate_event_args_t args = new activate_event_args(m, status); try { handled = it->value->invoke(args.get()); } catch (const exception & e) { } } if (!handled) def_wndproc(m); else m.result(0); return m.result(); } dword core_app::on_display_event(events::message& m) { auto it = m_event_listeners.find(m.msg()); if (it.is_valid()) { dword value = (dword)m.lparam(); display_invalidate_reason_t reason = m.msg() == core_msg::size ? display_invalidate_reason::size_changed : m.msg() == core_msg::display_change ? display_invalidate_reason::display_invalidate : m.msg() == core_msg::orientation ? display_invalidate_reason::orientation_changed : display_invalidate_reason::none; display::display_info info = { system_info::current_screen_orientation(), system_info::current_screen_orientation(), graphics::size<float>((float)LOWORD(value), (float)HIWORD(value)), core_view_scale_factor(), 96 }; m.result(-1); idisplay_info_event_args_t args = new display_info_event_args(m, this, reason, info); try { it->value->invoke(args.get()); } catch (const exception & e) { } } def_wndproc(m); return m.result(); } dword core_app::on_pointer_event(events::message& m) { int handled = 0; auto it = m_event_listeners.find(m.msg()); if (it.is_valid()) { WPARAM wprm = (WPARAM)m.wparam(); LPARAM lprm = (LPARAM)m.lparam(); short id; bool is_pa; bool is_sa; input::pointer_hardware_type_t type; input::key_modifiers_t modifiers = input::key_modifiers::none; POINTER_INFO pi; id = (short)GET_POINTERID_WPARAM(wprm); GetPointerInfo((uint)id, &pi); type = (input::pointer_hardware_type)(pi.pointerType - 2); is_pa = IS_POINTER_FIRSTBUTTON_WPARAM(wprm); is_sa = IS_POINTER_SECONDBUTTON_WPARAM(wprm); //POINTER_MOD_SHIFT modifiers += ((POINTER_MOD_CTRL & pi.dwKeyStates) == POINTER_MOD_CTRL) ? input::key_modifiers::control : input::key_modifiers::none; modifiers += ((POINTER_MOD_SHIFT & pi.dwKeyStates) == POINTER_MOD_SHIFT) ? input::key_modifiers::shift : input::key_modifiers::none; ipointer_event_args_t args = new pointer_event_args(m, { graphics::point<float>((float)GET_X_LPARAM(lprm), (float)GET_Y_LPARAM(lprm)), id, is_pa, is_sa, type, modifiers, }); int count = 0; try { handled = it->value->invoke(args.get()); } catch (const exception & e) { } } if (!handled) def_wndproc(m); else m.result(0); return m.result(); } dword core_app::on_mouse_event(events::message& m) { int handled = 0; auto it = m_event_listeners.find(m.msg()); if (it.is_valid()) { WPARAM wprm = (WPARAM)m.wparam(); LPARAM lprm = m.lparam(); short id; bool is_pa; bool is_sa; input::pointer_hardware_type_t type; input::key_modifiers_t modifiers = input::key_modifiers::none; id = 1U; is_pa = (MK_LBUTTON & wprm) == MK_LBUTTON; is_sa = (MK_RBUTTON & wprm) == MK_RBUTTON; type = input::pointer_hardware_type::mouse; modifiers += ((MK_CONTROL & wprm) == MK_CONTROL) ? input::key_modifiers::control : input::key_modifiers::none; modifiers += ((MK_SHIFT & wprm) == MK_SHIFT) ? input::key_modifiers::shift : input::key_modifiers::none; ipointer_event_args_t args = new pointer_event_args(m, { graphics::point<float>((float)GET_X_LPARAM(lprm), (float)GET_Y_LPARAM(lprm)), id, is_pa, is_sa, type, modifiers, }); int count = 0; try { handled = it->value->invoke(args.get()); } catch (const exception & e) { } } if (!handled) def_wndproc(m); else m.result(0); return m.result(); } dword core_app::on_key_event(events::message& m) { auto it = m_event_listeners.find(m.msg()); if (it.is_valid()) { uint modifiers = 0; if (GetKeyState(VK_CONTROL) && 0x8000) modifiers |= (uint)input::key_modifiers::control; if (GetKeyState(VK_SHIFT) && 0x8000) modifiers |= (uint)input::key_modifiers::shift; if (GetKeyState(VK_MENU) && 0x8000) modifiers |= (uint)input::key_modifiers::alt; if (GetKeyState(VK_CAPITAL) && 0x0001) modifiers |= (uint)input::key_modifiers::caps_lock; if (GetKeyState(VK_NUMLOCK) && 0x0001) modifiers |= (uint)input::key_modifiers::num_lock; ikey_event_args_t args = new key_event_args(m, { (input::virtual_key)m.wparam(), //property<const virtual_key> key; (char32_t)m.wparam(), //property<const virtual_key> key; (word)(uint)m.lparam(), //property<const word> flags; m.msg() == core_msg::key_down ? input::key_state::pressed : m.msg() == core_msg::put_char ? input::key_state::pressed : input::key_state::released, (input::key_modifiers)modifiers //property<const key_modifiers> modifiers; }); m.result(-1); try { it->value->invoke(args.get()); } catch (const exception & e) { } } def_wndproc(m); return m.result(); } dword core_app::on_task_command(events::message& m) { auto task = reinterpret_cast<async_task*>(m.lparam()); task->execute(); task->release(); m.result(0); return 0; }
23.353846
134
0.691041
ChuyX3
1dbb1922e53cbb91c97d0eb823fb5d585d09ed3a
876
cpp
C++
CodeFights/differentSubstrings.cpp
AREA44/competitive-programming
00cede478685bf337193bce4804f13c4ff170903
[ "MIT" ]
null
null
null
CodeFights/differentSubstrings.cpp
AREA44/competitive-programming
00cede478685bf337193bce4804f13c4ff170903
[ "MIT" ]
null
null
null
CodeFights/differentSubstrings.cpp
AREA44/competitive-programming
00cede478685bf337193bce4804f13c4ff170903
[ "MIT" ]
null
null
null
// Given a string, find the number of different non-empty substrings in it. // Example // For inputString = "abac", the output should be // differentSubstrings(inputString) = 9. string substring(std::string inputString, int start, int end){ std::string resultString; for(int i=start;i<end;i++) resultString+=inputString[i]; return resultString; } int differentSubstrings(std::string inputString) { std::vector<std::string> substrings; int result = 1; for (int i = 0; i < inputString.size(); i++) { for (int j = i + 1; j <= inputString.size(); j++) { substrings.push_back(substring(inputString,i,j)); } } sort(substrings.begin(),substrings.end()); for (int i = 1; i < substrings.size(); i++) { if (substrings[i] != substrings[i - 1]) { result++; } } return result; }
30.206897
75
0.606164
AREA44
1dbf91e581bdbaf7c3e59cdfeaf4f7d19790ba7e
1,648
hpp
C++
lumino/Graphics/src/Animation/AnimationManager.hpp
lriki/Lumino
1a80430f4a83dbdfbe965b3d5b16064991b3edb0
[ "MIT" ]
30
2016-01-24T05:35:45.000Z
2020-03-03T09:54:27.000Z
lumino/Graphics/src/Animation/AnimationManager.hpp
lriki/Lumino
1a80430f4a83dbdfbe965b3d5b16064991b3edb0
[ "MIT" ]
35
2016-04-18T06:14:08.000Z
2020-02-09T15:51:58.000Z
lumino/Graphics/src/Animation/AnimationManager.hpp
lriki/Lumino
1a80430f4a83dbdfbe965b3d5b16064991b3edb0
[ "MIT" ]
5
2016-04-03T02:52:05.000Z
2018-01-02T16:53:06.000Z
#pragma once #include <LuminoGraphics/Animation/Common.hpp> #include <LuminoGraphics/Animation/AnimationClip.hpp> #include <LuminoEngine/Base/detail/RefObjectCache.hpp> namespace ln { class AnimationClock; namespace detail { class AnimationManager : public RefObject { public: struct Settings { AssetManager* assetManager = nullptr; }; static AnimationManager* initialize(const Settings& settings); static void terminate(); static inline AnimationManager* instance() { return s_instance; } // void setSceneManager(SceneManager* sceneManager) { m_sceneManager = sceneManager; } const Ref<AnimationClipImportSettings>& defaultAnimationClipImportSettings() const { return m_defaultAnimationClipImportSettings; } void addClockToAffiliation(AnimationClock* clock, AnimationClockAffiliation affiliation); Ref<GenericTask<Ref<AnimationClip>>> loadAnimationClip(const StringView& filePath); // Ref<AnimationClipPromise> loadAnimationClipAsync(const StringView& filePath); // Ref<AnimationClip> acquireAnimationClip(const AssetPath& assetPath); // void loadAnimationClip(AnimationClip* clip, const AssetPath& assetPath); void updateFrame(float elapsedSeconds); private: AnimationManager(); virtual ~AnimationManager(); Result init(const Settings& settings); void dispose(); AssetManager* m_assetManager; // SceneManager* m_sceneManager; ObjectCache<String, AnimationClip> m_animationClipCache; Ref<AnimationClipImportSettings> m_defaultAnimationClipImportSettings; static Ref<AnimationManager> s_instance; }; } // namespace detail } // namespace ln
34.333333
135
0.771238
lriki
1dc0cf1354ab9c6c14c387bb3ada9152c85a255a
3,536
cpp
C++
Source/Core/DX_12/DX_12Image.cpp
glowing-chemist/Bell
0cf4d0ac925940869077779700c1d3bd45ff841f
[ "MIT" ]
14
2020-02-12T19:13:46.000Z
2022-03-05T02:26:06.000Z
Source/Core/DX_12/DX_12Image.cpp
glowing-chemist/Bell
0cf4d0ac925940869077779700c1d3bd45ff841f
[ "MIT" ]
5
2020-08-06T07:19:47.000Z
2021-01-05T21:20:51.000Z
Source/Core/DX_12/DX_12Image.cpp
glowing-chemist/Bell
0cf4d0ac925940869077779700c1d3bd45ff841f
[ "MIT" ]
2
2021-09-18T13:36:47.000Z
2021-12-04T15:08:53.000Z
#include "DX_12Image.hpp" #include "DX_12RenderDevice.hpp" #include "Core/ConversionUtils.hpp" #include <algorithm> DX_12Image::DX_12Image( RenderDevice* device, const Format format, const ImageUsage usage, const uint32_t x, const uint32_t y, const uint32_t z, const uint32_t mips, const uint32_t levels, const uint32_t samples, const std::string& name) : ImageBase(device, format, usage, x, y, z, mips, levels, samples, name), mIsOwned(true) { D3D12_RESOURCE_DIMENSION type; if (x != 0 && y == 0 && z == 0) type = D3D12_RESOURCE_DIMENSION::D3D12_RESOURCE_DIMENSION_TEXTURE1D; if (x != 0 && y != 0 && z == 1) type = D3D12_RESOURCE_DIMENSION::D3D12_RESOURCE_DIMENSION_TEXTURE2D; if (x != 0 && y != 0 && z > 1) type = D3D12_RESOURCE_DIMENSION::D3D12_RESOURCE_DIMENSION_TEXTURE3D; D3D12_RESOURCE_DESC imageDesc{}; imageDesc.Width = x; imageDesc.Height = y; imageDesc.DepthOrArraySize = std::max(z, levels); imageDesc.Dimension = type; imageDesc.Layout = D3D12_TEXTURE_LAYOUT::D3D12_TEXTURE_LAYOUT_UNKNOWN; imageDesc.Format = getDX12ImageFormat(format); imageDesc.MipLevels = mips; imageDesc.Alignment = D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT; imageDesc.Flags = getDX12ImageUsage(usage); DXGI_SAMPLE_DESC sampleDesc{}; sampleDesc.Count = samples; sampleDesc.Quality = 0; imageDesc.SampleDesc = sampleDesc; DX_12RenderDevice* dev = static_cast<DX_12RenderDevice*>(getDevice()); const D3D12MA::ALLOCATION_DESC allocDesc = dev->getResourceAllocationDescription(usage); dev->createResource(imageDesc, allocDesc, D3D12_RESOURCE_STATE_COMMON , &mImage, &mImageMemory); } DX_12Image::DX_12Image(RenderDevice* device, ID3D12Resource* resource, const Format format, const ImageUsage usage, const uint32_t x, const uint32_t y, const uint32_t z, const uint32_t mips, const uint32_t levels, const uint32_t samples, const std::string& name) : ImageBase(device, format, usage, x, y, z, mips, levels, samples, name) { mImage = resource; mImageMemory = nullptr; mIsOwned = false; } DX_12Image::~DX_12Image() { if(mIsOwned) getDevice()->destroyImage(*this); } void DX_12Image::swap(ImageBase& other) { ImageBase::swap(other); DX_12Image& DXImage = static_cast<DX_12Image&>(other); ID3D12Resource* tmpImage = mImage; D3D12MA::Allocation* tmpMemory = DXImage.mImageMemory; mImage = DXImage.mImage; mImageMemory = DXImage.mImageMemory; DXImage.mImage = tmpImage; DXImage.mImageMemory = tmpMemory; } void DX_12Image::setContents( const void* data, const uint32_t xsize, const uint32_t ysize, const uint32_t zsize, const uint32_t level, const uint32_t lod, const int32_t offsetx, const int32_t offsety, const int32_t offsetz) { BELL_LOG("DX_12Image::SetContents not implemented") } void DX_12Image::clear(const float4&) { BELL_LOG("DX_12Image::clear not implemented") } void DX_12Image::generateMips() { BELL_LOG("DX_12Image::generateMips not implemented") }
31.017544
104
0.628394
glowing-chemist
1dc22fe9dcdc182e9673745eb5fc1111e9063e9e
418
cpp
C++
Volume118/11879 - Brick Game/11879.cpp
rstancioiu/uva-online-judge
31c536d764462d389b48b4299b9731534824c9f5
[ "MIT" ]
1
2017-01-25T18:07:49.000Z
2017-01-25T18:07:49.000Z
Volume118/11879 - Brick Game/11879.cpp
rstancioiu/uva-online-judge
31c536d764462d389b48b4299b9731534824c9f5
[ "MIT" ]
null
null
null
Volume118/11879 - Brick Game/11879.cpp
rstancioiu/uva-online-judge
31c536d764462d389b48b4299b9731534824c9f5
[ "MIT" ]
null
null
null
// Author: Stancioiu Nicu Razvan // Problem: http://uva.onlinejudge.org/external/118/11879.html #include <iostream> #include <string> #define MOD 17 using namespace std; bool Divide(string a) { int t=0; for(int i=0;i<a.length();++i) { t*=10; t+=a[i]-'0'; t%=MOD; } if(t==0) return true; else return false; } int main() { string s; while(cin>>s && s!="0") { cout<<Divide(s)<<endl; } return 0; }
13.0625
62
0.610048
rstancioiu
1dc53e9641207626cc069fd7d6a480be67324a19
7,594
cpp
C++
GPTP/src/hooks/unit_morph_inject.cpp
idmontie/gptp
14d68e5eac84c2f3085ac25a7fff31a07ea387f6
[ "0BSD" ]
8
2015-04-03T16:50:59.000Z
2021-01-06T17:12:29.000Z
GPTP/src/hooks/unit_morph_inject.cpp
idmontie/gptp
14d68e5eac84c2f3085ac25a7fff31a07ea387f6
[ "0BSD" ]
6
2015-04-03T18:10:56.000Z
2016-02-18T05:04:21.000Z
GPTP/src/hooks/unit_morph_inject.cpp
idmontie/gptp
14d68e5eac84c2f3085ac25a7fff31a07ea387f6
[ "0BSD" ]
6
2015-04-04T04:37:33.000Z
2018-04-09T09:03:50.000Z
#include "unit_morph.h" #include <hook_tools.h> #include <SCBW/api.h> #include <cassert> namespace { //-------- CMDRECV_UnitMorph --------// const u32 Func_AddUnitToBuildQueue = 0x00467250; bool addUnitToBuildQueue(const CUnit *unit, u16 unitId) { static u32 result; u32 unitId_ = unitId; __asm { PUSHAD PUSH unitId_ MOV EDI, unit CALL Func_AddUnitToBuildQueue MOV result, EAX POPAD } return result != 0; } void __stdcall unitMorphWrapper_CMDRECV_UnitMorph(u8 *commandData) { const u16 morphUnitId = *((u16*)&commandData[1]); *selectionIndexStart = 0; while (CUnit *unit = getActivePlayerNextSelection()) { if (hooks::unitCanMorphHook(unit, morphUnitId) && unit->mainOrderId != OrderId::Morph1 && addUnitToBuildQueue(unit, morphUnitId)) { unit->orderTo(OrderId::Morph1); } } scbw::refreshConsole(); } //-------- BTNSCOND_CanBuildUnit --------// s32 __fastcall unitMorphWrapper_BTNSCOND_CanBuildUnit(u16 buildUnitId, s32 playerId, const CUnit *unit) { if (*clientSelectionCount <= 1 || hooks::getUnitMorphEggTypeHook(unit->id) != UnitId::None) return unit->canMakeUnit(buildUnitId, playerId); return 0; } //-------- Orders_Morph1 --------// const u32 Hook_Orders_Morph1_Check_Success = 0x0045DFCA; void __declspec(naked) unitMorphWrapper_Orders_Morph1_Check() { static CUnit *unit; __asm { PUSHAD MOV EBP, ESP MOV unit, ESI } if (hooks::getUnitMorphEggTypeHook(unit->id) != UnitId::None) { __asm { POPAD JMP Hook_Orders_Morph1_Check_Success } } else { __asm { POPAD POP EDI POP ESI MOV ESP, EBP POP EBP RETN } } } const u32 Hook_Orders_Morph1_EggType_Return = 0x0045E048; void __declspec(naked) unitMorphWrapper_Orders_Morph1_EggType() { static CUnit *unit; static u32 morphEggType; __asm { PUSHAD MOV EBP, ESP MOV unit, ESI } unit->status &= ~(UnitStatus::Completed); morphEggType = hooks::getUnitMorphEggTypeHook(unit->id); assert(hooks::isEggUnitHook(morphEggType)); __asm { POPAD PUSH morphEggType JMP Hook_Orders_Morph1_EggType_Return } } //-------- hasSuppliesForUnit --------// Bool32 __stdcall hasSuppliesForUnitWrapper(u8 playerId, u16 unitId, Bool32 canShowErrorMessage) { if (hooks::hasSuppliesForUnitHook(playerId, unitId, canShowErrorMessage != 0)) return 1; else return 0; } //-------- cancelBuild --------// typedef void(__stdcall *CancelZergBuildingFunc)(CUnit*); CancelZergBuildingFunc cancelZergBuilding = (CancelZergBuildingFunc)0x0045DA40; const u32 Func_ChangeUnitType = 0x0049FED0; void changeUnitType(CUnit *unit, u16 newUnitId) { u32 newUnitId_ = newUnitId; __asm { PUSHAD PUSH newUnitId_ MOV EAX, unit CALL Func_ChangeUnitType POPAD } } const u32 Func_ReplaceSpriteImages = 0x00499BB0; void replaceSpriteImages(CSprite *sprite, u16 imageId, u8 imageDirection) { u32 imageId_ = imageId, imageDirection_ = imageDirection; __asm { PUSHAD PUSH imageDirection_ PUSH imageId_ MOV EAX, sprite CALL Func_ReplaceSpriteImages POPAD } } //-------- cancelUnit --------// void __fastcall cancelUnitWrapper(CUnit *unit) { //Default StarCraft behavior if (unit->isDead()) return; if (unit->status & UnitStatus::Completed) return; if (unit->id == UnitId::nydus_canal && unit->building.nydusExit) return; //Don't bother if unit is not morphed yet if (unit->id == UnitId::mutalisk || unit->id == UnitId::hydralisk) return; //Don't bother if unit has finished morphing if (unit->id == UnitId::guardian || unit->id == UnitId::devourer || unit->id == UnitId::lurker) return; if (unit->status & UnitStatus::GroundedBuilding) { if (unit->getRace() == RaceId::Zerg) { cancelZergBuilding(unit); return; } resources->minerals[unit->playerId] += units_dat::MineralCost[unit->id] * 3 / 4; resources->gas[unit->playerId] += units_dat::GasCost[unit->id] * 3 / 4; } else { u16 refundUnitId; if (hooks::isEggUnitHook(unit->id)) refundUnitId = unit->buildQueue[unit->buildQueueSlot % 5]; else refundUnitId = unit->id; resources->minerals[unit->playerId] += units_dat::MineralCost[refundUnitId]; resources->gas[unit->playerId] += units_dat::GasCost[refundUnitId]; } u16 cancelChangeUnitId = hooks::getCancelMorphRevertTypeHook(unit); if (cancelChangeUnitId == UnitId::None) { if (unit->id == UnitId::nuclear_missile) { CUnit *silo = unit->connectedUnit; if (silo) { silo->building.silo.nuke = NULL; silo->mainOrderState = 0; } scbw::refreshConsole(); } unit->remove(); } else { changeUnitType(unit, cancelChangeUnitId); unit->remainingBuildTime = 0; unit->buildQueue[unit->buildQueueSlot] = UnitId::None; replaceSpriteImages(unit->sprite, sprites_dat::ImageId[flingy_dat::SpriteID[units_dat::Graphic[unit->displayedUnitId]]], 0); unit->orderSignal &= ~0x4; unit->playIscriptAnim(IscriptAnimation::SpecialState2); unit->orderTo(OrderId::ZergBirth); } } //-------- getRemainingBuildTimePct --------// s32 getRemainingBuildTimePctHook(const CUnit *unit) { u16 unitId = unit->id; if (hooks::isEggUnitHook(unitId) || unit->isRemorphingBuilding()) unitId = unit->buildQueue[unit->buildQueueSlot]; return 100 * (units_dat::TimeCost[unitId] - unit->remainingBuildTime) / units_dat::TimeCost[unitId]; } //Inject @ 0x004669E0 void __declspec(naked) getRemainingBuildTimePctWrapper() { static CUnit *unit; static s32 percentage; __asm { PUSHAD MOV unit, ESI MOV EBP, ESP } percentage = getRemainingBuildTimePctHook(unit); __asm { POPAD MOV EAX, percentage RETN } } //-------- orders_zergBirth --------// //Inject @ 0x0045DE00 const u32 Hook_GetUnitVerticalOffsetOnBirth_Return = 0x0045DE2C; void __declspec(naked) getUnitVerticalOffsetOnBirthWrapper() { static CUnit *unit; static s16 yOffset; __asm { PUSHAD MOV unit, EDI } yOffset = hooks::getUnitVerticalOffsetOnBirth(unit); __asm { POPAD MOVSX EAX, yOffset JMP Hook_GetUnitVerticalOffsetOnBirth_Return } } //Inject @ 0x0045DE57 const u32 Hook_IsRallyableEggUnit_Yes = 0x0045DE6C; const u32 Hook_IsRallyableEggUnit_No = 0x0045DE8B; void __declspec(naked) isRallyableEggUnitWrapper() { static CUnit *unit; __asm { POP ESI POP EBX PUSHAD MOV unit, EDI } if (hooks::isRallyableEggUnitHook(unit->displayedUnitId)) { __asm { POPAD JMP Hook_IsRallyableEggUnit_Yes } } else { __asm { POPAD JMP Hook_IsRallyableEggUnit_No } } } } //unnamed namespace namespace hooks { void injectUnitMorphHooks() { callPatch(unitMorphWrapper_CMDRECV_UnitMorph, 0x00486B50); jmpPatch(unitMorphWrapper_BTNSCOND_CanBuildUnit, 0x00428E60); jmpPatch(unitMorphWrapper_Orders_Morph1_Check, 0x0045DFB0); jmpPatch(unitMorphWrapper_Orders_Morph1_EggType, 0x0045E019); jmpPatch(hasSuppliesForUnitWrapper, 0x0042CF70); jmpPatch(cancelUnitWrapper, 0x00468280); jmpPatch(getRemainingBuildTimePctWrapper, 0x004669E0); jmpPatch(getUnitVerticalOffsetOnBirthWrapper, 0x0045DE00); jmpPatch(isRallyableEggUnitWrapper, 0x0045DE57); } } //hooks
25.145695
107
0.667501
idmontie
1dc58721a7bf7de73e554838d8cf09c48780043b
1,661
hpp
C++
include/codegen/include/System/Security/Cryptography/X509Certificates/X509Utils.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
1
2021-11-12T09:29:31.000Z
2021-11-12T09:29:31.000Z
include/codegen/include/System/Security/Cryptography/X509Certificates/X509Utils.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
null
null
null
include/codegen/include/System/Security/Cryptography/X509Certificates/X509Utils.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
2
2021-10-03T02:14:20.000Z
2021-11-12T09:29:36.000Z
// Autogenerated from CppHeaderCreator on 7/27/2020 3:10:18 PM // Created by Sc2ad // ========================================================================= #pragma once #pragma pack(push, 8) // Begin includes #include "utils/typedefs.h" // Including type: System.Object #include "System/Object.hpp" #include "utils/il2cpp-utils.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: System::Security::Cryptography namespace System::Security::Cryptography { // Forward declaring type: OidGroup struct OidGroup; } // Completed forward declares // Type namespace: System.Security.Cryptography.X509Certificates namespace System::Security::Cryptography::X509Certificates { // Autogenerated type: System.Security.Cryptography.X509Certificates.X509Utils class X509Utils : public ::Il2CppObject { public: // static System.String FindOidInfo(System.UInt32 keyType, System.String keyValue, System.Security.Cryptography.OidGroup oidGroup) // Offset: 0x1206A30 static ::Il2CppString* FindOidInfo(uint keyType, ::Il2CppString* keyValue, System::Security::Cryptography::OidGroup oidGroup); // static System.String FindOidInfoWithFallback(System.UInt32 key, System.String value, System.Security.Cryptography.OidGroup group) // Offset: 0x12036A0 static ::Il2CppString* FindOidInfoWithFallback(uint key, ::Il2CppString* value, System::Security::Cryptography::OidGroup group); }; // System.Security.Cryptography.X509Certificates.X509Utils } DEFINE_IL2CPP_ARG_TYPE(System::Security::Cryptography::X509Certificates::X509Utils*, "System.Security.Cryptography.X509Certificates", "X509Utils"); #pragma pack(pop)
48.852941
147
0.747742
Futuremappermydud
1dca671d290cc993c2c5635fd7c85612ac28634f
1,943
cpp
C++
Src/EB/AMReX_EB_utils.cpp
khou2020/amrex
2a75167fd3febd46e0090a89941e42793224ad15
[ "BSD-3-Clause-LBNL" ]
null
null
null
Src/EB/AMReX_EB_utils.cpp
khou2020/amrex
2a75167fd3febd46e0090a89941e42793224ad15
[ "BSD-3-Clause-LBNL" ]
null
null
null
Src/EB/AMReX_EB_utils.cpp
khou2020/amrex
2a75167fd3febd46e0090a89941e42793224ad15
[ "BSD-3-Clause-LBNL" ]
1
2020-01-17T05:00:26.000Z
2020-01-17T05:00:26.000Z
#include <AMReX_EB_F.H> #include <AMReX_MultiFab.H> #include <AMReX_EB_utils.H> #include <AMReX_Geometry.H> #include <AMReX_MultiCutFab.H> #include <AMReX_EBFabFactory.H> namespace amrex { void FillEBNormals(MultiFab & normals, const EBFArrayBoxFactory & eb_factory, const Geometry & geom) { BoxArray ba = normals.boxArray(); DistributionMapping dm = normals.DistributionMap(); int n_grow = normals.nGrow(); // Dummy array for MFIter MultiFab dummy(ba, dm, 1, n_grow, MFInfo(), eb_factory); // Area fraction data std::array<const MultiCutFab*, AMREX_SPACEDIM> areafrac = eb_factory.getAreaFrac(); const auto & flags = eb_factory.getMultiEBCellFlagFab(); #ifdef _OPENMP #pragma omp parallel #endif for(MFIter mfi(dummy, true); mfi.isValid(); ++mfi) { Box tile_box = mfi.growntilebox(); const int * lo = tile_box.loVect(); const int * hi = tile_box.hiVect(); const auto & flag = flags[mfi]; if (flag.getType(tile_box) == FabType::singlevalued) { // Target for compute_normals(...) auto & norm_tile = normals[mfi]; // Area fractions in x, y, and z directions const auto & af_x_tile = (* areafrac[0])[mfi]; const auto & af_y_tile = (* areafrac[1])[mfi]; const auto & af_z_tile = (* areafrac[2])[mfi]; amrex_eb_compute_normals(lo, hi, BL_TO_FORTRAN_3D(flag), BL_TO_FORTRAN_3D(norm_tile), BL_TO_FORTRAN_3D(af_x_tile), BL_TO_FORTRAN_3D(af_y_tile), BL_TO_FORTRAN_3D(af_z_tile) ); } } normals.FillBoundary(geom.periodicity()); } }
34.696429
91
0.545548
khou2020
1dca85fc7bffe94417030860dbab852e517643dc
14,326
hpp
C++
tm_kit/basic/CalculationsOnInit.hpp
cd606/tm_basic
ea2d13b561dd640161823a5e377f35fcb7fe5d48
[ "Apache-2.0" ]
1
2020-05-22T08:47:02.000Z
2020-05-22T08:47:02.000Z
tm_kit/basic/CalculationsOnInit.hpp
cd606/tm_basic
ea2d13b561dd640161823a5e377f35fcb7fe5d48
[ "Apache-2.0" ]
null
null
null
tm_kit/basic/CalculationsOnInit.hpp
cd606/tm_basic
ea2d13b561dd640161823a5e377f35fcb7fe5d48
[ "Apache-2.0" ]
null
null
null
#ifndef TM_KIT_BASIC_CALCULATIONS_ON_INIT_HPP_ #define TM_KIT_BASIC_CALCULATIONS_ON_INIT_HPP_ #include <tm_kit/infra/RealTimeApp.hpp> #include <tm_kit/infra/SinglePassIterationApp.hpp> #include <tm_kit/infra/TopDownSinglePassIterationApp.hpp> #include <tm_kit/infra/Environments.hpp> #include <tm_kit/infra/TraceNodesComponent.hpp> #include <type_traits> namespace dev { namespace cd606 { namespace tm { namespace basic { //Importers for calculating value on init //Please notice that Func takes only one argument (the logger) //This is deliberate choice. The reason is that if Func needs anything //inside Env, it should be able to capture that by itself outside this //logic. If we force Env to maintain something for use of Func, which is //only executed at startup, there will be trickly resource-release timing //questions, and by not doing that, we allow Func to manage resources by //itself. template <class App, class Func> class ImporterOfValueCalculatedOnInit {}; template <class Env, class Func> class ImporterOfValueCalculatedOnInit<infra::template RealTimeApp<Env>, Func> : public infra::template RealTimeApp<Env>::template AbstractImporter< decltype((* ((Func *) nullptr))( std::function<void(infra::LogLevel, std::string const &)>() )) > { private: Func f_; public: using OutputT = decltype((* ((Func *) nullptr))( std::function<void(infra::LogLevel, std::string const &)>() )); ImporterOfValueCalculatedOnInit(Func &&f) : f_(std::move(f)) {} virtual void start(Env *env) override final { TM_INFRA_IMPORTER_TRACER(env); this->publish(env, f_( [env](infra::LogLevel level, std::string const &s) { env->log(level, s); } )); } }; template <class Env, class Func> class ImporterOfValueCalculatedOnInit<infra::template SinglePassIterationApp<Env>, Func> : public infra::template SinglePassIterationApp<Env>::template AbstractImporter< decltype((* ((Func *) nullptr))( std::function<void(infra::LogLevel, std::string const &)>() )) > { public: using OutputT = decltype((* ((Func *) nullptr))( std::function<void(infra::LogLevel, std::string const &)>() )); private: Func f_; typename infra::template SinglePassIterationApp<Env>::template Data<OutputT> data_; public: ImporterOfValueCalculatedOnInit(Func &&f) : f_(std::move(f)), data_(std::nullopt) {} virtual void start(Env *env) override final { TM_INFRA_IMPORTER_TRACER(env); data_ = infra::template SinglePassIterationApp<Env>::template pureInnerData<OutputT>( env , f_( [env](infra::LogLevel level, std::string const &s) { env->log(level, s); } ) , true ); } virtual typename infra::template SinglePassIterationApp<Env>::template Data<OutputT> generate() override final { return data_; } }; template <class Env, class Func> class ImporterOfValueCalculatedOnInit<infra::template TopDownSinglePassIterationApp<Env>, Func> : public infra::template TopDownSinglePassIterationApp<Env>::template AbstractImporter< decltype((* ((Func *) nullptr))( std::function<void(infra::LogLevel, std::string const &)>() )) > { public: using OutputT = decltype((* ((Func *) nullptr))( std::function<void(infra::LogLevel, std::string const &)>() )); private: Func f_; typename infra::template TopDownSinglePassIterationApp<Env>::template Data<OutputT> data_; public: ImporterOfValueCalculatedOnInit(Func &&f) : f_(std::move(f)), data_(std::nullopt) {} virtual void start(Env *env) override final { TM_INFRA_IMPORTER_TRACER(env); data_ = infra::template TopDownSinglePassIterationApp<Env>::template pureInnerData<OutputT>( env , f_( [env](infra::LogLevel level, std::string const &s) { env->log(level, s); } ) , true ); } virtual std::tuple<bool, typename infra::template TopDownSinglePassIterationApp<Env>::template Data<OutputT>> generate() override final { return {false, std::move(data_)}; } }; template <class App, class Func> auto importerOfValueCalculatedOnInit(Func &&f) -> std::shared_ptr<typename App::template Importer< typename ImporterOfValueCalculatedOnInit<App,Func>::OutputT >> { return App::importer( new ImporterOfValueCalculatedOnInit<App,Func>(std::move(f)) ); } //on order facilities for holding pre-calculated value and returning it on query template <class App, class Req, class PreCalculatedResult> class LocalOnOrderFacilityReturningPreCalculatedValue : public App::template AbstractIntegratedLocalOnOrderFacility<Req, PreCalculatedResult, PreCalculatedResult> { private: std::conditional_t<App::PossiblyMultiThreaded, std::mutex, bool> mutex_; PreCalculatedResult preCalculatedRes_; public: LocalOnOrderFacilityReturningPreCalculatedValue() : mutex_(), preCalculatedRes_() {} virtual void start(typename App::EnvironmentType *) {} virtual void handle(typename App::template InnerData<typename App::template Key<Req>> &&req) override final { TM_INFRA_FACILITY_TRACER_WITH_SUFFIX(req.environment, ":handle"); std::conditional_t<App::PossiblyMultiThreaded, std::lock_guard<std::mutex>, bool> _(mutex_); this->publish( req.environment , typename App::template Key<PreCalculatedResult> { req.timedData.value.id(), preCalculatedRes_ } , true ); } virtual void handle(typename App::template InnerData<PreCalculatedResult> &&data) override final { TM_INFRA_FACILITY_TRACER_WITH_SUFFIX(data.environment, ":input"); std::conditional_t<App::PossiblyMultiThreaded, std::lock_guard<std::mutex>, bool> _(mutex_); preCalculatedRes_ = std::move(data.timedData.value); } }; template <class App, class Req, class PreCalculatedResult> auto localOnOrderFacilityReturningPreCalculatedValue() -> std::shared_ptr<typename App::template LocalOnOrderFacility<Req, PreCalculatedResult, PreCalculatedResult>> { return App::localOnOrderFacility(new LocalOnOrderFacilityReturningPreCalculatedValue<App,Req,PreCalculatedResult>()); } template <class App, class Req, class PreCalculatedResult, class Func> class LocalOnOrderFacilityUsingPreCalculatedValue : public App::template AbstractIntegratedLocalOnOrderFacility< Req , decltype( (* ((Func *) nullptr))( * ((PreCalculatedResult const *) nullptr) , * ((Req const *) nullptr) ) ) , PreCalculatedResult > { private: Func f_; std::conditional_t<App::PossiblyMultiThreaded, std::mutex, bool> mutex_; PreCalculatedResult preCalculatedRes_; public: using OutputT = decltype( (* ((Func *) nullptr))( * ((PreCalculatedResult const *) nullptr) , * ((Req const *) nullptr) ) ); LocalOnOrderFacilityUsingPreCalculatedValue(Func &&f) : f_(std::move(f)), mutex_(), preCalculatedRes_() {} virtual void start(typename App::EnvironmentType *) override final {} virtual void handle(typename App::template InnerData<typename App::template Key<Req>> &&req) override final { TM_INFRA_FACILITY_TRACER_WITH_SUFFIX(req.environment, ":handle"); std::conditional_t<App::PossiblyMultiThreaded, std::lock_guard<std::mutex>, bool> _(mutex_); this->publish( req.environment , typename App::template Key<OutputT> { req.timedData.value.id(), f_(preCalculatedRes_, req.timedData.value.key()) } , true ); } virtual void handle(typename App::template InnerData<PreCalculatedResult> &&data) override final { TM_INFRA_FACILITY_TRACER_WITH_SUFFIX(data.environment, ":input"); std::conditional_t<App::PossiblyMultiThreaded, std::lock_guard<std::mutex>, bool> _(mutex_); preCalculatedRes_ = std::move(data.timedData.value); } }; template <class App, class Req, class PreCalculatedResult, class Func> auto localOnOrderFacilityUsingPreCalculatedValue(Func &&f) -> std::shared_ptr<typename App::template LocalOnOrderFacility<Req, typename LocalOnOrderFacilityUsingPreCalculatedValue<App,Req,PreCalculatedResult,Func>::OutputT, PreCalculatedResult>> { return App::localOnOrderFacility(new LocalOnOrderFacilityUsingPreCalculatedValue<App,Req,PreCalculatedResult,Func>(std::move(f))); } //combination of the two above, on order facilities for //holding pre-calculated value which is calculated internally //at init, and returning it on query template <class App, class Req, class CalcFunc> class OnOrderFacilityReturningInternallyPreCalculatedValue : public virtual App::IExternalComponent , public App::template AbstractOnOrderFacility< Req , decltype((std::declval<CalcFunc>())( std::function<void(infra::LogLevel, std::string const &)>() )) > { public: using PreCalculatedResult = decltype((std::declval<CalcFunc>())( std::function<void(infra::LogLevel, std::string const &)>() )); private: CalcFunc f_; PreCalculatedResult preCalculatedRes_; public: OnOrderFacilityReturningInternallyPreCalculatedValue(CalcFunc &&f) : f_(f), preCalculatedRes_() {} virtual void start(typename App::EnvironmentType *env) override final { preCalculatedRes_ = f_( [env](infra::LogLevel level, std::string const &s) { env->log(level, s); } ); } virtual void handle(typename App::template InnerData<typename App::template Key<Req>> &&req) override final { this->publish( req.environment , typename App::template Key<PreCalculatedResult> { req.timedData.value.id(), preCalculatedRes_ } , true ); } }; template <class App, class Req, class CalcFunc> auto onOrderFacilityReturningInternallyPreCalculatedValue(CalcFunc &&f) -> std::shared_ptr<typename App::template OnOrderFacility<Req, typename OnOrderFacilityReturningInternallyPreCalculatedValue<App,Req,CalcFunc>::PreCalculatedResult>> { return App::fromAbstractOnOrderFacility(new OnOrderFacilityReturningInternallyPreCalculatedValue<App,Req,CalcFunc>(std::move(f))); } template <class App, class Req, class CalcFunc, class FetchFunc> class OnOrderFacilityUsingInternallyPreCalculatedValue : public virtual App::IExternalComponent , public App::template AbstractOnOrderFacility< Req , decltype( (std::declval<FetchFunc>())( * ((typename OnOrderFacilityReturningInternallyPreCalculatedValue<App,Req,CalcFunc>::PreCalculatedResult const *) nullptr) , * ((Req const *) nullptr) ) ) > { public: using PreCalculatedResult = decltype((std::declval<CalcFunc>())( std::function<void(infra::LogLevel, std::string const &)>() )); using OutputT = decltype( (std::declval<FetchFunc>())( * ((PreCalculatedResult const *) nullptr) , * ((Req const *) nullptr) ) ); private: CalcFunc calcFunc_; FetchFunc fetchFunc_; PreCalculatedResult preCalculatedRes_; public: OnOrderFacilityUsingInternallyPreCalculatedValue(CalcFunc &&calcFunc, FetchFunc &&fetchFunc) : calcFunc_(std::move(calcFunc)), fetchFunc_(std::move(fetchFunc)), preCalculatedRes_() {} virtual void start(typename App::EnvironmentType *env) override final { TM_INFRA_FACILITY_TRACER_WITH_SUFFIX(env, ":start"); preCalculatedRes_ = calcFunc_( [env](infra::LogLevel level, std::string const &s) { env->log(level, s); } ); } virtual void handle(typename App::template InnerData<typename App::template Key<Req>> &&req) override final { TM_INFRA_FACILITY_TRACER_WITH_SUFFIX(req.environment, ":handle"); this->publish( req.environment , typename App::template Key<OutputT> { req.timedData.value.id(), fetchFunc_(preCalculatedRes_, req.timedData.value.key()) } , true ); } }; template <class App, class Req, class CalcFunc, class FetchFunc> auto onOrderFacilityUsingInternallyPreCalculatedValue(CalcFunc &&calcFunc, FetchFunc &&fetchFunc) -> std::shared_ptr<typename App::template OnOrderFacility<Req, typename OnOrderFacilityUsingInternallyPreCalculatedValue<App,Req,CalcFunc,FetchFunc>::OutputT>> { return App::fromAbstractOnOrderFacility(new OnOrderFacilityUsingInternallyPreCalculatedValue<App,Req,CalcFunc,FetchFunc>(std::move(calcFunc), std::move(fetchFunc))); } } } } } #endif
43.150602
194
0.615594
cd606
1dca89bec5153c7fe6683305110842690050fd61
1,608
cpp
C++
Sample/Sample_URLWriter/URLWriter.cpp
sherry0319/YTSvrLib
5dda75aba927c4bf5c6a727592660bfc2619a063
[ "MIT" ]
61
2016-10-13T09:24:31.000Z
2022-03-26T09:59:34.000Z
Sample/Sample_URLWriter/URLWriter.cpp
sherry0319/YTSvrLib
5dda75aba927c4bf5c6a727592660bfc2619a063
[ "MIT" ]
3
2018-05-15T10:42:22.000Z
2021-07-02T01:38:08.000Z
Sample/Sample_URLWriter/URLWriter.cpp
sherry0319/YTSvrLib
5dda75aba927c4bf5c6a727592660bfc2619a063
[ "MIT" ]
36
2016-12-28T04:54:41.000Z
2021-12-15T06:02:56.000Z
// URLWriter.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include <cstdlib> #include "URLWriter.h" static struct { const char* url; const char* post; }g_data[] = { {"http://v.juhe.cn/postcode/query?postcode=215001&key=%E7%94%B3%E8%AF%B7%E7%9A%84KEY",NULL}, {"http://v.juhe.cn/postcode/query","postcode=215001&key=%E7%94%B3%E8%AF%B7%E7%9A%84KEY"}, }; void OnURLRequestCallback(YTSvrLib::CURLRequest* pReq) { cout << "request index = " << pReq->m_ayParam[0] << endl; cout << "request code = " << pReq->m_nReturnCode << endl; cout << "return field = " << pReq->m_strReturn << endl; } void OnURLRequestSync() { std::string outdata; int nResponseCode = YTSvrLib::CGlobalCURLRequest::GetInstance()->SendHTTPGETMessage(g_data[0].url, &outdata); cout << "sync get request code = " << nResponseCode << endl; cout << "sync get request return field = " << outdata << endl; outdata.clear(); outdata.shrink_to_fit(); nResponseCode = YTSvrLib::CGlobalCURLRequest::GetInstance()->SendHTTPPOSTMessage(g_data[1].url, g_data[1].post, &outdata); cout << "sync post request code = " << nResponseCode << endl; cout << "sync post request return field = " << outdata << endl; } int _tmain(int argc, TCHAR* argv[], TCHAR* envp[]) { OnURLRequestSync(); CURLWriter::GetInstance()->StartURLWriter(5); int index = 0; while (true) { index++; for (int i = 0; i < _countof(g_data);++i) { CURLWriter::GetInstance()->AddURLRequest(g_data[i].url, g_data[i].post, (YTSvrLib::URLPARAM)index, 0, 0, 0, OnURLRequestCallback); } CURLWriter::GetInstance()->WaitForAllRequestDone(); } return 0; }
25.52381
133
0.675373
sherry0319
1dcc5344ae39d835e42f333a013c3e3cf8c500a5
3,731
cpp
C++
ocs2_core/test/initialization/InitializationTest.cpp
grizzi/ocs2
4b78c4825deb8b2efc992fdbeef6fdb1fcca2345
[ "BSD-3-Clause" ]
126
2021-07-13T13:59:12.000Z
2022-03-31T02:52:18.000Z
ocs2_core/test/initialization/InitializationTest.cpp
grizzi/ocs2
4b78c4825deb8b2efc992fdbeef6fdb1fcca2345
[ "BSD-3-Clause" ]
27
2021-07-14T12:14:04.000Z
2022-03-30T16:27:52.000Z
ocs2_core/test/initialization/InitializationTest.cpp
grizzi/ocs2
4b78c4825deb8b2efc992fdbeef6fdb1fcca2345
[ "BSD-3-Clause" ]
55
2021-07-14T07:08:47.000Z
2022-03-31T15:54:30.000Z
/****************************************************************************** Copyright (c) 2017, Farbod Farshidian. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ******************************************************************************/ #include <iostream> #include <gtest/gtest.h> #include <ocs2_core/initialization/OperatingPoints.h> class InitializationTest : public testing::Test { protected: static constexpr size_t stateDim_ = 3; static constexpr size_t inputDim_ = 2; using OperatingPoints = ocs2::OperatingPoints; using scalar_t = ocs2::scalar_t; using scalar_array_t = ocs2::scalar_array_t; using vector_t = ocs2::vector_t; using vector_array_t = ocs2::vector_array_t; InitializationTest() = default; vector_t input, nextState; }; TEST_F(InitializationTest, SingleOperatingPoint) { const scalar_t t0 = 0.0; const scalar_t tf = 1.0; const vector_array_t xTraj = {vector_t::Random(stateDim_)}; const vector_array_t uTraj = {vector_t::Random(inputDim_)}; OperatingPoints operatingPoints({t0}, xTraj, uTraj); operatingPoints.compute(t0, xTraj[0], tf, input, nextState); ASSERT_TRUE(nextState.isApprox(xTraj[0])); ASSERT_TRUE(input.isApprox(uTraj[0])); } TEST_F(InitializationTest, ZeroTimeInterval) { const scalar_t t0 = 0.0; const vector_array_t xTraj{vector_t::Random(stateDim_)}; const vector_array_t uTraj = {vector_t::Random(inputDim_)}; OperatingPoints operatingPoints({t0}, xTraj, uTraj); operatingPoints.compute(t0, xTraj[0], t0, input, nextState); ASSERT_TRUE(nextState.isApprox(xTraj[0])); ASSERT_TRUE(input.isApprox(uTraj[0])); } TEST_F(InitializationTest, Trajectory) { constexpr size_t N = 20; scalar_array_t tTraj(N); scalar_t n = 0; std::generate(tTraj.begin(), tTraj.end(), [&n]() mutable { return n++; }); vector_array_t xTraj(N); std::generate(xTraj.begin(), xTraj.end(), [&]() { return vector_t::Random(stateDim_); }); vector_array_t uTraj(N); std::generate(uTraj.begin(), uTraj.end(), [&]() { return vector_t::Random(inputDim_); }); OperatingPoints operatingPoints(tTraj, xTraj, uTraj); for (size_t i = 0; i < N - 1; i++) { operatingPoints.compute(tTraj[i], xTraj[i], tTraj[i + 1], input, nextState); ASSERT_TRUE(input.isApprox(uTraj[i])); ASSERT_TRUE(nextState.isApprox(xTraj[i + 1])); } }
40.554348
91
0.724471
grizzi
1dcf151528f700d45c1e338fee82bb360d85b540
525
cpp
C++
solutions/986.interval-list-intersections.379341654.ac.cpp
satu0king/Leetcode-Solutions
2edff60d76c2898d912197044f6284efeeb34119
[ "MIT" ]
78
2020-10-22T11:31:53.000Z
2022-02-22T13:27:49.000Z
solutions/986.interval-list-intersections.379341654.ac.cpp
satu0king/Leetcode-Solutions
2edff60d76c2898d912197044f6284efeeb34119
[ "MIT" ]
null
null
null
solutions/986.interval-list-intersections.379341654.ac.cpp
satu0king/Leetcode-Solutions
2edff60d76c2898d912197044f6284efeeb34119
[ "MIT" ]
26
2020-10-23T15:10:44.000Z
2021-11-07T16:13:50.000Z
class Solution { public: vector<vector<int>> intervalIntersection(vector<vector<int>> &A, vector<vector<int>> &B) { int i = 0; int j = 0; int n1 = A.size(); int n2 = B.size(); vector<vector<int>> result; while (i < n1 && j < n2) { int r = min(A[i][1], B[j][1]); int l = max(A[i][0], B[j][0]); if (l <= r) result.push_back({l, r}); if (A[i][1] < B[j][1]) i++; else j++; } return result; } };
21.875
68
0.420952
satu0king
1dd041fd30ae293dfe082ac481b2680792b6bf81
3,781
cpp
C++
client/udpfwdclient.cpp
Skycoder42/Udp-Forward-Server
54028bf8b46658dc1915956e80791abd67477715
[ "BSD-3-Clause" ]
1
2022-03-24T15:45:26.000Z
2022-03-24T15:45:26.000Z
client/udpfwdclient.cpp
Skycoder42/Udp-Forward-Server
54028bf8b46658dc1915956e80791abd67477715
[ "BSD-3-Clause" ]
null
null
null
client/udpfwdclient.cpp
Skycoder42/Udp-Forward-Server
54028bf8b46658dc1915956e80791abd67477715
[ "BSD-3-Clause" ]
null
null
null
#include "udpfwdclient.h" #include <QNetworkDatagram> #include <announcepeermessage.h> #include <tunnelinmessage.h> using namespace UdpFwdProto; UdpFwdClient::UdpFwdClient(QObject *parent) : UdpFwdClient{10000, parent} {} UdpFwdClient::UdpFwdClient(int replyCacheSize, QObject *parent) : QObject{parent}, _socket{new QUdpSocket{this}}, _replyCache{replyCacheSize} { connect(_socket, qOverload<QAbstractSocket::SocketError>(&QUdpSocket::error), this, &UdpFwdClient::socketError); connect(_socket, &QUdpSocket::readyRead, this, &UdpFwdClient::readyRead); } bool UdpFwdClient::setup(PrivateKey key, QHostAddress fwdSvcAddress, quint16 port) { _key = std::move(key); _peerHost = std::move(fwdSvcAddress); _peerPort = port; if (_socket->isOpen()) _socket->close(); if (_socket->bind(QHostAddress::Any, 0, QAbstractSocket::DontShareAddress)) return true; else { _lastError = _socket->errorString(); emit error(); return false; } } const PrivateKey &UdpFwdClient::key() const { return _key; } QString UdpFwdClient::errorString() const { return _lastError; } void UdpFwdClient::send(const PublicKey &peer, const QByteArray &data, quint16 replyCount) { sendImpl(peer, data, replyCount, false); } bool UdpFwdClient::reply(const QByteArray &peer, const QByteArray &data, quint16 replyCount, bool lastReply) { auto info = _replyCache.object(peer); if (info) { sendImpl(info->key, data, replyCount, lastReply); if (lastReply || --info->limit == 0) _replyCache.remove(peer); return true; } else return false; } CryptoPP::RandomNumberGenerator &UdpFwdClient::rng() { return _rng; } void UdpFwdClient::socketError() { _lastError = _socket->errorString(); emit error(); } void UdpFwdClient::readyRead() { while (_socket->hasPendingDatagrams()) { const auto datagram = _socket->receiveDatagram(); try { MsgHandler handler{this, datagram.senderAddress(), static_cast<quint16>(datagram.senderPort())}; std::visit(handler, Message::deserialize<TunnelOutMessage, ErrorMessage>(datagram.data())); } catch (std::bad_variant_access &) { qWarning() << "UdpFwdClient: Ignoring invalid message from" << datagram.senderAddress() << "on port" << datagram.senderPort(); } } } void UdpFwdClient::sendImpl(const UdpFwdProto::PublicKey &peer, const QByteArray &data, quint16 replyCount, bool lastReply) { sendImpl(TunnelInMessage::createEncrypted(_rng, peer, data, replyCount != 0 ? PrivateReplyInfo{_key, replyCount} : PrivateReplyInfo{}, lastReply)); } void UdpFwdClient::MsgHandler::operator()(TunnelOutMessage &&message) { auto data = message.decrypt(self->_rng, self->_key); if (message.replyInfo) { if (message.replyInfo.key.Validate(self->_rng, 3)) { const auto fp = fingerPrint(message.replyInfo.key); self->_replyCache.insert(fp, new ReplyInfo{std::move(message.replyInfo)}); emit self->messageReceived(data, fp); } else { self->_lastError = tr("Received message with invalid reply key - message has been dropped!"); emit self->error(); } } else emit self->messageReceived(data); } void UdpFwdClient::MsgHandler::operator()(ErrorMessage &&message) { switch (message.error) { case ErrorMessage::Error::InvalidPeer: self->_lastError = tr("Unabled to deliver message - unknown peer!"); break; case ErrorMessage::Error::InvalidSignature: self->_lastError = tr("Message was rejected by the forward server - invalid signature!"); break; case ErrorMessage::Error::InvalidKey: self->_lastError = tr("Message was rejected by the forward server - invalid public key!"); break; case ErrorMessage::Error::Unknown: self->_lastError = self->_socket->errorString(); // maybe info is here break; } emit self->error(); }
27.59854
123
0.718593
Skycoder42
1dd243e9dd341e76a28815fe0330b7f92c0306b5
2,603
cpp
C++
src/CFG/production.cpp
angeligareta/Context-Free-Grammar
4f8e8c547145813e7309a28c9c96ee1136a7f904
[ "MIT" ]
1
2019-11-13T10:39:30.000Z
2019-11-13T10:39:30.000Z
src/CFG/production.cpp
angeligareta/Context-Free-Grammar
4f8e8c547145813e7309a28c9c96ee1136a7f904
[ "MIT" ]
null
null
null
src/CFG/production.cpp
angeligareta/Context-Free-Grammar
4f8e8c547145813e7309a28c9c96ee1136a7f904
[ "MIT" ]
null
null
null
#include "production.h" ostream& operator<<(ostream& output, const Production& production_in) { output << production_in.set_symbol_; return output; } Production::Production(const string& string_in): set_symbol_(string_in), num_no_terminal_(0), num_terminal_(0), epsilon_symbol_(0) { Update(); } Production::Production(const char* string_in): set_symbol_(string_in), num_no_terminal_(0), num_terminal_(0), epsilon_symbol_(0) { Update(); } Production::~Production(){} string Production::get_set_symbol() const { return set_symbol_; } int Production::get_num_terminal() const { return num_terminal_; } set<char> Production::get_set_no_terminal() const { set<char> set_no_terminal; for(int i=0;i<set_symbol_.size();i++) if(isupper(set_symbol_[i])) set_no_terminal.insert(set_symbol_[i]); return set_no_terminal; } int Production::get_num_no_terminal() const { return num_no_terminal_; } set<char> Production::get_set_terminal() const { set<char> set_terminal; for(int i=0;i<set_symbol_.size();i++) if(!isupper(set_symbol_[i]) && set_symbol_[i]!=' ') set_terminal.insert(set_symbol_[i]); return set_terminal; } bool Production::has_only_terminal_symbols() const { return (num_terminal_>0 && num_no_terminal_==0); } bool Production::has_epsilon_symbol() const { return epsilon_symbol_; } void Production::set_set_symbol_(const string& string_in) { set_symbol_=string_in; Update(); } void Production::Update() { for(int i=0; i<set_symbol_.size();i++){ if(isupper(set_symbol_[i])) ++num_no_terminal_; else if (set_symbol_[i]=='~') epsilon_symbol_=1; else ++num_terminal_; } } Production& Production::operator=(const Production& production_in) { this->set_symbol_= production_in.set_symbol_; this->num_terminal_= production_in.num_terminal_; this->num_no_terminal_= production_in.num_no_terminal_; this->epsilon_symbol_= production_in.epsilon_symbol_; return *this; } int Production::operator==(const Production& production_in) const { if( this->set_symbol_ == production_in.set_symbol_) return 0; return 1; } int Production::operator<(const Production& production_in) const { if( this->set_symbol_.length() == production_in.set_symbol_.length()){ if (this->set_symbol_ < production_in.set_symbol_) return 1; } else if( this->set_symbol_.length() > production_in.set_symbol_.length()) return 1; return 0; }
22.059322
87
0.68229
angeligareta
1dd3f9694e9a14131f1c3a3fd946a6b960734c00
241
cpp
C++
cpp/examples/factorial.cpp
arturparkhisenko/til
6fe7ddf2466d8090b9cf83fa5f7ae5fe5cacc19b
[ "MIT" ]
5
2017-01-20T01:48:25.000Z
2020-07-19T11:15:49.000Z
cpp/examples/factorial.cpp
arturparkhisenko/til
6fe7ddf2466d8090b9cf83fa5f7ae5fe5cacc19b
[ "MIT" ]
null
null
null
cpp/examples/factorial.cpp
arturparkhisenko/til
6fe7ddf2466d8090b9cf83fa5f7ae5fe5cacc19b
[ "MIT" ]
1
2017-08-22T12:21:04.000Z
2017-08-22T12:21:04.000Z
#include <iostream> using namespace std; int factorial(int n) { if (n == 1) { return 1; } else { return n * factorial(n - 1); } } int main(int argc, const char * argv[]) { cout << factorial(5); return 0; } // Outputs 120
14.176471
41
0.576763
arturparkhisenko
1dd40b3a3b616f7f6b16eca5cde65327ae8366ef
3,370
cc
C++
NEST-14.0-FPGA/sli/stringdatum.cc
OpenHEC/SNN-simulator-on-PYNQcluster
14f86a76edf4e8763b58f84960876e95d4efc43a
[ "MIT" ]
45
2019-12-09T06:45:53.000Z
2022-01-29T12:16:41.000Z
NEST-14.0-FPGA/sli/stringdatum.cc
zlchai/SNN-simulator-on-PYNQcluster
14f86a76edf4e8763b58f84960876e95d4efc43a
[ "MIT" ]
2
2020-05-23T05:34:21.000Z
2021-09-08T02:33:46.000Z
NEST-14.0-FPGA/sli/stringdatum.cc
OpenHEC/SNN-simulator-on-PYNQcluster
14f86a76edf4e8763b58f84960876e95d4efc43a
[ "MIT" ]
10
2019-12-09T06:45:59.000Z
2021-03-25T09:32:56.000Z
/* * stringdatum.cc * * This file is part of NEST. * * Copyright (C) 2004 The NEST Initiative * * NEST is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * NEST is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with NEST. If not, see <http://www.gnu.org/licenses/>. * */ #include "stringdatum.h" // C++ includes: #include <algorithm> #include <cctype> // Includes from sli: #include "tokenutils.h" // initialization of static members requires template<> // see Stroustrup C.13.1 --- HEP 2001-08-09 template <> sli::pool AggregateDatum< std::string, &SLIInterpreter::Stringtype >::memory( sizeof( AggregateDatum< std::string, &SLIInterpreter::Stringtype > ), 100, 1 ); template <> void AggregateDatum< std::string, &SLIInterpreter::Stringtype >::pprint( std::ostream& out ) const { out << '('; print( out ); out << ')'; } // explicit template instantiation needed // because otherwise methods defined in // numericdatum_impl.h will not be instantiated // Moritz, 2007-04-16 template class AggregateDatum< std::string, &SLIInterpreter::Stringtype >; const ToUppercase_sFunction touppercase_sfunction; const ToLowercase_sFunction tolowercase_sfunction; /* BeginDocumentation Name: ToUppercase - Convert a string to upper case. Synopsis: (string) ToUppercase -> (string) Description: ToUppercase converts a string to upper case. If no upper case representation of a letter exists, the letter is kept unchanged. Examples: SLI ] (MiXeD cAsE) ToUppercase (MIXED CASE) Author: Jochen Martin Eppler SeeAlso: ToLowercase */ void ToUppercase_sFunction::execute( SLIInterpreter* i ) const { i->assert_stack_load( 1 ); StringDatum sd = getValue< StringDatum >( i->OStack.top() ); std::string* str = dynamic_cast< std::string* >( &sd ); std::transform( str->begin(), str->end(), str->begin(), toupper ); i->OStack.pop(); i->OStack.push( new StringDatum( str->c_str() ) ); i->EStack.pop(); } /* BeginDocumentation Name: ToLowercase - Convert a string to lower case. Synopsis: (string) ToLowercase -> (string) Description: ToLowercase converts a string to lower case. If no lower case representation of a letter exists, the letter is kept unchanged. Examples: SLI ] (MiXeD cAsE) ToLowercase (mixed case) Author: Jochen Martin Eppler SeeAlso: ToUppercase */ void ToLowercase_sFunction::execute( SLIInterpreter* i ) const { i->assert_stack_load( 1 ); StringDatum sd = getValue< StringDatum >( i->OStack.top() ); std::string* str = dynamic_cast< std::string* >( &sd ); std::transform( str->begin(), str->end(), str->begin(), tolower ); i->OStack.pop(); i->OStack.push( new StringDatum( str->c_str() ) ); i->EStack.pop(); } void init_slistring( SLIInterpreter* i ) { i->createcommand( "ToUppercase", &touppercase_sfunction ); i->createcommand( "ToLowercase", &tolowercase_sfunction ); }
27.398374
77
0.702374
OpenHEC
1dd5e29237ac4f550a143346a1d76ddb9383d3a3
1,332
cpp
C++
Master/XC-OS/BSP/BSP_Motor.cpp
robojkj/XC-OS
dbbd970d8ca6c7cdbd84cc1cf929d8c6ad13dec5
[ "MIT" ]
6
2020-11-21T03:03:07.000Z
2022-03-30T00:00:05.000Z
Master/XC-OS/BSP/BSP_Motor.cpp
robojkj/XC-OS
dbbd970d8ca6c7cdbd84cc1cf929d8c6ad13dec5
[ "MIT" ]
null
null
null
Master/XC-OS/BSP/BSP_Motor.cpp
robojkj/XC-OS
dbbd970d8ca6c7cdbd84cc1cf929d8c6ad13dec5
[ "MIT" ]
2
2021-02-08T05:57:19.000Z
2021-07-24T21:10:49.000Z
#include "Basic/FileGroup.h" #include "Basic/TasksManage.h" #include "BSP.h" static bool State_MotorVibrate = true; static uint32_t MotorStop_TimePoint = 0; static bool IsMotorRunning = false; static uint8_t PWM_PIN; static void Init_Motor() { uint8_t temp; if(Motor_DIR) { PWM_PIN = Motor_IN1_Pin; temp = Motor_IN2_Pin; }else { PWM_PIN = Motor_IN2_Pin; temp = Motor_IN1_Pin; } PWM_Init(PWM_PIN, 1000, 80); pinMode(temp, OUTPUT); pinMode(Motor_SLP_Pin, OUTPUT); digitalWrite(temp, LOW); digitalWrite(Motor_SLP_Pin, HIGH); Motor_Vibrate(0.9f, 1000); } void Task_MotorRunning(TimerHandle_t xTimer) { __ExecuteOnce(Init_Motor()); if(IsMotorRunning && millis() >= MotorStop_TimePoint) { analogWrite(PWM_PIN, 0); digitalWrite(Motor_SLP_Pin, LOW); IsMotorRunning = false; } } void Motor_SetEnable(bool en) { State_MotorVibrate = en; } void Motor_Vibrate(float strength, uint32_t time) { if(!State_MotorVibrate) return; __LimitValue(strength, 0.0f, 1.0f); digitalWrite(Motor_SLP_Pin, HIGH); analogWrite(PWM_PIN, strength * 1000); IsMotorRunning = true; MotorStop_TimePoint = millis() + time; } void Motor_SetState(bool state) { if(!State_MotorVibrate) return; analogWrite(PWM_PIN, state ? 1000 : 0); }
18.5
57
0.690691
robojkj