void DynamicPartialLoudnessGM::loadParameterSet(ParameterSet set)
    {
        //common to all
        setTimeStep(0.001);
        setHpf(true);
        setDiffuseField(false);
        setGoertzel(false);
        setDiotic(true);
        setUniform(true);
        setInterpRoexBank(false);
        setFilterSpacing(0.25);
        setCompressionCriterion(0.0);
        setFastBank(false);
        setStereoToMono(true);

        switch(set){
            case GM02:
                break;
            case FASTER1:
                setFastBank(true);
                setInterpRoexBank(true);
                setCompressionCriterion(0.3);
                break;
            default:
                setFastBank(true);
                setCompressionCriterion(0.3);
        }
    }
    //sets species and periodic boundary
    AngledPeriodicBoundaryUnitTest()
    {
        LinearViscoelasticFrictionReversibleAdhesiveSpecies species;
        //set density such that mass is 1.0 for diameter 1.0 particles
        species.setDensity(6.0 / constants::pi);
        species.setStiffness(1e2);
        species.setAdhesionStiffness(1e2);
        //set such that the overlap for force balance is 10%
        species.setAdhesionForceMax(1e-1 * species.getAdhesionStiffness());
        species.setRollingFrictionCoefficient(1e20);
        species.setRollingStiffness(1.0);
        speciesHandler.copyAndAddObject(species);
        setTimeStep(1e-5);

        PeriodicBoundary b1;
        b1.set({0,1,0},0,4);
        //boundaryHandler.copyAndAddObject(b1);

        AngledPeriodicBoundary b;
        Mdouble c = cos(constants::pi/2.0);
        Mdouble s = sqrt(1.0-c*c);
        Vec3D normal_left(s,-c,0.0);
        Vec3D normal_right(0.0,-1.0,0.0);
        Vec3D origin(0.0,0.0,0.0);
        b.set(normal_left,normal_right,origin);
        //comment line below to see how the system behaves w/o AngledPeriodicBoundary
        boundaryHandler.copyAndAddObject(b);
    }
Esempio n. 3
0
void AWidget::timerEvent(QTimerEvent *)
{
    QElapsedTimer timer;
    timer.start();
    updateGL();
    setTimeStep(timer.elapsed()+15);
}
Esempio n. 4
0
Sim::Sim()
    : sim::Sim(), _arena(0)
{
#if ODE == 1
    DBG("Using ODE");
    sim::ode::World *w = new sim::ode::World();

    setWorld(w);

    w->setCFM(.0001);
    w->setERP(0.8);
    w->setStepType(sim::ode::World::STEP_TYPE_QUICK);
    w->setAutoDisable(0.01, 0.01, 5, 0.);

    w->setContactApprox1(true);
    w->setContactApprox2(true);
    w->setContactBounce(0.1, 0.1);
#else
    DBG("Using Bullet");
    sim::bullet::World *w = new sim::bullet::World();
    setWorld(w);
#endif

    setTimeStep(sim::Time::fromMs(5));
    setTimeSubSteps(2);

    pauseSimulation();
    setSimulateReal(false);

    _povray = 0;

    createArena();
    createRobots();
}
// TODO: Changes for turbulent simulation not implemented yet!
void TurbulentSimulation::solveTimestep(){

	// determine and set max. timestep which is allowed in this simulation
	setTimeStep();
	// compute fgh
	_turbulentFghIterator.iterate();
	// set global boundary values
	_wallFGHIterator.iterate();
	// compute the right hand side
	_rhsIterator.iterate();
	// solve for pressure
	_solver.solve();
	// TODO WS2: communicate pressure values
	_parallelManagerTurbulent.communicatePressure();
	// compute velocity
	_velocityIterator.iterate();
	// set obstacle boundaries
	_obstacleIterator.iterate();
	// TODO WS2: communicate velocity values
	_parallelManagerTurbulent.communicateVelocity();
	// Iterate for velocities on the boundary
	_wallVelocityIterator.iterate();

	_parallelManagerTurbulent.communicateCenterLineVelocity();
	_turbulentViscosityIterator.iterate();
	_parallelManagerTurbulent.communicateViscosity();
	_turbulentViscosityBoundaryIterator.iterate();
}
Esempio n. 6
0
ofxMSAPhysics::ofxMSAPhysics() {
	verbose = false;
	setTimeStep(0.000010);
	setDrag();
	setNumIterations();
	enableCollision();
	setGravity();
	clearWorldSize();
	
#ifdef MSAPHYSICS_USE_RECORDER
	_frameCounter = 0;
	setReplayMode(OFX_MSA_DATA_IDLE);
	setReplayFilename("recordedData/physics/physics");
#endif	
}
    void setupInitialConditions()
    {
        setParticleDimensions(2);
        setSystemDimensions(2);
        setXMin(-2.0);
        setXMax(2.0);
        setYMin(-2.0);
        setYMax(2.0);
        species->setDensity(6.0 / constants::pi);
        setGravity(Vec3D(0.0, 0.0, 0.0));
        species->setCollisionTimeAndRestitutionCoefficient(0.01, 1.0, 1.0);
        setTimeStep(0.0002);
        setTimeMax(1.0);
        setSaveCount(helpers::getSaveCountFromNumberOfSavesAndTimeMaxAndTimestep(20, getTimeMax(), getTimeStep()));

        p1f = particleHandler.copyAndAddObject(BaseParticle());
        p2f = particleHandler.copyAndAddObject(BaseParticle());
        p3f = particleHandler.copyAndAddObject(BaseParticle());
        p1e = particleHandler.copyAndAddObject(BaseParticle());
        p2e = particleHandler.copyAndAddObject(BaseParticle());
        p3e = particleHandler.copyAndAddObject(BaseParticle());
        triangle = wallHandler.copyAndAddObject(IntersectionOfWalls());
        std::vector<Vec3D> points={Vec3D(0.5,-std::sqrt(3)/6.0,0.0),Vec3D(0.0,std::sqrt(3)/3.0,0.0),Vec3D(-0.5,-std::sqrt(3)/6.0,0.0),Vec3D(0.5,-std::sqrt(3)/6.0,0.0)};
        triangle->createOpenPrism(points,Vec3D(0.0,0.0,1.0));
                        
        p1f->setRadius(0.1);
        p2f->setRadius(0.1);
        p3f->setRadius(0.1);      
        p1f->setPosition(Vec3D(-0.5, std::sqrt(3)/6.0,0.0));
        p2f->setPosition(Vec3D(-0.0,-std::sqrt(3)/3.0,0.0));
        p3f->setPosition(Vec3D( 0.5, std::sqrt(3)/6.0,0.0));
        p1f->setVelocity(Vec3D( 0.5,-std::sqrt(3)/6.0,0.0));
        p2f->setVelocity(Vec3D( 0.0, std::sqrt(3)/3.0,0.0));
        p3f->setVelocity(Vec3D(-0.5,-std::sqrt(3)/6.0,0.0));
        p1e->setRadius(0.1);
        p2e->setRadius(0.1);
        p3e->setRadius(0.1);      
        p1e->setPosition(1.5*Vec3D( 0.5,-std::sqrt(3)/6.0,0.0));
        p2e->setPosition(1.5*Vec3D( 0.0, std::sqrt(3)/3.0,0.0));
        p3e->setPosition(1.5*Vec3D(-0.5,-std::sqrt(3)/6.0,0.0));
        p1e->setVelocity(Vec3D(-0.5, std::sqrt(3)/6.0,0.0));
        p2e->setVelocity(Vec3D( 0.0,-std::sqrt(3)/3.0,0.0));
        p3e->setVelocity(Vec3D( 0.5, std::sqrt(3)/6.0,0.0));
	}
Esempio n. 8
0
	void setupInitialConditions()
	{
        relVelocity_ = 1e-1;
        setName("AdhesiveForceUnitTest_ParticleWallInteractionWithPlasticForces");

        setSystemDimensions(3);
		setParticleDimensions(3);
		setGravity(Vec3D(0,0,0));

        species->setDensity(2000.0);
        species->setStiffness(1e2);
	    species->setAdhesionStiffness(1e2);
	    species->setAdhesionForceMax(1e-5*species->getAdhesionStiffness());
	    Mdouble R = 1e-3;
        species->setSlidingStiffness(1.2e1);
        species->setSlidingFrictionCoefficient(0.01);
        setTimeStep(5e-6 / 2.0);
        
	    setXMax( 2*R);
		setYMax(   R);
		setZMax(   R);
		setXMin(0);
		setYMin(-R);
		setZMin(-R);
		
        particleHandler.clear();
		BaseParticle P;
		P.setRadius(R);
		P.setPosition(Vec3D(R+species->getInteractionDistance()*1/3,0,0));
		P.setVelocity(Vec3D(-relVelocity_/2,0,0));
		particleHandler.copyAndAddObject(P);
		
   		wallHandler.clear();
		InfiniteWall w;
		w.set(Vec3D(-1, 0, 0), Vec3D(getXMin(), 0, 0));
		wallHandler.copyAndAddObject(w);
     
		setTimeMax(getTimeStep()*250*4);
        setFileType(FileType::ONE_FILE);
		setSaveCount(1);
	}
Esempio n. 9
0
    void setupInitialConditions()
    {
        setParticleDimensions(3);
        setXMax(2);
        setYMax(2);
        setZMax(2);
        setSystemDimensions(3);
        species->setDensity(6.0 / constants::pi);
        setGravity(Vec3D(0.0, 0.0, 0.0));
        species->setCollisionTimeAndRestitutionCoefficient(0.01, 1.0, 1.0);
        setTimeStep(0.0002);
        setTimeMax(1.0);
        setSaveCount(helpers::getSaveCountFromNumberOfSavesAndTimeMaxAndTimestep(20, getTimeMax(), getTimeStep()));

        //set particles
        particle->setRadius(0.5);
        particle->setPosition(Vec3D(1.0, 1.0, 1.0));
        particle->setVelocity(Vec3D(0.0, 0.0, -1.0));

        //set walls
        wall->setNormal(Vec3D(0.0, 0.0, -1.0));

    }
 InputControlerSet::InputControlerSet(Kernel::Model* model)
 : Kernel::ControlerSet(model)
 {
   setTimeStep(0.02) ;
 }
Esempio n. 11
0
int main()
{
    int  dimension  = 3;
    auto resolution = Manta::Vec3i(128);

    if (dimension == 2) resolution.z = 1;

    auto main_solver = Manta::FluidSolver(resolution, dimension);
    main_solver.setTimeStep(0.5f);
    Real minParticles = pow(2, dimension);

    Real radiusFactor = 1.0f;

    // solver grids
    auto flags      = Manta::FlagGrid(&main_solver);
    auto phi        = Manta::LevelsetGrid(&main_solver);

    auto vel        = Manta::MACGrid(&main_solver);
    auto vel_old    = Manta::MACGrid(&main_solver);
    auto pressure   = Manta::Grid<Real>(&main_solver);
    auto tmp_vec3   = Manta::Grid<Manta::Vec3>(&main_solver);
    auto tstGrid    = Manta::Grid<Real>(&main_solver);

    // particles
    auto pp         = Manta::BasicParticleSystem(&main_solver);
    auto pVel       = Manta::PdataVec3(&pp);
    auto pTest      = Manta::PdataReal(&pp);
    auto mesh       = Manta::Mesh(&main_solver);

    // acceleration data for particle nbs
    auto pindex     = Manta::ParticleIndexSystem(&main_solver);
    auto gpi        = Manta::Grid<int>(&main_solver);

    int setup = 0;
    int boundaryWidth = 1;
    flags.initDomain(boundaryWidth);
    auto fluidVel = Manta::Sphere(&main_solver, Manta::Vec3(0.0f), 1.0f);
    Manta::Vec3 fluidSetVel;

    if (setup == 0)
    {
        // breakin dam
        auto fluidbox   = Manta::Box(&main_solver, Manta::Vec3::Invalid,
                                                   Manta::Vec3(0.0f, 0.0f, 0.0f),
                                                   Manta::Vec3(resolution.x * 0.4f, resolution.y * 0.6f, resolution.z * 0.1f));
        phi.copyFrom(fluidbox.computeLevelset());

    } else if (setup == 1)
    {
        // drop into box
        auto fluidbasin = Manta::Box(&main_solver, Manta::Vec3::Invalid,
                                                   Manta::Vec3(0.0f, 0.0f, 0.0f),
                                                   Manta::Vec3(resolution.x * 1.0f, resolution.y * 0.1f, resolution.z * 1.0f));
        auto dropCenter = Manta::Vec3(0.5f, 0.3f, 0.5f);
        Real dropRadius = 0.1f;
        auto fluidDrop  = Manta::Sphere(&main_solver, Manta::Vec3(resolution.x * dropCenter.x, resolution.y * dropCenter.y, resolution.z * dropCenter.z),
                                                      resolution.x * dropRadius);
        fluidVel        = Manta::Sphere(&main_solver, Manta::Vec3(resolution.x * dropCenter.x, resolution.y * dropCenter.y, resolution.z * dropCenter.z),
                                                      resolution.x * (dropRadius + 0.05f));
        fluidSetVel     = Manta::Vec3(0.0f, -1.0f, 0.0f);
        phi.copyFrom(fluidbasin.computeLevelset());
        phi.join(fluidDrop.computeLevelset());
    }

    flags.updateFromLevelset(phi);
    Manta::sampleLevelsetWithParticles(phi, flags, pp, 2, 0.05f);

    if (setup == 1)
    {
        fluidVel.applyToGrid(&vel, fluidSetVel);
        Manta::mapGridToPartsVec3(vel, pp, pVel);
    }

    Manta::testInitGridWithPos(tstGrid);
    pTest.setConst(0.1f);

    for (int t = 0; t < 250; t++)
    {
        // FLIP
        pp.advectInGrid(flags, vel, Manta::IntegrationMode::IntRK4, false);

        // make sure we have velocities throught liquid region
        Manta::mapParticlesToMAC(flags, vel, vel_old, pp, pVel, &tmp_vec3);
        Manta::extrapolateMACFromWeight(vel, tmp_vec3, 2);
        Manta::markFluidCells(pp, flags);

        // create approximate surface level set, resample particles
        Manta::gridParticleIndex(pp, pindex, flags, gpi);
        Manta::unionParticleLevelset(pp, pindex, flags, gpi, phi, radiusFactor);
        Manta::resetOutflow(flags, nullptr, &pp, nullptr, &gpi,&pindex);

	    // extend levelset somewhat, needed by particle resampling in adjustNumber
	    Manta::extrapolateLsSimple(phi, 4, true);

        // forces and pressure solve
        Manta::addGravity(flags, vel, Manta::Vec3(0.0f, -0.001f, 0.0f));
        Manta::setWallBcs(flags, vel);
        Manta::solvePressure(vel, pressure, flags, &phi);
        Manta::setWallBcs(flags, vel);

        // set source grids for resampling, used in adjustNumber!
        pVel.setSource(&vel, true);
        pTest.setSource(&tstGrid);
        Manta::adjustNumber(pp, vel, flags, 1 * minParticles, 2 * minParticles, phi, radiusFactor);

        // make sure we have proper velocities
        Manta::extrapolateMACSimple(flags, vel);
        Manta::flipVelocityUpdate(flags, vel, vel_old, pp, pVel, 0.97f);

        if (dimension == 3) phi.createMesh(mesh);

        main_solver.step();

    	// generate data directly and for flip03_gen.py surface generation scene
        std::stringstream filename1, filename2;
        filename1 << "simulation data\\flip02_surface\\fluidsurface_final_" << std::setw(4) << std::setfill('0') << t << ".bobj.gz";
        filename2 << "simulation data\\flip02_surface\\flipParts_"          << std::setw(4) << std::setfill('0') << t << ".uni";

        mesh.save(filename1.str());
        pp.save(filename2.str());
    }

}
Esempio n. 12
0
int main()
{
	GLFWwindow* window;
	
	if (!glfwInit()) 
	{
		printf("Error initializing GLFW\n");
		return -1;
	}
	
	glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, GL_VERSION_MAJOR);
	glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, GL_VERSION_MINOR);
	glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
	glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
	
	//glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
	
	glfwWindowHint(GLFW_SAMPLES, 8);
	
	window = glfwCreateWindow(1920, 1080, "Test Window", glfwGetPrimaryMonitor(), NULL);
	
	if (!window)
	{
		printf("Error creating GLFW window\n");
		glfwTerminate();
		return -1;
	}
	
	glfwMakeContextCurrent(window);
	
	glfwSetKeyCallback(window, key_callback);
	glfwSetMouseButtonCallback(window, mouse_button_callback);
	glfwSetCursorPosCallback(window, cursor_position_callback);
	glfwSetScrollCallback(window, scroll_callback);
	
	if (gl3wInit())
	{
		printf("Error initializing OpenGL\n");
		glfwTerminate();
		return -1;
	}
	
	printf("OpenGL %s GLSL %s\n", glGetString(GL_VERSION), glGetString(GL_SHADING_LANGUAGE_VERSION));
	
	if (!gl3wIsSupported(GL_VERSION_MAJOR, GL_VERSION_MINOR))
	{
		printf("OpenGL %i.%i is not supported\n", GL_VERSION_MAJOR, GL_VERSION_MINOR);
		glfwTerminate();
		return -1;
	}
	
	glViewport(0, 0, 1920, 1080);
	
	glEnable(GL_CULL_FACE);
	glEnable(GL_DEPTH_TEST);
	
	GLuint programID = loadShadersvf("shaders/simple.vsh", "shaders/simple.fsh");
	
	GLuint vao;
	glGenVertexArrays(1, &vao);
	glBindVertexArray(vao);
	
	
	GLuint vbo;
	glGenBuffers(1, &vbo);
	glBindBuffer(GL_ARRAY_BUFFER, vbo);
	//glBufferData(GL_ARRAY_BUFFER, sizeof(vertex_buffer_data), vertex_buffer_data, GL_STATIC_DRAW);
	glBufferData(GL_ARRAY_BUFFER, sizeof(sphere_model), sphere_model, GL_STATIC_DRAW);
	
	GLuint ibo;
	glGenBuffers(1, &ibo);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);
	glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(sphere_indices), sphere_indices, GL_STATIC_DRAW);
	//glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(index_buffer_data), index_buffer_data, GL_STATIC_DRAW);
	
	glEnableVertexAttribArray(0);
	glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);
	glDisableVertexAttribArray(0);
	
	glBindBuffer(GL_ARRAY_BUFFER, 0);
	glBindVertexArray(0);
	
	
	double timesteps[] = {1, 60, 60 * 60, 60 * 60 * 24, 60 * 60 * 24 * 7, 60 * 60 * 24 * 30, 60 * 60 * 24 * 365};
	int timestepCounter = 0;
	
	
	World world;
	world.num_functions = 0;
	//Add the functions for gravitational attraction to the world's object list, and have it execute when updateWorld() is called
	addFunction(&world, attract, COMPONENT_POSITION | COMPONENT_VELOCITY);
	addFunction(&world, move, COMPONENT_POSITION | COMPONENT_VELOCITY);
	
	unsigned int bodies[11];
	
	//Create all the planets with the correct masses, sizes, and velocities
	bodies[0] = createStar(&world, "Sun", 0, 0, 0, 0, 0, 0, 1.989 * pow(10, 30), 6.963 * pow(10,8), 1);
	
	bodies[1] = createPlanet(&world, "Mercury", -0.35790 * AU, -0.04240 * AU, -0.11618 * AU,
		-0.00000004 * AU, 0.00000003 * AU, 0.00000031 * AU, 3.285 * pow(10,23), 2.44 * pow(10,6), 0.4549, 0.4509, 0.4705);
	
	bodies[2] = createPlanet(&world, "Venus", -0.46075 * AU, -0.03422 * AU, -0.56289 * AU,
		-0.00000017 * AU, -0.00000001 * AU, 0.00000014 * AU, 4.867 * pow(10, 24), 6.052 * pow(10,6), 0.4627, 0.568, 0.380);
	
	bodies[3] = createPlanet(&world, "Earth", 0.99542 * AU, 0, 0.01938 * AU,
		0.00000001 * AU, 0, -0.00000019 * AU, 5.972 * pow(10, 24), 6.371 * pow(10,6), 0, 0.4, 0.6);
	
	bodies[4] = createPlanet(&world, "Moon", 0.99708 * AU, -0.00016 * AU, 0.02141 * AU,
		0.00000001 * AU + 722.66, 0, -0.00000019 * AU - 722.66, 7.348 * pow(10, 22), 1.737 * pow(10,6), 0.4, 0.4, 0.4);
	
	bodies[5] = createPlanet(&world, "Mars", 1.38763 * AU, 0.01755 * AU, -0.79510 * AU,
		-0.00000009 * AU, -0.00000001 * AU, -0.00000013 * AU, 6.39 * pow(10, 23), 3.39 * pow(10,6), 0.8157, 0.5294, 0.3922);
	
	bodies[6] = createPlanet(&world, "Jupiter", 5.32462 * AU, 0.11488 * AU, 1.04223 * AU,
		0.00000002 * AU, 0, -0.00000008 * AU, 1.898 * pow(10,27), 69.911 * pow(10,6), 0.8824, 0.7961, 0.7412);
	
	bodies[7] = createPlanet(&world, "Saturn", 3.30063 * AU, 0.29595 * AU, -9.47771 * AU,
		-0.00000006 * AU, 0, -0.00000002 * AU, 5.683 * pow(10,26), 58.232 * pow(10,6), 0.7843, 0.6392, 0.4314);
	
	bodies[8] = createPlanet(&world, "Uranus", -18.76415 * AU, -0.21783 * AU, 6.83528 * AU,
		0.00000002 * AU, 0, 0.00000004 * AU, 8.681 * pow(10,25), 25.362 * pow(10,6), 0.8314, 0.9804, 0.9922);
	
	bodies[9] = createPlanet(&world, "Neptune", -28.07048 * AU, -0.42924 * AU, -10.42730 * AU,
		-0.00000002 * AU, 0, 0.0000003 * AU, 1.024 * pow(10,26), 24.622 * pow(10,6), 0.2, 0.2902, 0.7451);
	
	bodies[10] = createPlanet(&world, "Pluto", -8.88081 * AU, 0.86973 * AU, -31.76914 * AU,
		-0.00000003 * AU, -0.00000001 * AU, 0.0000001 / 41.0 * AU, 1.309 * pow(10,22), 1.186 * pow(10, 6), 0.7137, 0.6824, 0.6314);
	
	
	double mat4d_projection[4][4] = MATRIX_IDENTITY_4;
	mat4dProjection(M_PI / 2.0, 16.0/9.0, pow(10,6), pow(10,13), mat4d_projection);
	
	
	unsigned int parent = 3;
	
	Camera camera;
	makeCamera(&camera, 0, 0, pow(10, 9), &world, bodies[parent]);
	
	double mat4d_camera[4][4] = MATRIX_IDENTITY_4;
	float mat4_camera[4][4];

	
	
	double sensitivity = 0.005;
	
	printf("Starting main loop\n");
	
	while (!glfwWindowShouldClose(window))
	{
		clearInput();
		glfwPollEvents();
		
		//rotate or zoom out the camera depending on camera movement and scrolling
		double dx, dy, dz;
		getMouseDelta(&dx, &dy, &dz);
		updateCamera(&camera, dx * sensitivity, dy * sensitivity, dz);
		
		if (getClicked())
		{
			if(++parent > 10) parent = 0;
			changeCameraParent(&camera, pow(10, 9), &world, bodies[parent]);
		}
		
		timestepCounter += getTimeStepChange();
		if (timestepCounter > 6) timestepCounter = 0;
		else if (timestepCounter < 0) timestepCounter = 6;
		setTimeStep(timesteps[timestepCounter]);
		
		//get the time since the last frame to do proper delta-timing for the gravitational attraction and movement
		double delta = timeTick();
		updateWorld(&world, delta);
		
		getCameraMatrix(&camera, mat4d_camera);
		
		double modelView[4][4];
		mat4dMlt(mat4d_projection, mat4d_camera, modelView);
		
		
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
		
		glUseProgram(programID);
		
		glBindVertexArray(vao);
		glEnableVertexAttribArray(0);
		
		//For each of the objects in the world, loop through them and render them if they have a position and radius,
		//rendering works by rendering the same sphere over and over, with a different translation and scale
		//because all objects in this program are spheres
		for (int i = 0; i < WORLD_MAX_ENTITIES; ++i)
		{
			if (isEntity(&world, i, COMPONENT_POSITION | COMPONENT_RADIUS))
			{
				/*double pos[4] = {world.position[i].position[0], world.position[i].position[1], world.position[i].position[2], 1};
				vec4dMltMat(mat4d_camera, pos, pos);
				double distance = vec3dLength(pos);
				printf("%i: %f\n", i, distance);
				
				double mat4d_model[4][4] = MATRIX_IDENTITY_4;
				
				double radius = world.radius[i].radius;
				
				double scaleFactor = distance * (1 / pow(radius,2));
				printf("Scale factor: %f\n", scaleFactor);
				
				if (scaleFactor > pow(10,-3))
				{
					printf("Has been scaled\n");
					radius = radius / scaleFactor;
				}
				printf("Radius: %f\n", radius);*/
				
				double mat4d_model[4][4] = MATRIX_IDENTITY_4;
				
				double radius = world.radius[i].radius;
				
				double scale[3] = {radius, radius, radius};
				mat4dGenScale(scale, mat4d_model);
				mat4dTranslate(world.position[i].position, mat4d_model);
				
				double modelViewProjection[4][4];
				mat4dMlt(modelView, mat4d_model, modelViewProjection);
				
				float modelViewProjectionf[4][4];
				doubleToSingle(modelViewProjection[0], modelViewProjectionf[0], 16);
				
				double color[3] = {1,1,1};
				
				if (isEntity(&world, i, COMPONENT_COLOR))
				{
					vec3dSetEqual(world.color[i].color, color);
				}
				
				float colorf[3];
				doubleToSingle(color, colorf, 3);
				
				GLint colorLoc = glGetUniformLocation(programID, "in_color");
				glUniform3fv(colorLoc, 1, colorf);
				
				GLint mvpLoc = glGetUniformLocation(programID, "mvp");
				glUniformMatrix4fv(mvpLoc, 1, GL_FALSE, modelViewProjectionf[0]);
				
				glDrawElements(GL_TRIANGLES, sphere_num_indices, GL_UNSIGNED_INT, 0);
			}
		}
		
		glDisableVertexAttribArray(0);
		
		glBindVertexArray(0);
		
		
		glfwSwapBuffers(window);
	}
	
	glfwDestroyWindow(window);
	glfwTerminate();
	return 0;
}
Esempio n. 13
0
void Sequencer::touch(double nexttimestep){
    touch();
    setTimeStep(nexttimestep);
}
Esempio n. 14
0
void Simulation::configure(const config::Configuration& config)
{
    // Resize world
    {
        auto size = config.get<SizeVector>("world-size");

        if (size.getWidth() == Zero || size.getHeight() == Zero)
            throw config::Exception("Width or height is zero!");

        setWorldSize(size);
    }

    // Time step
    setTimeStep(config.get<units::Time>("dt"));

    if (config.has("length-coefficient"))
    {
        m_converter.setLengthCoefficient(config.get<RealType>("length-coefficient"));
    }

    // Set gravity
    setGravity(config.get("gravity", getGravity()));

    // Number of iterations
    setIterations(config.get("iterations", getIterations()));

    // Background color
    setBackgroundColor(config.get("background", getBackgroundColor()));

#if CONFIG_RENDER_TEXT_ENABLE
    setFontColor(config.get("text-color", getBackgroundColor().inverted()));
#endif

#if CONFIG_RENDER_TEXT_ENABLE
    setFontSize(config.get("text-size", getFontSize()));
#endif

#if CONFIG_RENDER_TEXT_ENABLE
    setSimulationTimeRender(config.get("show-simulation-time", isSimulationTimeRender()));
#endif

#ifdef CECE_ENABLE_RENDER
    setVisualized(config.get("visualized", isVisualized()));
#endif

    // Parse plugins
    for (auto&& pluginConfig : config.getConfigurations("plugin"))
    {
        // Returns valid pointer or throws an exception
        requirePlugin(pluginConfig.get("name"))->configure(*this, pluginConfig);
    }

    // Parse parameters
    for (auto&& parameterConfig : config.getConfigurations("parameter"))
    {
        setParameter(parameterConfig.get("name"), units::parse(parameterConfig.get("value")));
    }

    // Register user types
    for (auto&& typeConfig : config.getConfigurations("type"))
    {
        addObjectType({
            typeConfig.get("name"),
            typeConfig.get("base"),
            typeConfig.toMemory()
        });
    }

    // Parse init
    for (auto&& initConfig : config.getConfigurations("init"))
    {
        const String typeName = initConfig.has("language")
            ? initConfig.get("language")
            : initConfig.get("type");

        auto initializer = getPluginContext().createInitializer(typeName);

        if (initializer)
        {
            // Configure initializer
            initializer->loadConfig(*this, initConfig);

            // Register initializer
            addInitializer(std::move(initializer));
        }
    }

    // Parse modules
    for (auto&& moduleConfig : config.getConfigurations("module"))
    {
        // Get name
        auto name = moduleConfig.get("name");

        if (hasModule(name))
            continue;

        const String typeName = moduleConfig.has("language")
            ? moduleConfig.get("language")
            : moduleConfig.has("type")
                ? moduleConfig.get("type")
                : name
        ;

        auto module = getPluginContext().createModule(typeName, *this);

        if (module)
        {
            module->loadConfig(*this, moduleConfig);

            addModule(std::move(name), std::move(module));
        }
    }

    // Parse programs
    for (auto&& programConfig : config.getConfigurations("program"))
    {
        const String typeName = programConfig.has("language")
            ? programConfig.get("language")
            : programConfig.get("type");

        auto program = getPluginContext().createProgram(typeName);

        if (program)
        {
            // Configure program
            program->loadConfig(*this, programConfig);

            // Register program
            addProgram(programConfig.get("name"), std::move(program));
        }
    }

    // Parse objects
    for (auto&& objectConfig : config.getConfigurations("object"))
    {
        // Create object
        auto object = buildObject(
            objectConfig.get("class"),
            objectConfig.get("type", object::Object::Type::Dynamic)
        );

        if (object)
            object->configure(objectConfig, *this);
    }

    if (config.has("data-out-objects-filename"))
    {
        m_dataOutObjects = makeUnique<OutFileStream>(config.get("data-out-objects-filename"));
        *m_dataOutObjects << "iteration;totalTime;id;typeName;posX;posY;velX;velY\n";
    }
}
    void setupInitialConditions()
    {
        auto species = speciesHandler.copyAndAddObject(LinearViscoelasticFrictionSpecies());
        species->setDensity(constants::pi / 6.0);

        double stiffness = 1e5;
        setParticleDimensions(2);
        species->setDensity(2500);
        species->setStiffness(stiffness);
        species->setSlidingStiffness(2.0 / 7.0 * stiffness);
	species->setSlidingFrictionCoefficient(0.5);
        species->setRollingStiffness(2.0 / 5.0 * stiffness);
        species->setRollingFrictionCoefficient(0.5);
        species->setTorsionStiffness(2.0 / 5.0 * stiffness);
        species->setTorsionFrictionCoefficient(0.5);

        setGravity(Vec3D(0.0, 0.0, 0.0));
        setTimeMax(8e-2);
        setTimeStep(2.0e-4);
        setFileType(FileType::NO_FILE);

        setXMin(0.0);
        setYMin(0.0);
        setXMax(1.0);
        setYMax(1.0);

        PeriodicBoundary b0;
        b0.set(Vec3D(1, 0, 0), getXMin(), getXMax());
        boundaryHandler.copyAndAddObject(b0);
        b0.set(Vec3D(0, 1, 0), getYMin(), getYMax());
        boundaryHandler.copyAndAddObject(b0);

        BaseParticle P0, P1, P2, P3, P4, P5, P6, P7;

        //Particle to be removed
        P0.setPosition(Vec3D(0.1, 0.1, 0.0));
        P1.setPosition(Vec3D(0.3, 0.3, 0.0));
        //Contacts starts normal becomes periodic
        P2.setPosition(Vec3D(0.6, 0.041, 0.0));
        P2.setAngularVelocity(Vec3D(0.3, 0.6, 0.9));
        P3.setPosition(Vec3D(0.4, 0.001, 0.0));
        //Normal case
        P4.setPosition(Vec3D(0.6, 0.82, 0.0));
        P4.setAngularVelocity(Vec3D(0.3, 0.6, 0.9));
        P5.setPosition(Vec3D(0.4, 0.78, 0.0));
        //Contact starts periodic becomes normal and periodic again
        P6.setPosition(Vec3D(0.02, 0.42, 0.0));
        P6.setAngularVelocity(Vec3D(0.3, 0.6, 0.9));
        P7.setPosition(Vec3D(0.82, 0.38, 0.0));

        P0.setVelocity(Vec3D(0.0, 0.0, 0.0));
        P1.setVelocity(Vec3D(0.0, 0.0, 0.0));
        P2.setVelocity(Vec3D(-1.0, 0.0, 0.0));
        P3.setVelocity(Vec3D(1.0, 0.0, 0.0));
        P4.setVelocity(Vec3D(-1.0, 0.0, 0.0));
        P5.setVelocity(Vec3D(1.0, 0.0, 0.0));
        P6.setVelocity(Vec3D(-1.0, 0.0, 0.0));
        P7.setVelocity(Vec3D(1.0, 0.0, 0.0));

        P0.setRadius(0.1);
        P1.setRadius(0.1);
        P2.setRadius(0.1);
        P3.setRadius(0.1);
        P4.setRadius(0.1);
        P5.setRadius(0.1);
        P6.setRadius(0.1);
        P7.setRadius(0.1);

        particleHandler.copyAndAddObject(P0);
        particleHandler.copyAndAddObject(P1);
        particleHandler.copyAndAddObject(P2);
        particleHandler.copyAndAddObject(P3);
        particleHandler.copyAndAddObject(P4);
        particleHandler.copyAndAddObject(P5);
        particleHandler.copyAndAddObject(P6);
        particleHandler.copyAndAddObject(P7);
    }
Esempio n. 16
0
bool TimeSeriesMotion::load(const QString &fileName, bool defaults, double scale)
{
    m_accel.clear();

    setFileName(fileName);
    const QString ext = m_fileName.right(3).toUpper();

    // Load the file
    QFile file(m_fileName);
    if (!file.open( QIODevice::ReadOnly | QIODevice::Text )) {
        qWarning() << "Unable to open the time series file:" << qPrintable(m_fileName);
        return false;
    }
    QTextStream stream(&file);

    if (defaults) {
        if (ext == "AT2") {
            // Set format
            setFormat(Rows);
            setStartLine(5);
            setStopLine(0);
            setScale(scale);

            // Read in the header information
            Q_UNUSED(stream.readLine());

            setDescription(stream.readLine());

            Q_UNUSED(stream.readLine());

            QStringList parts = stream.readLine().split(QRegExp("\\s+"));

            bool b;
            const int count = parts.at(0).toInt(&b);
            if (b && count > 1) {
                // Greater than one condition to catch if an acceleration value is read
                setPointCount(count);
            } else {
                qCritical() << "Unable to parse the point count in AT2 file!";
                return false;
            }

            const double timeStep = parts.at(1).toDouble(&b);

            if (b) {
                setTimeStep(timeStep);
            } else {
                qCritical() << "Unable to parse the time step in AT2 file!";
                return false;
            }
        } else {
            // Unknown file format can't process with default settings
            return false;
        }
    } else {
        // Check the input
        if (m_timeStep <= 0) {
            qCritical("Time step must be greater than one");
            return false;
        }
        if (m_startLine < 0) {
            qCritical("Number of header lines must be positive");
            return false;
        }
    }

    // Move back to the start of the stream
    stream.seek(0);

    int lineNum = 1;
    // Skip the header lines
    while (lineNum < m_startLine) {
        Q_UNUSED(stream.readLine());
        ++lineNum;
    }

    // Initialize the length of m_accel
    m_accel.resize(m_pointCount);

    // Process each of the lines
    int index = 0;
    // Read the first line
    QString line =stream.readLine();

    bool finished = false;
    bool stopLineReached = false;

    // Modify the scale for unit conversion
    scale = unitConversionFactor() * m_scale;

    while (!finished && !line.isNull()) {
        // Stop if line exceeds number of lines.  The line number has
        // to be increased by one because the user display starts at
        // line number 1 instead of 0
        if (m_stopLine > 0 &&  m_stopLine <= lineNum+1) {
            stopLineReached = true;
            break;
        }

        // Read the line and split the line
        QRegExp rx("(-?\\d*\\.\\d+(?:[eE][+-]?\\d+)?)");
        int pos = 0;
        QStringList row;

        while ((pos = rx.indexIn(line, pos)) != -1) {
            row << rx.cap(1);
            pos += rx.matchedLength();
        }

        // Process the row based on the format
        bool ok;
        switch (m_format) {
        case Rows:
            // Use all parts of the data
            for(int i = 0; i < row.size(); ++i) {
                if ( index == m_pointCount ) {
                    qWarning("Point count reached before end of data!");
                    finished = true;
                    break;
                }
                // Apply the scale factor and read the acceleration
                m_accel[index] = scale * row.at(i).trimmed().toDouble(&ok);
                // Increment the index
                ++index;
                // Stop if there was an error in the conversion
                if (!ok) {
                    continue;
                }
            }
            break;
                case Columns:
            // Use only the important column, however at the end of the
            // file that column may not exist -- this only happens when the
            // row format is applied, but it still causes the program to
            // crash.
            if ( m_dataColumn - 1 < row.size() ) {
                m_accel[index] = scale * row.at(m_dataColumn-1).trimmed().toDouble(&ok);
            }

            // Increment the index
            ++index;
            break;
        }

        // Throw an error if there was a problem
        if (!ok) {
            qCritical() << "Error converting string to double in line: \n\""
                    << qPrintable(line) << "\"\nCheck starting line.";
            return false;
        }

        // Read the next line
        ++lineNum;
        line = stream.readLine();
    }

    if (m_pointCount != index) {
        if (stopLineReached) {
            qWarning() << "Number of points limited by stop line.";
        } else {
            qCritical() << "Number of points read does not equal specified point count!";
            return false;
        }
    }

    // Compute motion properties
    calculate();

    setIsLoaded(true);
    return true;
}