Esempio n. 1
0
	bool View::traceWorld(int x, int y, Vector3& result, int part) {
		if (selectRegion(Rect(x-1, y-1, 3, 3), part, result)) {
			return true;
		}

		Plane ground(0, 0, 1, 0);
		Vector3 start = m_camera.screenToWorld(Vector3(x, y, -1));
		Vector3 end = m_camera.screenToWorld(Vector3(x, y, 1));
		Vector3 dir = (end - start).getNormalized();
		float scale;

		bool v = ground.rayIntersection(start, dir, scale);

		if (!v)
			return false;

		result = start + dir * scale;

		if (m_context->getState()->isSnapToGrid) {
			result = Internal::snap(result, m_context->getState()->snapToGrid);
		}

		m_context->getState()->setTransformState(false, false, result);

		return true;
	}
//--------------------------------------------------------------------------------------------------
/// Close interface (for now, no files are kept open after calling methods, so just clear members)
//--------------------------------------------------------------------------------------------------
void RifReaderEclipseOutput::close()
{
    m_ecl_file     = NULL;
    m_dynamicResultsAccess    = NULL;

    ground();
}
sf::Sprite ObjectStyle::createGround(OffsetCoords position, int texture_id)
{
	PixelCoords position_px = hex_style.toPixel(position);
	sf::Sprite ground(impTileset.getTileset(), impTileset.getTile(texture_id));
	scaleToken(ground);
	float temp = (hex_style.horizontalSize() - miscTileset.getTileSize().x * ground.getScale().x) * 0.5;
	ground.setPosition(sf::Vector2f((float)position_px.x + temp, (float)position_px.y));
	return ground;
}
Esempio n. 4
0
int main() 
{
	int v = 3;
	deep( data, s, v );

	printf("\n.................,,,,,,,,\n");

	ground( data, s , v );
	printf("\n.................,,,,,,,,\n");
}
Esempio n. 5
0
MBoundingBox ProxyViz::boundingBox() const
{   
	BoundingBox bbox = plantExample(0)->geomBox();
	if(numPlants() > 0) bbox = gridBoundingBox();
	else if(!isGroundEmpty() ) bbox = ground()->getBBox();
	
	MPoint corner1(bbox.m_data[0], bbox.m_data[1], bbox.m_data[2]);
	MPoint corner2(bbox.m_data[3], bbox.m_data[4], bbox.m_data[5]);

	return MBoundingBox( corner1, corner2 );
}
void Segmentation::doSegmentation(pcl::PointCloud<pcl::PointXYZRGBA>::Ptr &cloud)
{
    //MainPlane groundMainPlane;
    // Variables
    isComputed = false ;
    struct timeval tbegin,tend;
    double texec=0.0;

    // Start timer
    gettimeofday(&tbegin,NULL);

    pcl::PointCloud<pcl::PointXYZRGBA>::Ptr cloudFiltered(new pcl::PointCloud<pcl::PointXYZRGBA>);
    //pcl::PointCloud<pcl::PointXYZRGBA>::Ptr cloudFilteredCopy(new pcl::PointCloud<pcl::PointXYZRGBA>);
    _mainCloud.reset(new pcl::PointCloud<pcl::PointXYZRGBA>);
    (void) passthroughFilter(-5.0, 5.0, -5.0, 5.0, -5.0, 5.0, cloud, cloudFiltered); // 3.0, 3.0, -0.2, 2.0, -4.0, 4.0
    pcl::copyPointCloud(*cloudFiltered, *_mainCloud);

    pcl::PointCloud<pcl::PointXYZRGBA>::Ptr ground (new pcl::PointCloud<pcl::PointXYZRGBA>);
    pcl::PointCloud<pcl::PointXYZRGBA>::Ptr Hullground (new pcl::PointCloud<pcl::PointXYZRGBA>);

    std::vector<pcl::PointIndices> vectorInliers(0);
    std::vector <pcl::ModelCoefficients> vectorCoeff(0);
    std::vector < pcl::PointCloud<pcl::PointXYZRGBA>::Ptr > vectorCloudinliers(0);
    std::vector < pcl::PointCloud<pcl::PointXYZRGBA>::Ptr > vectorHull(0);
    std::vector < pcl::PointCloud<pcl::PointXYZRGBA>::Ptr > vectorCluster(0);

    pcl::ModelCoefficients::Ptr coefficientsGround (new pcl::ModelCoefficients);
    pcl::PointIndices::Ptr inliersGround (new pcl::PointIndices);

    //    pcl::VoxelGrid< pcl::PointXYZRGBA > sor;
    //    sor.setInputCloud (_mainCloud);
    //    sor.setLeafSize (0.01f, 0.01f, 0.01f);
    //    sor.filter (*_mainCloud);
    //(void) findGround(_mainCloud,_ground);
    //isComputed = true;
    if(findGround(_mainCloud,_ground))
    {
        Eigen::Vector3f gravityVector(_ground.getCoefficients()->values[0], _ground.getCoefficients()->values[1], _ground.getCoefficients()->values[2]);

        //(void) findOtherPlanesRansac(_mainCloud,gravityVector,vectorCoeff , vectorCloudinliers,vectorHull);

        //(void) regionGrowing(vectorCloudinliers, vectorCluster);
        euclidianClustering(_mainCloud,vectorCloudinliers);
        ransac(vectorCloudinliers,gravityVector,vectorCluster );
        createPlane(vectorCluster);
        // End timer
    }

    gettimeofday(&tend,NULL);
    // Compute execution time
    texec = ((double)(1000*(tend.tv_sec-tbegin.tv_sec)+((tend.tv_usec-tbegin.tv_usec)/1000)))/1000;
    std::cout << "time : " << texec << std::endl;
}
Esempio n. 7
0
DrawingState::DrawingState()
{
  // reasonable defaults for everything
  timeOfDay = 9;				// morning
  sky(.7f,.7f,1);					// blue sky
  ground(0,84,24);				// green grass
  camera = 0;
  fieldOfView = 45;
  backCull = 0;
  drGrTex = 0;
  counter = 0;
}
Esempio n. 8
0
cv::Mat Bridge::createImgMap(const boost::numeric::ublas::matrix<STATE> &groundMap) {
    cv::Mat ground(groundMap.size1(), groundMap.size2(), CV_8UC3, cv::Scalar(0, 0, 0));
    for (unsigned int i = 0; i < groundMap.size1(); ++i) {
        for (unsigned int j = 0; j < groundMap.size2(); ++j) {
            if (groundMap(i, j) == 0) {
                ground.at<cv::Vec3b>(i, j) = cv::Vec3b(0, 0, 0);
            } else {
                ground.at<cv::Vec3b>(i, j) = cv::Vec3b(255, 255, 255);
            }
        }
    }
    return ground;
}
Esempio n. 9
0
// We are going to override (is that the right word?) the draw()
// method of ModelerView to draw out RobotArm
void RobotArm::draw()
{
	/* pick up the slider values */

	float theta = VAL( BASE_ROTATION );
	float phi = VAL( LOWER_TILT );
	float psi = VAL( UPPER_TILT );
	float cr = VAL( CLAW_ROTATION );
	float h1 = VAL( BASE_LENGTH );
	float h2 = VAL( LOWER_LENGTH );
	float h3 = VAL( UPPER_LENGTH );
	float pc = VAL( PARTICLE_COUNT );


    // This call takes care of a lot of the nasty projection 
    // matrix stuff
	ModelerView::draw();
	static GLfloat lmodel_ambient[] = { 0.4, 0.4, 0.4, 1.0 };
	Mat4f temp = getModelViewMatrix();

	// define the model

	ground(-0.2);
	
	if (true) {
		Ariou();
	} else {
		base(0.8);

	    glTranslatef( 0.0, 0.8, 0.0 );			// move to the top of the base
	    glRotatef( theta, 0.0, 1.0, 0.0 );		// turn the whole assembly around the y-axis. 
		rotation_base(h1);						// draw the rotation base

	    glTranslatef( 0.0, h1, 0.0 );			// move to the top of the base
	    glRotatef( phi, 0.0, 0.0, 1.0 );		// rotate around the z-axis for the lower arm
		glTranslatef( -0.1, 0.0, 0.4 );
		lower_arm(h2);							// draw the lower arm

	    glTranslatef( 0.0, h2, 0.0 );			// move to the top of the lower arm
	    glRotatef( psi, 0.0, 0.0, 1.0 );		// rotate  around z-axis for the upper arm
		upper_arm(h3);							// draw the upper arm

		glTranslatef( 0.0, h3, 0.0 );
		glRotatef(cr, 0.0, 0.0, 1.0);
		claw(1.0);
		SpawnParticles(temp);
	}

	//*** DON'T FORGET TO PUT THIS IN YOUR OWN CODE **/
	endDraw();
}
Esempio n. 10
0
void cView::draw()
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
    glLoadIdentity();

    glPushMatrix();
        useShader(shader);
        object();
    glPopMatrix();

    glPushMatrix();
        useShader(shader_ground);
        ground();
    glPopMatrix();
}
Esempio n. 11
0
	static std::pair<AbstractGroundTheory*, StructureExtender*> createGroundingAndExtender(AbstractTheory* theory, Structure* structure,
			Vocabulary* outputvocabulary, Term* term, TraceMonitor* tracemonitor, bool nbModelsEquivalent, GroundingReceiver* solver) {
		if (theory == NULL || structure == NULL) {
			throw IdpException("Unexpected NULL-pointer.");
		}
		auto t = dynamic_cast<Theory*>(theory); // TODO handle other cases
		if (t == NULL) {
			throw notyetimplemented("Grounding of already ground theories");
		}
		if (t->vocabulary() != structure->vocabulary()) {
			throw IdpException("Grounding requires that the theory and structure range over the same vocabulary.");
		}
		auto m = new GroundingInference(t, structure, outputvocabulary, term, tracemonitor, nbModelsEquivalent, solver);
		auto grounding = m->ground();
		auto result = std::pair<AbstractGroundTheory*, StructureExtender*>{grounding, m->getManager()};
		delete(m);
		return result;
	}
Esempio n. 12
0
static int
can_share(Word p ARG_LD)
{
again:
  switch(tag(*p))
  { case TAG_VAR:
    case TAG_ATTVAR:
      return FALSE;
    case TAG_REFERENCE:
      p = unRef(*p);
      goto again;
    case TAG_COMPOUND:
    { Functor t = valueTerm(*p);
      return ground(t->definition);
    }
    default:
      return TRUE;
  }
}
Esempio n. 13
0
Body Collision::create_ground_body(PhysicsWorld &phys_world)
{
	PhysicsContext pc = phys_world.get_pc();
	BodyDescription ground_desc(phys_world);
	ground_desc.set_position(Vec2f((float)window_x_size/2.0f,(float)window_y_size));
	ground_desc.set_type(body_static);

	Body ground(pc, ground_desc);

	//Setup ground fixture
	PolygonShape ground_shape(phys_world);
	ground_shape.set_as_box((float)window_x_size/2,20.0f);

	FixtureDescription fixture_desc(phys_world);
	fixture_desc.set_shape(ground_shape);
	fixture_desc.set_friction(1.0f);
	fixture_desc.set_density(1000.0f);

	Fixture ground_fixture(pc, ground, fixture_desc);
	return ground;
}
Esempio n. 14
0
// We are going to override (is that the right word?) the draw()
// method of ModelerView to draw out RobotArm
void RobotArm::draw()
{
    /* pick up the slider values */
    float theta = baseRotation.getValue();
    float phi = lowerTilt.getValue();
    float psi = upperTilt.getValue();
    float cr = clawRotation.getValue();
    float h1 = baseLength.getValue();
    float h2 = lowerLength.getValue();
    float h3 = upperLength.getValue();




    static GLfloat lmodel_ambient[] = {0.4,0.4,0.4,1.0};

    // define the model

    ground(-0.2);

    base(0.8);

    glTranslatef( 0.0, 0.8, 0.0 );			// move to the top of the base
    glRotatef( theta, 0.0, 1.0, 0.0 );		// turn the whole assembly around the y-axis.
    rotation_base(h1);						// draw the rotation base

    glTranslatef( 0.0, h1, 0.0 );			// move to the top of the base
    glRotatef( phi, 0.0, 0.0, 1.0 );		// rotate around the z-axis for the lower arm
    glTranslatef( -0.1, 0.0, 0.4 );
    lower_arm(h2);							// draw the lower arm

    glTranslatef( 0.0, h2, 0.0 );			// move to the top of the lower arm
    glRotatef( psi, 0.0, 0.0, 1.0 );		// rotate  around z-axis for the upper arm
    upper_arm(h3);							// draw the upper arm

    glTranslatef( 0.0, h3, 0.0 );
    glRotatef( cr, 0.0, 0.0, 1.0 );
    claw(1.0);

}
Esempio n. 15
0
void	LibOpenGL::draw_background()
{
  Pave 	ground(0, 0, 0, 64, 64, 64, _tex["stone"]);
  Pave 	wall(0, 0, 0, 64, 64, 64, _tex["wood"]);
  Pave 	body2(0, 0, 0, 8, 32, 16, _tex["body2"]);

  glTranslated(-_x*320, -_y*320, 0);
  _tex["grass"]["top"].load();
  glBegin(GL_QUADS);
  glTexCoord2d(0, 0);
  glVertex3d(0, 0, 0);
  glTexCoord2d(_x*5, 0);
  glVertex3d(_x*640, 0, 0);
  glTexCoord2d(_x*5, _y*5);
  glVertex3d(_x*640, _y*640,0);
  glTexCoord2d(0, _y*5);
  glVertex3d(0, _y*640,0);
  glEnd();
  glTranslated(_x*320, _y*320, 0);
  for(int i = 0; i < _y+2; ++i)
  {
    for(int j = 0; j < _x+2; ++j)
    {
     ground.setpos(j*64, i*64, 0);
     ground.draw();
      if (j == 0 || i == 0)
      {
        wall.setpos(j*64, i*64, 64);
        wall.draw();
      }
      else if (j == (_x + 1) || i == (_y + 1))
      {
        wall.setpos(j*64, i*64, 64);
        wall.draw();
      }
    }
  }
}
Esempio n. 16
0
// The start of the Application
int Raycasting::start(const std::vector<std::string> &args)
{
	//Remove the need to send physic world to every object. Instead send just the description.

	//Fix having two fixtures working weirdly.
	quit = false;

	int window_x_size = 640;
	int window_y_size = 480;
	// Set the window
	DisplayWindowDescription desc;
	desc.set_title("ClanLib Raycasting Example");
	desc.set_size(Size(window_x_size, window_y_size), true);
	desc.set_allow_resize(false);

	DisplayWindow window(desc);
	
	// Connect the Window close event
	Slot slot_quit = window.sig_window_close().connect(this, &Raycasting::on_window_close);

	// Connect a keyboard handler to on_key_up()
	Slot slot_input_up = (window.get_ic().get_keyboard()).sig_key_up().connect(this, &Raycasting::on_input_up);

	// Create the canvas
	Canvas canvas(window);

	//Setup physic world
	PhysicsWorldDescription phys_desc;
	phys_desc.set_gravity(0.0f,10.0f);
	phys_desc.set_sleep(true);
	phys_desc.set_physic_scale(100);
	phys_desc.set_timestep(1.0f/200.0f);

	PhysicsWorld phys_world(phys_desc);

	//Get the Physics Context
	PhysicsContext pc = phys_world.get_pc();

	//Setup ground body
	BodyDescription ground_desc(phys_world);
	ground_desc.set_position(Vec2f((float)window_x_size/2.0f,(float)window_y_size));
	ground_desc.set_type(body_static);

	Body ground(pc, ground_desc);
	//Setup ground fixture
	PolygonShape ground_shape(phys_world);
	ground_shape.set_as_box((float)window_x_size/2,20.0f);

	FixtureDescription fixture_desc(phys_world);
	fixture_desc.set_shape(ground_shape);
	
	Fixture ground_fixture(pc, ground, fixture_desc);

	//Setup box body
	BodyDescription box_desc(phys_world);
	box_desc.set_position(Vec2f(10.0f,10.0f));
	box_desc.set_type(body_dynamic);
	box_desc.set_linear_velocity(Vec2f(100.0f,0.0f));
	Body box(pc, box_desc);

	box_desc.set_position(Vec2f((float)window_x_size-50.0f,100.0f));
	box_desc.set_linear_velocity(Vec2f(-80.0f,0.0f));
	Body box2(pc, box_desc);

	//Setup box fixture
	PolygonShape box_shape(phys_world);
	box_shape.set_as_box(30.0f, 30.0f);

	FixtureDescription fixture_desc2(phys_world);
	fixture_desc2.set_shape(box_shape);
	fixture_desc2.set_restitution(0.6f);
	fixture_desc2.set_friction(0.0005f);

	Fixture box_fixture(pc, box, fixture_desc2);
	Fixture box_fixture2(pc, box2, fixture_desc2);

	Vec2f ground_pos = ground.get_position();

	unsigned int last_time = System::get_time();
	
	//Setup debug draw.
	PhysicsDebugDraw debug_draw(phys_world);
	debug_draw.set_flags(f_shape|f_aabb);

	GraphicContext gc = canvas.get_gc();
	PhysicsQueryAssistant qa = phys_world.get_qa();

	clan::Font font(canvas, "Tahoma", 12);

	// Set raycast points
	Pointf p1(300,500);
	Pointf p2(100,100);

	// Set query rect;
	Rectf rect1(400.0f, 380.0f, Sizef(50.0f,50.0f));

	// Run until someone presses escape
	while (!quit)
	{
		unsigned int current_time = System::get_time();
		float time_delta_ms = static_cast<float> (current_time - last_time);
		last_time = current_time;

		canvas.clear();
		
		//Raycast
		
		font.draw_text(canvas, 10,20, "Raycasting...");
		
		qa.raycast_first(p1, p2);
		if(qa.has_query_result())
		{
			font.draw_text(canvas, 100,20, "Found object !");
			canvas.draw_line(p1,p2, Colorf::green);
		}
		else canvas.draw_line(p1, p2, Colorf::red);
		
		//Raycast

		//Query
		
		font.draw_text(canvas, 10,35, "Querying...");

		qa.query_any(rect1);

		if(qa.has_query_result())
		{
			font.draw_text(canvas, 100,35, "Found object !");
			canvas.draw_box(rect1, Colorf::green);

		}
		else canvas.draw_box(rect1, Colorf::red);
		//Query

		phys_world.step();
		debug_draw.draw(canvas);
		
		canvas.flush();
		window.flip(1);

		// This call processes user input and other events
		KeepAlive::process(0);

		System::sleep(10);
	}

	return 0;
}
Esempio n. 17
0
int main(int argc, char *argv[]){
	//Initialise GLFW
	if (!glfwInit()) {
		fprintf(stderr, "There was a problem initializing glfw");
		exit(EXIT_FAILURE);
	}

	//glfw hints
	glfwOpenWindowHint(GLFW_FSAA_SAMPLES, 4);
	glfwOpenWindowHint(GLFW_OPENGL_VERSION_MAJOR, 3);
	glfwOpenWindowHint(GLFW_OPENGL_VERSION_MINOR, 3);
	glfwOpenWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

	//Open a window
	if (!glfwOpenWindow(WINDOW_WIDTH, WINDOW_HEIGHT, 0, 0, 0, 0, 0, 0, GLFW_WINDOW)) {
		fprintf(stderr, "There was a problem opening a window");
		exit(EXIT_FAILURE);
	}

	//Turn on experimental features to prevent seg fault
	glewExperimental = GL_TRUE;

	//Intitialize GLEW
	if (glewInit() != GLEW_OK) {
		fprintf(stderr, "There was a problem initialising GLEW");
		exit(EXIT_FAILURE);
	}

	//various glfw settings
	glfwEnable(GLFW_STICKY_KEYS);
	glfwSetKeyCallback(&key_callback);
	glfwSetWindowTitle(TITLE);	
	glEnable(GL_CULL_FACE);
	glCullFace(GL_BACK);
	glEnable(GL_DEPTH_TEST);
	glEnable(GL_DEPTH_CLAMP);

	//Create text generator
	GLuint textShaderID = setupShaders("shaders/text/vert.gls", "shaders/text/frag.gls");
	TextGenerator tg((char*)"textures/font.png", textShaderID, ' ', '~', 16, 8, WINDOW_WIDTH, WINDOW_HEIGHT);
	loading(&tg);

	//Load in and set program (Shaders)
	// GLuint simpleShaderID = setupShaders("shaders/simple/vert.gls", "shaders/simple/frag.gls");
	// GLuint phongShaderID = setupShaders("shaders/phong/vert.gls", "shaders/phong/frag.gls");
	GLuint perFragmentShaderID = setupShaders("shaders/perFragment/vert.gls", "shaders/perFragment/frag.gls");

	//Load in terrain and sky box
	HeightMapLoader groundObj = HeightMapLoader("textures", "img2.png");
	ObjLoader skyboxObj = ObjLoader("models","skybox.obj");

	Object ground(&groundObj, perFragmentShaderID, viewer, GL_FILL);
	Skybox skybox(&skyboxObj, perFragmentShaderID, viewer, GL_FILL);
	loading(&tg);

	//Load in thunder birds
	ObjLoader thunderBird1Obj = ObjLoader("models", "thunderbird1.obj");
	ObjLoader t2ContainerObj = ObjLoader("models","t2container.obj");
	ObjLoader thunderBird2Obj = ObjLoader("models","thunderbird2.obj");
	ObjLoader thunderBird3Obj = ObjLoader("models","thunderbird3.obj");
	ObjLoader eggObj = ObjLoader("models", "egg.obj");

	Object thunderBird1(&thunderBird1Obj, perFragmentShaderID, viewer, GL_FILL);
	Object thunderBird1B(&thunderBird1Obj, perFragmentShaderID, viewer, GL_FILL);
	Object thunderBird1C(&thunderBird1Obj, perFragmentShaderID, viewer, GL_FILL);

	Object t2container(&t2ContainerObj, perFragmentShaderID, viewer, GL_FILL);
	Object thunderBird2(&thunderBird2Obj, perFragmentShaderID, viewer, GL_FILL);
	Object t2containerB(&t2ContainerObj, perFragmentShaderID, viewer, GL_FILL);
	Object thunderBird2B(&thunderBird2Obj, perFragmentShaderID, viewer, GL_FILL);

	Object thunderBird3(&thunderBird3Obj, perFragmentShaderID, viewer, GL_FILL);
	Object thunderBird3B(&thunderBird3Obj, perFragmentShaderID, viewer, GL_FILL);
	Object thunderBird3C(&thunderBird3Obj, perFragmentShaderID, viewer, GL_FILL);
	loading(&tg);

	//Set up collisions
	viewer->addTerrain(&ground);

	loading(&tg);

	thunderBird1.setPosition(glm::vec3(-2,0.1,0));

	t2container.setPosition(glm::vec3(-7.5,0.15,5));
	t2container.setScale(glm::vec3(0.2,0.2,0.2));
	t2container.setRotation(90, glm::vec3(0,1,0));

	thunderBird2.setPosition(glm::vec3(-7.5,0.15,5));
	thunderBird2.setScale(glm::vec3(0.2,0.2,0.2));
	thunderBird2.setRotation(90, glm::vec3(0,1,0));

	t2containerB.setPosition(glm::vec3(-13.7941, 0.0, -11.716));
	t2containerB.setScale(glm::vec3(0.2,0.2,0.2));
	t2containerB.setRotation(120, glm::vec3(0,1,0));

	thunderBird2B.setPosition(glm::vec3(-13.7941, 0.0, -11.716));
	thunderBird2B.setScale(glm::vec3(0.2,0.2,0.2));
	thunderBird2B.setRotation(120, glm::vec3(0,1,0));


	thunderBird3.setPosition(glm::vec3(2,2,12.5));
	thunderBird3.setScale(glm::vec3(0.4,0.4,0.4));
	thunderBird3.setRotation(-90, glm::vec3(1,0,0));

	thunderBird3B.setPosition(glm::vec3(22.3989, 0.541667, -5.00961));
	thunderBird3B.setScale(glm::vec3(0.4,0.4,0.4));
	thunderBird3B.setRotation(-90, glm::vec3(1,0,0));

	thunderBird3B.setPosition(glm::vec3(2,2,12.5));
	thunderBird3B.setScale(glm::vec3(0.4,0.4,0.4));
	thunderBird3B.setRotation(-90, glm::vec3(1,0,0));


	ground.setScale(glm::vec3(0.35,0.025,0.35));
	ground.setPosition(glm::vec3(-groundObj.width/2 * 0.35,0,-groundObj.height/2 * 0.35));

	std::vector<glm::vec3> positions;

	positions.push_back(glm::vec3(-6.42059,0.25837,4.494014));
	positions.push_back(glm::vec3(-3.85007,0.1,7.12377));
	positions.push_back(glm::vec3(-0.601204,0.1,3.592329));
	positions.push_back(glm::vec3(8.2538,0.1,2.5428));
	positions.push_back(glm::vec3(10.6809,0.38337,-3.84069));
	positions.push_back(glm::vec3(-5.13897,0.1,-11.4451));
	positions.push_back(glm::vec3(-14.3374,0.1,-8.11471));
	positions.push_back(glm::vec3(-20.2777, 0.1, 8.26625));
	positions.push_back(glm::vec3(-22.3929, 1.35833,19.6362));
	positions.push_back(glm::vec3(1.64004, 0.1, 33.6688));
	positions.push_back(glm::vec3(30.9513, 0.683333, 18.214));
	positions.push_back(glm::vec3(32.9145, 1.56667, -11.0445));
	positions.push_back(glm::vec3(31.17666, 0.808333, -22.8479));
	positions.push_back(glm::vec3(-29.7966, 0.35, -27.9126));
	positions.push_back(glm::vec3(-33.6018, 0.433333, -25.1177));
	positions.push_back(glm::vec3(-29.1175, 2.39167, -17.2737));
	positions.push_back(glm::vec3(-27.6434, 2.1833, -14.5711));
	positions.push_back(glm::vec3(-33.0654, 3.5, 2.62864));
	positions.push_back(glm::vec3(-20.6909, 4, 3.49496));
	positions.push_back(glm::vec3(-3.85007, 3.5 , 7.12377));
	positions.push_back(glm::vec3(1.42417, 2.116667, 0.276567));



	WayPoint w1 = WayPoint(positions[0], positions[1] - positions[0]);
	WayPoint w2 = WayPoint(positions[1], positions[2] - positions[1]);
	WayPoint w3 = WayPoint(positions[2], positions[3] - positions[2]);
	WayPoint w4 = WayPoint(positions[3], positions[4] - positions[3]);
	WayPoint w5 = WayPoint(positions[4], positions[5] - positions[4]);
	WayPoint w6 = WayPoint(positions[5], positions[6] - positions[5]);
	WayPoint w7 = WayPoint(positions[6], positions[7] - positions[6]);
	WayPoint w8 = WayPoint(positions[7], positions[8] - positions[7]);
	WayPoint w9 = WayPoint(positions[8], positions[9] - positions[8]);
	WayPoint w10 = WayPoint(positions[9], positions[10] - positions[9]);
	WayPoint w11 = WayPoint(positions[10], positions[11] - positions[10]);
	WayPoint w12 = WayPoint(positions[11], positions[12] - positions[11]);
	WayPoint w13 = WayPoint(positions[12], positions[13] - positions[12]);
	WayPoint w14 = WayPoint(positions[13], positions[14] - positions[13]);
	WayPoint w15 = WayPoint(positions[14], positions[15] - positions[14]);
	WayPoint w16 = WayPoint(positions[15], positions[16] - positions[15]);
	WayPoint w17 = WayPoint(positions[16], positions[17] - positions[16]);
	WayPoint w18 = WayPoint(positions[17], positions[18] - positions[17]);
	WayPoint w19 = WayPoint(positions[18], positions[19] - positions[18]);
	WayPoint w20 = WayPoint(positions[19], positions[20] - positions[19]);
	WayPoint w21 = WayPoint(positions[20], glm::vec3(0,0,1));

	t.addWayPoint(0.0, &w1, 1);
	t.addWayPoint(2.0, &w2, 1);
	t.addWayPoint(4.0, &w3, 1);
	t.addWayPoint(6.0, &w4, 1);
	t.addWayPoint(8.0, &w5, 1);
	t.addWayPoint(10.0, &w6, 1);
	t.addWayPoint(12.0, &w7, 1);
	t.addWayPoint(14.0, &w8, 1);
	t.addWayPoint(16.0, &w9, 1);
	t.addWayPoint(18.0, &w10, 1);
	t.addWayPoint(20.0, &w11, 1);
	t.addWayPoint(22.0, &w12, 1);
	t.addWayPoint(24.0, &w13, 1);
	t.addWayPoint(26.0, &w14, 1);
	t.addWayPoint(28.0, &w15, 1);
	t.addWayPoint(30.0, &w16, 1);
	t.addWayPoint(32.0, &w17, 1);
	t.addWayPoint(34.0, &w18, 1);
	t.addWayPoint(36.0, &w19, 1);
	t.addWayPoint(38.0, &w20, 1);
	t.addWayPoint(40.0, &w21, 1);

	Animutator* tb1Anim = new Animutator();

	KeyFrame tb1KF1 = KeyFrame(glm::vec3(0,1,1), 90, glm::vec3(0,1,0), glm::vec3(0.5,0.5,0.5));
	KeyFrame tb1KF2 = KeyFrame(glm::vec3(10,1,1), 90, glm::vec3(0,1,0), glm::vec3(0.5,0.5,0.5));
	KeyFrame tb1KF3 = KeyFrame(glm::vec3(10,1,1), -90, glm::vec3(0,1,0), glm::vec3(0.5,0.5,0.5)); 
	KeyFrame tb1KF4 = KeyFrame(glm::vec3(0,1,1), -90, glm::vec3(0,1,0), glm::vec3(0.5,0.5,0.5));

	tb1Anim->addKeyFrame(0.0, &tb1KF1);
	tb1Anim->addKeyFrame(10.0, &tb1KF2);
	tb1Anim->addKeyFrame(12.5, &tb1KF3);
	tb1Anim->addKeyFrame(22.5, &tb1KF4);
	tb1Anim->addKeyFrame(25.0, &tb1KF1);

	thunderBird1.addAnimutator(tb1Anim);


	Animutator* tb1BAnim = new Animutator();

	KeyFrame tb1BKF1 = KeyFrame(glm::vec3(-23.027, 1.35, 16.35409), -110.328, glm::vec3(0,1,0), glm::vec3(0.5,0.5,0.5));
	KeyFrame tb1BKF2 = KeyFrame(glm::vec3(-24.5907, 2.29167, 15.7748), -110.328, glm::vec3(0,1,0), glm::vec3(0.5,0.5,0.5));
	KeyFrame tb1BKF3 = KeyFrame(glm::vec3(-24.5907, 2.29167, 15.7748), -38.604, glm::vec3(0,1,0), glm::vec3(0.5,0.5,0.5));
	KeyFrame tb1BKF4 = KeyFrame(glm::vec3(-32.497, 1, 25.6773), -38.604, glm::vec3(0,1,0), glm::vec3(0.5,0.5,0.5)); 
	KeyFrame tb1BKF5 = KeyFrame(glm::vec3(-32.497, 1, 25.6773), 5.98309, glm::vec3(0,1,0), glm::vec3(0.5,0.5,0.5)); 
	KeyFrame tb1BKF6 = KeyFrame(glm::vec3(-31.8602, 1.55833, 31.7533), 5.98309, glm::vec3(0,1,0), glm::vec3(0.5,0.5,0.5));
	KeyFrame tb1BKF7 = KeyFrame(glm::vec3(-31.8602, 1.55833, 31.7533), 38.384, glm::vec3(0,1,0), glm::vec3(0.5,0.5,0.5));
	KeyFrame tb1BKF8 = KeyFrame(glm::vec3(-28.5349, 1, 35.9512), 38.384, glm::vec3(0,1,0), glm::vec3(0.5,0.5,0.5));
	KeyFrame tb1BKF9 = KeyFrame(glm::vec3(-28.5349, 1, 35.9512), 99.0798, glm::vec3(0,1,0), glm::vec3(0.5,0.5,0.5));
	KeyFrame tb1BKF10 = KeyFrame(glm::vec3(-13.2714, 1, 33.5119), 99.0798, glm::vec3(0,1,0), glm::vec3(0.5,0.5,0.5));
	KeyFrame tb1BKF11 = KeyFrame(glm::vec3(-13.2714, 1, 33.5119), -150.378, glm::vec3(0,1,0), glm::vec3(0.5,0.5,0.5));
	KeyFrame tb1BKF12 = KeyFrame(glm::vec3(-23.027, 1.35, 16.35409), -150.378, glm::vec3(0,1,0), glm::vec3(0.5,0.5,0.5));

	tb1BAnim->addKeyFrame(0.0, &tb1BKF1);
	tb1BAnim->addKeyFrame(5.0, &tb1BKF2);
	tb1BAnim->addKeyFrame(5.5, &tb1BKF3);
	tb1BAnim->addKeyFrame(10.5, &tb1BKF4);
	tb1BAnim->addKeyFrame(11.0, &tb1BKF5);
	tb1BAnim->addKeyFrame(16.0, &tb1BKF6);
	tb1BAnim->addKeyFrame(16.5, &tb1BKF7);
	tb1BAnim->addKeyFrame(21.5, &tb1BKF8);
	tb1BAnim->addKeyFrame(22.0, &tb1BKF9);
	tb1BAnim->addKeyFrame(27.0, &tb1BKF10);
	tb1BAnim->addKeyFrame(27.5, &tb1BKF11);
	tb1BAnim->addKeyFrame(32.5, &tb1BKF12);
	tb1BAnim->addKeyFrame(33.0, &tb1BKF1);

	thunderBird1B.addAnimutator(tb1BAnim);

	Animutator* tb1CAnim = new Animutator();

	KeyFrame tb1CKF1 = KeyFrame(glm::vec3(25.7527, 1.5, -29.4807), -77.7031, glm::vec3(0,1,0), glm::vec3(0.5,0.5,0.5));
	KeyFrame tb1CKF2 = KeyFrame(glm::vec3(-24.549, 2.76667, -18.516), -77.7031, glm::vec3(0,1,0), glm::vec3(0.5,0.5,0.5));
	KeyFrame tb1CKF3 = KeyFrame(glm::vec3(-24.549, 2.76667, -18.516), 102.297, glm::vec3(0,1,0), glm::vec3(0.5,0.5,0.5)); 
	KeyFrame tb1CKF4 = KeyFrame(glm::vec3(25.7527, 1.5, -29.4807), 102.297, glm::vec3(0,1,0), glm::vec3(0.5,0.5,0.5));

	tb1CAnim->addKeyFrame(0.0, &tb1CKF1);
	tb1CAnim->addKeyFrame(7.5, &tb1CKF2);
	tb1CAnim->addKeyFrame(9, &tb1CKF3);
	tb1CAnim->addKeyFrame(16.5, &tb1CKF4);
	tb1CAnim->addKeyFrame(18, &tb1CKF1);

	thunderBird1C.addAnimutator(tb1CAnim);


	Animutator* tb2cAnim = new Animutator();

	KeyFrame tbc2KF1 = KeyFrame(glm::vec3(-7.5, 0.15, 5), 90, glm::vec3(0,1,0), glm::vec3(0.2,0.2,0.2));
	KeyFrame tbc2KF2 = KeyFrame(glm::vec3(-7.5, -0.3, 5), 90, glm::vec3(0,1,0), glm::vec3(0.2,0.2,0.2));

	tb2cAnim->addKeyFrame(0.0, &tbc2KF1);
	tb2cAnim->addKeyFrame(5.0, &tbc2KF2);
	tb2cAnim->addKeyFrame(5.5, &tbc2KF2);
	tb2cAnim->addKeyFrame(10.0, &tbc2KF1);
	tb2cAnim->addKeyFrame(10.5, &tbc2KF1);

	t2container.addAnimutator(tb2cAnim);

	Animutator* tb2cBAnim = new Animutator();

	KeyFrame tbc2BKF1 = KeyFrame(glm::vec3(-13.7941, 0.0, -11.716), 120, glm::vec3(0,1,0), glm::vec3(0.2,0.2,0.2));
	KeyFrame tbc2BKF2 = KeyFrame(glm::vec3(-13.7941, -0.4, -11.716), 120, glm::vec3(0,1,0), glm::vec3(0.2,0.2,0.2));

	tb2cBAnim->addKeyFrame(0.0, &tbc2BKF1);
	tb2cBAnim->addKeyFrame(5.0, &tbc2BKF2);
	tb2cBAnim->addKeyFrame(5.5, &tbc2BKF2);
	tb2cBAnim->addKeyFrame(10.0, &tbc2BKF1);
	tb2cBAnim->addKeyFrame(10.5, &tbc2BKF1);

	t2containerB.addAnimutator(tb2cBAnim);


	Animutator* tb3cAnim = new Animutator();
	KeyFrame tb3KF1 = KeyFrame(glm::vec3(2, 1.90, 12.5), -90, glm::vec3(1,0,0), glm::vec3(0.4,0.4,0.4));
	KeyFrame tb3KF2 = KeyFrame(glm::vec3(2, 4, 12.5), -90, glm::vec3(1,0,0), glm::vec3(0.4,0.4,0.4));

	tb3cAnim->addKeyFrame(0.0, &tb3KF1);
	tb3cAnim->addKeyFrame(5.0, &tb3KF2);
	tb3cAnim->addKeyFrame(10.0, &tb3KF1);

	thunderBird3.addAnimutator(tb3cAnim);

	Animutator* tb3BcAnim = new Animutator();
	KeyFrame tb3BKF1 = KeyFrame(glm::vec3(22.3989, 2, -5.00961), -90, glm::vec3(1,0,0), glm::vec3(0.4,0.4,0.4));
	KeyFrame tb3BKF2 = KeyFrame(glm::vec3(22.3989, 4.5, -5.00961), -90, glm::vec3(1,0,0), glm::vec3(0.4,0.4,0.4));

	tb3BcAnim->addKeyFrame(0.0, &tb3BKF1);
	tb3BcAnim->addKeyFrame(5.0, &tb3BKF2);
	tb3BcAnim->addKeyFrame(10.0, &tb3BKF1);

	thunderBird3B.addAnimutator(tb3BcAnim);

	Animutator* tb3CcAnim = new Animutator();
	KeyFrame tb3CKF1 = KeyFrame(glm::vec3(-30.3314, 1.9, 2.7756), -90, glm::vec3(1,0,0), glm::vec3(0.4,0.4,0.4));
	KeyFrame tb3CKF2 = KeyFrame(glm::vec3(-30.3314, 4.6, 2.7756), -90, glm::vec3(1,0,0), glm::vec3(0.4,0.4,0.4));

	tb3CcAnim->addKeyFrame(0.0, &tb3CKF1);
	tb3CcAnim->addKeyFrame(5.0, &tb3CKF2);
	tb3CcAnim->addKeyFrame(10.0, &tb3CKF1);

	thunderBird3C.addAnimutator(tb3CcAnim);

	int frame_count = 0;
	int last_fps = 0; 
	GLfloat lastTime = glfwGetTime();

	loading(&tg);

	do {
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);

		if(tour){
			t.update();
		} else {
			viewer->update();
		}

		thunderBird1.draw();
		thunderBird1B.draw();
		thunderBird1C.draw();

		thunderBird2.draw();
		t2container.draw();
		thunderBird2B.draw();
		t2containerB.draw();

		thunderBird3.draw();
		thunderBird3B.draw();
		thunderBird3C.draw();

		ground.draw();
		skybox.draw();

		if(glfwGetTime() - lastTime < 1) {
			frame_count++;
		} else {
			lastTime = glfwGetTime();
			last_fps = frame_count;
			frame_count = 0;
		}

		if(show_help){
			showHelp(tg, last_fps);
		}

		glfwSwapBuffers();
	} while ( (glfwGetKey(GLFW_KEY_ESC) != GLFW_PRESS) && 
			(glfwGetKey('q') != GLFW_PRESS) &&
			(glfwGetKey('Q') != GLFW_PRESS) &&
			(glfwGetWindowParam( GLFW_OPENED )) );

	glfwTerminate();

	//Everything was okay, return success
	exit(EXIT_SUCCESS);
}
Esempio n. 18
0
int main(int argc, char *argv[])
{
    (void) argc;
    (void) argv;

    //SDL is used for inputs and time
    SDL_Init(SDL_INIT_VIDEO);
    atexit(SDL_Quit);
    SDL_EnableKeyRepeat(10, 10);


    Graph *graph=new Graph_SDL();
    graph->init();
    //create vox obj
    std::vector<VoxImg*> walk_anim;
    walk_anim.push_back(new VoxImg("data/perso_stand.vox",VOX_FILE));
    walk_anim.push_back(new VoxImg("data/perso_walk1.vox",VOX_FILE));
    walk_anim.push_back(new VoxImg("data/perso_walk2.vox",VOX_FILE));
    walk_anim.push_back(new VoxImg("data/perso_walk1.vox",VOX_FILE));
    walk_anim.push_back(new VoxImg("data/perso_stand.vox",VOX_FILE));
    walk_anim.push_back(new VoxImg("data/perso_walk3.vox",VOX_FILE));
    walk_anim.push_back(new VoxImg("data/perso_walk4.vox",VOX_FILE));
    walk_anim.push_back(new VoxImg("data/perso_walk3.vox",VOX_FILE));
    float anim_index=0;

    VoxImg img_palet("data/palet2.vox",VOX_FILE);
    Vox_Scene scene(160,120,70,img_palet);
    Vox_Scene ground(160,120,70,img_palet);
    VoxSpr perso(walk_anim.at(anim_index));
    VoxSpr palet(&img_palet);
    ground.init();

    Draw_Vox_Ortho *draw=new Draw_Vox_Ortho(graph,&scene);//maybe create a generic class for otho or perspective
    new Particle_Manager(&scene,&ground);

    //----- events -----
    SDL_Event event;

    //----- timing -----
    Uint32 last_time = SDL_GetTicks();
    Uint32 current_time,ellapsed_time,start_time;
    Uint32 previous_fps_time=SDL_GetTicks()/1000;
    int fps=0;


    double angleZ = 0;
    double angleY = 0;
    double angleX = 0;

    Pt3d pos(10,10,10);

    Pt3d ball(10,10,1);
    double ball_r=4;

    Pt3d ball_v(1,1,1);


    bool run=true;
    double t=0.0;
    while (run)
    {
        fps++;

        start_time = SDL_GetTicks();
        while (SDL_PollEvent(&event))
        {

            switch(event.type)
            {
            case SDL_QUIT:
                exit(0);
                break;

            case SDL_KEYDOWN:
                switch(event.key.keysym.sym)
                {
                case SDLK_ESCAPE:
                    run=false;
                    break;
                case SDLK_UP:
                    pos.x-=pseudo_normalize(draw->vect_vox_x_c.z,graph->ORTHO_ZOOM);
                    pos.y-=pseudo_normalize(draw->vect_vox_y_c.z,graph->ORTHO_ZOOM);
                    anim_index+=0.5;
                    break;
                case SDLK_DOWN:
                    pos.x+=pseudo_normalize(draw->vect_vox_x_c.z,graph->ORTHO_ZOOM);
                    pos.y+=pseudo_normalize(draw->vect_vox_y_c.z,graph->ORTHO_ZOOM);
                    anim_index+=0.5;
                    break;
                case SDLK_RIGHT:
                    pos.x+=pseudo_normalize(draw->vect_vox_x_c.x,graph->ORTHO_ZOOM);
                    pos.y+=pseudo_normalize(draw->vect_vox_y_c.x,graph->ORTHO_ZOOM);
                    anim_index+=0.5;
                    break;
                case SDLK_LEFT:
                    pos.x-=pseudo_normalize(draw->vect_vox_x_c.x,graph->ORTHO_ZOOM);
                    pos.y-=pseudo_normalize(draw->vect_vox_y_c.x,graph->ORTHO_ZOOM);
                    anim_index+=0.5;
                    break;
                case SDLK_q:
                    pos.x-=pseudo_normalize(draw->vect_vox_x_c.y,graph->ORTHO_ZOOM);
                    pos.y-=pseudo_normalize(draw->vect_vox_y_c.y,graph->ORTHO_ZOOM);
                    anim_index+=0.5;
                    break;
                case SDLK_w:
                    pos.x+=pseudo_normalize(draw->vect_vox_x_c.y,graph->ORTHO_ZOOM);
                    pos.y+=pseudo_normalize(draw->vect_vox_y_c.y,graph->ORTHO_ZOOM);
                    anim_index+=0.5;
                    break;
                default:
                    break;
                }
                break;

            case SDL_MOUSEMOTION:
                angleZ -= event.motion.xrel*0.01;
                angleX += event.motion.yrel*0.01;
                break;

            case SDL_MOUSEBUTTONDOWN:
                if ((event.button.button == SDL_BUTTON_WHEELUP)&&(event.button.type == SDL_MOUSEBUTTONDOWN))
                {
                }
                if ((event.button.button == SDL_BUTTON_WHEELDOWN)&&(event.button.type == SDL_MOUSEBUTTONDOWN))
                {
                }
                break;

            }
        }

        for (int i=0; i<10; i++)
        {
            Pt3d snow(rand()%scene.xsiz,rand()%scene.ysiz,0);
            Pt3d snow_speed(0,0,1);
            /*if (int(t*20)%10==0)*/ Particle_Manager::the_one->add_particle(31,snow,snow_speed,0);
        }
        Particle_Manager::the_one->update();
        ground.sub(palet);
        if (anim_index>=walk_anim.size()) anim_index=0;
        if (anim_index<0) anim_index=walk_anim.size()-0.01;
        perso.set_img(walk_anim.at((int)anim_index));
        perso.set_pos(pos);
        palet.set_pos(ball);
        scene.reinit(ground);//have to reinit scene AFTER modifications (add, sub, particle update), and JUST before blit!
        Particle_Manager::the_one->blit_all();
        scene.blit(perso);
        scene.blit(palet);

        //angleZ += 0.00020 * ellapsed_time;
        //angleY += 0.00023 * ellapsed_time;
        //angleX += 0.00027 * ellapsed_time;
        t+=0.05;

        ball.add(ball_v,&ball);
        if (ball.x>=scene.xsiz-ball_r-1) ball_v.x*=-1;
        if (ball.y>=scene.ysiz-ball_r-1) ball_v.y*=-1;
        if (ball.z>=scene.zsiz-1) ball_v.z*=-1;
        if (ball.x<=ball_r) ball_v.x*=-1;
        if (ball.y<=ball_r) ball_v.y*=-1;
        if (ball.z<=0) ball_v.z*=-1;
        if (ground.collide(palet) && (ball_v.z>0)) ball_v.z*=-1;

        if (!ground.touch_bottom(perso)) pos.z+=1;
        else if (ground.collide(perso)) pos.z-=1;
        /*else
        {
            //if (obj1.pos.z<scene.zsiz)
            {
                obj1.pos.z+=1;
                if (!ground.collide(perso)) pos.z+=1;
                obj1.pos.z-=1;
            }
        }*/

        //drawing
        draw->update_camera(100,100,0,angleX,angleY,angleZ);
        draw->render();


        //----- timing -----
        if (previous_fps_time!=current_time/1000)
        {
            std::cout<<"FPS: "<<fps<<std::endl;
            previous_fps_time=current_time/1000;
            fps=0;
        }
        current_time = SDL_GetTicks();
        ellapsed_time = current_time - last_time;
        last_time = current_time;
        ellapsed_time = SDL_GetTicks() - start_time;
        //if (ellapsed_time < 20)
        //    SDL_Delay(20 - ellapsed_time);
        //----- end timing -----
    }


    return 0;
}
Esempio n. 19
0
/* Focntion de dessin */
void DrawGLScene()
{
// Effacement du buffer de couleur et de profondeur
  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);		
  glLoadIdentity();		

// Paramètrage de l'éclairage
  glLightfv(GL_LIGHT0,GL_DIFFUSE,light_diffuse);
  glLightfv(GL_LIGHT0,GL_POSITION,light_position);


//////////////////////////////////////////////////
// camera

//  gluLookAt(0.0,5.0,30.0,0.0,5.0,0.0,0.0,1.0,0.0); // premère partie : robot seul

  gluLookAt(cam_pos_x,10.0,cam_pos_z,cam_look_x,5.0,cam_look_z,0.0,1.0,0.0); 

//////////////////////////////////////////////////
// Compilation des listes

  Make_CallListes();

//////////////////////////////////////////////////
// sol  

  glPushMatrix();
  ground();
  glPopMatrix();


//////////////////////////////////////////////////
// Bras articulé

	
/*Mettre les degré de liberté au fur et a mesure des objets*/
/*
// base
glTranslatef(base_x,0.0,base_z);
glRotatef(base_rot,0.0,1.0,0.0);
glCallList(OBJET_3);




// segment 1
float first_y = 0.25*5.5;
glTranslatef(0.0,first_y,0.0);
glRotatef(first_x,1.0,0.0,0.0);
glRotatef(first_z,0.0,0.0,1.0);
glCallList(OBJET_4);
glCallList(OBJET_1);

// segment2
float second_y = 0.6*8.0;
glTranslatef(0.0,second_y,0.0);
glRotatef(second_x,1.0,0.0,0.0);
glRotatef(second_z,0.0,0.0,1.0);
glCallList(OBJET_4);
glCallList(OBJET_1);


// segment 3	
glTranslatef(0.0,second_y,0.0);
glRotatef(third_x,1.0,0.0,0.0);
glRotatef(third_z,0.0,0.0,1.0);
glCallList(OBJET_4);
glCallList(OBJET_1);


// pinces 1 & 2
//float finger_x = 45.0;

glTranslatef(0.0,second_y,0.0);
glCallList(OBJET_4);

glPushMatrix();

glRotatef(finger_x,0.0,0.0,1.0);
glCallList(OBJET_2);
glTranslatef(0.0,5.85*0.3,0.0);
glRotatef(-45.0,0.0,0.0,1.0);
glCallList(OBJET_2);

glPopMatrix();


glRotatef(-finger_x,0.0,0.0,1.0);
glCallList(OBJET_2);

glTranslatef(0.0,5.85*0.3,0.0);
glRotatef(45.0,0.0,0.0,1.0);
glCallList(OBJET_2);
*/
//////////////////////////////////////////////////

//////////////////////////////////////////////////
// Robot complet

/////////////////////////////////
// Base
glTranslatef(base_x,0.0,base_z);
glPushMatrix();
glScalef(2.0,2.0,2.0);
glCallList(OBJET_3);
glPopMatrix();


/////////////////////////////////
// Tronc

glTranslatef(0.0,4.0+(2.0*1.375),0.0);
glRotatef(base_rot,0.0,1.0,0.0);
glPushMatrix();
glScalef(3.0,4.0,3.0);
tronc_robot();
glPopMatrix();
//////////////////////////////////////////////////
// bras 1
glPushMatrix();
glTranslatef(-3.0,2.0,0.0);
glRotatef(90.0,0.0,0.0,1.0);
bras_robot();
glPopMatrix();

//////////////////////////////////////////////////

//////////////////////////////////////////////////
// bras 2
glPushMatrix();
glTranslatef(3.0,2.0,0.0);
glRotatef(-90.0,0.0,0.0,1.0);
glScalef(-1.0,1.0,1.0);
bras_robot();
glPopMatrix();
//////////////////////////////////////////////////
//Tête du robot
glTranslatef(0.0,5.0,0.0);
glutSolidSphere(2.5,20,20);

  // Permutation des buffers
   glutSwapBuffers();
   glutPostRedisplay();
}
Esempio n. 20
0
ItemTreePtr Solver::compute()
{
	const auto nodeStackElement = app.getPrinter().visitNode(decomposition);

	// Compute item trees of child nodes
	ChildItemTrees childItemTrees;
	for(const auto& child : decomposition.getChildren()) {
		ItemTreePtr itree = child->getSolver().compute();
		if(!itree)
			return itree;
		childItemTrees.emplace(child->getNode().getGlobalId(), std::move(itree));
	}

	// Input: Child item trees
	std::unique_ptr<std::stringstream> childItemTreesInput(new std::stringstream);
	*childItemTreesInput << "% Child item tree facts" << std::endl;

	for(const auto& childItemTree : childItemTrees) {
		std::ostringstream rootItemSetName;
		rootItemSetName << 'n' << childItemTree.first;
		asp_utils::declareItemTree(*childItemTreesInput, childItemTree.second.get(), tableMode, childItemTree.first, rootItemSetName.str());
	}
	app.getPrinter().solverInvocationInput(decomposition, childItemTreesInput->str());

	// Input: Induced subinstance
	std::unique_ptr<std::stringstream> instanceInput(new std::stringstream);
	asp_utils::induceSubinstance(*instanceInput, app.getInstance(), decomposition.getNode().getBag());
	app.getPrinter().solverInvocationInput(decomposition, instanceInput->str());

	// Input: Decomposition
	std::unique_ptr<std::stringstream> decompositionInput(new std::stringstream);
	asp_utils::declareDecomposition(decomposition, *decompositionInput);
	app.getPrinter().solverInvocationInput(decomposition, decompositionInput->str());

	// Set up ASP solver
	Clasp::ClaspConfig config;
	config.solve.numModels = 0;
	Clasp::ClaspFacade clasp;
	// TODO The last parameter of clasp.startAsp in the next line is "allowUpdate". Does setting it to false have benefits?
	Clasp::Asp::LogicProgram& claspProgramBuilder = dynamic_cast<Clasp::Asp::LogicProgram&>(clasp.startAsp(config));
	std::unique_ptr<Gringo::Output::LparseOutputter> lpOut(newGringoOutputProcessor(claspProgramBuilder, childItemTrees, tableMode));
	std::unique_ptr<Gringo::Output::OutputBase> out(new Gringo::Output::OutputBase({}, *lpOut));
	Gringo::Input::Program program;
	asp_utils::DummyGringoModule module;
	Gringo::Scripts scripts(module);
	Gringo::Defines defs;
	Gringo::Input::NongroundProgramBuilder gringoProgramBuilder(scripts, program, *out, defs);
	Gringo::Input::NonGroundParser parser(gringoProgramBuilder);

	// Pass input to ASP solver
	for(const auto& file : encodingFiles)
		parser.pushFile(std::string(file));
	parser.pushStream("<instance>", std::move(instanceInput));
	parser.pushStream("<decomposition>", std::move(decompositionInput));
	parser.pushStream("<child_itrees>", std::move(childItemTreesInput));
	parser.parse();

	// Ground and solve
	program.rewrite(defs);
	program.check();
	if(Gringo::message_printer()->hasError())
		throw std::runtime_error("Grounding stopped because of errors");
	auto gPrg = program.toGround(out->domains);
	Gringo::Ground::Parameters params;
	params.add("base", {});
	gPrg.ground(params, scripts, *out);
	params.clear();
	// Finalize ground program and create solver variables
	claspProgramBuilder.endProgram();

	std::unique_ptr<asp_utils::ClaspCallback> cb(newClaspCallback(tableMode, *lpOut, childItemTrees, app, decomposition.isRoot(), decomposition, cardinalityCost));
	cb->prepare(claspProgramBuilder);
	clasp.prepare();
	clasp.solve(cb.get());

	if(printStatistics) {
		std::cout << "Solver statistics for decomposition node " << decomposition.getNode().getGlobalId() << ':' << std::endl;
		Clasp::Cli::TextOutput{true, Clasp::Cli::TextOutput::format_asp}.printStatistics(clasp.summary(), true);
	}

	ItemTreePtr result = cb->finalize(decomposition.isRoot(), app.isPruningDisabled() == false || decomposition.isRoot());
	app.getPrinter().solverInvocationResult(decomposition, result.get());
	return result;
}
Esempio n. 21
0
Solver::Solver(const Decomposition& decomposition, const Application& app, const std::vector<std::string>& encodingFiles, bool reground, BranchAndBoundLevel bbLevel)
	: ::LazySolver(decomposition, app, bbLevel)
	, reground(reground)
	, encodingFiles(encodingFiles)
{
	Gringo::message_printer()->disable(Gringo::W_ATOM_UNDEFINED);

	if(!reground) {
		// Set up ASP solver
		config.solve.numModels = 0;
		Clasp::Asp::LogicProgram& claspProgramBuilder = static_cast<Clasp::Asp::LogicProgram&>(clasp.startAsp(config, true)); // TODO In leaves updates might not be necessary.

		struct LazyGringoOutputProcessor : GringoOutputProcessor
		{
			LazyGringoOutputProcessor(Solver* s, Clasp::Asp::LogicProgram& prg)
				: GringoOutputProcessor(prg), self(s)
			{
			}

			void storeAtom(unsigned int atomUid, Gringo::Value v) override
			{
				const std::string& n = *v.name();
				if(n == "childItem") {
					ASP_CHECK(v.args().size() == 1, "'childItem' predicate does not have arity 1");
					std::ostringstream argument;
					v.args().front().print(argument);
					self->itemsToLitIndices.emplace(String(argument.str()), self->literals.size());
					self->literals.push_back(Clasp::posLit(atomUid));
				}
				else if(n == "childAuxItem") {
					ASP_CHECK(v.args().size() == 1, "'childAuxItem' predicate does not have arity 1");
					std::ostringstream argument;
					v.args().front().print(argument);
					self->auxItemsToLitIndices.emplace(String(argument.str()), self->literals.size());
					self->literals.push_back(Clasp::posLit(atomUid));
				}
				GringoOutputProcessor::storeAtom(atomUid, v);
			}

			Solver* self;
		} gringoOutput(this, claspProgramBuilder);

		std::unique_ptr<Gringo::Output::OutputBase> out(new Gringo::Output::OutputBase({}, gringoOutput));
		Gringo::Input::Program program;
		asp_utils::DummyGringoModule module;
		Gringo::Scripts scripts(module);
		Gringo::Defines defs;
		Gringo::Input::NongroundProgramBuilder gringoProgramBuilder(scripts, program, *out, defs);
		Gringo::Input::NonGroundParser parser(gringoProgramBuilder);

		// Input: Induced subinstance
		std::unique_ptr<std::stringstream> instanceInput(new std::stringstream);
		asp_utils::induceSubinstance(*instanceInput, app.getInstance(), decomposition.getNode().getBag());
		app.getPrinter().solverInvocationInput(decomposition, instanceInput->str());

		// Input: Decomposition
		std::unique_ptr<std::stringstream> decompositionInput(new std::stringstream);
		asp_utils::declareDecomposition(decomposition, *decompositionInput);
		app.getPrinter().solverInvocationInput(decomposition, decompositionInput->str());

		// Pass input to ASP solver
		for(const auto& file : encodingFiles)
			parser.pushFile(std::string(file));
		parser.pushStream("<instance>", std::move(instanceInput));
		parser.pushStream("<decomposition>", std::move(decompositionInput));
		parser.parse();

		// Ground
		program.rewrite(defs);
		program.check();
		if(Gringo::message_printer()->hasError())
			throw std::runtime_error("Grounding stopped because of errors");
		auto gPrg = program.toGround(out->domains);
		Gringo::Ground::Parameters params;
		params.add("base", {});
		gPrg.ground(params, scripts, *out);
		params.clear();

		// Set value of external atoms to free
		for(const auto& p : literals)
			claspProgramBuilder.freeze(p.var(), Clasp::value_free);

		// Finalize ground program and create solver literals
		claspProgramBuilder.endProgram();

		// Map externals to their solver literals
		for(auto& p : literals) {
			p = claspProgramBuilder.getLiteral(p.var());
			assert(!p.watched()); // Literal must not be watched
		}

		for(const auto& atom : gringoOutput.getItemAtomInfos())
			itemAtomInfos.emplace_back(ItemAtomInfo(atom, claspProgramBuilder));
		for(const auto& atom : gringoOutput.getAuxItemAtomInfos())
			auxItemAtomInfos.emplace_back(AuxItemAtomInfo(atom, claspProgramBuilder));
//		for(const auto& atom : gringoOutput->getCurrentCostAtomInfos())
//			currentCostAtomInfos.emplace_back(CurrentCostAtomInfo(atom, claspProgramBuilder));
//		for(const auto& atom : gringoOutput->getCostAtomInfos())
//			costAtomInfos.emplace_back(CostAtomInfo(atom, claspProgramBuilder)));

		// Prepare for solving.
		clasp.prepare();
	}
}
Esempio n. 22
0
void Solver::startSolvingForCurrentRowCombination()
{
//	++solverSetups;
	asyncResult.reset();

	if(reground) {
		// Set up ASP solver
		config.solve.numModels = 0;
		// TODO The last parameter of clasp.startAsp in the next line is "allowUpdate". Does setting it to false have benefits?
		// WORKAROUND for BUG in ClaspFacade::startAsp()
		// TODO remove on update to new version
		if(clasp.ctx.numVars() == 0 && clasp.ctx.frozen())
			clasp.ctx.reset();

		Clasp::Asp::LogicProgram& claspProgramBuilder = static_cast<Clasp::Asp::LogicProgram&>(clasp.startAsp(config));
		GringoOutputProcessor gringoOutput(claspProgramBuilder);
		std::unique_ptr<Gringo::Output::OutputBase> out(new Gringo::Output::OutputBase({}, gringoOutput));
		Gringo::Input::Program program;
		asp_utils::DummyGringoModule module;
		Gringo::Scripts scripts(module);
		Gringo::Defines defs;
		Gringo::Input::NongroundProgramBuilder gringoProgramBuilder(scripts, program, *out, defs);
		Gringo::Input::NonGroundParser parser(gringoProgramBuilder);

		// Input: Induced subinstance
		std::unique_ptr<std::stringstream> instanceInput(new std::stringstream);
		asp_utils::induceSubinstance(*instanceInput, app.getInstance(), decomposition.getNode().getBag());
		app.getPrinter().solverInvocationInput(decomposition, instanceInput->str());

		// Input: Decomposition
		std::unique_ptr<std::stringstream> decompositionInput(new std::stringstream);
		asp_utils::declareDecomposition(decomposition, *decompositionInput);
		app.getPrinter().solverInvocationInput(decomposition, decompositionInput->str());

		// Input: Child rows
		std::unique_ptr<std::stringstream> childRowsInput(new std::stringstream);
		*childRowsInput << "% Child row facts" << std::endl;
		for(const auto& row : getCurrentRowCombination()) {
			for(const auto& item : row->getItems())
				*childRowsInput << "childItem(" << item << ")." << std::endl;
			for(const auto& item : row->getAuxItems())
				*childRowsInput << "childAuxItem(" << item << ")." << std::endl;
			// TODO costs, etc.
		}
		app.getPrinter().solverInvocationInput(decomposition, childRowsInput->str());

		// Pass input to ASP solver
		for(const auto& file : encodingFiles)
			parser.pushFile(std::string(file));
		parser.pushStream("<instance>", std::move(instanceInput));
		parser.pushStream("<decomposition>", std::move(decompositionInput));
		parser.pushStream("<child_rows>", std::move(childRowsInput));
		parser.parse();

		// Ground
		program.rewrite(defs);
		program.check();
		if(Gringo::message_printer()->hasError())
			throw std::runtime_error("Grounding stopped because of errors");
		auto gPrg = program.toGround(out->domains);
		Gringo::Ground::Parameters params;
		params.add("base", {});
		gPrg.ground(params, scripts, *out);
		params.clear();

		claspProgramBuilder.endProgram();

		itemAtomInfos.clear();
		for(const auto& atom : gringoOutput.getItemAtomInfos())
			itemAtomInfos.emplace_back(ItemAtomInfo(atom, claspProgramBuilder));
		auxItemAtomInfos.clear();
		for(const auto& atom : gringoOutput.getAuxItemAtomInfos())
			auxItemAtomInfos.emplace_back(AuxItemAtomInfo(atom, claspProgramBuilder));
		// TODO costs etc.

		clasp.prepare();
	}

	else {
		// Set external variables to the values of the current child row combination
		clasp.update(false, false);

		clasp.prepare();

		// Mark atoms corresponding to items from the currently extended rows
		for(const auto& row : getCurrentRowCombination()) {
			for(const auto& item : row->getItems()) {
				assert(itemsToLitIndices.find(item) != itemsToLitIndices.end());
				assert(itemsToLitIndices.at(item) < literals.size());
#ifdef DISABLE_CHECKS
				literals[itemsToLitIndices.at(item)].watch();
#else
				try {
					literals[itemsToLitIndices.at(item)].watch();
				}
				catch(const std::out_of_range&) {
					std::ostringstream msg;
					msg << "Unknown variable; atom childItem(" << *item << ") not shown or not declared as external?";
					throw std::runtime_error(msg.str());
				}
#endif
			}
			for(const auto& item : row->getAuxItems()) {
				assert(auxItemsToLitIndices.find(item) != auxItemsToLitIndices.end());
				assert(auxItemsToLitIndices.at(item) < literals.size());
#ifdef DISABLE_CHECKS
				literals[auxItemsToLitIndices.at(item)].watch();
#else
				try {
					literals[auxItemsToLitIndices.at(item)].watch();
				}
				catch(const std::out_of_range&) {
					std::ostringstream msg;
					msg << "Unknown variable; atom childAuxItem(" << *item << ") not shown or not declared as external?";
					throw std::runtime_error(msg.str());
				}
#endif
			}
		}
		// Set marked literals to true and all others to false
		for(auto& lit : literals) {
			if(lit.watched()) {
				lit.clearWatch();
				clasp.assume(lit);
			}
			else
				clasp.assume(~lit);
		}
	}

	asyncResult.reset(new BasicSolveIter(clasp));
}
Esempio n. 23
0
int HeightAboveGroundKernel::execute()
{
    // we require separate contexts for the input and ground files
    PointContextRef input_ctx;
    PointContextRef ground_ctx;

    // because we are appending HeightAboveGround to the input buffer, we must
    // register it's Dimension
    input_ctx.registerDim(Dimension::Id::HeightAboveGround);

    // StageFactory will be used to create required stages
    StageFactory f;

    // setup the reader, inferring driver type from the filename
    std::string reader_driver = f.inferReaderDriver(m_input_file);
    std::unique_ptr<Reader> input(f.createReader(reader_driver));
    Options readerOptions;
    readerOptions.add("filename", m_input_file);
    input->setOptions(readerOptions);

    // go ahead and execute to get the PointBuffer
    input->prepare(input_ctx);
    PointBufferSet pbSetInput = input->execute(input_ctx);
    PointBufferPtr input_buf = *pbSetInput.begin();

    PointBufferSet pbSetGround;
    PointBufferPtr ground_buf;

    if (m_use_classification)
    {
        // the user has indicated that the classification dimension exists, so
        // we will find all ground returns
        Option source("source",
                      "import numpy as np\n"
                      "def yow1(ins,outs):\n"
                      "  cls = ins['Classification']\n"
                      "  keep_classes = [2]\n"
                      "  keep = np.equal(cls, keep_classes[0])\n"
                      "  outs['Mask'] = keep\n"
                      "  return True\n"
                     );
        Option module("module", "MyModule");
        Option function("function", "yow1");
        Options opts;
        opts.add(source);
        opts.add(module);
        opts.add(function);

        // and create a PointBuffer of only ground returns
        std::unique_ptr<Filter> pred(f.createFilter("filters.predicate"));
        pred->setOptions(opts);
        pred->setInput(input.get());
        pred->prepare(ground_ctx);
        pbSetGround = pred->execute(ground_ctx);
        ground_buf = *pbSetGround.begin();
    }
    else
    {
        // the user has provided a file containing only ground returns, setup
        // the reader, inferring driver type from the filename
        std::string ground_driver = f.inferReaderDriver(m_ground_file);
        std::unique_ptr<Reader> ground(f.createReader(ground_driver));
        Options ro;
        ro.add("filename", m_ground_file);
        ground->setOptions(ro);

        // go ahead and execute to get the PointBuffer
        ground->prepare(ground_ctx);
        pbSetGround = ground->execute(ground_ctx);
        ground_buf = *pbSetGround.begin();
    }

    typedef pcl::PointXYZ PointT;
    typedef pcl::PointCloud<PointT> Cloud;
    typedef Cloud::Ptr CloudPtr;

    // convert the input PointBuffer to a PointCloud
    CloudPtr cloud(new Cloud);
    BOX3D const& bounds = input_buf->calculateBounds();
    pclsupport::PDALtoPCD(*input_buf, *cloud, bounds);

    // convert the ground PointBuffer to a PointCloud
    CloudPtr cloud_g(new Cloud);
    // here, we offset the ground cloud by the input bounds so that the two are aligned
    pclsupport::PDALtoPCD(*ground_buf, *cloud_g, bounds);

    // create a set of planar coefficients with X=Y=0,Z=1
    pcl::ModelCoefficients::Ptr coefficients(new pcl::ModelCoefficients());
    coefficients->values.resize(4);
    coefficients->values[0] = coefficients->values[1] = 0;
    coefficients->values[2] = 1.0;
    coefficients->values[3] = 0;

    // create the filtering object and project ground returns into xy plane
    pcl::ProjectInliers<PointT> proj;
    proj.setModelType(pcl::SACMODEL_PLANE);
    proj.setInputCloud(cloud_g);
    proj.setModelCoefficients(coefficients);
    CloudPtr cloud_projected(new Cloud);
    proj.filter(*cloud_projected);

    // setup the KdTree
    pcl::KdTreeFLANN<PointT> tree;
    tree.setInputCloud(cloud_projected);

    // loop over all points in the input cloud, finding the nearest neighbor in
    // the ground returns (XY plane only), and calculating the difference in z
    int32_t k = 1;
    for (size_t idx = 0; idx < cloud->points.size(); ++idx)
    {
        // Search for nearesrt neighbor of the query point
        std::vector<int32_t> neighbors(k);
        std::vector<float> distances(k);
        PointT temp_pt = cloud->points[idx];
        temp_pt.z = 0.0f;
        int num_neighbors = tree.nearestKSearch(temp_pt, k, neighbors, distances);

        double hag = cloud->points[idx].z - cloud_g->points[neighbors[0]].z;
        input_buf->setField(Dimension::Id::HeightAboveGround, idx, hag);
    }

    // populate BufferReader with the input PointBuffer, which now has the
    // HeightAboveGround dimension
    BufferReader bufferReader;
    bufferReader.addBuffer(input_buf);

    // we require that the output be BPF for now, to house our non-standard
    // dimension
    Options wo;
    wo.add("filename", m_output_file);
    std::unique_ptr<Writer> writer(f.createWriter("writers.bpf"));
    writer->setOptions(wo);
    writer->setInput(&bufferReader);
    writer->prepare(input_ctx);
    writer->execute(input_ctx);

    return 0;
}
/*
* Find the ground in the environment.
* Params[in/out]: the cloud, the coeff of the planes, the indices, the ground cloud, the hull cloud
*/
bool Segmentation::findGround(pcl::PointCloud<pcl::PointXYZRGBA>::Ptr &cloud, MainPlane &mp)
{
    pcl::ModelCoefficients::Ptr coeff(new pcl::ModelCoefficients);
    pcl::PointIndices::Ptr indices(new pcl::PointIndices);
    pcl::PointCloud<pcl::PointXYZRGBA>::Ptr ground(new pcl::PointCloud<pcl::PointXYZRGBA>);
    pcl::PointCloud<pcl::PointXYZRGBA>::Ptr hullGround(new pcl::PointCloud<pcl::PointXYZRGBA>);

    // Create the segmentation object
    pcl::SACSegmentation<pcl::PointXYZRGBA> seg;
    // Optional
    seg.setOptimizeCoefficients (true);

    // Mandatory
    seg.setModelType (pcl::SACMODEL_PERPENDICULAR_PLANE); // We search a plane perpendicular to the y
    seg.setMethodType (pcl::SAC_RANSAC);

    seg.setDistanceThreshold (0.030); //0.25 / 35

    seg.setAxis(_axis); // Axis Y 0, -1, 0
    seg.setEpsAngle(30.0f * (M_PI/180.0f)); // 50 degrees of error

    pcl::ExtractIndices<pcl::PointXYZRGBA> extract;
    seg.setInputCloud (cloud);
    seg.segment (*indices, *coeff);
    mp.setCoefficients(coeff);
    //mp.setIndices(indices);

    if (indices->indices.size () == 0)
    {
        PCL_ERROR ("Could not estimate a planar model (Ground).");
        return false;
    }
    else
    {
        extract.setInputCloud(cloud);
        extract.setIndices(indices);
        extract.setNegative(false);
        extract.filter(*ground);
        mp.setPlaneCloud(ground);

        pcl::PointCloud<pcl::PointXYZRGBA>::Ptr concaveHull(new pcl::PointCloud<pcl::PointXYZRGBA>);
        pcl::PointCloud<pcl::PointXYZRGBA>::Ptr plane(new pcl::PointCloud<pcl::PointXYZRGBA>);
        // Copy the points of the plane to a new cloud.
        pcl::ExtractIndices<pcl::PointXYZRGBA> extractHull;
        extractHull.setInputCloud(cloud);
        extractHull.setIndices(indices);
        extractHull.filter(*plane);


        pcl::ConcaveHull<pcl::PointXYZRGBA> chull;
        chull.setInputCloud (plane);
        chull.setAlpha (0.1);
        chull.reconstruct (*concaveHull);

        mp.setHull(concaveHull);
        //vectorCloudinliers.push_back(convexHull);
        extract.setNegative(true);
        pcl::PointCloud<pcl::PointXYZRGBA>::Ptr cloud_f (new pcl::PointCloud<pcl::PointXYZRGBA>);
        extract.filter(*cloud_f);
        cloud.swap(cloud_f);


        return true;
    }

}
Esempio n. 25
0
void Solver::workerThreadMain()
{
	std::unique_lock<std::mutex> lock(workerMutex);

	// Set up ASP solver
	Clasp::ClaspFacade clasp;
	Clasp::ClaspConfig config;
	config.solve.numModels = 0;
	Clasp::Asp::LogicProgram& claspProgramBuilder = dynamic_cast<Clasp::Asp::LogicProgram&>(clasp.startAsp(config, true));
	std::unique_ptr<Gringo::Output::LparseOutputter> lpOut(new GringoOutputProcessor(claspProgramBuilder));
	claspCallback.reset(new ClaspCallback(dynamic_cast<GringoOutputProcessor&>(*lpOut), app, *this, lock));
	std::unique_ptr<Gringo::Output::OutputBase> out(new Gringo::Output::OutputBase({}, *lpOut));
	Gringo::Input::Program program;
	Gringo::Scripts scripts;
	Gringo::Defines defs;
	Gringo::Input::NongroundProgramBuilder gringoProgramBuilder(scripts, program, *out, defs);
	Gringo::Input::NonGroundParser parser(gringoProgramBuilder);

	// Input: Original problem instance
	std::unique_ptr<std::stringstream> instanceInput(new std::stringstream);
	*instanceInput << app.getInputString();

	// Input: Decomposition
	std::unique_ptr<std::stringstream> decompositionInput(new std::stringstream);
	solver::asp::Solver::declareDecomposition(decomposition, *decompositionInput);
	app.getPrinter().solverInvocationInput(decomposition, decompositionInput->str());

	// Pass input to ASP solver
	for(const auto& file : encodingFiles)
		parser.pushFile(std::string(file));
	parser.pushStream("<instance>", std::move(instanceInput));
	parser.pushStream("<decomposition>", std::move(decompositionInput));
	parser.parse();

	// Ground
	program.rewrite(defs);
	program.check();
	if(Gringo::message_printer()->hasError())
		throw std::runtime_error("Grounding stopped because of errors");
	auto gPrg = program.toGround(out->domains);
	Gringo::Ground::Parameters params;
	params.add("base", {});
	gPrg.ground(params, scripts, *out);
	params.clear();

	// Prepare for solving. (This makes clasp's symbol table available.)
	clasp.prepare();
	claspCallback->prepare(clasp.ctx.symbolTable());

	// We need to know which clasp variable corresponds to each childItem(_) atom.
	for(const auto& pair : clasp.ctx.symbolTable()) {
		if(!pair.second.name.empty()) {
			const std::string name = pair.second.name.c_str();
			if(name.compare(0, 10, "childItem(") == 0) {
				const std::string argument = name.substr(10, name.length()-11);
				itemsToVars.emplace(argument, pair.first);
			}
		}
	}

	// Let main thread finish the constructor
	wakeMainThreadRequested = true;
	wakeMainThread.notify_one();

	// Wait until we should do work
	wakeWorkerThread.wait(lock, [&]() { return wakeWorkerThreadRequested; });
	wakeWorkerThreadRequested = false;

	if(decomposition.getChildren().empty()) {
		// This is a leaf solver.
		clasp.solve(claspCallback.get());
	}
	else {
		// Get the first row from each child node
		std::unordered_map<unsigned int, ItemTree::Children::const_iterator> childRows;
		childRows.reserve(decomposition.getChildren().size());
		for(const auto& child : decomposition.getChildren()) {
			const ItemTree::Children::const_iterator newRow = dynamic_cast<Solver&>(child->getSolver()).nextRow();
			if(newRow == dynamic_cast<Solver&>(child->getSolver()).getItemTreeSoFar()->getChildren().end()) {
				// Notify main thread that solving is complete
				noMoreModels = true;
				wakeMainThreadRequested = true;
				wakeMainThread.notify_one();
				return;
			}
			childRows.emplace(child->getNode().getGlobalId(), newRow);
		}

		// Let the combination of these rows be the input for our ASP call
		ItemTreeNode::ExtensionPointerTuple rootExtensionPointers;
		for(const auto& child : decomposition.getChildren())
			rootExtensionPointers.emplace(child->getNode().getGlobalId(), dynamic_cast<Solver&>(child->getSolver()).getItemTreeSoFar()->getNode());
		claspCallback->setRootExtensionPointers(std::move(rootExtensionPointers));

		ItemTreeNode::ExtensionPointerTuple extendedRows;
		for(const auto& nodeIdAndRow : childRows)
			extendedRows.emplace(nodeIdAndRow.first, (*nodeIdAndRow.second)->getNode());
		claspCallback->setExtendedRows(std::move(extendedRows));

		{
			Clasp::Asp::LogicProgram& prg = static_cast<Clasp::Asp::LogicProgram&>(clasp.update());
			for(const auto& nodeIdAndRow : childRows) {
				for(const auto& item : (*nodeIdAndRow.second)->getNode()->getItems()) {
					prg.freeze(itemsToVars.at(item), Clasp::value_true);
				}
			}
		}
		clasp.prepare();
		claspCallback->prepare(clasp.ctx.symbolTable());
		clasp.solve(claspCallback.get());
		{
			// XXX Necessary to update so often? Is the overhead bad?
			Clasp::Asp::LogicProgram& prg = static_cast<Clasp::Asp::LogicProgram&>(clasp.update());
			for(const auto& nodeIdAndRow : childRows) {
				for(const auto& item : (*nodeIdAndRow.second)->getNode()->getItems()) {
					prg.freeze(itemsToVars.at(item), Clasp::value_false);
				}
			}
		}

		// Now there are no models anymore for this row combination
		// Until there are no new rows anymore, generate one new row at some child node and combine it with all rows from other child nodes
		bool foundNewRow;
		do {
			foundNewRow = false;
			for(const auto& child : decomposition.getChildren()) {
				ItemTree::Children::const_iterator newRow = dynamic_cast<Solver&>(child->getSolver()).nextRow();
				if(newRow != dynamic_cast<Solver&>(child->getSolver()).getItemTreeSoFar()->getChildren().end()) {
					foundNewRow = true;
					aspCallsOnNewRowFromChild(newRow, child, clasp);
				}
			}
		} while(foundNewRow);
	}

	// Notify main thread that solving is complete
	noMoreModels = true;
	wakeMainThreadRequested = true;
	wakeMainThread.notify_one();
}
Esempio n. 26
0
static int
copy_term(Word from, Word to, int flags ARG_LD)
{ term_agendaLR agenda;
  int rc = TRUE;

  initTermAgendaLR(&agenda, 1, from, to);
  while( nextTermAgendaLR(&agenda, &from, &to) )
  {
  again:

    switch(tag(*from))
    { case TAG_REFERENCE:
      { Word p2 = unRef(*from);

	if ( *p2 == VAR_MARK )		/* reference to a copied variable */
	{ *to = makeRef(p2);
	} else
	{ from = p2;			/* normal reference */
	  goto again;
	}

	continue;
      }
      case TAG_VAR:
      { if ( shared(*from) )
	{ *to = VAR_MARK;
	  *from = makeRef(to);
	  TrailCyclic(from PASS_LD);
	} else
	{ setVar(*to);
	}

	continue;
      }
      case TAG_ATTVAR:
	if ( flags&COPY_ATTRS )
	{ Word p = valPAttVar(*from);

	  if ( isAttVar(*p) )		/* already copied */
	  { *to = makeRefG(p);
	  } else
	  { Word attr;

	    if ( !(attr = alloc_attvar(PASS_LD1)) )
	    { rc = GLOBAL_OVERFLOW;
	      goto out;
	    }
	    TrailCyclic(p PASS_LD);
	    TrailCyclic(from PASS_LD);
	    *from = consPtr(attr, STG_GLOBAL|TAG_ATTVAR);
	    *to = makeRefG(attr);

	    from = p;
	    to = &attr[1];
	    goto again;
	  }
	} else
	{ if ( shared(*from) )
	  { Word p = valPAttVar(*from & ~BOTH_MASK);

	    if ( *p == VAR_MARK )
	    { *to = makeRef(p);
	    } else
	    { *to = VAR_MARK;
	      *from = consPtr(to, STG_GLOBAL|TAG_ATTVAR)|BOTH_MASK;
	      TrailCyclic(p PASS_LD);
	      TrailCyclic(from PASS_LD);
	    }
	  } else
	  { setVar(*to);
	  }
	}
	continue;
      case TAG_COMPOUND:
      { Functor ff = valueTerm(*from);

	if ( isRef(ff->definition) )
	{ *to = consPtr(unRef(ff->definition), TAG_COMPOUND|STG_GLOBAL);
	  continue;
	}

	if ( ground(ff->definition) )
	{ *to = *from;
	  continue;
	}

	if ( shared(ff->definition) )
	{ int arity = arityFunctor(ff->definition);
	  Functor ft;

	  if ( !(ft = (Functor)allocGlobalNoShift(arity+1)) )
	  { rc = GLOBAL_OVERFLOW;
	    goto out;
	  }
	  ft->definition = ff->definition & ~BOTH_MASK;
	  ff->definition = makeRefG((Word)ft);
	  TrailCyclic(&ff->definition PASS_LD);
	  *to = consPtr(ft, TAG_COMPOUND|STG_GLOBAL);

	  if ( pushWorkAgendaLR(&agenda, arity, ff->arguments, ft->arguments) )
	    continue;
	  rc = MEMORY_OVERFLOW;
	  goto out;
	} else				/* unshared term */
	{ int arity = arityFunctor(ff->definition);
	  Functor ft;

	  if ( !(ft = (Functor)allocGlobalNoShift(arity+1)) )
	  { rc = GLOBAL_OVERFLOW;
	    goto out;
	  }
	  ft->definition = ff->definition & ~BOTH_MASK;
	  *to = consPtr(ft, TAG_COMPOUND|STG_GLOBAL);

	  if ( pushWorkAgendaLR(&agenda, arity, ff->arguments, ft->arguments) )
	    continue;
	  rc = MEMORY_OVERFLOW;
	  goto out;
	}
      }
      default:
	*to = *from;
        continue;
    }
  }

out:
  clearTermAgendaLR(&agenda);
  return rc;
}
Esempio n. 27
0
int main()
{

	glm::vec3 cross = glm::cross(glm::vec3(2.5, 2.5, 0),glm::vec3(0, 2.5, 0));
	try
	{
		GLfloat currentFrame;

		GLFWwindow *window = JPGLHelper::InitEverything(HEIGHT, WIDTH);
		glfwSetKeyCallback(window, keyCallback);
		
		if (glewInit() != GLEW_OK)
			throw std::runtime_error("glewInit() failed");

		ShaderCompiler shaderGround("ground.vert", "ground.frag");
		ShaderCompiler shaderTrain("train.vert", "train.frag");

		MatrixWrapper	modelPlane(shaderGround.GetProgramID(), "model"),
			modelIdentity(shaderTrain.GetProgramID(), "model"),
						projection(shaderGround.GetProgramID(), "projection");

		modelPlane.mat4	= glm::rotate(modelPlane.mat4, glm::radians(-90.0f), glm::vec3(1.0f, 0.0f, 0.0f));
		projection.mat4 = glm::perspective(glm::radians(45.0f), (GLfloat)WIDTH / (GLfloat)HEIGHT, 0.1f, 2500.0f);

		Camera camera(-180.0f, 180.0f, 0.0f, 360.0f, 5.0f, shaderGround.GetProgramID(), 25.0f);
		
		camera.UpdateTargetPosition(glm::vec3(0.0f, 0.0f, 0.0f));

		modelPlane.mat4 = glm::scale(modelPlane.mat4, glm::vec3(300.0f,300.0f, 1.0f));
		modelIdentity.mat4 = glm::mat4(1.0f);
		
		Plane ground(shaderGround.GetProgramID(),32);
		Train train(shaderTrain.GetProgramID());
		Light light;
	
		TextureWrapper groundTexture(GL_TEXTURE0, shaderGround.GetProgramID(), "ground.png", "Texture0");

		keyboardManager.RegisterKey(GLFW_KEY_ESCAPE, std::bind(glfwSetWindowShouldClose, window, GL_TRUE));
		keyboardManager.RegisterKey(GLFW_KEY_H, std::bind(&Camera::YawDown, std::ref(camera)));
		keyboardManager.RegisterKey(GLFW_KEY_J, std::bind(&Camera::PitchDown, std::ref(camera)));
		keyboardManager.RegisterKey(GLFW_KEY_K, std::bind(&Camera::PitchUp, std::ref(camera)));
		keyboardManager.RegisterKey(GLFW_KEY_L, std::bind(&Camera::YawUp, std::ref(camera)));
		keyboardManager.RegisterKey(GLFW_KEY_U, std::bind(&Camera::DistanceUp, std::ref(camera)));
		keyboardManager.RegisterKey(GLFW_KEY_I, std::bind(&Camera::DistanceDown, std::ref(camera)));

		keyboardManager.RegisterKey(GLFW_KEY_A, std::bind(&Train::Go, std::ref(train)));
		keyboardManager.RegisterKey(GLFW_KEY_Z, std::bind(&Train::Back, std::ref(train)));


		keyboardManager.RegisterKey(GLFW_KEY_S, std::bind(&Light::AmbientUp, std::ref(light)));
		keyboardManager.RegisterKey(GLFW_KEY_X, std::bind(&Light::AmbientDown, std::ref(light)));
		keyboardManager.RegisterKey(GLFW_KEY_D, std::bind(&Light::DiffuseUp, std::ref(light)));
		keyboardManager.RegisterKey(GLFW_KEY_C, std::bind(&Light::DiffuseDown, std::ref(light)));

		glEnable(GL_MULTISAMPLE);
		glEnable(GL_DEPTH_TEST);
		glEnable(GL_CULL_FACE);

		while (!glfwWindowShouldClose(window))
		{
			currentFrame = glfwGetTime();
			JPGLHelper::deltaTime = currentFrame - JPGLHelper::lastTime;
			JPGLHelper::lastTime = currentFrame;

			glfwPollEvents();
			keyboardManager.ProcessKeys();
			
			camera.UpdateTargetPosition(train.GetLocation());
			train.DoPhysics();

			glClearColor(light.InterpolateR(), light.InterpolateG(), light.InterpolateB(), 1.0f);
			glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

			/*
			
				rysowanie p³aszczyzny

			*/

			groundTexture.SendToGPU();

			shaderGround.Execute();

			light.UpdateLight(shaderGround.GetProgramID(), camera.cameraPosition);

			camera.UpdateShader(shaderGround.GetProgramID());
			camera.SendUpdatedMatrix();
			
			projection.SetShader(shaderGround.GetProgramID());
			projection.SendToGPU();

			ground.Draw(modelPlane);


			/*
			
				rysowanie poci¹gu
			
			*/

			shaderTrain.Execute();
			light.UpdateLight(shaderTrain.GetProgramID(), camera.cameraPosition);
			camera.UpdateShader(shaderGround.GetProgramID());
			camera.SendUpdatedMatrix();
			
			projection.SetShader(shaderTrain.GetProgramID());
			projection.SendToGPU();

			
			train.Draw();

		
			
			glfwSwapBuffers(window);
		}

	
	}
	catch (std::exception &e)
	{
		std::cout << e.what() << std::endl;
		system("pause");
	}

	glfwTerminate();
	return 0;
}
Esempio n. 28
0
	void initialize() override
	{
		const float max_depth = 6000;
		const float min_depth = 0;
		const unsigned num_planes = 75;
		const unsigned rects_per_plane = 10;
		const float interval = ((max_depth - min_depth) / num_planes);
		const auto center = windowHalfDimensions();
		const auto dimensions = windowDimensions();

		auto plane = VanishPlane::backPlane(sf::Vector2f(center.x, center.y*1.2), 0);
		planes.reserve(num_planes);

		const sf::Vector2f rect_size(50, 250);
		sf::RectangleShape shape_base(rect_size);
		shape_base.setOrigin(rect_size.x / 2, rect_size.y);
		shape_base.setFillColor(sf::Color::Black);
		shape_base.setOutlineColor(sf::Color::White);
		const unsigned num_points = shape_base.getPointCount();

		const sf::Vector2f ground_size(100000, 100);
		sf::RectangleShape ground(ground_size);
		ground.setOrigin(ground_size.x / 2, 0);
		ground.setPosition(center.x, dimensions.y);
		ground.setFillColor(sf::Color::White);
		ground.setOutlineColor(sf::Color::Transparent);
		
		maxProgress(num_planes * (rects_per_plane+1));

		for(unsigned n_plane = num_planes; n_plane > 0; --n_plane)
		{
			plane.intersect = (n_plane * interval) + min_depth;

			planes.emplace_back();
			auto& rects = planes.back().rects;
			rects.reserve(rects_per_plane);

			if(n_plane == int(num_planes*.6))
			{
				const sf::Vector2f mighty_size(2000, 20000);
				sf::RectangleShape mighty(mighty_size);
				mighty.setOrigin(mighty_size.x / 2, mighty_size.y);
				mighty.setPosition(center.x * 10, dimensions.y);
				mighty.setFillColor(sf::Color::Black);
				mighty.setOutlineColor(sf::Color::White);
				rects.push_back(convertRectToConvex(mighty, plane));
			}


			for(unsigned rect = 0; rect < rects_per_plane; ++rect)
			{
				shape_base.setPosition(
					randcentered(center.x, center.x * sqrt(n_plane) * 5),
					dimensions.y + randuniform(0, 50));
				shape_base.setRotation(randuniform(-30, 30));
				rects.push_back(convertRectToConvex(shape_base, plane));
				addProgress(1);
			}
			rects.push_back(convertRectToConvex(ground, plane));
			addProgress(1);
		}
	}
Esempio n. 29
0
void phys(){
	if (v.cam == NULL || v.cm == NULL){
		return;
	}

	v.yvel -= v.gravity;

	v.yvel = max(-0.50, v.yvel);

	if (v.isonground){
		v.xvel *= v.friction;
		v.zvel *= v.friction;
	}
	else{
		v.xvel *= 0.9;
		v.zvel *= 0.9;
	}

	int g = ground();

	v.isonground = v.cam->y <= g;
	if (v.cam->y + v.yvel < g && v.yvel < 0){
		v.yvel = 0;
		v.cam->y = g;
	}
	else if (v.yvel > 0 && !tr(v.cam->x + v.xvel, v.cam->y + v.cam->height + 1.0 + v.yvel, v.cam->z)){
		v.yvel = 0;
	}
	if (!tr(v.cam->x + v.xvel, v.cam->y + v.yvel + 1, v.cam->z + v.zvel) && tr(v.cam->x + v.xvel, v.cam->y + v.yvel + v.cam->height + 2.0, v.cam->z + v.zvel)){
		v.yvel = max(0.08, v.yvel + 0.01);
	}
	//v.isonground = true;

	bool step = true;
	bool collided = false;
	float nxv = v.xvel, nzv = v.zvel;
	for (int i = 1; i <= ceil(v.cam->height) + 1; i++){
		bool both = true;
		if (!tr(v.cam->x + t(v.xvel), v.cam->y + i, v.cam->z)){
			both = false;
			if (i != 1)
				step = false;
			if (i != ceil(v.cam->height) + 1){
				nxv = 0;
				collided = true;
			}
		}
		if (!tr(v.cam->x, v.cam->y + i, v.cam->z + t(v.zvel))){
			both = false;
			if (i != 1)
				step = false;
			if (i != ceil(v.cam->height) + 1){
				nzv = 0;
				collided = true;
			}
		}
		if (both && !tr(v.cam->x + t(v.xvel), v.cam->y + i, v.cam->z + t(v.zvel))){
			if (i != 1)
				step = false;
			if (i != ceil(v.cam->height) + 1){
				nzv = 0;
				collided = true;
			}
		}
	}
	v.xvel = nxv;
	v.zvel = nzv;

	/*if (collided && step && tr(v.cam->x, v.cam->y + v.cam->height + 1, v.cam->z))
		v.yvel = min(0.10f, v.yvel + 0.90f);*/

	v.cam->x += v.xvel;
	v.cam->z += v.zvel;
	v.cam->y += v.yvel;
}
Esempio n. 30
0
//--------------------------------------------------------------------------------------------------
/// Constructor
//--------------------------------------------------------------------------------------------------
RifReaderEclipseOutput::RifReaderEclipseOutput()
{
    ground();
}