void SeedFeatureFactory::train( const std::vector< std::shared_ptr<ImageOverSegmentation> > &ios, const std::vector<VectorXs> & lbl ) { printf(" * Training SeedFeature\n"); static std::mt19937 rand; const int N_SAMPLES = 5000; int n_pos=0, n_neg=0; for( VectorXs l: lbl ) { n_pos += (l.array()>=0).cast<int>().sum(); n_neg += (l.array()==-1).cast<int>().sum(); } // Collect training examples float sampling_freq[] = {0.5f*N_SAMPLES / n_neg, 0.5f*N_SAMPLES / n_pos}; std::vector<RowVectorXf> f; std::vector<float> l; #pragma omp parallel for for( int i=0; i<ios.size(); i++ ) { RMatrixXf ftr = SeedFeature::computeObjFeatures( *ios[i] ); for( int j=0; j<ios[i]->Ns(); j++ ) if( lbl[i][j] >= -1 && rand() < rand.max()*sampling_freq[ lbl[i][j]>=0 ] ) { #pragma omp critical { l.push_back( lbl[i][j]>=0 ); f.push_back( ftr.row(j) ); } } } printf(" - Computing parameters\n"); // Fit the ranking functions RMatrixXf A( f.size(), f[0].size() ); VectorXf b( l.size() ); for( int i=0; i<f.size(); i++ ) { A.row(i) = f[i]; b[i] = l[i]; } // Solve A*x = b param_ = A.colPivHouseholderQr().solve(b); printf(" - done %f\n",(A*param_-b).array().abs().mean()); }
int GameMain() { s_rng.seed(1729); TestConstructors(); TestMagnAndNorm(); TestMembers(); TestNonMembers(); TestOperators(); Sleep(1000); return 0; }
void init(dynamo::Simulation& Sim, const double density) { RNG.seed(std::random_device()()); Sim.ranGenerator.seed(std::random_device()()); const double elasticity = 1.0; const size_t cells = 7; const double wallkT = 1.0; std::unique_ptr<dynamo::UCell> packptr(new dynamo::CUFCC(std::array<long, 3>{{cells, cells, cells}}, dynamo::Vector(1,1,1), new dynamo::UParticle())); packptr->initialise(); std::vector<dynamo::Vector> latticeSites(packptr->placeObjects(dynamo::Vector(0,0,0))); const size_t N = latticeSites.size(); const double boxL = std::cbrt(N / density); Sim.primaryCellSize = dynamo::Vector(boxL, boxL, boxL); dynamo::shared_ptr<dynamo::ParticleProperty> D(new dynamo::ParticleProperty(N, dynamo::Property::Units::Length(), "D", 1.0)); dynamo::shared_ptr<dynamo::ParticleProperty> M(new dynamo::ParticleProperty(N, dynamo::Property::Units::Mass(), "M", 1.0)); Sim._properties.push(D); Sim._properties.push(M); Sim.dynamics = dynamo::shared_ptr<dynamo::Dynamics>(new dynamo::DynGravity(&Sim, dynamo::Vector(0, -1, 0))); Sim.BCs = dynamo::shared_ptr<dynamo::BoundaryCondition>(new dynamo::BCNone(&Sim)); Sim.ptrScheduler = dynamo::shared_ptr<dynamo::SNeighbourList>(new dynamo::SNeighbourList(&Sim, new dynamo::FELBoundedPQ<dynamo::PELMinMax<3> >())); Sim.interactions.push_back(dynamo::shared_ptr<dynamo::Interaction>(new dynamo::IHardSphere(&Sim, "D", elasticity, new dynamo::IDPairRangeAll(), "Bulk"))); Sim.addSpecies(dynamo::shared_ptr<dynamo::Species>(new dynamo::SpPoint(&Sim, new dynamo::IDRangeAll(&Sim), "M", "Bulk", 0))); Sim.locals.push_back(dynamo::shared_ptr<dynamo::Local>(new dynamo::LWall(&Sim, elasticity, "D", dynamo::Vector(1, 0, 0), dynamo::Vector(-0.5 * Sim.primaryCellSize[0] - 1, 0, 0), "XwallLow", new dynamo::IDRangeAll(&Sim)))); Sim.locals.push_back(dynamo::shared_ptr<dynamo::Local>(new dynamo::LWall(&Sim, elasticity, "D", dynamo::Vector(-1, 0, 0), dynamo::Vector(0.5 * Sim.primaryCellSize[0] + 1, 0, 0), "XwallHigh", new dynamo::IDRangeAll(&Sim)))); Sim.locals.push_back(dynamo::shared_ptr<dynamo::Local>(new dynamo::LWall(&Sim, elasticity, "D", dynamo::Vector(0, 0, 1), dynamo::Vector(0, 0, -0.5 * Sim.primaryCellSize[2] - 1), "ZwallLow", new dynamo::IDRangeAll(&Sim)))); Sim.locals.push_back(dynamo::shared_ptr<dynamo::Local>(new dynamo::LWall(&Sim, elasticity, "D", dynamo::Vector(0, 0, -1), dynamo::Vector(0, 0, 0.5 * Sim.primaryCellSize[2] + 1), "ZwallHigh", new dynamo::IDRangeAll(&Sim)))); Sim.locals.push_back(dynamo::shared_ptr<dynamo::Local>(new dynamo::LWall(&Sim, elasticity, "D", dynamo::Vector(0, 1, 0), dynamo::Vector(0, - 0.5 * Sim.primaryCellSize[1] - 1, 0), "GroundPlate", new dynamo::IDRangeAll(&Sim), wallkT))); for (size_t i(0); i < latticeSites.size(); ++i) { Sim.particles.push_back(dynamo::Particle(boxL * latticeSites[i], getRandVelVec(), Sim.particles.size())); D->getProperty(i) = (i < 100) ? 1 : 0.5; M->getProperty(i) = (i < 100) ? 1 : 0.5 * 0.5 * 0.5; } Sim.ensemble = dynamo::Ensemble::loadEnsemble(Sim); dynamo::InputPlugin(&Sim, "Rescaler").zeroMomentum(); dynamo::InputPlugin(&Sim, "Rescaler").rescaleVels(1.0); BOOST_CHECK_EQUAL(Sim.N(), 1372); BOOST_CHECK_CLOSE(Sim.getNumberDensity() * Sim.units.unitVolume(), density, 0.000000001); }
void init(dynamo::Simulation& Sim, const double density) { RNG.seed(std::random_device()()); Sim.ranGenerator.seed(std::random_device()()); Sim.dynamics = dynamo::shared_ptr<dynamo::Dynamics>(new dynamo::DynNewtonian(&Sim)); Sim.BCs = dynamo::shared_ptr<dynamo::BoundaryCondition>(new dynamo::BCPeriodic(&Sim)); Sim.ptrScheduler = dynamo::shared_ptr<dynamo::SNeighbourList>(new dynamo::SNeighbourList(&Sim, new DefaultSorter())); std::unique_ptr<dynamo::UCell> packptr(new dynamo::CUSC(std::array<long, 3>{{128, 128, 1}}, dynamo::Vector{1,1,1}, new dynamo::UParticle())); packptr->initialise(); std::vector<dynamo::Vector> latticeSites(packptr->placeObjects(dynamo::Vector{0,0,0})); //As we're in 2D we need to take the square root double particleDiam = std::sqrt(density / latticeSites.size()); Sim.units.setUnitLength(particleDiam); Sim.units.setUnitTime(particleDiam); Sim.primaryCellSize = dynamo::Vector{1, 1, 4 * particleDiam}; typedef std::pair<double,double> Step; std::vector<Step> steps; steps.push_back(Step{1.0,0.1}); steps.push_back(Step{0.9,0.2}); steps.push_back(Step{0.8,0.3}); steps.push_back(Step{0.7,0.4}); steps.push_back(Step{0.6,0.5}); steps.push_back(Step{0.5,0.6}); steps.push_back(Step{0.4,0.7}); steps.push_back(Step{0.3,0.8}); steps.push_back(Step{0.2,0.9}); steps.push_back(Step{0.1,1.0}); Sim.interactions.push_back(dynamo::shared_ptr<dynamo::Interaction>(new dynamo::IStepped(&Sim, dynamo::shared_ptr<dynamo::Potential>(new dynamo::PotentialStepped(steps, false)), new dynamo::IDPairRangeAll(), "Bulk", particleDiam, 1.0))); Sim.addSpecies(dynamo::shared_ptr<dynamo::Species>(new dynamo::SpPoint(&Sim, new dynamo::IDRangeAll(&Sim), 1.0, "Bulk", 0))); unsigned long nParticles = 0; Sim.particles.reserve(latticeSites.size()); for (const dynamo::Vector & position : latticeSites) Sim.particles.push_back(dynamo::Particle(position, getRandVelVec() * Sim.units.unitVelocity(), nParticles++)); for (auto& particle : Sim.particles) particle.getVelocity()[2] = 0; dynamo::InputPlugin(&Sim, "Rescaler").zeroMomentum(); dynamo::InputPlugin(&Sim, "Rescaler").rescaleVels(2.0 / 3.0); Sim.ensemble = dynamo::Ensemble::loadEnsemble(Sim); BOOST_CHECK_EQUAL(Sim.N(), 128 * 128); }
void init(dynamo::Simulation& Sim, const double density) { RNG.seed(std::random_device()()); Sim.ranGenerator.seed(std::random_device()()); double massFrac = 0.001, sizeRatio = 0.5; size_t Na=100; Sim.dynamics = dynamo::shared_ptr<dynamo::Dynamics>(new dynamo::DynNewtonian(&Sim)); Sim.BCs = dynamo::shared_ptr<dynamo::BoundaryCondition>(new dynamo::BCPeriodic(&Sim)); Sim.ptrScheduler = dynamo::shared_ptr<dynamo::SNeighbourList>(new dynamo::SNeighbourList(&Sim, new DefaultSorter())); std::unique_ptr<dynamo::UCell> packptr(new dynamo::CUFCC(std::array<long, 3>{{10, 10, 10}}, dynamo::Vector(1, 1, 1), new dynamo::UParticle())); packptr->initialise(); std::vector<dynamo::Vector> latticeSites(packptr->placeObjects(dynamo::Vector(0,0,0))); Sim.primaryCellSize = dynamo::Vector(1,1,1); double simVol = 1.0; for (size_t iDim = 0; iDim < NDIM; ++iDim) simVol *= Sim.primaryCellSize[iDim]; double particleDiam = std::cbrt(simVol * density / latticeSites.size()); Sim.interactions.push_back(dynamo::shared_ptr<dynamo::Interaction>(new dynamo::IHardSphere(&Sim, particleDiam, new dynamo::IDPairRangeSingle(new dynamo::IDRangeRange(0, Na - 1)), "AAInt"))); Sim.interactions.push_back(dynamo::shared_ptr<dynamo::Interaction>(new dynamo::IHardSphere(&Sim, ((1.0 + sizeRatio) / 2.0) * particleDiam, new dynamo::IDPairRangePair(new dynamo::IDRangeRange(0, Na - 1), new dynamo::IDRangeRange(Na, latticeSites.size() - 1)), "ABInt"))); Sim.interactions.push_back(dynamo::shared_ptr<dynamo::Interaction>(new dynamo::IHardSphere(&Sim, sizeRatio * particleDiam, new dynamo::IDPairRangeAll(), "BBInt"))); Sim.addSpecies(dynamo::shared_ptr<dynamo::Species>(new dynamo::SpPoint(&Sim, new dynamo::IDRangeRange(0, Na - 1), 1.0, "A", 0))); Sim.addSpecies(dynamo::shared_ptr<dynamo::Species>(new dynamo::SpPoint(&Sim, new dynamo::IDRangeRange(Na, latticeSites.size() - 1), massFrac, "B", 0))); Sim.units.setUnitLength(particleDiam); unsigned long nParticles = 0; Sim.particles.reserve(latticeSites.size()); for (const dynamo::Vector & position : latticeSites) Sim.particles.push_back(dynamo::Particle(position, getRandVelVec() * Sim.units.unitVelocity(), nParticles++)); Sim.ensemble = dynamo::Ensemble::loadEnsemble(Sim); dynamo::InputPlugin(&Sim, "Rescaler").zeroMomentum(); dynamo::InputPlugin(&Sim, "Rescaler").rescaleVels(1.0); BOOST_CHECK_EQUAL(Sim.N(), 4000); //BOOST_CHECK_CLOSE(Sim.getNumberDensity() * Sim.units.unitVolume(), density, 0.000000001); //BOOST_CHECK_CLOSE(Sim.getPackingFraction(), Sim.getNumberDensity() * Sim.units.unitVolume() * M_PI / 6.0, 0.000000001); }
int main(int argc, char** argv) { rng.seed(); CALL(TEST_HashFunctions); CALL(overview::TEST_Construction); CALL(overview::TEST_Retreival); CALL(overview::TEST_Resizing); CALL(separate_chaining::TEST_Construction); CALL(separate_chaining::TEST_Retreival); CALL(open_addressing::TEST_Construction); CALL(open_addressing::TEST_Retreival); CALL(cuckoo::TEST_CuckooHashing); CALL(TEST_MostCommon); CALL(TEST_Cache); return 0; }
// ------------------------------------------------------------------------- int hpx_main(boost::program_options::variables_map& vm) { std::size_t device = vm["device"].as<std::size_t>(); std::size_t sizeMult = vm["sizemult"].as<std::size_t>(); std::size_t iterations = vm["iterations"].as<std::size_t>(); // unsigned int seed = std::random_device{}(); if (vm.count("seed")) seed = vm["seed"].as<unsigned int>(); gen.seed(seed); std::cout << "using seed: " << seed << std::endl; // sizeMult = (std::min)(sizeMult, std::size_t(100)); sizeMult = (std::max)(sizeMult, std::size_t(1)); // // use a larger block size for Fermi and above, query default cuda target properties hpx::compute::cuda::target target(device); std::cout << "GPU Device " << target.native_handle().get_device() << ": \"" << target.native_handle().processor_name() << "\" " << "with compute capability " << target.native_handle().processor_family() << "\n"; int block_size = (target.native_handle().processor_family() < 2) ? 16 : 32; sMatrixSize matrix_size; matrix_size.uiWA = 2 * block_size * sizeMult; matrix_size.uiHA = 4 * block_size * sizeMult; matrix_size.uiWB = 2 * block_size * sizeMult; matrix_size.uiHB = 4 * block_size * sizeMult; matrix_size.uiWC = 2 * block_size * sizeMult; matrix_size.uiHC = 4 * block_size * sizeMult; printf("MatrixA(%u,%u), MatrixB(%u,%u), MatrixC(%u,%u)\n\n", matrix_size.uiWA, matrix_size.uiHA, matrix_size.uiWB, matrix_size.uiHB, matrix_size.uiWC, matrix_size.uiHC); matrixMultiply<float>(matrix_size, device, iterations); return hpx::finalize(); }
void init(dynamo::Simulation& Sim, double density = 0.5) { RNG.seed(std::random_device()()); Sim.ranGenerator.seed(std::random_device()()); const double elasticity = 1.0; const double lambda = 1.5; const double welldepth = 1.0; Sim.dynamics = dynamo::shared_ptr<dynamo::Dynamics>(new dynamo::DynNewtonian(&Sim)); Sim.BCs = dynamo::shared_ptr<dynamo::BoundaryCondition>(new dynamo::BCPeriodic(&Sim)); Sim.ptrScheduler = dynamo::shared_ptr<dynamo::SNeighbourList>(new dynamo::SNeighbourList(&Sim, new DefaultSorter())); std::unique_ptr<dynamo::UCell> packptr(new dynamo::CUFCC(std::array<long, 3>{{7,7,7}}, dynamo::Vector(1,1,1), new dynamo::UParticle())); packptr->initialise(); std::vector<dynamo::Vector> latticeSites(packptr->placeObjects(dynamo::Vector(0,0,0))); Sim.primaryCellSize = dynamo::Vector(1,1,1); double simVol = 1.0; for (size_t iDim = 0; iDim < NDIM; ++iDim) simVol *= Sim.primaryCellSize[iDim]; double particleDiam = std::cbrt(simVol * density / latticeSites.size()); Sim.interactions.push_back(dynamo::shared_ptr<dynamo::Interaction>(new dynamo::ISquareWell(&Sim, particleDiam, lambda, welldepth, elasticity, new dynamo::IDPairRangeAll(), "Bulk"))); Sim.addSpecies(dynamo::shared_ptr<dynamo::Species>(new dynamo::SpPoint(&Sim, new dynamo::IDRangeAll(&Sim), 1.0, "Bulk", 0))); Sim.units.setUnitLength(particleDiam); Sim.units.setUnitTime(particleDiam); unsigned long nParticles = 0; Sim.particles.reserve(latticeSites.size()); for (const dynamo::Vector & position : latticeSites) Sim.particles.push_back(dynamo::Particle(position, getRandVelVec() * Sim.units.unitVelocity(), nParticles++)); Sim.ensemble = dynamo::Ensemble::loadEnsemble(Sim); dynamo::InputPlugin(&Sim, "Rescaler").zeroMomentum(); dynamo::InputPlugin(&Sim, "Rescaler").rescaleVels(1.0); BOOST_CHECK_EQUAL(Sim.N(), 1372); BOOST_CHECK_CLOSE(Sim.getNumberDensity() * Sim.units.unitVolume(), density, 0.000000001); BOOST_CHECK_CLOSE(Sim.getPackingFraction(), Sim.getNumberDensity() * Sim.units.unitVolume() * M_PI / 6.0, 0.000000001); }
Random::Random(UInt64 seed) { if (seed == 0) { if( !static_gen_seeded ) { #if NDEBUG unsigned int static_seed = (unsigned int)std::chrono::system_clock::now().time_since_epoch().count(); #else unsigned int static_seed = DEBUG_RANDOM_SEED; #endif static_gen.seed( static_seed ); static_gen_seeded = true; NTA_INFO << "Random seed: " << static_seed; } seed_ = static_gen(); //generate random value from HW RNG } else { seed_ = seed; } // if seed is zero at this point, there is a logic error. NTA_CHECK(seed_ != 0); gen.seed((unsigned int)seed_); //seed the generator steps_ = 0; }
namespace rng { std::mt19937 r; void init() { r.seed((unsigned)std::chrono::system_clock::now().time_since_epoch().count()); } int d6(std::mt19937& urng) { return d6Gen(urng); } int degrees(std::mt19937& urng) { return degreesGen(urng); } double radians(std::mt19937& urng) { return radiansGen(urng); } bool boolean(std::mt19937& urng) { return booleanGen(urng); } int getInt(int lo, int hi, std::mt19937& urng) { return std::uniform_int_distribution<int>(lo, hi)(urng); } int getInt(int hi, std::mt19937& urng) { return std::uniform_int_distribution<int>(0, hi)(urng); } bool oneInX(double x, std::mt19937& urng) { return std::bernoulli_distribution(1.0 / x)(urng); } bool xInY(double x, double y, std::mt19937& urng) { return std::bernoulli_distribution(x / y)(urng); } }
void use_graph_generator(const vle::devs::InitEventList& events) { model_number = events.getInt("model-number"); std::string generator_name = events.getString("graph-generator"); if (events.exist("graph-seed")) generator.seed(events.getInt("graph-seed")); if (generator_name == "defined") use_defined_graph_generator(events); else if (generator_name == "small-world") use_smallworld_graph_generator(events); else if (generator_name == "scale-free") use_scalefree_graph_generator(events); else if (generator_name == "sorted-erdos-renyi") use_sortederdesrenyi_graph_generator(events); else if (generator_name == "erdos_renyi") use_erdosrenyi_graph_generator(events); else throw vle::utils::ModellingError("Unknown graph gererator: %s", generator_name.c_str()); }
void init(dynamo::Simulation& Sim, const double density) { RNG.seed(std::random_device()()); Sim.ranGenerator.seed(std::random_device()()); const double elasticity = 1.0; const size_t N = 1000; Sim.dynamics = dynamo::shared_ptr<dynamo::Dynamics>(new dynamo::DynNewtonian(&Sim)); Sim.BCs = dynamo::shared_ptr<dynamo::BoundaryCondition>(new dynamo::BCPeriodic(&Sim)); Sim.ptrScheduler = dynamo::shared_ptr<dynamo::SNeighbourList>(new dynamo::SNeighbourList(&Sim, new DefaultSorter())); dynamo::CURandom packroutine(N, dynamo::Vector{1,1,1}, new dynamo::UParticle()); packroutine.initialise(); std::vector<dynamo::Vector> latticeSites(packroutine.placeObjects(dynamo::Vector{0,0,0})); Sim.BCs = dynamo::shared_ptr<dynamo::BoundaryCondition>(new dynamo::BCPeriodic(&Sim)); double particleDiam = std::cbrt(density / N); Sim.interactions.push_back(dynamo::shared_ptr<dynamo::Interaction>(new dynamo::ILines(&Sim, particleDiam, elasticity, new dynamo::IDPairRangeAll(), "Bulk"))); Sim.addSpecies(dynamo::shared_ptr<dynamo::Species>(new dynamo::SpSphericalTop(&Sim, new dynamo::IDRangeAll(&Sim), 1.0, "Bulk", 0, particleDiam * particleDiam / 12.0))); Sim.units.setUnitLength(particleDiam); unsigned long nParticles = 0; Sim.particles.reserve(latticeSites.size()); for (const dynamo::Vector & position : latticeSites) Sim.particles.push_back(dynamo::Particle(position, getRandVelVec() * Sim.units.unitVelocity(), nParticles++)); Sim.dynamics->initOrientations(); Sim.ensemble = dynamo::Ensemble::loadEnsemble(Sim); dynamo::InputPlugin(&Sim, "Rescaler").zeroMomentum(); dynamo::InputPlugin(&Sim, "Rescaler").rescaleVels(1.0); BOOST_CHECK_EQUAL(Sim.N(), N); BOOST_CHECK_CLOSE(Sim.getNumberDensity() * Sim.units.unitVolume(), density, 0.000000001); BOOST_CHECK_CLOSE(Sim.getPackingFraction(), 0, 0.000000001); }
/******************************************************************************* Function to initialize ODE. *******************************************************************************/ void initODE() { ///////////////// Initializing the ODE general features //////////////////// dInitODE(); //Initialize library. World = dWorldCreate(); //Crate a new dynamics, empty world. Space = dSimpleSpaceCreate(0); //Create a new space for collision (independent). ContactGroup = dJointGroupCreate(0); //Create a joints container, without specifying size. dWorldSetGravity( World, 0.0, -9.81, 0 ); //Add gravity to this World. //Define error conrrection constants. dWorldSetERP( World, 0.2 ); dWorldSetCFM( World, 1e-5 ); //Set the velocity that interpenetrating objects will separate at. dWorldSetContactMaxCorrectingVel( World, 0.9 ); //Set the safety area for contacts to be considered at rest. dWorldSetContactSurfaceLayer( World, 0.001 ); //Automatically disable objects that have come to a rest. dWorldSetAutoDisableFlag( World, false ); /////////////// Initializing the rigid bodies in the world ///////////////// //Create a collision plane and add it to space. The next parameters are the //literal components of ax + by + cz = d. dCreatePlane( Space, 0.0, 1.0, 0.0, 0.0 ); const dReal xPos = 0; const dReal yPos = 5; const dReal zPos = 0; const dReal xRot = 0; const dReal yRot = 0; const dReal zRot = 0; const dReal radius = .75; const dReal length = 4; const dReal sides[3] = { 2, 2, 2 }; //Create body body.Body = dBodyCreate(World); dBodySetPosition(body.Body, xPos, yPos, zPos); dMatrix3 Orient3; //dRFromAxisAndAngle(Orient3, 0, 0, 1, 3.14/4); dRFromEulerAngles(Orient3, xRot, yRot, zRot); //dRFromEulerAngles(Orient3, 0, 0, 0); dBodySetRotation(body.Body, Orient3); dBodySetLinearVel(body.Body, 0, 0, 0); dBodySetData(body.Body, (void *)0); dMass bodyMass; dMassSetCapsule(&bodyMass, 1.0, 3, radius, length); //dMassSetBox(&bodyMass, 10, sides[0], sides[1], sides[2]); dBodySetMass(body.Body, &bodyMass); body.Geom = dCreateCapsule(Space, radius, length); //body.Geom = dCreateBox(Space, sides[0], sides[1], sides[2]); dGeomSetBody(body.Geom, body.Body); float head_pos[ 3 ] = { 0.0f, 5.0f, -1.0f }; createInvisibleHead( head_pos ); createFrontLegs(); createMiddleLegs(); createBackLegs(); rng_engine.seed( std::chrono::duration_cast< std::chrono::microseconds >( std::chrono::system_clock::now().time_since_epoch() ).count() ); const int foodPrize = 10; dReal position[3] = { 10.0f, 0.0f, -20.0f }; addFoodParticle( position, foodPrize, &World, &Space ); }
void init_random_seed(int seed) { generator.seed(seed); }
int main(int argc, char * argv[]) { for(int i = 0; i <14; i++) { cout << " " << endl; } cout << "Welcome, my friend to the simplistic game of Trinity's Nightmare. Here, you have" << endl << "reached a dungeon where you are alone, standing with only your car keys and a trash" << endl << "can lid that you found. This is also where the level where the real danger begins." << endl << "You have conquered the attic of man eating camels -- You have trudged through" << endl << "the muddy swamps of Dr. Heinz'science experiment of alligator-dogs, only to" << endl << "come face to face with the most recent obstacle of the fire-breathing" << endl << "coffee-ingesting cookie-stealing SQUIRRELS!! Now, hold on to your" << endl << "Mountain Dew and Pizza, buckle up into your basement chair, and" << endl << "change your profile picture to that of a face of fear, because" << endl << "here you go..." << endl; cout << "To Play: " << endl; cout << "Unless otherwise declaried, you will show up as @" << endl; cout << "1.) Movement:" << endl; cout << " a - moves the player left" << endl; cout << " s - moves the player down" << endl; cout << " d - moves the player right" << endl; cout << " w - moves the player up" << endl; cout << " EXTRA: DIAGONAL:"<< endl; cout << " e - up to the right" << endl; cout << " x - down to the right" << endl; cout << " z - down to the left" << endl; cout << " ` - up to the right" << endl << endl; cout << "2.) Picking up and Using Items:" << endl; cout << " p - pick up, and thus using" << endl; cout << "3.) Attack:" << endl; cout << " - Creatures will attack you if you are within one space of them." << endl; cout << " - Weapons and Experience increase your attacking." << endl << endl; cout << "q will allow you to Quit -- if you are a Quitter..." << endl << endl << endl; mt.seed(time(NULL)); cout << "This is command line" << endl; cout << "Arguments Given : " << argc << endl; //load file into variable string inFileName; string outFileName; ifstream input; int inputValue = 0; if (argc >= 3) { inFileName = argv[1]; outFileName = argv[2]; } else { cout << "Enter a file name with .xml exstension: "; cin >> inFileName; cout << endl; cout << "What do you want to name the output file? " ; cin >> outFileName; cout << endl; } if (argc >= 4) { inputValue = atoi(argv[3]); } else { cout << "How many random Dungeons do you you want generated? " ; cin >> inputValue; cout << endl; } if(!input.good()) { cout << "No file by that name. Try Again. " << endl; return 1; } input.open(inFileName.c_str()); //make vector using XMLSerializable pointer vector<XMLSerializable*> vWorld; //send variables to parseXML parseXML(input, vWorld); //dumpOntoConsole(vWorld); //make output file ofstream output; bool creatureOccupied; bool wallOccupied; int tempX = 0; int tempY = 0; int thingTempX = 0; int thingTempY = 0; int playerX = 0; int playerY = 0; Player * pPlayer = new Player(); Weapon * punch = new Weapon(); Weapon * keys = new Weapon(); Armor * TrashCanLid = new Armor(); keys->setDamage(5); keys->setAccuracy(2); keys->setWeaponType("keychain"); keys->setName("Car Keys"); keys->setDisplayChar('x'); pPlayer->setWeapon(punch); punch->setDamage(5); punch->setAccuracy(5); punch->setWeaponType("flesh"); TrashCanLid->setArmorValue(3); TrashCanLid->setArmorType("trashlid"); TrashCanLid->setName("Trash Can Lid"); TrashCanLid->setDisplayChar('t'); pPlayer->setInventory(TrashCanLid); pPlayer->setInventory(keys); pPlayer->setExperience(0); string sMove; int dNum = 0; int iNum = 0; vector<DungeonLevel*> vDL; vector<vector<Creature*>> vvCreatures; vector<vector<vector<Item*>>> vvvItems; bool nextFloor = true; bool sameFloor = false; bool prevFloor = false; bool creatureTurn; int monsterHP = 0; int HP = 0; int attack = 0; int moveCount = 0; bool bWeapon = true; initscr(); noecho(); while(true) { clear(); if( nextFloor == true ) { nextFloor = false; if( sameFloor == false ) { vDL.push_back(new DungeonLevel(79,20)); } playerX = vDL[dNum]->upstairXCoord(); playerY = vDL[dNum]->upstairYCoord(); vvvItems.resize(dNum+1); vvvItems[dNum].resize(5); vvCreatures.resize(dNum+1); if( sameFloor == false ) { for(int i = 0 ; i<5; i++) { //Creature * pCreature = CreatureFactory::instance().generateCreature(4); vvCreatures[dNum].push_back(CreatureFactory::instance().generateCreature((vDL.size())*2)); while(true) { thingTempX = mt() % 79; thingTempY = mt() % 20; wallOccupied = vDL[dNum]->checkMove(thingTempX, thingTempY); if( wallOccupied == true ) { vDL[dNum]->setCreature(vvCreatures[dNum][i], thingTempX, thingTempY); vvCreatures[dNum][i]->setCoords(thingTempX, thingTempY); break; } } iNum =( (mt() % 5) + 1 ); for( size_t j = 0 ; j < iNum ; j++ ) { vvvItems[dNum][i].push_back(ItemFactory::instance().generateItem(vDL.size()*20)); } while(true) { thingTempX = mt() % 79; thingTempY = mt() % 20; wallOccupied = vDL[dNum]->checkMove( thingTempX, thingTempY ); if( wallOccupied == true ) { for( size_t j = 0 ; j < iNum ; j++ ) { vDL[dNum]->setItems(vvvItems[dNum][i][j], thingTempX,thingTempY); vvvItems[dNum][i][j]->setCoords(thingTempX, thingTempY); } break; } } /*if( pCreature ) { pCreature->dumpObject(); delete pCreature; }*/ } } } else if( prevFloor == true ) { if( dNum < 0 ) { break; //cout << "You Escaped... because you ran away like a pansy. Good Job." << endl; clear(); mvprintw(0,0,"You Escaped... because you ran away like a pansy. Good Job. "); refresh(); } prevFloor = false; playerX = vDL[dNum]->downstairXCoord(); playerY = vDL[dNum]->downstairYCoord(); } //dl.display(); //continue; //cout << endl << "Final State: " << endl << endl; tempX = playerX; tempY = playerY; vDL[dNum]->setCreature(pPlayer, playerX, playerY); while(true) { if( moveCount % 10 == 0 ) { if(pPlayer->getName() =="God") { pPlayer->setHP(1000000000); } else { if( pPlayer->getHP() < 97 ) { pPlayer->setHP( pPlayer->getHP() + 3 ); } } } if( moveCount == 20 ) { vvCreatures[dNum].push_back(CreatureFactory::instance().generateCreature((vDL.size())*2)); while(true) { thingTempX = mt() % 79; thingTempY = mt() % 20; wallOccupied = vDL[dNum]->checkMove(thingTempX, thingTempY); if( wallOccupied == true ) { vDL[dNum]->setCreature(vvCreatures[dNum][vvCreatures.size()-1], thingTempX, thingTempY); vvCreatures[dNum][vvCreatures.size()-1]->setCoords(thingTempX, thingTempY); break; } } } do { for( size_t y = 0; y < 20 ; y++ ) { for( size_t x = 0; x < 79 ; x++ ) { move(y,x); addch(vDL[dNum]->display(x,y)); } refresh(); //cout << endl; } sMove = getch(); move(23,0); clrtoeol(); move(24,0); clrtoeol(); move(25,0); clrtoeol(); move(26,0); clrtoeol(); move(21,0); clrtoeol(); //vDL[dNum]->display(); //refresh(); mvprintw(30,0,"Got it. Next? "); //cout << endl <<"Got it, " << pPlayer->getName() << " What Next? "; //getnstr(sMove, sizeof( users_name ) - 1 ); //cin >> sMove; //cout << endl; if( sMove == "w" ) { //up tempY--; break; } else if( sMove == "s" ) { //down tempY++; break; } else if( sMove == "a" ) { //left tempX--; break; } else if( sMove == "d" ) { //right tempX++; break; } else if( sMove == "e" ) { //up to the right tempX++; tempY--; break; } else if( sMove == "x" ) { //down to the right tempX++; tempY++; break; } else if( sMove == "z" ) { //down to the left tempX--; tempY++; break; } else if( sMove == "`" ) { //up to the left tempX--; tempY--; break; } else if( sMove == "q" ) { clear(); mvprintw(0,0,"Really!? You just quit. Good going."); break; } else if( sMove == ">" ) { if( playerX == vDL[dNum]->downstairXCoord() && playerY == vDL[dNum]->downstairYCoord() ) { clear(); nextFloor = true; break; } pPlayer->setExperience(pPlayer->getExperience() + 5 * vDL.size()); } else if( sMove == "<" ) { if( playerX == vDL[dNum]->upstairXCoord() && playerY == vDL[dNum]->upstairYCoord() ) { prevFloor = true; break; } } else if( sMove == "p" ) { if( vDL[dNum]->checkItem(playerX, playerY) ) { vDL[dNum]->pickUpItem(playerX, playerY); if(pPlayer->getDropItem() != NULL) { vDL[dNum]->setItems(pPlayer->getDropItem(), playerX, playerY); } break; } } else if( sMove == "l" ) { pPlayer->setDropItem(); if( pPlayer->getDropItem() != NULL ) { vDL[dNum]->setItems(pPlayer->getDropItem(), playerX, playerY); } } else if( sMove == "u" ) { pPlayer->getInventory(); } else { //cout << endl << "What!? I try that again. I have no idea what you are trying to do." << endl; mvprintw(21,0,"What!? I try that again. I have no idea what you are trying to do."); } mvprintw(50,0,"Got it, What Next? "); refresh(); }while( sMove != "q" ); if( sMove == "q" ) { //cout << endl << "Really!? You just quit. Good going." << endl; break; } /////////////////////////////////////PLAYER MOVEMENT AND ATTACK/////////////////////////////////////////// for( size_t i = 0 ; i < vvCreatures[dNum].size() ; i++ ) { if( vvCreatures[dNum][i]->getCoordX() == tempX && vvCreatures[dNum][i]->getCoordY() == tempY ) { //cout << "creature occupied set to true" << endl; creatureOccupied = true; break; } } wallOccupied = vDL[dNum]->DungeonLevel::checkMove(tempX,tempY); if(wallOccupied == true && creatureOccupied == false && ( tempX <! 0 || tempX >! 79 || tempY <! 0 || tempY >! 20 )) { vDL[dNum]->removeCreature(playerX, playerY); playerX = tempX; playerY = tempY; vDL[dNum]->setCreature(pPlayer, playerX, playerY); creatureTurn = true; } else if( wallOccupied == true && creatureOccupied == true ) { if( bWeapon == false ) { attack = mt() % (pPlayer->getWeapon())->getDamage(); } else { attack = mt() % (punch->getDamage()); } HP = (vDL[dNum]->getCreature(tempX,tempY))->getHP(); //cout << endl << "Creature's HP before: " << HP << endl; mvprintw(24,0,"Creature's HP before: %i", HP); refresh(); (vDL[dNum]->getCreature(tempX,tempY))->setHP(HP - attack); //cout << endl << pPlayer->getName() << " attacked " << (vDL[dNum]->getCreature(tempX, tempY))->getName() << " for " << attack << " damage " << endl; if( HP - attack <= 0 ) { for( int i = 0 ; i < vvCreatures[dNum].size() ; i++ ) { if( vvCreatures[dNum][i]->getCoordX() == tempX && vvCreatures[dNum][i]->getCoordY() == tempY ) { vDL[dNum]->removeCreature( vvCreatures[dNum][i]->getCoordX(), vvCreatures[dNum][i]->getCoordY() ); //cout << pPlayer->getName() << " killed " << vvCreatures[dNum][i]->getName() << "!" << endl; mvprintw(27,0,"%s killed the creature!",pPlayer->getName().c_str()); delete vvCreatures[dNum][i]; vvCreatures[dNum].erase(vvCreatures[dNum].begin() + i); break; } } pPlayer->setExperience(pPlayer->getExperience() + vDL.size() * 5); } else { HP = (vDL[dNum]->getCreature(tempX,tempY))->getHP(); } //cout << endl << "Creature's HP after: " << HP << endl; mvprintw(26,0,"Creature's HP after: %i", HP); refresh(); creatureOccupied = false; tempX = playerX; tempY = playerY; } else if(wallOccupied == false) { tempX = playerX; tempY = playerY; } //cout << endl << pPlayer->getName() << "'s health is " << pPlayer->getHP() << endl; mvprintw(30,0,"%s's health is %i.", pPlayer->getName().c_str(), pPlayer->getHP()); //cout << endl << "There are " << vvCreatures[dNum].size() << " creatures left on the field. " << endl; mvprintw(31,0,"There are %i creatures left on the field. ", vvCreatures[dNum].size()); //cout << endl << pPlayer->getName() << " has " << pPlayer->getHP() << " Health and " << pPlayer->getExperience() << " Experience right now."; mvprintw(32,0,"%s has %i Health and %i Experience right now.",pPlayer->getName().c_str(),pPlayer->getHP(),pPlayer->getExperience()); //cout << pPlayer->getName() << " killed the monster and gained experience!" << endl; ////////////////////////////////////MONSTER MOVEMENT AND ATTACK///////////////////////////////////////////// for( size_t i = 0 ; i < vvCreatures[dNum].size() ; i++ ) { thingTempX = vvCreatures[dNum][i]->getCoordX(); thingTempY = vvCreatures[dNum][i]->getCoordY(); //cout << endl << "Creature " << i << " moved from (" << thingTempX << ", " << thingTempY << ") to ("; //mvprintw("Creature %i moved from (%i,%i) to (", i,thingTempX,thingTempY); refresh(); if( thingTempX < playerX ) { thingTempX ++; } else if( thingTempX > playerX ) { thingTempX --; } if( thingTempY < playerY ) { thingTempY ++; } else if( thingTempY > playerY ) { thingTempY --; } for( size_t j = 0 ; j < vvCreatures[dNum].size() ; j++ ) { if( vvCreatures[dNum][j]->getCoordX() == thingTempX && vvCreatures[dNum][j]->getCoordY() == thingTempY ) { creatureOccupied = true; } } //cout << ")" << endl; if(wallOccupied == false) { //vDL[dNum]->removeCreature(vvCreatures[dNum][i]->getCoordX(), vvCreatures[dNum][i]->getCoordY()); //cout << endl << "restraint" << endl; mvprintw(23,50,"You cannot move there...It's a wall."); //vDL[dNum]->setCreature(vvCreatures[dNum][i], vvCreatures[dNum][i]->getCoordX(), vvCreatures[dNum][i]->getCoordY()); } else if( (vDL[dNum]->checkMove(thingTempX, thingTempY) == true && creatureOccupied == false) && (playerX != thingTempX && playerY != thingTempY) ) { vDL[dNum]->removeCreature(vvCreatures[dNum][i]->getCoordX(), vvCreatures[dNum][i]->getCoordY()); vvCreatures[dNum][i]->setCoords(thingTempX, thingTempY); vDL[dNum]->setCreature(vvCreatures[dNum][i], thingTempX, thingTempY); } else if( ((abs( playerX - thingTempX ) == 1) && (abs( playerY - thingTempY ) == 1)) || (thingTempX == playerX && thingTempY == playerY) ) { //cout << endl << vvCreatures[dNum][i]->getName() << " attacked " << pPlayer->getName(); mvprintw(25,0,"%s atacked %s",vvCreatures[dNum][i]->getName().c_str(), pPlayer->getName().c_str()); HP = pPlayer->getHP(); attack = mt() % punch->getDamage() - (pPlayer->getArmorType())->getArmorValue(); if ( attack > 0 ) { pPlayer->setHP(HP - attack); //cout << " for " << attack << " damage." << endl; mvprintw(25,30," for %i damage.",attack); refresh(); } else { mvprintw(25,30," for 0 damage"); refresh(); //cout << "for 0 damage" << endl; } //If Player Died in the attack: if(pPlayer->getHP() <= 0) { char regen[ 4 ]; //cout << endl << "You were killed in battle!! Do you want to come back to life? y or n? " << endl; mvprintw(40,0,"You were killed in battle!! Do you want to come back to life? y or n? " ); refresh(); getnstr( regen, sizeof( regen ) - 1 ); //cin >> regen; if (regen == "y") { pPlayer->setHP(100); } break; } //cout << endl << pPlayer->getName() << " now has " << pPlayer->getHP() << " health left " << endl; //vDL[dNum]->setCreature(vvCreatures[dNum][i], vvCreatures[dNum][i]->getCoordX(), vvCreatures[dNum][i]->getCoordY()); creatureOccupied = false; } //cout << endl << vvCreatures[dNum][i]->getCoordX() << ", " << vvCreatures[dNum][i]->getCoordY() << ")" << endl; } if( nextFloor == true ) { dNum++; if( dNum < vDL.size() ) { sameFloor = true; } break; } else if( prevFloor == true ) { dNum--; break; } } if( sMove == "q" ) { //printw("\n You quit... you Quitter!"); //printw("\n"); break; } } for( size_t i = 0 ; i < vDL.size() ; i++ ) { for( size_t j ; j < vvCreatures[i].size() ; j++ ) { delete vvCreatures[i][j]; } } /*cout << "GAME OVER" << endl; cout << "Score - " << pPlayer->getExperience() << endl; cout << "Health at the end - " << pPlayer->getHP() << endl;*/ clear(); mvprintw(0,0,"GAME OVER" ); mvprintw(1,0,"Score - %i", pPlayer->getExperience() ); mvprintw(2,0, "Health at the end - %i", pPlayer->getHP() ); mvprintw(3,0," "); refresh(); delete pPlayer; delete punch; delete keys; delete TrashCanLid; output.open(outFileName); //outputXML(vWorld, output); //delete memory to avoid memory leaks for(auto it = vWorld.begin() ; it != vWorld.end() ; it++) { delete (*it); } //close input and output files! input.close(); output.close(); clear(); return 0; }
void Window::Init(int width, int height, std::string title) { // Intiate Random Number Generator m_Random.seed(time(0)); //initialize all SDL subsystems if (SDL_Init(SDL_INIT_EVERYTHING) == -1) throw std::runtime_error("SDL Init Failed"); //if (TTF_Init() == -1) //throw std::runtime_error("TTF Init Failed"); // -- For Music -- /* We're going to be requesting certain things from our audio device, so we set them up beforehand */ int audio_rate = 22050; Uint16 audio_format = AUDIO_S16; /* 16-bit stereo */ int audio_channels = 2; int audio_buffers = 4096; SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO); /* This is where we open up our audio device. Mix_OpenAudio takes as its parameters the audio format we'd /like/ to have. */ if (Mix_OpenAudio(audio_rate, audio_format, audio_channels, audio_buffers)) throw std::runtime_error("Unable to open audio!\n"); /* If we actually care about what we got, we can ask here. In this program we don't, but I'm showing the function call here anyway in case we'd want to know later. */ Mix_QuerySpec(&audio_rate, &audio_format, &audio_channels); /* Every sound that gets played is assigned to a channel. Note that this is different from the number of channels you request when you open the audio device; a channel in SDL_mixer holds information about a sound sample that is playing, while the number of channels you request when opening the device is dependant on what sort of sound you want (1 channel = mono, 2 = stereo, etc) */ //-- For Sounds -- /* Mix_Chunk is like Mix_Music, only it's for ordinary sounds. */ //Setup our window size mBox.x = 0; mBox.y = 0; mBox.w = width; mBox.h = height; /* Create the windows and initialize the renderers */ //Create our window mWindow.reset(SDL_CreateWindow(title.c_str(), SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, mBox.w, mBox.h, SDL_WINDOW_SHOWN)); //Make sure it created ok if (mWindow == nullptr) throw std::runtime_error("Failed to create window"); mRenderer.reset(SDL_CreateRenderer(mWindow.get(), -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC)); //Make sure it created ok if (mRenderer == nullptr) throw std::runtime_error("Failed to create renderer"); Clear(); SDL_SetRenderDrawBlendMode(mRenderer.get(), SDL_BLENDMODE_NONE); SDL_RenderFillRect(mRenderer.get(), NULL); }
Controller() : network(this), model(this), resources(), display(this) { _generator.seed(42); }
inline double rndf() { return fabs(rng())/rng.max(); }
void setSeed(int val) { s_random.seed(val); }
namespace math /** Miscellaneous math routines. */ { // Global random object. extern std::mt19937 randGen; // Global uniform distribution. extern std::uniform_real_distribution<> randUniformDist; // Global normal distribution. extern std::normal_distribution<> randNormalDist; /** * Set the random seed used by the random functions (Random() and RandInt()). * The seed is casted to a 32-bit integer before being given to the random * number generator, but a size_t is taken as a parameter for API consistency. * * @param seed Seed for the random number generator. */ inline void RandomSeed(const size_t seed) { randGen.seed((uint32_t) seed); srand((unsigned int) seed); #if ARMA_VERSION_MAJOR > 3 || \ (ARMA_VERSION_MAJOR == 3 && ARMA_VERSION_MINOR >= 930) // Armadillo >= 3.930 has its own random number generator internally that we // need to set the seed for also. arma::arma_rng::set_seed(seed); #endif } /** * Generates a uniform random number between 0 and 1. */ inline double Random() { return randUniformDist(randGen); } /** * Generates a uniform random number in the specified range. */ inline double Random(const double lo, const double hi) { return lo + (hi - lo) * randUniformDist(randGen); } /** * Generates a uniform random integer. */ inline int RandInt(const int hiExclusive) { return (int) std::floor((double) hiExclusive * randUniformDist(randGen)); } /** * Generates a uniform random integer. */ inline int RandInt(const int lo, const int hiExclusive) { return lo + (int) std::floor((double) (hiExclusive - lo) * randUniformDist(randGen)); } /** * Generates a normally distributed random number with mean 0 and variance 1. */ inline double RandNormal() { return randNormalDist(randGen); } /** * Generates a normally distributed random number with specified mean and * variance. * * @param mean Mean of distribution. * @param variance Variance of distribution. */ inline double RandNormal(const double mean, const double variance) { return variance * randNormalDist(randGen) + mean; } } // namespace math
static void updateRandomSeed(uint32_t seed_number) { m_random_engine.seed(seed_number); } // updateRandomSeed
void init() { r.seed((unsigned)std::chrono::system_clock::now().time_since_epoch().count()); }
namespace random { static std::mt19937 __random_generator; static bool __random_initialized = false; static std::recursive_mutex __random_lock; void initialize( uint32_t seed ) { TRACE_MESSAGE(TRACE_LEVEL_VERBOSE, "+sola::component::random::initialize"); SERIALIZE_CALL(std::recursive_mutex, __random_lock); std::srand((uint32_t) std::time(NULL)); if(seed == GENERATE_RANDOM_SEED) { __random_generator.seed(rand()); } else { __random_generator.seed(seed); } __random_initialized = true; TRACE_MESSAGE(TRACE_LEVEL_VERBOSE, "-sola::component::random::initialize"); } double generate_normalized( double mean, double sigma, double crop_min, double crop_max ) { TRACE_MESSAGE(TRACE_LEVEL_VERBOSE, "+sola::component::random::generate_normalized"); SERIALIZE_CALL(std::recursive_mutex, __random_lock); double result; std::normal_distribution<double> normal_dist(mean, sigma); if(!__random_initialized) { THROW_RANDOM_EXCEPTION(RANDOM_EXCEPTION_UNINITIALIZED); } if(sigma < 0.0) { THROW_RANDOM_EXCEPTION_MESSAGE( RANDOM_EXCEPTION_INVALID_PARAMETER, "spread < 0.0" ); } if(crop_min > crop_max) { THROW_RANDOM_EXCEPTION_MESSAGE( RANDOM_EXCEPTION_INVALID_PARAMETER, "crop_min > crop_max" ); } result = normal_dist(__random_generator); if(result < crop_min) { result = crop_min; } else if(result > crop_max) { result = crop_max; } TRACE_MESSAGE(TRACE_LEVEL_VERBOSE, "-sola::component::random::generate_normalized, result. " << result); return result; } double generate_uniform( double min, double max ) { TRACE_MESSAGE(TRACE_LEVEL_VERBOSE, "+sola::component::random::generate_uniform"); SERIALIZE_CALL(std::recursive_mutex, __random_lock); double result; std::uniform_real_distribution<double> uniform_dist; if(!__random_initialized) { THROW_RANDOM_EXCEPTION(RANDOM_EXCEPTION_UNINITIALIZED); } if(min > max) { THROW_RANDOM_EXCEPTION_MESSAGE( RANDOM_EXCEPTION_INVALID_PARAMETER, "min > max" ); } result = ((max - min) * uniform_dist(__random_generator)) + min; TRACE_MESSAGE(TRACE_LEVEL_VERBOSE, "-sola::component::random::generate_uniform, result. " << result); return result; } }
int main(int argc, char *argv[]) { RNG.seed(); double errlvl = 1e-12; size_t testcount = 100000; std::cout << "Quaternion Testing:" << std::endl; std::cout << "Quaternion::fromToVector()" << std::endl; for (size_t i(0); i < testcount; ++i) { Vector start = random_unit_vec(); Vector end = random_unit_vec(); Vector err = end - (Quaternion::fromToVector(end, start) * start); if ((std::abs(err[0]) > errlvl) || (std::abs(err[1]) > errlvl) || (std::abs(err[2]) > errlvl)) { std::cout << "test " << i << ": error " << err.toString() << std::endl; return EXIT_FAILURE; } } std::cout << "Quaternion::fromAngleAxis()" << std::endl; for (size_t i(0); i < testcount; ++i) { double angle = angle_dist(RNG); Vector axis = random_unit_vec(); Vector start = random_unit_vec(); Vector end = Rodrigues(axis * angle) * start; Vector err = end - (Quaternion::fromAngleAxis(angle, axis) * start); if ((std::abs(err[0]) > errlvl) || (std::abs(err[1]) > errlvl) || (std::abs(err[2]) > errlvl)) { std::cout << "test " << i << ": error " << err.toString() << std::endl; return EXIT_FAILURE; } } std::cout << "Quaternion::toMatrix()" << std::endl; for (size_t i(0); i < testcount; ++i) { double angle = angle_dist(RNG); Vector axis = random_unit_vec(); Vector start = random_unit_vec(); Vector end = Rodrigues(axis * angle) * start; Vector err = end - (Quaternion::fromAngleAxis(angle, axis).toMatrix() * start); if ((std::abs(err[0]) > errlvl) || (std::abs(err[1]) > errlvl) || (std::abs(err[2]) > errlvl)) { std::cout << "test " << i << ": error " << err.toString() << std::endl; return EXIT_FAILURE; } } std::cout << "Quaternion::operator*(Quaternion&)" << std::endl; for (size_t i(0); i < testcount; ++i) { Vector start = random_unit_vec(); double angle1 = angle_dist(RNG); Vector axis1 = random_unit_vec(); double angle2 = angle_dist(RNG); Vector axis2 = random_unit_vec(); double angle3 = angle_dist(RNG); Vector axis3 = random_unit_vec(); Vector end = Rodrigues(axis3 * angle3) * Rodrigues(axis2 * angle2) * Rodrigues(axis1 * angle1) * start; Vector err = end - (Quaternion::fromAngleAxis(angle3, axis3) * Quaternion::fromAngleAxis(angle2, axis2) * Quaternion::fromAngleAxis(angle1, axis1) * start); if ((std::abs(err[0]) > errlvl) || (std::abs(err[1]) > errlvl) || (std::abs(err[2]) > errlvl)) { std::cout << "test " << i << ": error " << err.toString() << std::endl; return EXIT_FAILURE; } } std::cout << "Quaternion::inverse()" << std::endl; for (size_t i(0); i < testcount; ++i) { Vector start = random_unit_vec(); double angle1 = angle_dist(RNG); Vector axis1 = random_unit_vec(); double angle2 = angle_dist(RNG); Vector axis2 = random_unit_vec(); Vector end = Rodrigues(axis1 * angle1) * start; Vector err = end - (Quaternion::fromAngleAxis(angle1, axis1) * Quaternion::fromAngleAxis(angle2, axis2) * Quaternion::fromAngleAxis(angle2, axis2).inverse() * start); if ((std::abs(err[0]) > errlvl) || (std::abs(err[1]) > errlvl) || (std::abs(err[2]) > errlvl)) { std::cout << "test " << i << ": error " << err.toString() << std::endl; return EXIT_FAILURE; } } std::cout << "GLSL rotation()" << std::endl; for (size_t i(0); i < testcount; ++i) { Vector start = random_unit_vec(); Vector end = random_unit_vec(); Quaternion q = Quaternion::fromToVector(end, start); Vector result = start + 2.0 * (q.imaginary() ^ ((q.imaginary() ^ start) + q.real() * start)); Vector err = end - result; if ((std::abs(err[0]) > errlvl) || (std::abs(err[1]) > errlvl) || (std::abs(err[2]) > errlvl)) { std::cout << "test " << i << ": error " << err.toString() << std::endl; return EXIT_FAILURE; } } return EXIT_SUCCESS; }
void init(){ rng.seed((unsigned int)time(NULL)); }
static int cmdfunc_intcmd( int cmd ) { // cmdfunc : TYPE_INTCMD // (内蔵コマンド) // int p1,p2,p3; // code_next(); // 次のコードを取得(最初に必ず必要です) switch( cmd ) { // サブコマンドごとの分岐 case 0x00: // onexit case 0x01: // onerror case 0x02: // onkey case 0x03: // onclick case 0x04: // oncmd { /* rev 45 不具合 : (onxxx系命令) (ラベル型変数) 形式の書式でエラー に対処 */ int tval = *type; int opt = IRQ_OPT_GOTO; int cust; int actid; IRQDAT *irq; unsigned short *sbr; if ( tval == TYPE_VAR ) { if ( ( ctx->mem_var + *val )->flag == HSPVAR_FLAG_LABEL ) tval = TYPE_LABEL; } if (( tval != TYPE_PROGCMD )&&( tval != TYPE_LABEL )) { // ON/OFF切り替え int i = code_geti(); code_enableirq( cmd, i ); break; } if ( tval == TYPE_PROGCMD ) { // ジャンプ方法指定 opt = *val; if ( opt >= 2 ) throw HSPERR_SYNTAX; code_next(); } sbr = code_getlb2(); if ( cmd != 0x04 ) { code_setirq( cmd, opt, -1, sbr ); break; } cust = code_geti(); actid = *(exinfo->actscr); irq = code_seekirq( actid, cust ); if ( irq == NULL ) irq = code_addirq(); irq->flag = IRQ_FLAG_ENABLE; irq->opt = opt; irq->ptr = sbr; irq->custom = cust; irq->custom2 = actid; break; } case 0x11: // exist case 0x12: // delete case 0x13: // mkdir case 0x14: // chdir code_event( HSPEVENT_FNAME, 0, 0, code_gets() ); code_event( HSPEVENT_FEXIST + (cmd - 0x11), 0, 0, NULL ); break; case 0x15: // dirlist { PVal *pval; APTR aptr; char *ptr; aptr = code_getva( &pval ); code_event( HSPEVENT_FNAME, 0, 0, code_gets() ); p1=code_getdi(0); code_event( HSPEVENT_FDIRLIST1, p1, 0, &ptr ); code_setva( pval, aptr, TYPE_STRING, ptr ); code_event( HSPEVENT_FDIRLIST2, 0, 0, NULL ); break; } case 0x16: // bload case 0x17: // bsave { PVal *pval; char *ptr; int size; int tmpsize; code_event( HSPEVENT_FNAME, 0, 0, code_gets() ); ptr = code_getvptr( &pval, &size ); p1 = code_getdi( -1 ); p2 = code_getdi( -1 ); if (( p1 < 0 )||( p1 > size )) p1 = size; if ( cmd == 0x16 ) { tmpsize = p2;if ( tmpsize<0 ) tmpsize = 0; code_event( HSPEVENT_FREAD, tmpsize, p1, ptr ); } else { code_event( HSPEVENT_FWRITE, p2, p1, ptr ); } break; } case 0x18: // bcopy code_event( HSPEVENT_FNAME, 0, 0, code_gets() ); code_event( HSPEVENT_FCOPY, 0, 0, code_gets() ); break; case 0x19: // memfile { PVal *pval; char *ptr; int size; ptr = code_getvptr( &pval, &size ); p1=code_getdi( 0 ); p2=code_getdi( 0 ); if ( p2==0 ) p2 = size - p1; dpm_memfile( ptr+p1, p2 ); break; } case 0x1a: // poke case 0x1b: // wpoke case 0x1c: // lpoke { PVal *pval; char *ptr; int size; int fl; int len; char *bp; ptr = code_getvptr( &pval, &size ); p1 = code_getdi( 0 ); if ( p1<0 ) throw HSPERR_BUFFER_OVERFLOW; ptr += p1; if ( code_get() <= PARAM_END ) { fl = HSPVAR_FLAG_INT; bp = (char *)&p2; p2 = 0; } else { fl = mpval->flag; bp = mpval->pt; } if ( cmd == 0x1a ) { switch( fl ) { case HSPVAR_FLAG_INT: if ( p1 >= size ) throw HSPERR_BUFFER_OVERFLOW; *ptr = *bp; break; case HSPVAR_FLAG_STR: len = (int)strlen( bp ); ctx->strsize = len; len++; if ( (p1+len)>size ) throw HSPERR_BUFFER_OVERFLOW; strcpy( ptr, bp ); break; default: throw HSPERR_TYPE_MISMATCH; } break; } if ( fl != HSPVAR_FLAG_INT ) throw HSPERR_TYPE_MISMATCH; if ( cmd == 0x1b ) { if ( (p1+2)>size ) throw HSPERR_BUFFER_OVERFLOW; *(short *)ptr = (short)(*(short *)bp); } else { if ( (p1+4)>size ) throw HSPERR_BUFFER_OVERFLOW; *(int *)ptr = (*(int *)bp); } break; } case 0x1d: // getstr { PVal *pval2; PVal *pval; APTR aptr; char *ptr; char *p; int size; aptr = code_getva( &pval ); ptr = code_getvptr( &pval2, &size ); p1 = code_getdi( 0 ); p2 = code_getdi( 0 ); p3 = code_getdi( 1024 ); if ( p1 >= size ) throw HSPERR_BUFFER_OVERFLOW; ptr += p1; p = code_stmp( p3 + 1 ); strsp_ini(); ctx->stat = strsp_get( ptr, p, p2, p3 ); ctx->strsize = strsp_getptr(); code_setva( pval, aptr, HSPVAR_FLAG_STR, p ); break; } case 0x1e: // chdpm code_event( HSPEVENT_FNAME, 0, 0, code_gets() ); p1 = code_getdi( -1 ); dpm_bye(); p2 = dpm_ini( ctx->fnbuffer, 0, -1, p1 ); if ( p2 ) throw HSPERR_FILE_IO; #ifndef HSP3IMP #ifdef HSPWIN Sleep( 1000 ); #endif #endif break; case 0x1f: // memexpand { PVal *pval; APTR aptr; PDAT *ptr; aptr = code_getva( &pval ); ptr = HspVarCorePtrAPTR( pval, aptr ); if (( pval->support & HSPVAR_SUPPORT_FLEXSTORAGE ) == 0 ) throw HSPERR_TYPE_MISMATCH; p1 = code_getdi( 0 ); if ( p1 < 64 ) p1 = 64; HspVarCoreAllocBlock( pval, ptr, p1 ); break; } case 0x20: // memcpy { PVal *pval; char *sptr; char *tptr; int bufsize_t,bufsize_s; tptr = code_getvptr( &pval, &bufsize_t ); sptr = code_getvptr( &pval, &bufsize_s ); p1 = code_getdi( 0 ); p2 = code_getdi( 0 ); p3 = code_getdi( 0 ); if( p2 < 0 || p3 < 0 ) throw HSPERR_BUFFER_OVERFLOW; tptr += p2; sptr += p3; if ( (p1+p2)>bufsize_t ) throw HSPERR_BUFFER_OVERFLOW; if ( (p1+p3)>bufsize_s ) throw HSPERR_BUFFER_OVERFLOW; if ( p1>0 ) { memmove( tptr, sptr, p1 ); } break; } case 0x21: // memset { PVal *pval; char *ptr; int size; ptr = code_getvptr( &pval, &size ); p1 = code_getdi( 0 ); p2 = code_getdi( 0 ); p3 = code_getdi( 0 ); if ( p3 < 0 ) throw HSPERR_BUFFER_OVERFLOW; ptr += p3; if ( (p3+p2)>size ) throw HSPERR_BUFFER_OVERFLOW; if ( p2>0 ) { memset( ptr, p1, p2 ); } break; } case 0x22: // notesel ctx->notep_aptr = ctx->note_aptr; ctx->notep_pval = ctx->note_pval; ctx->note_aptr = code_getva( &ctx->note_pval ); if ( ctx->note_pval->flag != HSPVAR_FLAG_STR ) { code_setva( ctx->note_pval, ctx->note_aptr, TYPE_STRING, "" ); } break; case 0x23: // noteadd { char *np; char *ps; char *tmp; int size; np = note_update(); ps = code_gets(); size = (int)strlen( ps ) + 8; HspVarCoreAllocBlock( ctx->note_pval, (PDAT *)np, (int)strlen(np) + size ); tmp = code_stmpstr( ps ); p1 = code_getdi( -1 ); p2 = code_getdi( 0 ); np = note_update(); note.PutLine( tmp, p1, p2 ); break; } case 0x24: // notedel p1 = code_getdi( 0 ); note_update(); note.PutLine( NULL, p1, 1 ); break; case 0x25: // noteload { int size; char *ptr; char *pdat; code_event( HSPEVENT_FNAME, 0, 0, code_gets() ); p1 = code_getdi( -1 ); code_event( HSPEVENT_FEXIST, 0, 0, NULL ); size = ctx->strsize; if ( size < 0 ) throw HSPERR_FILE_IO; if ( p1>=0 ) if ( size >= p1 ) { ctx->strsize = size = p1; } pdat = note_update(); HspVarCoreAllocBlock( ctx->note_pval, (PDAT *)pdat, size+1 ); ptr = (char *)note_update(); code_event( HSPEVENT_FREAD, 0, size, ptr ); ptr[size] = 0; break; } case 0x26: // notesave { char *pdat; int size; code_event( HSPEVENT_FNAME, 0, 0, code_gets() ); pdat = note_update(); size = (int)strlen( pdat ); code_event( HSPEVENT_FWRITE, -1, size, pdat ); break; } case 0x27: // randomize #ifdef HSPWIN p2 = (int)GetTickCount(); // Windowsの場合はtickをシード値とする #else p2 = (int)time(0); // Windows以外のランダムシード値 #endif p1 = code_getdi( p2 ); #ifdef HSPRANDMT mt.seed( p1 ); #else srand( p1 ); #endif break; case 0x28: // noteunsel ctx->note_aptr = ctx->notep_aptr; ctx->note_pval = ctx->notep_pval; break; case 0x29: // noteget { PVal *pval; APTR aptr; char *p; note_update(); aptr = code_getva( &pval ); p1 = code_getdi( 0 ); p = note.GetLineDirect( p1 ); code_setva( pval, aptr, TYPE_STRING, p ); note.ResumeLineDirect(); break; } case 0x2a: // split { // 指定した文字列で分割された要素を代入する(fujidig) PVal *pval = NULL; int aptr = 0; char *sptr; char *sep; char *newsptr; int size; int sep_len; int n = 0; int is_last = 0; sptr = code_getvptr( &pval, &size ); if ( pval->flag != HSPVAR_FLAG_STR ) throw HSPERR_TYPE_MISMATCH; sep = code_gets(); sep_len = (int)strlen( sep ); while (1) { newsptr = strstr2( sptr, sep ); if ( !is_last && *exinfo->npexflg & EXFLG_1 ) { // 分割結果の数が格納する変数より多ければ最後の変数に配列で格納していく // ただし最後の要素が a.2 のように要素指定があればそれ以降は全く格納しない if ( aptr != 0 ) pval = NULL; is_last = 1; aptr = 0; } if ( is_last ) { aptr ++; if ( pval != NULL && aptr >= pval->len[1] ) { if ( pval->len[2] != 0 ) throw HSPVAR_ERROR_ARRAYOVER; HspVarCoreReDim( pval, 1, aptr+1 ); } } else { aptr = code_getva( &pval ); } if ( pval != NULL ) { if ( newsptr == NULL ) { code_setva( pval, aptr, HSPVAR_FLAG_STR, sptr ); } else { var_set_str_len( pval, aptr, sptr, (int)(newsptr - sptr) ); } } n ++; if ( newsptr == NULL ) { // 格納する変数の数が分割できた数より多ければ残った変数それぞれに空文字列を格納する while( ( *exinfo->npexflg & EXFLG_1 ) == 0 ) { aptr = code_getva( &pval ); code_setva( pval, aptr, HSPVAR_FLAG_STR, "" ); } break; } sptr = newsptr + sep_len; } ctx->stat = n; break; } case 0x02b: // strrep { PVal *pval; APTR aptr; char *ss; char *s_rep; char *s_buffer; char *s_result; aptr = code_getva( &pval ); if ( pval->flag != HSPVAR_FLAG_STR ) throw HSPERR_TYPE_MISMATCH; s_buffer = (char *)HspVarCorePtrAPTR( pval, aptr ); ss = code_gets(); if ( *ss == 0 ) throw HSPERR_ILLEGAL_FUNCTION; ReplaceSetMatch( s_buffer, ss ); s_rep = code_gets(); s_result = ReplaceStr( s_rep ); code_setva( pval, aptr, TYPE_STRING, s_result ); ctx->stat = ReplaceDone(); break; } case 0x02c: // setease { HSPREAL dval; HSPREAL dval2; dval = code_getd(); dval2 = code_getd(); p1 = code_getdi( ease_type ); setEase( p1, dval, dval2 ); break; } case 0x02d: // sortval { int a,i; PVal *p1; APTR ap; int order; ap = code_getva( &p1 ); // パラメータ1:変数 order = code_getdi( 0 ); // パラメータ2:数値 i=p1->len[1]; if (i<=0) throw HSPERR_ILLEGAL_FUNCTION; switch(p1->flag) { case HSPVAR_FLAG_DOUBLE: { double *dp; dp=(double *)p1->pt; DataIni( i ); for(a=0;a<i;a++) { dtmp[a].as.dkey=dp[a]; dtmp[a].info=a; } if (order == 0) { std::sort(dtmp, dtmp + i, less_double_1); } else { std::sort(dtmp, dtmp + i, less_double_0); } for(a=0;a<i;a++) { code_setva( p1, a, HSPVAR_FLAG_DOUBLE, &(dtmp[a].as.dkey) ); // 変数に値を代入 } break; } case HSPVAR_FLAG_INT: { int *p; p=(int *)p1->pt; DataIni( i ); for(a=0;a<i;a++) { dtmp[a].as.ikey=p[a]; dtmp[a].info=a; } if (order == 0) { std::sort(dtmp, dtmp + i, less_int_1); } else { std::sort(dtmp, dtmp + i, less_int_0); } for(a=0;a<i;a++) { p[a]=dtmp[a].as.ikey; } break; } default: throw HSPERR_ILLEGAL_FUNCTION; } break; } case 0x02e: // sortstr { int i,len,order; char *p; PVal *pv; APTR ap; HspVarProc *proc; char **pvstr; ap = code_getva( &pv ); // パラメータ1:変数 order = code_getdi( 0 ); // パラメータ2:数値 if ( pv->flag != 2 ) throw HSPERR_TYPE_MISMATCH; if (( pv->len[2] != 0 )||( ap != 0 )) throw HSPERR_ILLEGAL_FUNCTION; proc = HspVarCoreGetProc( pv->flag ); len = pv->len[1]; DataIni( len ); for(i=0;i<len;i++) { p = (char *)HspVarCorePtrAPTR( pv, i ); dtmp[i].as.skey = p; dtmp[i].info = i; } if (order == 0) { std::sort(dtmp, dtmp + i, less_str_1); } else { std::sort(dtmp, dtmp + i, less_str_0); } pvstr = (char **)(pv->master); // 変数に直接sbポインタを書き戻す for(i=0;i<len;i++) { if ( i == 0 ) { pv->pt = dtmp[i].as.skey; sbSetOption(pv->pt, &pv->pt); } else { pvstr[i] = dtmp[i].as.skey; sbSetOption(pvstr[i], &pvstr[i]); } } break; } case 0x02f: // sortnote { int i,sflag; char *p; char *stmp; PVal *pv; APTR ap; ap = code_getva( &pv ); // パラメータ1:変数 sflag = code_getdi( 0 ); // パラメータ2:数値 p = (char *)HspVarCorePtrAPTR( pv, ap ); i = GetNoteLines(p); if ( i <= 0 ) throw HSPERR_ILLEGAL_FUNCTION; DataIni( i ); NoteToData( p, dtmp ); if (sflag == 0) { std::sort(dtmp, dtmp + i, less_str_1); } else { std::sort(dtmp, dtmp + i, less_str_0); } stmp = code_stmp( (int)DataToNoteLen( dtmp, i ) + 1 ); DataToNote( dtmp, stmp, i ); code_setva( pv, ap, HSPVAR_FLAG_STR, stmp ); // 変数に値を代入 break; } case 0x030: // sortget { PVal *pv; APTR ap; int result; int n; ap = code_getva( &pv ); n = code_getdi( 0 ); if ( dtmp == NULL ) throw HSPERR_ILLEGAL_FUNCTION; if (0 <= n && n < dtmp_size ) { result=dtmp[n].info; } else { result=0; } code_setva( pv, ap, HSPVAR_FLAG_INT, &result ); break; } default: throw HSPERR_UNSUPPORTED_FUNCTION; } return RUNMODE_RUN; }
void srand(const Nan::FunctionCallbackInfo<v8::Value>& info) { gen.seed(static_cast<unsigned long>(info[0]->Int32Value())); }
namespace ogdf { #ifdef OGDF_DEBUG bool debugMode = true; #else bool debugMode = false; #endif Initialization::Initialization() { initializeOGDF(); } Initialization::~Initialization() { deinitializeOGDF(); } inline bool charCompareIgnoreCase(char a, char b) { return toupper(a) == toupper(b); } void removeTrailingWhitespace(std::string &str) { std::size_t found = str.find_last_not_of(" \t\v\f\n\r"); if (found != std::string::npos) { str.erase(found+1); } else { // string consists only of whitespacae str.clear(); } } bool equalIgnoreCase(const string &str1, const string &str2) { return str1.size() == str2.size() && std::equal(str1.begin(), str1.end(), str2.begin(), charCompareIgnoreCase); } bool prefixIgnoreCase(const string &prefix, const string &str) { string::size_type len = prefix.length(); return str.size() >= len && std::equal(prefix.begin(), prefix.end(), str.begin(), charCompareIgnoreCase); } static std::mt19937 s_random; #ifndef OGDF_MEMORY_POOL_NTS static std::mutex s_randomMutex; #endif long unsigned int randomSeed() { #ifndef OGDF_MEMORY_POOL_NTS std::lock_guard<std::mutex> guard(s_randomMutex); #endif return 7*s_random()+3; // do not directly return seed, add a bit of variation } void setSeed(int val) { s_random.seed(val); } int randomNumber(int low, int high) { OGDF_ASSERT(low <= high); std::uniform_int_distribution<> dist(low,high); #ifndef OGDF_MEMORY_POOL_NTS std::lock_guard<std::mutex> guard(s_randomMutex); #endif return dist(s_random); } double randomDouble(double low, double high) { OGDF_ASSERT(low <= high); std::uniform_real_distribution<> dist(low,high); #ifndef OGDF_MEMORY_POOL_NTS std::lock_guard<std::mutex> guard(s_randomMutex); #endif return dist(s_random); } double usedTime(double& T) { double t = T; #ifdef OGDF_SYSTEM_WINDOWS FILETIME creationTime; FILETIME exitTime; FILETIME kernelTime; FILETIME userTime; GetProcessTimes(GetCurrentProcess(), &creationTime, &exitTime, &kernelTime, &userTime); ULARGE_INTEGER user; user.LowPart = userTime.dwLowDateTime; user.HighPart = userTime.dwHighDateTime; T = double(user.QuadPart) * 0.0000001; #else struct tms now; times (&now); T = (double)now.tms_utime / (double)sysconf(_SC_CLK_TCK); #endif return T - t; } }
application::impl::impl(application * owner) : _owner { owner }, _db { 3, owner->_service }, _config { { "server.xml", "misc.xml" } } { _rng.seed(time(nullptr)); }
int main(int argc, char* args[]) { //Start up SDL and create window int screenmode = 0; if (argc > 1) { screenmode = std::stoi(args[1]); } if (!init(screenmode)) { printf("Failed to initialize!\n"); } else { Menu menu = Menu(); //Load media if (!menu.init()) { printf("Failed to load media!\n"); } else { //Main loop flag bool quit = false; int state = STATE_MENU; int mode = M_SINGLEPLAYER; rngGfx.seed(time(NULL)); glLoadIdentity(); glTranslated(-1, 1, 0); glScaled(2.0 / SCREEN_WIDTH, -2.0 / SCREEN_HEIGHT, 1.0); const Uint8 *keyboard = SDL_GetKeyboardState(NULL); //Event handler SDL_Event e; frame = 0; unsigned int endTime = SDL_GetTicks(); GameLogic g; //While application is running while (!quit) { endTime = endTime + 17; frame++; if (frame % 3 == 0) endTime--; //Handle events on queue SDL_Scancode keydown = SDL_SCANCODE_UNKNOWN; while (SDL_PollEvent(&e) != 0) { //User requests quit if (e.type == SDL_QUIT) { quit = true; } if (e.type == SDL_MOUSEMOTION) { //Get the mouse offsets mouseX = e.motion.x; mouseY = e.motion.y; if (screenmode == 1 || screenmode == 3) { mouseX /= 1.5; mouseY /= 1.5; } } if (e.type == SDL_MOUSEBUTTONDOWN || e.type == SDL_MOUSEBUTTONUP) { mouseX = e.button.x; mouseY = e.button.y; if (e.button.button == SDL_BUTTON_LEFT) clicked = (e.button.state == SDL_PRESSED); if (screenmode == 1 || screenmode == 3) { mouseX /= 1.5; mouseY /= 1.5; } } if (e.type == SDL_KEYDOWN) { keydown = e.key.keysym.scancode; } } if (keyboard[SDL_SCANCODE_ESCAPE]) { quit = true; } //Clear screen glClearColor(0.1f, 0.1f, 0.1f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); switch (state) { case STATE_MENU: g = GameLogic(); g.write_other_players = SDL_CreateMutex(); mode = menu.step( mouseX, mouseY, clicked, keyboard, keydown);//returns mode if changed, 0 if no change if (mode != 0) { std::cout << mode; state = (mode == M_SERVER) ? STATE_WAIT_FOR_CLIENT : STATE_BEGINGAME; } menu.draw( mouseX, mouseY); break; case STATE_WAIT_FOR_CLIENT: uint32_t rng_seed; IPaddress ip; glColor3f(1.0f, .4f, .9f); menu.draw_text(80, 300, "Waiting for client"); menu.draw_text(180, 400, "to connect"); if (server_begin(&rng_seed, &ip)) { state = STATE_BEGINGAME; g.addOtherPlayer(100, 100, 0, ip); rngGame.seed(rng_seed); SDL_CreateThread(receive_packets, "Network", &g); } break; case STATE_BEGINGAME: if (mode == M_CLIENT) { //Client uint32_t rng_seed = time(NULL); g.addOtherPlayer(100, 100, 0, client_begin(menu.tmpip, rng_seed)); rngGame.seed(rng_seed); SDL_CreateThread(receive_packets, "Network", &g); } if (mode == M_SINGLEPLAYER) { rngGame.seed(time(NULL)); } g.rings.init(); state = STATE_GAMEPLAY;//don't break, continue directly to gameplay case STATE_GAMEPLAY: g.step(keyboard); g.draw(); if (g.rings.thisRing >= 20) { g.haveWon = g.haveWon || ((g.multiplayer && g.opponent_rings < 20) || !g.multiplayer); glColor3f(1.0f, .4f, .9f); if (g.haveWon) menu.draw_text(10, 10, "You won"); else menu.draw_text(10, 10, "You lost"); menu.draw_text(10, 110, "Time taken:"); menu.draw_text(10 + chrw * 11, 110, const_cast<char *>((std::to_string(g.timeFlying)).c_str())); menu.draw_text(10, 200, "Press Enter to return"); menu.draw_text(10, 300, "to menu"); if (keydown == SDL_SCANCODE_RETURN) { state = STATE_MENU; if (mode == M_CLIENT || mode == M_SERVER) server_stop(); } } else { glColor3f(0.0f, 1.0f, 0.0f); if (g.rings.thisRing >= 10) menu.draw_text(10, 10, const_cast<char *>((std::to_string(g.rings.thisRing)).c_str())); else menu.draw_text(10 + chrw, 10, const_cast<char *>((std::to_string(g.rings.thisRing)).c_str())); menu.draw_text(10 + 2 * chrw, 10, "/20"); glColor3f(1.0f, 0.0f, 0.0f); if (g.multiplayer) { if (g.opponent_rings >= 10) menu.draw_text(10, 30, const_cast<char *>((std::to_string(g.opponent_rings)).c_str())); else menu.draw_text(10 + chrw, 30, const_cast<char *>((std::to_string(g.opponent_rings)).c_str())); menu.draw_text(10 + 2 * chrw, 30, "/20"); } } break; } menu.drawGrid(); //Update screen SDL_GL_SwapWindow(gWindow); if (SDL_GetTicks() < endTime) { //Sleep the remaining frame time SDL_Delay(endTime-SDL_GetTicks()); } else { //std::cout << SDL_GetTicks()-endTime << "\n"; } } } } //Free resources and close SDL close(); return 0; }