/* ** main program: ** initialise, timestep loop, finalise */ int main(int argc, char* argv[]) { char* paramfile; /* name of the input parameter file */ char* obstaclefile; /* name of a the input obstacle file */ t_param params; /* struct to hold parameter values */ t_speed* cells = NULL; /* grid containing fluid densities */ t_speed* tmp_cells = NULL; /* scratch space */ int* obstacles = NULL; /* grid indicating which cells are blocked */ float* av_vels = NULL; /* a record of the av. velocity computed for each timestep */ int ii; /* generic counter */ struct timeval timstr; /* structure to hold elapsed time */ struct rusage ru; /* structure to hold CPU time--system and user */ double tic,toc; /* floating point numbers to calculate elapsed wallclock time */ double usrtim; /* floating point number to record elapsed user CPU time */ double systim; /* floating point number to record elapsed system CPU time */ /* parse the command line */ if(argc != 3) { usage(argv[0]); } else{ paramfile = argv[1]; obstaclefile = argv[2]; } /* initialise our data structures and load values from file */ initialise(paramfile, obstaclefile, ¶ms, &cells, &tmp_cells, &obstacles, &av_vels); /* iterate for maxIters timesteps */ gettimeofday(&timstr,NULL); tic=timstr.tv_sec+(timstr.tv_usec/1000000.0); for (ii=0;ii<params.maxIters;ii++) { timestep(params,cells,tmp_cells,obstacles); av_vels[ii] = av_velocity(params,cells,obstacles); #ifdef DEBUG printf("==timestep: %d==\n",ii); printf("av velocity: %.12E\n", av_vels[ii]); printf("tot density: %.12E\n",total_density(params,cells)); #endif } gettimeofday(&timstr,NULL); toc=timstr.tv_sec+(timstr.tv_usec/1000000.0); getrusage(RUSAGE_SELF, &ru); timstr=ru.ru_utime; usrtim=timstr.tv_sec+(timstr.tv_usec/1000000.0); timstr=ru.ru_stime; systim=timstr.tv_sec+(timstr.tv_usec/1000000.0); /* write final values and free memory */ printf("==done==\n"); printf("Reynolds number:\t\t%.12E\n",calc_reynolds(params,cells,obstacles)); printf("Elapsed time:\t\t\t%.6lf (s)\n", toc-tic); printf("Elapsed user CPU time:\t\t%.6lf (s)\n", usrtim); printf("Elapsed system CPU time:\t%.6lf (s)\n", systim); write_values(params,cells,obstacles,av_vels); finalise(¶ms, &cells, &tmp_cells, &obstacles, &av_vels); return EXIT_SUCCESS; }
/* ** main program: ** initialise, timestep loop, finalise */ int main(int argc, char* argv[]) { char * final_state_file = NULL; char * av_vels_file = NULL; char * param_file = NULL; accel_area_t accel_area; param_t params; /* struct to hold parameter values */ speed_t* cells = NULL; /* grid containing fluid densities */ speed_t* tmp_cells = NULL; /* scratch space */ int* obstacles = NULL; /* grid indicating which cells are blocked */ double* av_vels = NULL; /* a record of the av. velocity computed for each timestep */ int ii; /* generic counter */ struct timeval timstr; /* structure to hold elapsed time */ struct rusage ru; /* structure to hold CPU time--system and user */ double tic,toc; /* floating point numbers to calculate elapsed wallclock time */ double usrtim; /* floating point number to record elapsed user CPU time */ double systim; /* floating point number to record elapsed system CPU time */ parse_args(argc, argv, &final_state_file, &av_vels_file, ¶m_file); initialise(param_file, &accel_area, ¶ms, &cells, &tmp_cells, &obstacles, &av_vels); /* iterate for max_iters timesteps */ gettimeofday(&timstr,NULL); tic=timstr.tv_sec+(timstr.tv_usec/1000000.0); for (ii = 0; ii < params.max_iters; ii++) { timestep(params, accel_area, cells, tmp_cells, obstacles); av_vels[ii] = av_velocity(params, cells, obstacles); #ifdef DEBUG printf("==timestep: %d==\n", ii); printf("av velocity: %.12E\n", av_vels[ii]); printf("tot density: %.12E\n", total_density(params, cells)); #endif } gettimeofday(&timstr,NULL); toc=timstr.tv_sec+(timstr.tv_usec/1000000.0); getrusage(RUSAGE_SELF, &ru); timstr=ru.ru_utime; usrtim=timstr.tv_sec+(timstr.tv_usec/1000000.0); timstr=ru.ru_stime; systim=timstr.tv_sec+(timstr.tv_usec/1000000.0); printf("==done==\n"); printf("Reynolds number:\t\t%.12E\n", calc_reynolds(params,cells,obstacles)); printf("Elapsed time:\t\t\t%.6f (s)\n", toc-tic); printf("Elapsed user CPU time:\t\t%.6f (s)\n", usrtim); printf("Elapsed system CPU time:\t%.6f (s)\n", systim); write_values(final_state_file, av_vels_file, params, cells, obstacles, av_vels); finalise(&cells, &tmp_cells, &obstacles, &av_vels); return EXIT_SUCCESS; }
void Particle::regenerate(float dt) { // slow the simulation if we can't keep the frame rate up around 10 fps if (dt > 0.1) speed *= 0.75; else speed *= 1; dt *= speed; // resurrect a few particles for (int i=0; i < (flow * dt); i++) { generate(&particles[living], dt); if (++living >= number) living = 0; } // expire some particles for (int n=0; n < number; n++) { timestep(&particles[n], dt); // collision with ground ? if (particles[n].pos[2] <= ground) //bounce(&particles[n], dt); // dead particle ? if (particles[n].pos[2] < (ground + 0.005)) { //particles[n].alive = false; // death } if (fequal(particles[n].vel[2], 0)) { particles[n].alive = false; // death //generate(&particles[n], dt); } } }
void mainLoop(const char* configFile, int generations) { // need a pair of arrays, one to hold grid and the other to hold updates //(unless we invent a more complex datastructure/algorithm to allow in-place // modification of the array) ARRAY2D arrays[2] = {0}; // keep track of which array is active, the other is used for updates int active = 0; int i; // bounds on the rows this node handles int upper, lower; setupArrays(configFile, arrays, &upper, &lower); // loop over number of generations for(i = 0; i < generations; i++) { display(arrays[active], i); // calculate updates timestep(arrays[active], arrays[!active], lower, upper); // swap arrays active = !active; updateOtherProcesses(upper, lower, arrays[active]); } display(arrays[active], i); // cleanup freeArray(arrays[0]); freeArray(arrays[1]); }
// Main loop void main(){ struct system sys = initialize(); int ii; // Initialize iterators printf("Sum: %E\n",densintegrate(sys)); printf("WithGroundState: %d\t %E\n",-1,innerproductwithgroundstate(sys)); for(ii=0;ii<50000;ii++){ if(ii % 1000 == 0) printf("WithGroundState: %d\t %E\n",ii,innerproductwithgroundstate(sys)); sys = imaginarytimestep(sys); } printf("Done with imaginary time evolution!\n"); for(ii=-1;ii<50000;ii++){ if(ii % 100 == 0){ printf("WithGroundState: %d\t %E\tSum: %E\n",ii,innerproductwithgroundstate(sys),densintegrate(sys)); writetofile(sys,ii/100); } sys = timestep(sys); } //writetofile(sys,0); printf("Sum: %E\n",sys.dt); return; }
void InitPolicyInterpolation< mesh_Type >:: initSimulation ( bcContainerPtr_Type /*bchandler*/, vectorPtr_Type solution ) { ASSERT ( problem()->hasExactSolution(), "Error: You cannot use the interpolation method if the problem has not an analytical solution." ); Real currentTime = initialTime() - timestep() * bdf()->order(); UInt pressureOffset = uFESpace()->fieldDim() * uFESpace()->dof().numTotalDof(); vectorPtr_Type velocity; velocity.reset ( new vector_Type ( uFESpace()->map(), Unique ) ); vectorPtr_Type pressure; pressure.reset ( new vector_Type ( pFESpace()->map(), Unique ) ); *solution = 0.0; uFESpace()->interpolate ( problem()->uexact(), *velocity, currentTime ); pFESpace()->interpolate ( problem()->pexact(), *pressure, currentTime ); solution->add ( *velocity ); solution->add ( *pressure, pressureOffset ); bdf()->setInitialCondition ( *solution ); currentTime += timestep(); for ( ; currentTime <= initialTime() + timestep() / 2.0; currentTime += timestep() ) { *solution = 0.0; *velocity = 0.0; *pressure = 0.0; uFESpace()->interpolate ( problem()->uexact(), *velocity, currentTime ); pFESpace()->interpolate ( problem()->pexact(), *pressure, currentTime ); solution->add ( *velocity ); solution->add ( *pressure, pressureOffset ); // Updating bdf bdf()->shiftRight ( *solution ); } }
main(int argc, char *argv[]) { void init(),timestep(),stepvar(),dump(),diag() ; REAL tnext ; int seed,i,j,k ; tnext = 0. ; nstep = 0 ; if(argc < 1) { fprintf(stderr,"usage: bend3d \n") ; exit(0) ; } /* perform initializations */ init() ; /* do initial diagnostics */ diag(0) ; while(t < tf) { /* find timestep */ timestep() ; /* step variables forward in time */ stepvar() ; /* perform diagnostics */ if(t > tnext) { diag(1) ; tnext += DTl ; } //if(nstep == 64) exit(0) ; fprintf(stderr,"t,dt: %10.5g %10.5g\n",t,dt) ; nstep++ ; } /* do final diagnostics */ diag(2) ; fprintf(stderr,"nstep: %d\n",nstep) ; fprintf(stderr,"zone cycles: %g\n",(double)(NX*NY*NZ)* (double)(nstep)) ; return(0) ; }
void evolve_shared10(int clevel,struct sys s, DOUBLE stime, DOUBLE etime, DOUBLE dt, int calc_timestep) { FLOAT dtsys; CHECK_TIMESTEP(etime,stime,dt,clevel); if(calc_timestep) timestep(clevel,s,s,SIGN(dt)); dtsys = global_timestep(s); if(dtsys < fabs(dt)) { evolve_shared10(clevel+1,s,stime, stime+dt/2,dt/2,0); evolve_shared10(clevel+1,s,stime+dt/2, etime,dt/2,1); } else { diag->deepsteps++; diag->simtime+=dt; dkd10(clevel,s, stime, etime, dt); } }
void Particle::generate(tParticle *p, float dt) { p->pos[0] = pos.x; p->pos[1] = pos.y; p->pos[2] = pos.z; p->prev[0] = p->pos[0]; p->prev[1] = p->pos[1]; p->prev[2] = p->pos[2]; switch (system) { case WATERFALL: points = true; p->vel[0] = 2*((float) drand48()-.5); p->vel[1] = 2*((float) drand48()-.5); p->vel[2] = 0; p->damp = .45*(float) drand48(); break; case FOUNTAIN: points = true; p->vel[0] = 2*((float) drand48()-.5); p->vel[1] = 2*((float) drand48()-.5); p->vel[2] = .75*speed; p->damp = .35*(float) drand48(); break; case FIREWORK: points = true; p->vel[0] = 5*((float) drand48()-.5); p->vel[1] = 5*((float) drand48()-.5); p->vel[2] = 5*((float) drand48()-.5); p->damp = .35*(float) drand48(); break; case SNOW: points = true; p->vel[0] = 3*((float) drand48()-.5); p->vel[1] = 3*((float) drand48()-.5); p->vel[2] = .2*speed; p->damp = .25*(float) drand48(); break; case RAIN: points = false; p->vel[0] = 4*((float) drand48()-.5); p->vel[1] = 4*((float) drand48()-.5); p->vel[2] = 2*speed; p->damp = .15*(float) drand48(); break; } p->alive = true; timestep(p, dt * (float) drand48()); }
std::vector<state> flic(const std::vector<state> & X, int BCL, int BCR, double dx, double C, double t, int l) { double t0 = 0; int iter = 0; std::vector<state> ret = X; while (t0 < t) { std::vector<state> X0 = add_boundary_conditions(ret, BCL, BCR, 2); double dt = timestep(X0, dx, C, t0, t, iter); flic_stepper(ret, X0, dx, dt, C, l); t0 += dt; iter++; } return ret; }
// return any children objects in the hierarchy std::vector<ModelObject> SimulationControl_Impl::children() const { std::vector<ModelObject> result; OptionalConvergenceLimits ocl = convergenceLimits(); if (ocl) { result.push_back(*ocl); } //OptionalDaylightSavingsTime odst = daylightSavingsTime(); //if (odst) { result.push_back(*odst); } OptionalHeatBalanceAlgorithm ohba = heatBalanceAlgorithm(); if (ohba) { result.push_back(*ohba); } OptionalInsideSurfaceConvectionAlgorithm oisca = insideSurfaceConvectionAlgorithm(); if (oisca) { result.push_back(*oisca); } OptionalOutsideSurfaceConvectionAlgorithm oosca = outsideSurfaceConvectionAlgorithm(); if (oosca) { result.push_back(*oosca); } RunPeriodVector rps = runPeriods(); result.insert(result.end(),rps.begin(),rps.end()); OptionalShadowCalculation osc = shadowCalculation(); if (osc) { result.push_back(*osc); } //SpecialDaysVector sds = specialDays(); //result.insert(result.end(),sds.begin(),sds.end()); OptionalSizingParameters osp = sizingParameters(); if (osp) { result.push_back(*osp); } OptionalTimestep ot = timestep(); if (ot) { result.push_back(*ot); } OptionalZoneAirContaminantBalance ozacb = zoneAirContaminantBalance(); if (ozacb) { result.push_back(*ozacb); } OptionalZoneAirHeatBalanceAlgorithm ozahba = zoneAirHeatBalanceAlgorithm(); if (ozahba) { result.push_back(*ozahba); } OptionalZoneCapacitanceMultiplierResearchSpecial ozcmrs; ozcmrs = zoneCapacitanceMultiplierResearchSpecial(); if (ozcmrs) { result.push_back(*ozcmrs); } return result; }
// makes simulation void VelocityVerlet_LC::simulate() { // calculate forces for t=0 comp_F(); // write start values O_LC.notify(); // while simulation end time not reached while (W_LC.t < W_LC.t_end) { // make a timestep timestep(W_LC.delta_t); // notify observer O_LC.notify(); } }
int main() { // ants walk on a table const int m = 356; rarray<double,2> number_of_ants(m,m); rarray<double,2> new_number_of_ants(m,m); rarray<double,2> velocity_of_ants(m,m); const int total_ants = 1010;// initial number of ants //const variables const float c1 = 1.9; const float c2 = 0.8; const float c3 = 0.2; initial(number_of_ants, velocity_of_ants, total_ants, m);//initial condition timestep(number_of_ants, new_number_of_ants, velocity_of_ants, c1, c2, c3, m);//record the timestep and output return 0; }
typename A::GridScalar euler_local(A access, short res_type) { using value = typename A::GridValue; using scalar = typename A::GridScalar; std::vector<scalar> H; scalar res = -1; scalar h_min = 1, h_max = -1; value y = {0,0,0,0}; value f = {0,0,0,0}; value k1 = {0,0,0,0}; value k2 = {0,0,0,0}; value k3 = {0,0,0,0}; value k4 = {0,0,0,0}; // Stage 1 // Write k1 to cell_begin(0) eflux(access.cell_begin(),access.cell_end(),access.cell_begin(0)); nsflux(access.cell_begin(),access.cell_end(),access.cell_begin(0)); // Stage 2 auto flux_it = access.cell_begin(0); auto out_it = access.cell_begin(); for (auto it=access.cell_begin(); it!=access.cell_end(); ++it) { // Local time step approximation H.push_back(timestep(*it)); h_min = std::min(H.back(),h_min); // DEBUG h_max = std::max(H.back(),h_max); // Apply RK stage y = (*it).value(); f = (*flux_it).value(); (*out_it) = y + (H.back())*f; // update residual if (res_type == -1) res = std::max( (std::abs(f)).max(), res ); else if (res_type == 0) res = std::max( std::abs(f[0]), res ); else assert(false); // Iterate ++flux_it; ++out_it; } return res; }
void save_sequence_to_file(Sequence *sequence, const char *filename, unsigned int sample_rate) { double a; int16_t n; uint32_t len, pos; outfile.openFromFile(filename, sample_rate, 1); start(sequence); pos = 0; while (!is_end_of_sequence) { a = timestep(); n = (int16_t)(((double)0x7ffe) * a); file_buf[pos++] = n; if (pos == file_buf_size) { outfile.write(file_buf, pos); pos = 0; } } outfile.write(file_buf, pos); }
static void evolve_shared_collision_detection(struct sys s, DOUBLE dt, void (*dkd_func)(int, struct sys, DOUBLE, DOUBLE, DOUBLE)) { FLOAT dtsys; int next_level, current_level = 0; DOUBLE etime, stime; DOUBLE *dt_levels = (DOUBLE*) malloc (MAXLEVEL * sizeof(DOUBLE)); int *step_at_level = (int*) calloc (MAXLEVEL, sizeof(int)); int is_collision_detection_enabled; if (dt == 0.0L) { ENDRUN("timestep too small: dt=%Le\n", (long double) dt); } is_stopping_condition_enabled(COLLISION_DETECTION, &is_collision_detection_enabled); set_dt_levels(dt_levels, dt); do { timestep(current_level, s, s, SIGN(dt)); dtsys = global_timestep(s); while (dtsys < fabs(dt_levels[current_level])) { current_level++; if (current_level >= MAXLEVEL) { stime = time_from_steps(step_at_level, dt_levels); ENDRUN("timestep too small: stime=%Le dt=%Le clevel=%u\n", (long double) stime, (long double) dt_levels[current_level], current_level); } } diag->deepsteps++; diag->simtime+=dt_levels[current_level]; stime = time_from_steps(step_at_level, dt_levels); next_level = update_steps_and_get_next_level(step_at_level, current_level); etime = time_from_steps(step_at_level, dt_levels); dkd_func(current_level, s, stime, etime, dt_levels[current_level]); if (is_collision_detection_enabled) { detect_collisions(s); if (set_conditions & enabled_conditions) break; } current_level = next_level; } while (current_level > 0); free(dt_levels); free(step_at_level); }
int main(int argc, char **argv){ /* initialize sdl */ if (SDL_Init(SDL_INIT_VIDEO) < 0){ perror("could not initialize sdl"); return 1; } SDL_ShowCursor(SDL_DISABLE); SDL_WM_SetCaption("simple raytracer demo", ""); SDL_Surface *screen = SDL_SetVideoMode(WIDTH, HEIGHT, BPP*8, SDL_HWSURFACE|SDL_DOUBLEBUF); if(!screen) { perror("could not set video mode"); SDL_Quit(); return 1; } /* initialize graphics state */ graphics_state state; state.screen = screen; if(init_model(&state) != 0) return -1; if(init_lights(&state) != 0) return -1; if(init_graphics(&state) != 0) return -1; if(init_worker_threads(&state) != 0) return -1; /* main loop */ int run = 1; float ema_nanos = 0, ema_nanos2 = 0, max_nanos = 0; long start_time; start_time = now(); while(run){ /* change the scene */ timestep(&state); /* render the scene */ if(draw_screen(&state)){ perror("render error"); return 1; } /* performance metrics */ state.frame++; long nanos = now()-start_time; ema_nanos = 0.9f*ema_nanos + 0.1*nanos; ema_nanos2 = 0.9f*ema_nanos2 + 0.1*nanos*nanos; if(nanos > max_nanos) max_nanos = nanos; if(state.frame % 10 == 0){ float stdev_nanos = sqrtf(ema_nanos2 - ema_nanos*ema_nanos); float fps = 1000000000 / ema_nanos; float fps_sigma = 1000000000 / (ema_nanos + stdev_nanos); float fps_worst = 1000000000 / max_nanos; printf("%.2f +/- %.2f (worst: %.2f) fps\n", fps, fps-fps_sigma, fps_worst); max_nanos = 0; } start_time = now(); int sleep_us = TARGET_US - nanos/1000; if(sleep_us > 0) usleep(sleep_us); /* check if we need to exit */ SDL_Event event; while(SDL_PollEvent(&event)) { if(event.type == SDL_QUIT || event.type == SDL_MOUSEBUTTONDOWN){ run = 0; break; } } } /* reset resolution to normal, exit */ SDL_Quit(); return 0; }
CoMD_return CoMD_lib(CoMD_input *inputStruct) { // Prolog //profileStart(totalTimer); //initSubsystems(); //Command cmd = parseCommandLine(argc, argv); Command cmd = parseInputStruct(inputStruct); //Ignore stressSuffix for now SimFlat* sim = initSimulation(cmd); Validate* validate = initValidate(sim); // atom counts, energy // This is the CoMD main loop const int nSteps = sim->nSteps; const int printRate = sim->printRate; double avgStress[9]; int stressi; int iStep; for(stressi=0;stressi<9;stressi++) avgStress[stressi]=0; for (iStep=0; iStep<nSteps;iStep++) { sumAtoms(sim); //Find and intercept these to write to the struct //printThings(sim, iStep, getElapsedTime(timestepTimer)); printTensor(iStep, sim->defInfo->stress); timestep(sim, 1, sim->dt); if(iStep>500){ for(stressi=0;stressi<9;stressi++) avgStress[stressi]+=sim->defInfo->stress[stressi]/(nSteps-500); } } sumAtoms(sim); //Find and intercept //printThings(sim, iStep, getElapsedTime(timestepTimer)); CoMD_return retVal = printStuff(iStep, sim, avgStress); // Epilog //validateResult(validate, sim); //profileStop(totalTimer); /* if (sim->pot->dfEmbed!=NULL) { free(sim->pot->dfEmbed); sim->pot->dfEmbed=NULL; } if (sim->pot->rhobar!=NULL) { free(sim->pot->rhobar); sim->pot->rhobar=NULL; } if (sim->pot->forceExchangeData!=NULL) { free(sim->pot->forceExchangeData); sim->pot->forceExchangeData=NULL; }*/ destroySimulation(&sim); comdFree(validate); //finalizeSubsystems();//??? //destroyParallel(); //??? return retVal; }
int main(int argc, char** argv) { #if defined(_WIN32) LOG_INFO("Windows build."); #elif defined(_LINUX) LOG_INFO("Linux build."); #elif defined(_MACOS) LOG_INFO("MacOS build."); #endif bool useOpenGLCoreContext = false; #ifdef USE_CORE_CONTEXT useOpenGLCoreContext = true; #endif g_renderMode.outputType = RenderingMode::OVR_SDK; LOG_INFO("Using GLFW3 backend."); LOG_INFO("Compiled against GLFW %i.%i.%i", GLFW_VERSION_MAJOR, GLFW_VERSION_MINOR, GLFW_VERSION_REVISION); int major, minor, revision; glfwGetVersion(&major, &minor, &revision); LOG_INFO("Running against GLFW %i.%i.%i", major, minor, revision); LOG_INFO("glfwGetVersionString: %s", glfwGetVersionString()); // Command line options for (int i=0; i<argc; ++i) { const std::string a = argv[i]; LOG_INFO("argv[%d]: %s", i, a.c_str()); if (!a.compare("-sdk")) { g_renderMode.outputType = RenderingMode::OVR_SDK; } else if (!a.compare("-client")) { g_renderMode.outputType = RenderingMode::OVR_Client; } else if (!a.compare("-core")) { useOpenGLCoreContext = true; } else if (!a.compare("-compat")) { useOpenGLCoreContext = false; } } #ifdef USE_OCULUSSDK g_app.initHMD(); #else g_renderMode.outputType = RenderingMode::Mono_Buffered; #endif GLFWwindow* l_Window = NULL; glfwSetErrorCallback(ErrorCallback); if (!glfwInit()) { exit(EXIT_FAILURE); } // Log system monitor information const GLFWmonitor* pPrimary = glfwGetPrimaryMonitor(); int monitorCount = 0; GLFWmonitor** ppMonitors = glfwGetMonitors(&monitorCount); for (int i=0; i<monitorCount; ++i) { GLFWmonitor* pCur = ppMonitors[i]; const GLFWvidmode* mode = glfwGetVideoMode(pCur); if (mode != NULL) { (void)pPrimary; LOG_INFO("Monitor #%d: %dx%d @ %dHz %s", i, mode->width, mode->height, mode->refreshRate, pCur==pPrimary ? "Primary":""); } } bool swapBackBufferDims = false; // Context setup - before window creation glfwWindowHint(GLFW_DEPTH_BITS, 16); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, useOpenGLCoreContext ? GLFW_OPENGL_CORE_PROFILE : GLFW_OPENGL_COMPAT_PROFILE); //glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); #ifdef _DEBUG glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GL_TRUE); #endif #if defined(USE_OSVR) std::string windowTitle = ""; windowTitle = PROJECT_NAME "-GLFW-Osvr"; if (g_app.UsingDebugHmd()) { const hmdRes sz = { 800, 600 }; // Create a normal, decorated application window LOG_INFO("Using Debug HMD mode."); windowTitle = PROJECT_NAME "-GLFW-DebugHMD"; g_renderMode.outputType = RenderingMode::Mono_Buffered; l_Window = glfwCreateWindow(sz.w, sz.h, windowTitle.c_str(), NULL, NULL); } else { const hmdRes sz = { g_app.getHmdResolution().h, g_app.getHmdResolution().w }; const winPos pos = g_app.getHmdWindowPos(); g_renderMode.outputType = RenderingMode::SideBySide_Undistorted; LOG_INFO("Using Extended desktop mode."); windowTitle = PROJECT_NAME "-GLFW-Extended"; LOG_INFO("Creating GLFW_DECORATED window %dx%d@%d,%d", sz.w, sz.h, pos.x, pos.y); glfwWindowHint(GLFW_DECORATED, 0); l_Window = glfwCreateWindow(sz.w, sz.h, windowTitle.c_str(), NULL, NULL); glfwWindowHint(GLFW_DECORATED, 1); glfwSetInputMode(l_Window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); glfwSetWindowPos(l_Window, pos.x, pos.y); } #elif defined(OVRSDK06) std::string windowTitle = ""; LOG_INFO("Using SDK 0.6.0.0's direct mode."); windowTitle = PROJECT_NAME "-GLFW-06-Direct"; GLFWmonitor* monitor = glfwGetPrimaryMonitor(); const GLFWvidmode* mode = glfwGetVideoMode(monitor); ovrSizei sz; ovrVector2i pos; sz.w = mode->width/2; sz.h = mode->height/2; pos.x = 100; pos.y = 100; // Create just a regular window for presenting OVR SDK 0.6's mirror texture ///@todo Is it any faster with no mirror at all? LOG_INFO("Creating window %dx%d@%d,%d", sz.w, sz.h, pos.x, pos.y); l_Window = glfwCreateWindow(sz.w, sz.h, windowTitle.c_str(), NULL, NULL); g_app.SetAppWindowSize(sz); #else l_Window = glfwCreateWindow(800, 600, "GLFW Oculus Rift Test", NULL, NULL); std::string windowTitle = PROJECT_NAME; #endif //USE_OSVR|OVRSDK06 if (!l_Window) { LOG_INFO("Glfw failed to create a window. Exiting."); glfwTerminate(); exit(EXIT_FAILURE); } glfwMakeContextCurrent(l_Window); glfwSetWindowSizeCallback(l_Window, resize_Aux); glfwSetMouseButtonCallback(l_Window, mouseDown_Aux); glfwSetCursorPosCallback(l_Window, mouseMove_Aux); glfwSetScrollCallback(l_Window, mouseWheel_Aux); glfwSetKeyCallback(l_Window, keyboard_Aux); memset(m_keyStates, 0, GLFW_KEY_LAST*sizeof(int)); // joysticks for (int i = GLFW_JOYSTICK_1; i <= GLFW_JOYSTICK_LAST; ++i) { if (GL_FALSE == glfwJoystickPresent(i)) continue; const char* pJoyName = glfwGetJoystickName(i); if (pJoyName == NULL) continue; int numAxes = 0; int numButtons = 0; glfwGetJoystickAxes(i, &numAxes); glfwGetJoystickButtons(i, &numButtons); LOG_INFO("Glfw opened Joystick #%d: %s w/ %d axes, %d buttons", i, pJoyName, numAxes, numButtons); if (g_joystickIdx == -1) g_joystickIdx = i; } printGLContextInfo(l_Window); glfwMakeContextCurrent(l_Window); g_pHMDWindow = l_Window; // Don't forget to initialize Glew, turn glewExperimental on to // avoid problems fetching function pointers... glewExperimental = GL_TRUE; const GLenum l_Result = glewInit(); if (l_Result != GLEW_OK) { LOG_INFO("glewInit() error."); exit(EXIT_FAILURE); } #ifdef _DEBUG // Debug callback initialization // Must be done *after* glew initialization. glDebugMessageCallback(myCallback, NULL); glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, NULL, GL_TRUE); glDebugMessageInsert(GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_MARKER, 0, GL_DEBUG_SEVERITY_NOTIFICATION, -1 , "Start debugging"); glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS); #endif #ifdef USE_ANTTWEAKBAR LOG_INFO("Using AntTweakbar."); TwInit(useOpenGLCoreContext ? TW_OPENGL_CORE : TW_OPENGL, NULL); InitializeBar(); #endif LOG_INFO("Calling initGL..."); g_app.initGL(); LOG_INFO("Calling initVR..."); g_app.initVR(swapBackBufferDims); LOG_INFO("initVR(%d) complete.", swapBackBufferDims); SetVsync(0); // SDK 0.6 requires vsync OFF while (!glfwWindowShouldClose(l_Window)) { g_app.CheckForTapToDismissHealthAndSafetyWarning(); glfwPollEvents(); joystick(); timestep(); g_fps.OnFrame(); if (g_dynamicallyScaleFBO) { DynamicallyScaleFBO(); } #ifdef USE_ANTTWEAKBAR TwRefreshBar(g_pTweakbar); #endif g_app.pre_render_pass(); displayToHMD(); #ifndef _LINUX // Indicate FPS in window title // This is absolute death for performance in Ubuntu Linux 12.04 { std::ostringstream oss; oss << windowTitle << " " << static_cast<int>(g_fps.GetFPS()) << " fps"; glfwSetWindowTitle(l_Window, oss.str().c_str()); } #endif const float dumpInterval = 1.f; if (g_logDumpTimer.seconds() > dumpInterval) { LOG_INFO("Frame rate: %d fps", static_cast<int>(g_fps.GetFPS())); g_logDumpTimer.reset(); } } g_app.exitVR(); glfwDestroyWindow(l_Window); glfwTerminate(); exit(EXIT_SUCCESS); }
const void SandPile::timestep() { timestep(false); }
/** advance clock by one step */ void advance() { ++step_; // multiply instead of increment to avoid accumulated summation errors time_ = time_origin_ + (step_ - step_origin_) * timestep(); }
int main(int argc, char* argv[]) { char* paramfile; /* name of the input parameter file */ char* obstaclefile; /* name of a the input obstacle file */ t_param params; /* struct to hold parameter values */ t_speed* cells = NULL; /* grid containing fluid densities */ t_speed* tmp_cells = NULL; /* scratch space */ int* obstacles = NULL; /* grid indicating which cells are blocked */ float* av_vels = NULL; /* a record of the av. velocity computed for each timestep */ int ii; /* generic counter */ struct timeval timstr; /* structure to hold elapsed time */ struct rusage ru; /* structure to hold CPU time--system and user */ double tic,toc; /* floating point numbers to calculate elapsed wallclock time */ double usrtim; /* floating point number to record elapsed user CPU time */ double systim; /* floating point number to record elapsed system CPU time */ /* parse the command line */ if(argc != 3) { usage(argv[0]); } else{ paramfile = argv[1]; obstaclefile = argv[2]; } /* initialise our data structures and load values from file */ initialise(paramfile, obstaclefile, ¶ms, &cells, &tmp_cells, &obstacles, &av_vels); /* iterate for maxIters timesteps */ gettimeofday(&timstr,NULL); tic=timstr.tv_sec+(timstr.tv_usec/1000000.0); float tot_u_x=0; int tot_cells = 0; MPI_Init(&argc, &argv); MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Comm_size(MPI_COMM_WORLD, &nprocs); int start=0, end=0, ff, hh, gg; params.rest = params.ny%nprocs; for (ii=0;ii<params.maxIters;ii++) { timestep(params,cells,tmp_cells,obstacles); if(ii==1){ atyt = 0; } if(ii==2){ atyt = 1; } ///////////av_velocity................................................. int jj,kk, tt, source; float local_density; float l_tot_u_x=0; int l_tot_cells = 0; if(params.rest!=0){ if(rank>=params.rest){ start = params.rest*(params.ny/nprocs+1) + (rank-params.rest)*(params.ny/nprocs); end= start+params.ny/nprocs-1; } else{ start = rank*(params.ny/nprocs+1); end = start+params.ny/nprocs; } } for(kk=start;kk<=end;kk++) { for(jj=0;jj<params.nx;jj++) { if(!obstacles[kk*params.nx + jj]) { local_density= 0.0; for(tt=0;tt<NSPEEDS;tt++) { local_density += cells[kk*params.nx + jj].speeds[tt]; } l_tot_u_x += (cells[kk*params.nx + jj].speeds[1] + cells[kk*params.nx + jj].speeds[5] + cells[kk*params.nx + jj].speeds[8] - (cells[kk*params.nx + jj].speeds[3] + cells[kk*params.nx + jj].speeds[6] + cells[kk*params.nx + jj].speeds[7])) / local_density; l_tot_cells+=1; } } } if(rank!=MASTER){ MPI_Send(&l_tot_u_x, 1, MPI_FLOAT, dest, tag, MPI_COMM_WORLD); MPI_Send(&l_tot_cells, 1, MPI_INT, dest, tag, MPI_COMM_WORLD);} else{ tot_cells = l_tot_cells; for (source =1; source < nprocs; source++) { MPI_Recv(&l_tot_u_x, 1, MPI_FLOAT, source, tag, MPI_COMM_WORLD, &status); tot_u_x+=l_tot_u_x; MPI_Recv(&l_tot_cells, 1, MPI_INT, source, tag, MPI_COMM_WORLD, &status); tot_cells+=l_tot_cells; } av_vels[ii] = tot_u_x / (float)tot_cells; } } float mes[9*params.nx]; float mes2[9*params.nx]; if(rank!=MASTER){ if(params.rest!=0){ if(rank>=params.rest){ start = params.rest*(params.ny/nprocs+1) + (rank-params.rest)*(params.ny/nprocs); end= start+params.ny/nprocs-1; } else{ start = rank*(params.ny/nprocs+1); end = start+params.ny/nprocs; } } for(gg=start;gg<=end;gg++) { for(hh=0;hh<params.nx;hh++){ for(ff=0;ff<9;ff++){ mes[9*hh+ff] = cells[gg*params.nx + hh].speeds[ff]; } } } MPI_Isend(mes, 9*params.nx, MPI_FLOAT, MASTER, tag, MPI_COMM_WORLD, &request); } if(rank == MASTER){ for(source=1;source<nprocs;source++){ if(params.rest!=0){ if(source>=params.rest){ start = params.rest*(params.ny/nprocs+1) + (source-params.rest)*(params.ny/nprocs); end= start+params.ny/nprocs-1; } else{ start = source*(params.ny/nprocs+1); end = start+params.ny/nprocs; } } for(gg=start;gg<=end;gg++) { MPI_Irecv(mes2, 9*params.nx, MPI_FLOAT, source, tag, MPI_COMM_WORLD, &request); for(hh=0;hh<params.nx;hh++){ for(ff=0;ff<9;ff++){ cells[gg*params.nx + hh].speeds[ff]=mes2[9*hh+ff]; } } } } } ///////////av_velocity................................................. MPI_Finalize(); gettimeofday(&timstr,NULL); toc=timstr.tv_sec+(timstr.tv_usec/1000000.0); getrusage(RUSAGE_SELF, &ru); timstr=ru.ru_utime; usrtim=timstr.tv_sec+(timstr.tv_usec/1000000.0); timstr=ru.ru_stime; systim=timstr.tv_sec+(timstr.tv_usec/1000000.0); if(rank==0){ /* write final values and free memory */ printf("==done==\n"); printf("Reynolds number:\t\t%.12E\n",calc_reynolds(params,cells,obstacles)); printf("Elapsed time:\t\t\t%.6lf (s)\n", toc-tic); printf("Elapsed user CPU time:\t\t%.6lf (s)\n", usrtim); printf("Elapsed system CPU time:\t%.6lf (s)\n", systim); write_values(params,cells,obstacles,av_vels); finalise(¶ms, &cells, &tmp_cells, &obstacles, &av_vels); //openFile(); // OPEN THE MULTIPLE OUTPUT FILE //printf("\n\n%f\n", toc-tic); //printF(toc-tic); // fclose(ofp); } return EXIT_SUCCESS; }
int main(int argc, char** argv) { LOG_INFO("RiftRay version %s", pRiftRayVersion); #if defined(_WIN32) LOG_INFO("Windows build."); #elif defined(_LINUX) LOG_INFO("Linux build."); #elif defined(_MACOS) LOG_INFO("MacOS build."); #endif bool useOpenGLCoreContext = false; g_renderMode.outputType = RenderingMode::OVR_SDK; #ifdef USE_CORE_CONTEXT useOpenGLCoreContext = true; #endif #ifdef _LINUX // Linux driver seems to be lagging a bit useOpenGLCoreContext = false; #endif LOG_INFO("Using GLFW3 backend."); LOG_INFO("Compiled against GLFW %i.%i.%i", GLFW_VERSION_MAJOR, GLFW_VERSION_MINOR, GLFW_VERSION_REVISION); int major, minor, revision; glfwGetVersion(&major, &minor, &revision); LOG_INFO("Running against GLFW %i.%i.%i", major, minor, revision); LOG_INFO("glfwGetVersionString: %s", glfwGetVersionString()); // Command line options for (int i=0; i<argc; ++i) { const std::string a = argv[i]; LOG_INFO("argv[%d]: %s", i, a.c_str()); if (!a.compare("-sdk")) { g_renderMode.outputType = RenderingMode::OVR_SDK; } else if (!a.compare("-client")) { g_renderMode.outputType = RenderingMode::OVR_Client; } else if (!a.compare("-core")) { useOpenGLCoreContext = true; } else if (!a.compare("-compat")) { useOpenGLCoreContext = false; } } LoadConfigFile(); g_app.initHMD(); GLFWwindow* l_Window = NULL; glfwSetErrorCallback(ErrorCallback); if (!glfwInit()) { exit(EXIT_FAILURE); } #ifdef __APPLE__ // Set the working directory to the Resources dir of the .app bundle CFBundleRef mainBundle = CFBundleGetMainBundle(); CFURLRef resourcesURL = CFBundleCopyResourcesDirectoryURL(mainBundle); char path[PATH_MAX]; CFURLGetFileSystemRepresentation(resourcesURL, TRUE, (UInt8 *)path, PATH_MAX); CFRelease(resourcesURL); strcat( path, "/shaders" ); struct stat sb; if (stat(path, &sb) == 0 && S_ISDIR(sb.st_mode)) chdir(path); #endif #ifndef _LINUX glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4); # if defined(_MACOS) glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1); # else glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2); # endif #endif //ndef _LINUX if (useOpenGLCoreContext) { LOG_INFO("Using OpenGL core context."); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); } else { #ifndef _LINUX glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_COMPAT_PROFILE); #endif } glfwWindowHint(GLFW_SAMPLES, 0); #ifdef _DEBUG glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GL_TRUE); #endif std::string windowTitle = "RiftRay-v" + std::string(pRiftRayVersion); #ifdef USE_OCULUSSDK const ovrSizei sz = g_app.getHmdResolution(); const ovrVector2i pos = g_app.getHmdWindowPos(); if (g_app.UsingDebugHmd() == true) { // Create a normal, decorated application window LOG_INFO("Using Debug HMD mode."); windowTitle += "-GLFW-DebugHMD"; l_Window = glfwCreateWindow(sz.w, sz.h, windowTitle.c_str(), NULL, NULL); g_app.m_dashScene.m_bDraw = false; g_renderMode.outputType = RenderingMode::Mono_Buffered; } else if (g_app.UsingDirectMode()) { LOG_INFO("Using Direct to Rift mode."); windowTitle += "-GLFW-Direct"; l_Window = glfwCreateWindow(sz.w, sz.h, windowTitle.c_str(), NULL, NULL); #if defined(_WIN32) g_app.AttachToWindow((void*)glfwGetWin32Window(l_Window)); #endif } else { LOG_INFO("Using Extended desktop mode."); windowTitle += "-GLFW-Extended"; glfwWindowHint(GLFW_DECORATED, 0); l_Window = glfwCreateWindow(sz.w, sz.h, windowTitle.c_str(), NULL, NULL); glfwWindowHint(GLFW_DECORATED, 1); glfwSetWindowPos(l_Window, pos.x, pos.y); } resize(l_Window, sz.w, sz.h); // inform AppSkeleton of window size #else const glm::vec2 sz(800, 600); // Create a normal, decorated application window LOG_INFO("Using No VR SDK."); windowTitle += "-GLFW-NoVRSDK"; g_renderMode.outputType = RenderingMode::Mono_Buffered; l_Window = glfwCreateWindow(sz.x, sz.y, windowTitle.c_str(), NULL, NULL); resize(l_Window, sz.x, sz.y); // inform AppSkeleton of window size #endif //USE_OSVR|USE_OCULUSSDK if (!l_Window) { LOG_INFO("Glfw failed to create a window. Exiting."); glfwTerminate(); exit(EXIT_FAILURE); } #ifdef USE_OCULUSSDK // Required for SDK rendering (to do the buffer swap on its own) # if defined(_WIN32) g_app.setWindow(glfwGetWin32Window(l_Window)); # elif defined(__linux__) g_app.setWindow(glfwGetX11Display()); # endif #endif glfwMakeContextCurrent(l_Window); glfwSetWindowSizeCallback(l_Window, resize); glfwSetMouseButtonCallback(l_Window, mouseDown); glfwSetCursorPosCallback(l_Window, mouseMove); glfwSetScrollCallback(l_Window, mouseWheel); glfwSetKeyCallback(l_Window, keyboard); memset(m_keyStates, 0, GLFW_KEY_LAST*sizeof(int)); FindPreferredJoystick(); // Log system monitor information const GLFWmonitor* pPrimary = glfwGetPrimaryMonitor(); int monitorCount = 0; GLFWmonitor** ppMonitors = glfwGetMonitors(&monitorCount); for (int i=0; i<monitorCount; ++i) { GLFWmonitor* pCur = ppMonitors[i]; const GLFWvidmode* mode = glfwGetVideoMode(pCur); if (mode != NULL) { LOG_INFO("Monitor #%d: %dx%d @ %dHz %s", i, mode->width, mode->height, mode->refreshRate, pCur==pPrimary ? "Primary":""); } } printGLContextInfo(l_Window); glfwMakeContextCurrent(l_Window); g_pHMDWindow = l_Window; // Don't forget to initialize Glew, turn glewExperimental on to // avoid problems fetching function pointers... glewExperimental = GL_TRUE; const GLenum l_Result = glewInit(); if (l_Result != GLEW_OK) { LOG_INFO("glewInit() error."); exit(EXIT_FAILURE); } #ifdef _DEBUG // Debug callback initialization // Must be done *after* glew initialization. glDebugMessageCallback(myCallback, NULL); glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, NULL, GL_TRUE); glDebugMessageInsert(GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_MARKER, 0, GL_DEBUG_SEVERITY_NOTIFICATION, -1, "Start debugging"); glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS); #endif #ifdef USE_ANTTWEAKBAR LOG_INFO("Using AntTweakbar."); TwInit(useOpenGLCoreContext ? TW_OPENGL_CORE : TW_OPENGL, NULL); InitializeBar(); #endif LOG_INFO("Calling initGL..."); g_app.initGL(); LOG_INFO("Calling initVR..."); g_app.initVR(); LOG_INFO("initVR complete."); SetVsync(1); // default to vsync on StartShaderLoad(); while (!glfwWindowShouldClose(l_Window)) { const bool tapped = g_app.CheckForTapOnHmd(); if (tapped && (g_receivedFirstTap == false)) { g_app.RecenterPose(); g_receivedFirstTap = true; } glfwPollEvents(); joystick(); timestep(); g_fps.OnFrame(); if (g_dynamicallyScaleFBO) { DynamicallyScaleFBO(); } #ifdef USE_ANTTWEAKBAR TwRefreshBar(g_pTweakbar); TwRefreshBar(g_pShaderTweakbar); #endif displayToHMD(); #ifndef _LINUX // Indicate FPS in window title // This is absolute death for performance in Ubuntu Linux 12.04 { std::ostringstream oss; oss << windowTitle << " " << static_cast<int>(g_fps.GetFPS()) << " fps"; glfwSetWindowTitle(l_Window, oss.str().c_str()); if (g_AuxWindow != NULL) glfwSetWindowTitle(g_AuxWindow, oss.str().c_str()); } #endif const float dumpInterval = 1.f; if (g_logDumpTimer.seconds() > dumpInterval) { LOG_INFO("Frame rate: %d fps", static_cast<int>(g_fps.GetFPS())); g_logDumpTimer.reset(); } // Optionally display to auxiliary mono view if (g_AuxWindow != NULL) { glfwMakeContextCurrent(g_AuxWindow); glClearColor(0.f, 0.f, 0.f, 0.f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); ///@note VAOs *cannot* be shared between contexts. ///@note GLFW windows are inextricably tied to their own unique context. /// For these two reasons, calling draw a third time for the auxiliary window /// is not possible. Furthermore, it is not strictly desirable for the extra /// rendering cost. /// Instead, we share the render target texture from the stereo render and present /// just the left eye to the aux window. if (g_drawToAuxWindow) { presentSharedFboTexture(); } #ifdef USE_ANTTWEAKBAR TwDraw(); ///@todo Should this go first? Will it write to a depth buffer? #endif glfwSwapBuffers(g_AuxWindow); if (glfwWindowShouldClose(g_AuxWindow)) { destroyAuxiliaryWindow(g_AuxWindow); } // Set context to Rift window when done glfwMakeContextCurrent(l_Window); } } g_app.exitVR(); glfwDestroyWindow(l_Window); glfwTerminate(); exit(EXIT_SUCCESS); }
int main(int argc, char** argv) { #if defined(_WIN32) LOG_INFO("Windows build."); #elif defined(_LINUX) LOG_INFO("Linux build."); LOG_INFO("DISPLAY=%s", getenv("DISPLAY")); #elif defined(_MACOS) LOG_INFO("MacOS build."); #endif bool useOpenGLCoreContext = false; #ifdef USE_CORE_CONTEXT useOpenGLCoreContext = true; #endif g_renderMode.outputType = RenderingMode::OVR_SDK; LOG_INFO("Using GLFW3 backend."); LOG_INFO("Compiled against GLFW %i.%i.%i", GLFW_VERSION_MAJOR, GLFW_VERSION_MINOR, GLFW_VERSION_REVISION); int major, minor, revision; glfwGetVersion(&major, &minor, &revision); LOG_INFO("Running against GLFW %i.%i.%i", major, minor, revision); LOG_INFO("glfwGetVersionString: %s", glfwGetVersionString()); // Command line options for (int i=0; i<argc; ++i) { const std::string a = argv[i]; LOG_INFO("argv[%d]: %s", i, a.c_str()); if (!a.compare("-sdk")) { g_renderMode.outputType = RenderingMode::OVR_SDK; } else if (!a.compare("-client")) { g_renderMode.outputType = RenderingMode::OVR_Client; } else if (!a.compare("-core")) { useOpenGLCoreContext = true; } else if (!a.compare("-compat")) { useOpenGLCoreContext = false; } } #ifdef USE_OCULUSSDK g_app.initHMD(); #else g_renderMode.outputType = RenderingMode::Mono_Buffered; #endif GLFWwindow* l_Window = NULL; glfwSetErrorCallback(ErrorCallback); if (!glfwInit()) { exit(EXIT_FAILURE); } // Log system monitor information const GLFWmonitor* pPrimary = glfwGetPrimaryMonitor(); int monitorCount = 0; GLFWmonitor** ppMonitors = glfwGetMonitors(&monitorCount); for (int i=0; i<monitorCount; ++i) { GLFWmonitor* pCur = ppMonitors[i]; const GLFWvidmode* mode = glfwGetVideoMode(pCur); if (mode != NULL) { (void)pPrimary; LOG_INFO("Monitor #%d: %dx%d @ %dHz %s", i, mode->width, mode->height, mode->refreshRate, pCur==pPrimary ? "Primary":""); } } bool swapBackBufferDims = false; // Context setup - before window creation glfwWindowHint(GLFW_DEPTH_BITS, 16); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, useOpenGLCoreContext ? GLFW_OPENGL_CORE_PROFILE : GLFW_OPENGL_COMPAT_PROFILE); //glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); #ifdef _DEBUG glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GL_TRUE); #endif #if defined(USE_OSVR) LOG_INFO("USE_OSVR=1"); std::string windowTitle = ""; windowTitle = PROJECT_NAME "-GLFW-Osvr"; if (g_app.UsingDebugHmd()) { const hmdRes sz = { 800, 600 }; // Create a normal, decorated application window LOG_INFO("Using Debug HMD mode."); windowTitle = PROJECT_NAME "-GLFW-DebugHMD"; g_renderMode.outputType = RenderingMode::Mono_Buffered; l_Window = glfwCreateWindow(sz.w, sz.h, windowTitle.c_str(), NULL, NULL); } else { const hmdRes sz = { g_app.getHmdResolution().h, g_app.getHmdResolution().w }; const winPos pos = g_app.getHmdWindowPos(); g_renderMode.outputType = RenderingMode::SideBySide_Undistorted; LOG_INFO("Using Extended desktop mode."); windowTitle = PROJECT_NAME "-GLFW-Extended"; LOG_INFO("Creating GLFW_DECORATED window %dx%d@%d,%d", sz.w, sz.h, pos.x, pos.y); glfwWindowHint(GLFW_DECORATED, 0); l_Window = glfwCreateWindow(sz.w, sz.h, windowTitle.c_str(), NULL, NULL); glfwWindowHint(GLFW_DECORATED, 1); glfwSetInputMode(l_Window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); glfwSetWindowPos(l_Window, pos.x, pos.y); } #elif defined(USE_OCULUSSDK) LOG_INFO("USE_OCULUSSDK=1"); ovrSizei sz = g_app.getHmdResolution(); const ovrVector2i pos = g_app.getHmdWindowPos(); std::string windowTitle = ""; if (g_app.UsingDebugHmd() == true) { // Create a normal, decorated application window LOG_INFO("Using Debug HMD mode."); windowTitle = PROJECT_NAME "-GLFW-DebugHMD"; g_renderMode.outputType = RenderingMode::Mono_Buffered; l_Window = glfwCreateWindow(sz.w, sz.h, windowTitle.c_str(), NULL, NULL); } else if (g_app.UsingDirectMode()) { // HMD active - position undecorated window to fill HMD viewport LOG_INFO("Using Direct to Rift mode."); windowTitle = PROJECT_NAME "-GLFW-Direct"; GLFWmonitor* monitor = glfwGetPrimaryMonitor(); const GLFWvidmode* mode = glfwGetVideoMode(monitor); sz.w = mode->width; sz.h = mode->height; LOG_INFO("Creating window %dx%d@%d,%d", sz.w, sz.h, pos.x, pos.y); l_Window = glfwCreateWindow(sz.w, sz.h, windowTitle.c_str(), monitor, NULL); glfwSetInputMode(l_Window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); #ifdef _LINUX swapBackBufferDims = true; #endif #if defined(_WIN32) g_app.AttachToWindow((void*)glfwGetWin32Window(l_Window)); #endif } else { LOG_INFO("Using Extended desktop mode."); windowTitle = PROJECT_NAME "-GLFW-Extended"; LOG_INFO("Creating GLFW_DECORATED window %dx%d@%d,%d", sz.w, sz.h, pos.x, pos.y); glfwWindowHint(GLFW_DECORATED, 0); l_Window = glfwCreateWindow(sz.w, sz.h, windowTitle.c_str(), NULL, NULL); glfwWindowHint(GLFW_DECORATED, 1); glfwSetInputMode(l_Window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); glfwSetWindowPos(l_Window, pos.x, pos.y); } resize(l_Window, sz.w, sz.h); // inform AppSkeleton of window size #else const glm::vec2 sz(800, 600); // Create a normal, decorated application window LOG_INFO("Using No VR SDK."); const std::string windowTitle = PROJECT_NAME "-GLFW-NoVRSDK"; g_renderMode.outputType = RenderingMode::Mono_Buffered; l_Window = glfwCreateWindow(sz.x, sz.y, windowTitle.c_str(), NULL, NULL); #endif //USE_OSVR|USE_OCULUSSDK if (!l_Window) { LOG_INFO("Glfw failed to create a window. Exiting."); glfwTerminate(); exit(EXIT_FAILURE); } // Required for SDK rendering (to do the buffer swap on its own) #ifdef OVRSDK05 #if defined(_WIN32) g_app.setWindow(glfwGetWin32Window(l_Window)); #elif defined(__linux__) g_app.setWindow(NULL);//glfwGetX11Display()); #endif #endif //USE_OCULUSSDK glfwMakeContextCurrent(l_Window); glfwSetWindowSizeCallback(l_Window, resize); glfwSetMouseButtonCallback(l_Window, mouseDown); glfwSetCursorPosCallback(l_Window, mouseMove); glfwSetScrollCallback(l_Window, mouseWheel); glfwSetKeyCallback(l_Window, keyboard); memset(m_keyStates, 0, GLFW_KEY_LAST*sizeof(int)); // joysticks for (int i = GLFW_JOYSTICK_1; i <= GLFW_JOYSTICK_LAST; ++i) { if (GL_FALSE == glfwJoystickPresent(i)) continue; const char* pJoyName = glfwGetJoystickName(i); if (pJoyName == NULL) continue; int numAxes = 0; int numButtons = 0; glfwGetJoystickAxes(i, &numAxes); glfwGetJoystickButtons(i, &numButtons); LOG_INFO("Glfw opened Joystick #%d: %s w/ %d axes, %d buttons", i, pJoyName, numAxes, numButtons); if (g_joystickIdx == -1) g_joystickIdx = i; } printGLContextInfo(l_Window); glfwMakeContextCurrent(l_Window); g_pHMDWindow = l_Window; // Don't forget to initialize Glew, turn glewExperimental on to // avoid problems fetching function pointers... glewExperimental = GL_TRUE; const GLenum l_Result = glewInit(); if (l_Result != GLEW_OK) { LOG_INFO("glewInit() error."); exit(EXIT_FAILURE); } #ifdef _DEBUG // Debug callback initialization // Must be done *after* glew initialization. glDebugMessageCallback(myCallback, NULL); glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, NULL, GL_TRUE); glDebugMessageInsert(GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_MARKER, 0, GL_DEBUG_SEVERITY_NOTIFICATION, -1 , "Start debugging"); glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS); #endif #ifdef USE_ANTTWEAKBAR LOG_INFO("Using AntTweakbar."); TwInit(useOpenGLCoreContext ? TW_OPENGL_CORE : TW_OPENGL, NULL); InitializeBar(); #endif LOG_INFO("Calling initGL..."); g_app.initGL(); LOG_INFO("Calling initVR..."); g_app.initVR(swapBackBufferDims); LOG_INFO("initVR(%d) complete.", swapBackBufferDims); while (!glfwWindowShouldClose(l_Window)) { g_app.CheckForTapToDismissHealthAndSafetyWarning(); glfwPollEvents(); joystick(); timestep(); g_fps.OnFrame(); if (g_dynamicallyScaleFBO) { DynamicallyScaleFBO(); } #ifdef USE_ANTTWEAKBAR TwRefreshBar(g_pTweakbar); #endif displayToHMD(); #ifndef _LINUX // Indicate FPS in window title // This is absolute death for performance in Ubuntu Linux 12.04 { std::ostringstream oss; oss << windowTitle << " " << static_cast<int>(g_fps.GetFPS()) << " fps"; glfwSetWindowTitle(l_Window, oss.str().c_str()); if (g_AuxWindow != NULL) glfwSetWindowTitle(g_AuxWindow, oss.str().c_str()); } #endif const float dumpInterval = 1.f; if (g_logDumpTimer.seconds() > dumpInterval) { LOG_INFO("Frame rate: %d fps", static_cast<int>(g_fps.GetFPS())); g_logDumpTimer.reset(); } // Optionally display to auxiliary mono view if (g_AuxWindow != NULL) { glfwMakeContextCurrent(g_AuxWindow); glClearColor(0.f, 0.f, 0.f, 0.f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); ///@note VAOs *cannot* be shared between contexts. ///@note GLFW windows are inextricably tied to their own unique context. /// For these two reasons, calling draw a third time for the auxiliary window /// is not possible. Furthermore, it is not strictly desirable for the extra /// rendering cost. /// Instead, we share the render target texture from the stereo render and present /// just the left eye to the aux window. if (g_drawToAuxWindow) { presentSharedFboTexture(); } #ifdef USE_ANTTWEAKBAR TwDraw(); ///@todo Should this go first? Will it write to a depth buffer? #endif glfwSwapBuffers(g_AuxWindow); if (glfwWindowShouldClose(g_AuxWindow)) { destroyAuxiliaryWindow(g_AuxWindow); } // Set context to Rift window when done glfwMakeContextCurrent(l_Window); } } g_app.exitVR(); glfwDestroyWindow(l_Window); glfwTerminate(); exit(EXIT_SUCCESS); }
int main(int argc, char* argv[]) { char* paramfile; /* name of the input parameter file */ char* obstaclefile; /* name of a the input obstacle file */ t_param params; /* struct to hold parameter values */ t_speed* cells = NULL; /* grid containing fluid densities */ t_speed* tmp_cells = NULL; /* scratch space */ int* obstacles = NULL; /* grid indicating which cells are blocked */ float* av_vels = NULL; /* a record of the av. velocity computed for each timestep */ int ii; /* generic counter */ struct timeval timstr; /* structure to hold elapsed time */ struct rusage ru; /* structure to hold CPU time--system and user */ double tic,toc; /* floating point numbers to calculate elapsed wallclock time */ double usrtim; /* floating point number to record elapsed user CPU time */ double systim; /* floating point number to record elapsed system CPU time */ /* parse the command line */ if(argc != 3) { usage(argv[0]); } else{ paramfile = argv[1]; obstaclefile = argv[2]; } /* initialise our data structures and load values from file */ initialise(paramfile, obstaclefile, ¶ms, &cells, &tmp_cells, &obstacles, &av_vels); /* iterate for maxIters timesteps */ gettimeofday(&timstr,NULL); tic=timstr.tv_sec+(timstr.tv_usec/1000000.0); float tot_u_x=0; int tot_cells = 0; MPI_Init(&argc, &argv); MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Comm_size(MPI_COMM_WORLD, &nprocs); int start=0, end=0, ff, hh, gg; params.rest = params.ny%nprocs; for (ii=0;ii<params.maxIters;ii++) { timestep(params,cells,tmp_cells,obstacles); if(ii==1){ atyt = 0; } if(ii==2){ atyt = 1; } tot_u_x=0; tot_cells = 0; ///////////av_velocity................................................. int jj,kk, tt, source; float local_density=0; float l_tot_u_x=0; int l_tot_cells = 0; if(params.rest!=0){ if(rank>=params.rest){ start = params.rest*(params.ny/nprocs+1) + (rank-params.rest)*(params.ny/nprocs); end= start+params.ny/nprocs-1; } else{ start = rank*(params.ny/nprocs+1); end = start+params.ny/nprocs; } } for(kk=start;kk<=end;kk++) { for(jj=0;jj<params.nx;jj++) { if(!obstacles[kk*params.nx + jj]) { local_density= 0.0; for(tt=0;tt<NSPEEDS;tt++) { local_density += cells[kk*params.nx + jj].speeds[tt]; } l_tot_u_x += (cells[kk*params.nx + jj].speeds[1] + cells[kk*params.nx + jj].speeds[5] + cells[kk*params.nx + jj].speeds[8] - (cells[kk*params.nx + jj].speeds[3] + cells[kk*params.nx + jj].speeds[6] + cells[kk*params.nx + jj].speeds[7])) / local_density; l_tot_cells+=1; } } } if(rank!=MASTER){ MPI_Send(&l_tot_u_x, 1, MPI_FLOAT, dest, tag, MPI_COMM_WORLD); MPI_Send(&l_tot_cells, 1, MPI_INT, dest, tag, MPI_COMM_WORLD);} else{ tot_cells = l_tot_cells; tot_u_x = l_tot_u_x; for (source =1; source < nprocs; source++) { MPI_Recv(&l_tot_u_x, 1, MPI_FLOAT, source, tag, MPI_COMM_WORLD, &status); tot_u_x+=l_tot_u_x; MPI_Recv(&l_tot_cells, 1, MPI_INT, source, tag, MPI_COMM_WORLD, &status); tot_cells+=l_tot_cells; } av_vels[ii] = tot_u_x / (float)tot_cells; } } float mes[9*params.nx]; float mes2[9*params.nx]; int xx, kk, jj; if(params.rest!=0){ if(rank>=params.rest){ start = params.rest*(params.ny/nprocs+1) + (rank-params.rest)*(params.ny/nprocs); end= start+params.ny/nprocs-1; } else{ start = rank*(params.ny/nprocs+1); end = start+params.ny/nprocs; } } for(xx=0;xx<params.ny;xx++){ if(rank!=master){ if(xx>=start&&xx<=end){ for(jj=0;jj<params.nx;jj++) { for(kk=0;kk<NSPEEDS;kk++) { cell_c[jj*NSPEEDS+kk]=cells[ii*params.nx+jj].speeds[kk]; } } MPI_Send(cell_c, NSPEEDS*params.nx, MPI_FLOAT,0, 0, MPI_COMM_WORLD); } } if(rank==master){ for(source=1;source<nprocs;source++){ if(params.rest!=0){ if(source>=params.rest){ start = params.rest*(params.ny/nprocs+1) + (source-params.rest)*(params.ny/nprocs); end= start+params.ny/nprocs-1; } else{ start = source*(params.ny/nprocs+1); end = start+params.ny/nprocs; } } if(ii>=start&&ii<+end) MPI_Recv(mes2, NSPEEDS*params.nx, MPI_FLOAT, source, tag, MPI_COMM_WORLD, &status); for(hh=0;hh<params.nx;hh++){ for(ff=0;ff<NSPEEDS;ff++){ cells[gg*params.nx + hh].speeds[ff]=mes2[NSPEEDS*hh+ff]; } } } } } }
int main(int argc, char** argv) { LoadConfigFile(); initHMD(); glfwSetErrorCallback(ErrorCallback); if (!glfwInit()) { exit(EXIT_FAILURE); } glfwWindowHint(GLFW_DEPTH_BITS, 16); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);// : GLFW_OPENGL_COMPAT_PROFILE); //glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); #ifdef _DEBUG glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GL_TRUE); #endif const std::string windowName = "RiftRay v" + std::string(pRiftRayVersion); GLFWwindow* l_Window = glfwCreateWindow(g_mirrorWindowSz.x, g_mirrorWindowSz.y, windowName.c_str(), NULL, NULL); if (!l_Window) { LOG_ERROR("Glfw failed to create a window. Exiting."); glfwTerminate(); exit(EXIT_FAILURE); } glfwMakeContextCurrent(l_Window); glfwSetKeyCallback(l_Window, keyboard); glfwSetMouseButtonCallback(l_Window, mouseDown); glfwSetCursorPosCallback(l_Window, mouseMove); glfwSetScrollCallback(l_Window, mouseWheel); glfwSetWindowSizeCallback(l_Window, resize); glfwSetInputMode(l_Window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); g_pMirrorWindow = l_Window; memset(m_keyStates, 0, GLFW_KEY_LAST*sizeof(int)); FindPreferredJoystick(); glewExperimental = GL_TRUE; if (glewInit() != GLEW_OK) { LOG_INFO("glewInit() error."); exit(EXIT_FAILURE); } #ifdef _DEBUG // Debug callback initialization // Must be done *after* glew initialization. glDebugMessageCallback(myCallback, NULL); glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, NULL, GL_TRUE); glDebugMessageInsert(GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_MARKER, 0, GL_DEBUG_SEVERITY_NOTIFICATION, -1 , "Start debugging"); glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS); #endif #ifdef USE_ANTTWEAKBAR TwInit(TW_OPENGL_CORE, NULL); initAnt(); #endif g_pScene = &g_gallery;// new ShaderGalleryScene(); if (g_pScene != NULL) { g_pScene->initGL(); } g_gallery.SetHmdPositionPointer(&m_hmdRo); g_gallery.SetHmdDirectionPointer(&m_hmdRd); g_gallery.SetChassisPosPointer(&m_chassisPos); g_gallery.SetChassisYawPointer(&m_chassisYaw); g_gallery.SetHeadSizePointer(&m_headSize); initVR(); StartShaderLoad(); glfwSwapInterval(0); while (!glfwWindowShouldClose(l_Window)) { glfwPollEvents(); joystick(); timestep(); #ifdef USE_ANTTWEAKBAR TwRefreshBar(g_pMainTweakbar); TwRefreshBar(g_pShaderTweakbar); #endif g_gallery.RenderPrePass(); displayHMD(); glfwSwapBuffers(l_Window); } exitVR(); g_pScene->exitGL(); glfwDestroyWindow(l_Window); glfwTerminate(); exit(EXIT_SUCCESS); }
int main(int argc, char** argv) { // Prolog initParallel(&argc, &argv); profileStart(totalTimer); initSubsystems(); timestampBarrier("Starting Initialization\n"); yamlAppInfo(yamlFile); yamlAppInfo(screenOut); Command cmd = parseCommandLine(argc, argv); printCmdYaml(yamlFile, &cmd); printCmdYaml(screenOut, &cmd); SimFlat* sim = initSimulation(cmd); printSimulationDataYaml(yamlFile, sim); printSimulationDataYaml(screenOut, sim); Validate* validate = initValidate(sim); // atom counts, energy timestampBarrier("Initialization Finished\n"); timestampBarrier("Starting simulation\n"); // This is the CoMD main loop const int nSteps = sim->nSteps; const int printRate = sim->printRate; int iStep = 0; profileStart(loopTimer); for (; iStep<nSteps;) { startTimer(commReduceTimer); sumAtoms(sim); stopTimer(commReduceTimer); printThings(sim, iStep, getElapsedTime(timestepTimer)); startTimer(timestepTimer); timestep(sim, printRate, sim->dt); stopTimer(timestepTimer); iStep += printRate; } profileStop(loopTimer); sumAtoms(sim); printThings(sim, iStep, getElapsedTime(timestepTimer)); timestampBarrier("Ending simulation\n"); // Epilog validateResult(validate, sim); profileStop(totalTimer); printPerformanceResults(sim->atoms->nGlobal); printPerformanceResultsYaml(yamlFile); destroySimulation(&sim); comdFree(validate); finalizeSubsystems(); timestampBarrier("CoMD Ending\n"); destroyParallel(); return 0; }
typename A::GridScalar rk4_local(A access, short res_type) { using value = typename A::GridValue; using scalar = typename A::GridScalar; // short res_type = 0; // -1=all entries, 0=density std::vector<scalar> H; scalar res = -1; scalar h_min = 1, h_max = -1; value y = {0,0,0,0}; value f = {0,0,0,0}; value k1 = {0,0,0,0}; value k2 = {0,0,0,0}; value k3 = {0,0,0,0}; value k4 = {0,0,0,0}; // Stage 1 // Write k1 to cell_begin(0) eflux(access.cell_begin(),access.cell_end(),access.cell_begin(0)); nsflux(access.cell_begin(),access.cell_end(),access.cell_begin(0)); // Stage 2 auto flux_it = access.cell_begin(0); auto out_it = access.cell_begin(4); for (auto it=access.cell_begin(); it!=access.cell_end(); ++it) { // Local time step approximation H.push_back(timestep(*it)); h_min = std::min(H.back(),h_min); // DEBUG h_max = std::max(H.back(),h_max); // Apply RK stage y = (*it).value(); f = (*flux_it).value(); (*out_it) = y + scalar(0.5)*(H.back())*f; // Iterate ++flux_it; ++out_it; } // Write k2 to cell_begin(1) eflux(access.cell_begin(4),access.cell_end(4),access.cell_begin(1)); nsflux(access.cell_begin(4),access.cell_end(4),access.cell_begin(1)); // Stage 3 flux_it = access.cell_begin(1); out_it = access.cell_begin(4); auto h_it = H.begin(); for (auto it=access.cell_begin(); it!=access.cell_end(); ++it) { // Apply RK stage y = (*it).value(); f = (*flux_it).value(); (*out_it) = y + scalar(0.5)*(*h_it)*f; // Iterate ++flux_it; ++out_it; ++h_it; } // Write k3 to cell_begin(2) eflux(access.cell_begin(4),access.cell_end(4),access.cell_begin(2)); nsflux(access.cell_begin(4),access.cell_end(4),access.cell_begin(2)); // Stage 4 flux_it = access.cell_begin(2); out_it = access.cell_begin(4); h_it = H.begin(); for (auto it=access.cell_begin(); it!=access.cell_end(); ++it) { // Apply RK stage y = (*it).value(); f = (*flux_it).value(); (*out_it) = y + (*h_it)*f; // Iterate ++flux_it; ++out_it; ++h_it; } // Write k4 to cell_begin(3) eflux(access.cell_begin(4),access.cell_end(4),access.cell_begin(3)); nsflux(access.cell_begin(4),access.cell_end(4),access.cell_begin(3)); // Add all stages auto k1_it = access.cell_begin(0); auto k2_it = access.cell_begin(1); auto k3_it = access.cell_begin(2); auto k4_it = access.cell_begin(3); auto old_it = access.cell_begin(4); out_it = access.cell_begin(); h_it = H.begin(); for (auto it=access.cell_begin(); it!=access.cell_end(); ++it) { // Apply RK stage y = (*it).value(); k1 = (*k1_it).value(); k2 = (*k2_it).value(); k3 = (*k3_it).value(); k4 = (*k4_it).value(); f = (*h_it)/scalar(6.0)*(k1+scalar(2)*k2+scalar(2)*k3+k4); // update residual if (res_type == -1) res = std::max( (std::abs(f)).max(), res ); else if (res_type == 0) res = std::max( std::abs(f[0]), res ); else assert(false); (*old_it) = y; // store old value (*out_it) = y + f; // Iterate ++flux_it; ++out_it; ++old_it; ++k1_it; ++k2_it; ++k3_it; ++k4_it; ++h_it; } // DEBUG -- print min and max timesteps // std::cout << "h_min = " << h_min << std::endl; // std::cout << "h_max = " << h_max << std::endl; // return residual return res; }
const real iterate( const int n, real4 pos[], real4 vel[], real4 acc[], real4 jrk[], const real eta, const real eps2, const real dt) { std::vector<real4> acc0(n), jrk0(n); const real dt2 = dt*(1.0/2.0); const real dt3 = dt*(1.0/3.0); for (int i = 0; i < n; i++) { acc0[i] = acc[i]; jrk0[i] = jrk[i]; pos[i].x += dt*(vel[i].x + dt2*(acc[i].x + dt3*jrk[i].x)); pos[i].y += dt*(vel[i].y + dt2*(acc[i].y + dt3*jrk[i].y)); pos[i].z += dt*(vel[i].z + dt2*(acc[i].z + dt3*jrk[i].z)); vel[i].x += dt*(acc[i].x + dt2*jrk[i].x); vel[i].y += dt*(acc[i].y + dt2*jrk[i].y); vel[i].z += dt*(acc[i].z + dt2*jrk[i].z); } forces(n, pos, vel, acc, jrk, eps2); if (dt > 0.0) { const real h = dt*0.5; const real hinv = 1.0/h; const real f1 = 0.5*hinv*hinv; const real f2 = 3.0*hinv*f1; const real dt2 = dt *dt * (1.0/2.0); const real dt3 = dt2*dt * (1.0/3.0); const real dt4 = dt3*dt * (1.0/4.0); const real dt5 = dt4*dt * (1.0/5.0); for (int i = 0; i < n; i++) { /* compute snp & crk */ const real4 Am( acc[i].x - acc0[i].x, acc[i].y - acc0[i].y, acc[i].z - acc0[i].z); const real4 Jm(h*(jrk[i].x - jrk0[i].x), h*(jrk[i].y - jrk0[i].y), h*(jrk[i].z - jrk0[i].z)); const real4 Jp(h*(jrk[i].x + jrk0[i].x), h*(jrk[i].y + jrk0[i].y), h*(jrk[i].z + jrk0[i].z)); real4 snp(f1* Jm.x, f1* Jm.y, f1* Jm.z ); real4 crk(f2*(Jp.x - Am.x), f2*(Jp.y - Am.y), f2*(Jp.z - Am.z)); snp.x -= h*crk.x; snp.y -= h*crk.y; snp.z -= h*crk.z; /* correct */ pos[i].x += dt4*snp.x + dt5*crk.x; pos[i].y += dt4*snp.y + dt5*crk.y; pos[i].z += dt4*snp.z + dt5*crk.z; vel[i].x += dt3*snp.x + dt4*crk.x; vel[i].y += dt3*snp.y + dt4*crk.y; vel[i].z += dt3*snp.z + dt4*crk.z; } } return timestep(n, vel, acc, eta, eps2); }