bool solidShapesFromURDFString(const std::string & urdf_string,
                               const std::string & urdf_filename,
                               const Model & model,
                               const std::string urdfGeometryType,
                                     iDynTree::ModelSolidShapes & output)
{
    if (urdfGeometryType != "visual" && urdfGeometryType != "collision")
    {
        std::cerr << "[ERROR] unknown urdfGeometryType " << urdfGeometryType << std::endl;
        return false;
    }

    ModelLoader loader;
    ModelParserOptions options;
    options.originalFilename = urdf_filename;
    loader.setParsingOptions(options);
    bool ok = loader.loadModelFromString(urdf_string);

    if (ok && urdfGeometryType == "visual")
    {
        output = loader.model().visualSolidShapes();
    }

    if (ok && urdfGeometryType == "collision")
    {
        output = loader.model().collisionSolidShapes();
    }

    return ok;
}
bool solidShapesFromURDF(const std::string & urdf_filename,
                         const Model & model,
                         const std::string urdfGeometryType,
                               ModelSolidShapes & output)
{
    if (urdfGeometryType != "visual" && urdfGeometryType != "collision")
    {
        std::cerr << "[ERROR] unknown urdfGeometryType " << urdfGeometryType << std::endl;
        return false;
    }

    ModelLoader loader;
    bool ok = loader.loadModelFromFile(urdf_filename);

    if (ok && urdfGeometryType == "visual")
    {
        output = loader.model().visualSolidShapes();
    }

    if (ok && urdfGeometryType == "collision")
    {
        output = loader.model().collisionSolidShapes();
    }

    return ok;
}
Example #3
0
void Obj::load(string filename)
{
	this->name = filename;
	
	ModelLoader m;
	m.load_obj(filename, this);
}
SensorsList getSensors(const std::string& fileName)
{
    ModelLoader loader;
    bool ok = loader.loadModelFromFile(fileName);
    // Load model
    ASSERT_IS_TRUE(ok);
    SensorsList sensorList = loader.sensors();

    return sensorList;
}
Model getModel(const std::string& fileName)
{
    ModelLoader loader;
    bool ok = loader.loadModelFromFile(fileName);
    // Load model
    ASSERT_IS_TRUE(ok);
    Model model = loader.model();

    return model;
}
Example #6
0
void Object::readFromFile(const char *filename) {
    
    ModelLoader loader = *new ModelLoader();
    loader.read_from_file(filename);
    
    vertices_counter = loader.vertexs_counter;
    indices_counter = loader.indexes_counter;
    
    vertices_array = loader.vertexes_out;
    indices_array = loader.indexes;
    
}
Example #7
0
Object::Object()
{
	try
	{
		position = { { 0., 0., 0. }, 0., 0., -1, 0, 0, false };
		scale = .1f;

		ModelLoader modelLoader;
		model = modelLoader.ReadModel("resources\\objects\\Captain America.obj", "resources\\objects\\Captain America.mtl");

		if (!model)
		{
			throw "Can't load player's geometry";
		}
		else
		{
			boundingBox.isShowing = false;
			calculateSizes();

		 	glGenBuffers(1, &tid);
			glBindBuffer(GL_ARRAY_BUFFER, tid);
			glBufferData(GL_ARRAY_BUFFER, model->UV_vertices.size()*sizeof(float), NULL, GL_STATIC_DRAW);
			glBufferSubData(GL_ARRAY_BUFFER, 0, model->UV_vertices.size()*sizeof(float), &model->UV_vertices[0]);
			glBindBuffer(GL_ARRAY_BUFFER, 0);

			glGenBuffers(1, &nid);
			glBindBuffer(GL_ARRAY_BUFFER, nid);
			glBufferData(GL_ARRAY_BUFFER, model->normals.size()*sizeof(float), NULL, GL_STATIC_DRAW);
			glBufferSubData(GL_ARRAY_BUFFER, 0, model->normals.size()*sizeof(float), &model->normals[0]);
			glBindBuffer(GL_ARRAY_BUFFER, 0);


			glGenBuffers(1, &vid);
			glBindBuffer(GL_ARRAY_BUFFER, vid);
			glBufferData(GL_ARRAY_BUFFER, model->vertices.size()*sizeof(float), NULL, GL_STATIC_DRAW);
			glBufferSubData(GL_ARRAY_BUFFER, 0, model->vertices.size()*sizeof(float), &model->vertices[0]);
			glBindBuffer(GL_ARRAY_BUFFER, 0);

			glGenBuffers(1, &bbvid);
			glBindBuffer(GL_ARRAY_BUFFER, bbvid);
			glBufferData(GL_ARRAY_BUFFER, 72 * sizeof(float), NULL, GL_STATIC_DRAW);
			glBufferSubData(GL_ARRAY_BUFFER, 0, 72 * sizeof(float), &boundingBox.coords[0]);
			glBindBuffer(GL_ARRAY_BUFFER, 0);
		}
	}
	catch (const char* error)
	{
		model = NULL;
		std::cout << error << std::endl;
	}

}
Example #8
0
bool Model :: Load(std :: string name,ModelLoader &loader,Texture &tex)
{
	// attempt to load the file
	if(!loader.Load(name))
		return false;

	// do we have to clean up?
	if(frames)
		this->Clear();

	// get the model information
	int		modelframes=loader.GetNumFrames();
	int		nummeshes=loader.GetNumMeshes();
	float	modelfps=(float)loader.GetFPS();

	// tidy up the values
	if(modelframes<=0)
		return false;
	if(modelfps==0.0f)
		modelfps=1.0f;

	// and setup our model
	if(!this->Setup(modelframes,modelfps))
		return false;
	
	// now set up the frames
	for(int ct=0; ct<numframes; ct++)
	{
		// setup the frame
		if(!frames[ct].Setup(nummeshes))
		{
			this->Clear();
			return false;
		}
		
		// add the meshes
		for(int ct2=0; ct2<nummeshes; ct2++)
		{
			Mesh msh;	// temporary mesh
			
			// get the mesh
			if(!loader.Get(ct,ct2,&tex,&msh))
				return false;

			// and set it to the frame
			frames[ct].SetMesh(ct2,msh);
		}
	}

	// success
	return true;
}
Example #9
0
 Scene* makeScene(){
   ModelLoader loader;
   Object* o = loader.load("teapot.obj", true);
   o->setDrawMode( GL_TRIANGLES );// Render mode: triangluar mesh
   o->glSetTexture(0, "test0.png");// Texture
   o->glSetTexture(1, pSkyTech->getTexture() );  // Environment map.
   o->glSetTexture(2, pShadowTarget->getColorTexture() );  // Blurred shadows-only image. for soft-shadows.
   o->glSetTexture(3, pShadowsHV->getColorTexture() );
   o->glSetTexture(0, new Texture( GL_TEXTURE_2D, pCube->getTexture() ) );
   Scene* sc = new Scene();
   sc->addObject(o);
   return sc;
 }
//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
void EffectImplemented::UnloadResources()
{
	Setting* loader = GetSetting();
	
	TextureLoader* textureLoader = loader->GetTextureLoader();
	if( textureLoader != NULL )
	{
		for( int32_t ind = 0; ind < m_ImageCount; ind++ )
		{
			textureLoader->Unload( m_pImages[ind] );
			m_pImages[ind] = NULL;
		}

		for (int32_t ind = 0; ind < m_normalImageCount; ind++)
		{
			textureLoader->Unload(m_normalImages[ind]);
			m_normalImages[ind] = NULL;
		}

		for (int32_t ind = 0; ind < m_distortionImageCount; ind++)
		{
			textureLoader->Unload(m_distortionImages[ind]);
			m_distortionImages[ind] = NULL;
		}
	}

	SoundLoader* soundLoader = loader->GetSoundLoader();
	if( soundLoader != NULL )
	{
		for( int32_t ind = 0; ind < m_WaveCount; ind++ )
		{
			soundLoader->Unload( m_pWaves[ind] );
			m_pWaves[ind] = NULL;
		}
	}

	{
		ModelLoader* modelLoader = loader->GetModelLoader();
		if( modelLoader != NULL )
		{
			for( int32_t ind = 0; ind < m_modelCount; ind++ )
			{
				modelLoader->Unload( m_pModels[ind] );
				m_pModels[ind] = NULL;
			}
		}
	}
}
// Carga un ResourceMesh y guarda una referencia a este
ResourceMesh* ResourceManager::loadMesh(const char* filePath)
{
	ResourceMesh* mesh = NULL;
	ModelLoader* modelLoader = new ModelLoader();

	mesh = modelLoader->loadOBJ(filePath);

	// Si hay algun problema con el modelo cargamos uno de error por defecto
	if (mesh == NULL)
	{
		mesh = modelLoader->loadOBJ(Resources::MESH_ERROR);
	}

	mesh->fileName = filePath; //guardamos el filePath

	return mesh;
}
Example #12
0
void MyGLWindow::InitModels()
{
	Chrono chrono;

	// load models
	ModelLoader modelLoader;

	chrono.start();
	_actorLib["Tank"] = modelLoader.LoadFromFile("./data/model/stankbot/models/stankbot.dae");
	_actorLib["Tank"]->SetShaderProgram(_shaderProgLib["defaultShader"]);
	std::cout << "Load stankbot (ms) : " << chrono.ellapsed() << std::endl;

	chrono.start();
	_actorLib["Dragon"] = modelLoader.LoadFromFile("./data/model/dragon_vrip_res3.ply");
	_actorLib["Dragon"]->SetShaderProgram(_shaderProgLib["defaultShader"]);
	std::cout << "Load dragon (ms) : " << chrono.ellapsed() << std::endl;
}
TexturedModel::TexturedModel(Model model, std::vector<glm::vec2> uvs, GLuint textureID) {
	this->setVaoID(model.getVaoID());
	this->setVerticesVboID(model.getVerticesVboID());
	this->setVertexCount(model.getVertexCount());
	this->setScale(model.getScale());
	this->setPosition(model.getPosition());

	this->setTextured(true);

	ModelLoader modelLoader = ModelLoader();
	GLfloat *uvsTemp = &uvs[0].x;
	int uvsSize = uvs.size() * 2 * sizeof(GLfloat);

	this->uvVboID = modelLoader.storeData(2, uvsTemp, uvsSize);

	this->setColor(false);
	this->setColorsVboID(model.getColorsVboID());
}
/* Asking user if he would like to save his model */
void saveResults(NNModel* model){
	cout << endl << "Would you like to save this model? (Press y/n)";

	/* Wait for y or n click*/
	char key = ' ';
	do{
		key = _getch();
	} while ((key != 'n') && (key != 'y'));
	 
	/* Saving model if needed */
	if (key == 'y'){
		cout << endl << endl << endl;
		string fileName;
		cout << "--Enter file name: "; cin >> fileName;
		
		ModelLoader m;
		m.saveModel(model, (char*)fileName.c_str());
	}
Example #15
0
GLWidget::GLWidget(const QGLFormat & format, QWidget * parent) : QGLWidget(format, parent),
                                                                 mShaderProgram(this),
                                                                 mViewMatrix(),
                                                                 mProjectionMatrix(){

    float ratio = float(geometry().width())/float(geometry().height());
    mProjectionMatrix.perspective(60, ratio, .1, 100); // ortho(-5,5,-5,5,-5,5);//Orthogonal projection
    mViewMatrix.translate(0.0,0.0,-10.0);

    ModelLoader* loader = ModelFactory::getModelLoader("models/monkey.obj");
    if(loader != NULL){
        objTest = (StaticModel*)loader->loadModel();
    }
    objTest->mModelMatrix.translate(0,0,0);
    delete loader;

    manip = new SphereManipulator("cube manipulator", objTest);
    this->grabKeyboard();
}
void display() 
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glLoadIdentity();
    gluLookAt( 0,0,30, 0,0,0, 0,1,0);
    glPushMatrix();
    glRotatef(g_rotation,0,1,0);
    g_rotation += 0.5f;
    obj.draw();
    glPopMatrix();
    glutSwapBuffers();
}
Example #17
0
void LightSources::loadModel(QString ex_path)
{
    ModelLoader model;
    bool res = model.loadObjectFromFile(ex_path.toStdString());//ex_path.toStdString());
    if (res) {
        // Frage zu erwartende Array-Laeangen ab
        vboLength = model.lengthOfVBO();
        iboLength = model.lengthOfIndexArray();
        // Generiere VBO und Index-Array
        vboData = new GLfloat[vboLength];
        indexData = new GLuint[iboLength];
        model.genVBO(vboData,0,true,true);
        model.genIndexArray(indexData);
    }


    vbo = new QOpenGLBuffer(QOpenGLBuffer::VertexBuffer);
    ibo = new QOpenGLBuffer(QOpenGLBuffer::IndexBuffer);

    vbo->create();
    vbo->bind();
    vbo->setUsagePattern(QOpenGLBuffer::StaticDraw);
    vbo->allocate(vboData, sizeof(GLfloat) * vboLength); // modelloader
    vbo->release();

    ibo->create();
    ibo->bind();
    ibo->setUsagePattern(QOpenGLBuffer::StaticDraw);
    ibo->allocate(indexData, sizeof(GLuint) * iboLength); // modelloader
    ibo->release();
}
Example #18
0
void MyGLWidget::loadModel()
{
    // Lade Model aus Datei:
    ModelLoader model ;
    bool res = model.loadObjectFromFile("P3_models/sphere_low.obj");
    // Wenn erfolgreich, generiere VBO und Index-Array
    if (res) {
        // Frage zu erwartende Array-Längen ab
        //vboLength = model.lengthOfSimpleVBO();
        vboLength = model.lengthOfVBO(0,false,true);
        iboLength = model.lengthOfIndexArray();
        // Generiere VBO und Index-Array
        vboData = new GLfloat[vboLength];
        indexData = new GLuint[iboLength];
        //model.genSimpleVBO(vboData);
        model.genVBO(vboData,0,false,true);  // With textures
        model.genIndexArray(indexData);
    }
    else {
        // Modell konnte nicht geladen werden
        assert(0) ;
    }


}
void trainingMode(){
	/* *********************      Interface part      **********************/
	/* ********************* **** ************** **** **********************/
	cout << endl << endl;

	cout << " ================== Training mode  =============" << endl;
	cout << " == Enter number of training examples: "; 	cin >> numTrainingExamples;
	cout << " == Enter number of LBFGS iterations: " ; 	cin >> numLbfgsIterations;
	cout << " == Enter lambda: "                     ; 	cin >> lambda;

	/* Checking if input is valid */
	if (numTrainingExamples > 40000) numTrainingExamples = 40000;
	if (numTrainingExamples <= 0) numTrainingExamples = 150;
	if (numLbfgsIterations < 1) numLbfgsIterations = 5;

	/* Reading model */
	//NNModel* model = readModel();
	ModelLoader l;
	NNModel* model = l.loadModel("modelL56.nn");

	trainModel(model);
}
Example #20
0
BasicModel::BasicModel(ID3D11Device* device, const ModelLoader& modelLoader) :
    texture_(device, "red-ball-graphics/src/main/resources/seafloor.dds"),
    samplerState_(device),
    vertexCount_(modelLoader.indices()->size())
{
    assert(vertexCount_ > 0);

    D3D11_BUFFER_DESC vertexBufferDesc;
    ZeroMemory(&vertexBufferDesc, sizeof(vertexBufferDesc));
    vertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
    vertexBufferDesc.ByteWidth = modelLoader.vertices()->size() * sizeof(Vertex);
    vertexBufferDesc.Usage = D3D11_USAGE_DEFAULT;

    D3D11_SUBRESOURCE_DATA vertexBufferData;
    ZeroMemory(&vertexBufferData, sizeof(vertexBufferData));
    vertexBufferData.pSysMem = &modelLoader.vertices()->front();

    check(
            device->CreateBuffer(&vertexBufferDesc, &vertexBufferData, &vertexBuffer_.get()),
            "CreateBuffer failed for vertex buffer"
            );

    D3D11_BUFFER_DESC indexBufferDesc;
    ZeroMemory(&indexBufferDesc, sizeof(indexBufferDesc));
    indexBufferDesc.BindFlags = D3D11_BIND_INDEX_BUFFER;
    indexBufferDesc.ByteWidth = modelLoader.indices()->size() * sizeof(unsigned long);
    indexBufferDesc.Usage = D3D11_USAGE_DEFAULT;

    D3D11_SUBRESOURCE_DATA indexBufferData;
    ZeroMemory(&indexBufferData, sizeof(indexBufferData));
    indexBufferData.pSysMem = &modelLoader.indices()->front();

    check(
            device->CreateBuffer(&indexBufferDesc, &indexBufferData, &indexBuffer_.get()),
            "CreateBuffer failed for index buffer"
            );
}
Example #21
0
int main(int argc, char** argv) {
	init(argc, argv, "JointUpdateNode");
	NodeHandle nh;

	// get the filenames
	nh.param(string("joint_offsets_filename_suffix"), jointOffsetsFilename,
			string("calibration_joint_offsets.xacro"));
	nh.param(string("camera_transform_filename_suffix"),
			cameraTransformFilename,
			string("calibration_camera_transform.xacro"));
	nh.param(string("urdf_filename_suffix"), urdfFilename,
			string("robot_model_calibrated.xml"));
	nh.param(string("marker_transforms_filename_suffix"),
			markerTransformsFilename,
			string("calibration_marker_transformations.xacro"));
	nh.param(string("camera_intrnsics_filename"), cameraIntrnsicsFilename,
			string("nao_bottom_640x480.yaml"));

	ModelLoader modelLoader;
	modelLoader.initializeFromRos();

	urdf::Model model;
	modelLoader.getUrdfModel(model);

	// get the robot name and prepend to the filenames
	string filePrefix = model.getName();
	jointOffsetsFilename = filePrefix + "_" + jointOffsetsFilename;
	cameraTransformFilename = filePrefix + "_" + cameraTransformFilename;
	urdfFilename = filePrefix + "_" + urdfFilename;
	markerTransformsFilename = filePrefix + "_" + markerTransformsFilename;

    Subscriber sub = nh.subscribe("/onlineCalibration/calibration_result",
			1, resultCb);
	spin();
	return 0;
}
int main(int argc, char **argv)
{
    // set window values
    win.width = 640;
    win.height = 480;
    win.title = "OBJ Viewer Service";
    win.field_of_view_angle = 45;
    win.z_near = 1.0f;
    win.z_far = 500.0f;

    // initialize and run program
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_RGB | GLUT_SINGLE | GLUT_DEPTH );
    glutInitWindowSize(win.width,win.height);
    glutCreateWindow(win.title.c_str());
    glutDisplayFunc(display);
    glutIdleFunc( display );
    glutKeyboardFunc( keyboard );
    initialize();
    obj.loadFromFile("../models", "neuron.obj");
    glutMainLoop();
    return 0;
}
//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
void EffectImplemented::ReloadResources( const EFK_CHAR* materialPath )
{
	UnloadResources();

	const EFK_CHAR* matPath = materialPath != NULL ? materialPath : m_materialPath.c_str();
	
	Setting* loader = GetSetting();

	{
		TextureLoader* textureLoader = loader->GetTextureLoader();
		if( textureLoader != NULL )
		{
			for( int32_t ind = 0; ind < m_ImageCount; ind++ )
			{
				EFK_CHAR fullPath[512];
				PathCombine( fullPath, matPath, m_ImagePaths[ ind ] );
				m_pImages[ind] = textureLoader->Load( fullPath, TextureType::Color );
			}
		}
	}

	{
		TextureLoader* textureLoader = loader->GetTextureLoader();
		if (textureLoader != NULL)
		{
			for (int32_t ind = 0; ind < m_normalImageCount; ind++)
			{
				EFK_CHAR fullPath[512];
				PathCombine(fullPath, matPath, m_normalImagePaths[ind]);
				m_normalImages[ind] = textureLoader->Load(fullPath, TextureType::Normal);
			}
		}

	}
		{
			TextureLoader* textureLoader = loader->GetTextureLoader();
			if (textureLoader != NULL)
			{
				for (int32_t ind = 0; ind < m_distortionImageCount; ind++)
				{
					EFK_CHAR fullPath[512];
					PathCombine(fullPath, matPath, m_distortionImagePaths[ind]);
					m_distortionImages[ind] = textureLoader->Load(fullPath, TextureType::Distortion);
				}
			}
		}

	

	{
		SoundLoader* soundLoader = loader->GetSoundLoader();
		if( soundLoader != NULL )
		{
			for( int32_t ind = 0; ind < m_WaveCount; ind++ )
			{
				EFK_CHAR fullPath[512];
				PathCombine( fullPath, matPath, m_WavePaths[ ind ] );
				m_pWaves[ind] = soundLoader->Load( fullPath );
			}
		}
	}

	{
		ModelLoader* modelLoader = loader->GetModelLoader();
		
		if( modelLoader != NULL )
		{
			for( int32_t ind = 0; ind < m_modelCount; ind++ )
			{
				EFK_CHAR fullPath[512];
				PathCombine( fullPath, matPath, m_modelPaths[ ind ] );
				m_pModels[ind] = modelLoader->Load( fullPath );
			}
		}
	}
}
Example #24
0
int main(int argc, char** argv)
{
	if (argc == 3 && strncmp(argv[1], "--convert", 9) == 0)
	{
		Configuration* config = new IniConfig(argv[2]);
		Heightmap* map = new Heightmap(config->getFloatValue("terrain","spacing"));
		if (map->loadFromImage(config->getValue("terrain","heightmap").c_str()))
		{
			std::cout << "Generating Terrain.." << std::endl;
			TerrainGenerator(map, config->getIntValue("terrain","chunksize"), config->getValue("out","filename").c_str());
			std::cout << "..done" << std::endl;
			std::cout.flush();
		}
		else
			std::cout << "Generation failed." << std::endl;
		return 0;
	}
	if (argc == 4 && strncmp(argv[1], "--load", 6) == 0)
	{
		int id = atoi(argv[3]);
		TerrainFileReader* reader = new TerrainFileReader();
		reader->openFile(argv[2]);

		TerrainChunk* tc = reader->readId(id);
		if (tc == NULL || tc->getInfo()->getQuadId() != id)
		{
			std::cout << "Got ID" << tc->getInfo()->getQuadId()
					<< " instead of " << id << std::endl;
			return 1;
		}
		else
		{
			std::cout << "Successfully got Terrainchunk " << id << std::endl;
			std::cout << "Spacing of Heightmap is "
					<< tc->getHeightmap()->getSpacing() << " where origin is "
					<< tc->getOrigin().x << "," << tc->getOrigin().y << " and center at "
					<< tc->getCenter().x << "," << tc->getCenter().y << std::endl;
		}
		reader->closeFile();
		delete tc;
		delete reader;
	}
	if (argc != 2 || strncmp(argv[1], "--run", 5) != 0)
	{
		std::cout << "Usage of '" << argv[0] << "'" <<std::endl;
		std::cout << "\nAvailable Parameter:"
				<< "\n\t--convert terrain.desc"
				<< "\n\t--load terrain.terr chunkid(=0)"
				<< "\n\t--run" << std::endl;
		return 1;
	}

	int width, height;
	Configuration * win_config = new IniConfig("config.ini");
	WindowHints* hints = new WindowHints();
	hints->Fullscreen = win_config->getBooleanValue("Window","fullscreen");
	hints->Width = win_config->getIntValue("Window","width");
	hints->Height = win_config->getIntValue("Window","height");
	GraphicsSystem* GSystem = new GraphicsSystem(GraphicsSystem::PROFILE_GL3,
			hints);
	if (GSystem->isError())
		return -1;
	GraphicsContext* grctx = GSystem->getGraphicsContext();
	Window* win = GSystem->getWindow();
	TextureManager* tmgr = new TextureManager(grctx);
	ModelLoader* mmgr = new ModelLoader(grctx, tmgr);
	TerrainManager* terrmgr = new TerrainManager(grctx);
	Model* mdl, *mdl2;
	Camera* cam = new Camera();
	win->getSize(&width, &height);
	cam->setScreen(width,height);
	cam->setupLens(65.0f, 1.0f, 1000.0f);

	if ((mdl = mmgr->loadAsset("Resources/Models/ant01.ms3d")) == NULL)
		std::cerr << "Could not load Model" << std::endl;
	if ((mdl2 = mmgr->loadAsset("Resources/Models/dwarf1.ms3d")) == NULL)
		std::cerr << "Could not load Model" << std::endl;
	ModelAnimationController mdlanictrl(mdl), mdlanictrl2(mdl2);
	mdlanictrl.addAnimation("idle", 52, 67, 0.25f, true);
	mdlanictrl.addAnimation("die", 30, 49, 0.25f, false);
	mdlanictrl2.addAnimation("begin_walk", 1, 2, 0.25f, false, "walk");
	mdlanictrl2.addAnimation("walk", 2, 14, 0.25f, true);
	mdlanictrl2.addAnimation("jump", 28, 40, 0.5f, false, "begin_walk");
	mdlanictrl2.addAnimation("idle", 292, 325, 0.25f, false, "idle2");
	mdlanictrl2.addAnimation("idle2", 327, 360, 0.25f, true);
	mdlanictrl2.addAnimation("die", 230, 251, 0.25f, false);
	std::cout << "Using DesktopMode: " << width << "x" << height << std::endl;
	win->setTitle("Xng?! -> Yeah!");

	Shader* sh = grctx->createShader();
	if (!sh->loadFromFile("Shader/Animation.vs", "Shader/Animation.fs"))
		return 1;

	Shader* tsh = grctx->createShader();
	if (!tsh->loadFromFile("Shader/Terrain.vs", "Shader/Terrain.fs"))
			return 1;

	Timer* t = new Timer();
	double frames = 0;

	grctx->setClearColor(glm::vec4(1.0f, 0.5f, 0.25f, 1.0f));
	t->start();

	Terrain* terr = terrmgr->loadAsset("Resources/terrain/terrain.terr");
	terr->setDetail(0.05f,cam);

	glm::mat4 mdlm = glm::scale(
			glm::translate(glm::mat4(1.0f), glm::vec3(5.0f, -5.0f, -20.0f)),
			glm::vec3(0.5f));
	glm::mat4 mdlm2 = glm::scale(
			glm::translate(glm::mat4(1.0f), glm::vec3(-5.0f, -5.0f, -20.0f)),
			glm::vec3(0.18f));
	mdlm = glm::rotate(mdlm, 180.0f, glm::vec3(0.0f, 1.0f, 0.0f));
	mdlm2 = glm::rotate(mdlm2, 180.0f, glm::vec3(0.0f, 1.0f, 0.0f));
	glm::vec3 cam_pos = glm::vec3(0.0f,0.0f,0.0f);
	glm::quat cam_orient = glm::quat();
	float speed = 0.0f;

	float deltaTime = 0;
	float second = t->getMilli();
	float lastTime = second;

	while (win->isOpen())
	{
		second = t->getMilli();
		deltaTime = second - lastTime;
		lastTime = second;
		if (glfwGetKey(GLFW_KEY_ESC))
			break;
		if (glfwGetKey(GLFW_KEY_SPACE))
			mdlanictrl2.setActiveAnimation("jump");
		if (glfwGetKey('W'))
			mdlanictrl2.setActiveAnimation("begin_walk");
		if (glfwGetKey('S'))
			mdlanictrl2.setActiveAnimation("idle");
		if (glfwGetKey('F'))
			mdlanictrl.setActiveAnimation("die");
		if (glfwGetKey('G'))
			mdlanictrl2.setActiveAnimation("die");
		if (glfwGetKey('A'))
			mdlm2 = glm::rotate(mdlm2, -0.3f, glm::vec3(0.0f, 1.0f, 0.0f));
		if (glfwGetKey('D'))
			mdlm2 = glm::rotate(mdlm2, 0.3f, glm::vec3(0.0f, 1.0f, 0.0f));
		if( glfwGetKey(GLFW_KEY_LSHIFT) || glfwGetKey(GLFW_KEY_RSHIFT))
			speed = 1.0f;
		else speed = 0.1f;
		if (glfwGetKey('I'))
			cam_pos += glm::cross(cam->getUpVector(),cam->getRightVector()) * speed * deltaTime;
		if (glfwGetKey('K'))
			cam_pos -= glm::cross(cam->getUpVector(),cam->getRightVector()) * speed * deltaTime;
		if (glfwGetKey('J'))
			cam_pos -= cam->getRightVector() * speed * deltaTime;
		if (glfwGetKey('L'))
			cam_pos += cam->getRightVector() * speed * deltaTime;
		if (glfwGetKey('O'))
			cam_pos += cam->getUpVector() * speed * deltaTime;
		if (glfwGetKey('P'))
			cam_pos -= cam->getUpVector() * speed * deltaTime;
		if(glfwGetKey(GLFW_KEY_LEFT))
			cam_orient = glm::rotate(cam_orient,speed * deltaTime,glm::vec3(0.0f,1.0f,0.0f));
		if(glfwGetKey(GLFW_KEY_RIGHT))
			cam_orient =glm::rotate(cam_orient,-speed * deltaTime,glm::vec3(0.0f,1.0f,0.0f));
		if(glfwGetKey(GLFW_KEY_UP))
			cam_orient = glm::rotate(cam_orient,speed * deltaTime,glm::vec3(1.0f,0.0f,0.0f));
		if(glfwGetKey(GLFW_KEY_DOWN))
			cam_orient = glm::rotate(cam_orient,-speed * deltaTime,glm::vec3(1.0f,0.0f,0.0f));
		cam_pos.y = terr->getHeightAt(cam_pos.x,cam_pos.z) + 5;
		cam->setPosition(cam_pos);
		cam->setOrientation(cam_orient);
		mdlanictrl.update(deltaTime);
		mdlanictrl2.update(deltaTime);
		grctx->clearDisplay();
		grctx->setShader(sh);

		grctx->setProjectionMatrix(cam->getLens());
		grctx->setViewMatrix(cam->getView());
		grctx->setModelMatrix(&mdlm);
		for (int i = 0; i < mdl->getNumMeshes(); i++)
		{
			grctx->setMesh(mdl->getMesh(i));
			grctx->setMaterial(mdl->getMaterial(mdl->getMesh(i)->getMaterialId()));
			grctx->setBoneTransformation(mdlanictrl.getBoneTransformation(), mdlanictrl.getNumBones());

			grctx->draw();
		}

		grctx->setModelMatrix(&mdlm2);
		for (int i = 0; i < mdl2->getNumMeshes(); i++)
		{
			grctx->setMesh(mdl2->getMesh(i));
			grctx->setMaterial(mdl2->getMaterial(mdl2->getMesh(i)->getMaterialId()));
			grctx->setBoneTransformation(mdlanictrl2.getBoneTransformation(), mdlanictrl2.getNumBones());
			grctx->draw();
		}

		grctx->setShader(tsh);
		grctx->setProjectionMatrix(cam->getLens());
		grctx->setViewMatrix(cam->getView());
		terr->selectNodes(cam);

		grctx->swapBuffers();
		frames++;
	}
	t->end();

	delete sh;

	mmgr->removeAsset("Resources/Models/dwarf1.ms3d");
	mmgr->removeAsset("Resources/Models/ant01.ms3d");
	std::cout << "TpF: " << t->getLastMilli() / frames << " mspf was " << frames
			<< " Frames in " << t->getLastMilli() << "ms or "
			<< frames / t->getLastSecond() << "fps" << std::endl;
	delete mmgr;
	delete tmgr;
	delete t;
	delete GSystem;

	return 0;
}
Example #25
0
int main()
{
	// Create and initialize window.
	setErrorCallbackAndInit(error_callback);
	GraphicsWindow* window = new GraphicsWindow(1200,800,"Test Window",NULL,NULL,key_callback);
	window->makeContextCurrent();

	// Initalize glew.
	initGlew();

	// Create and initialize Camera
	FreeCamera* camera = new FreeCamera(45.0f, 16.0f/9.0f, 
					0.0f, 0.0f, 
					0.1f, 10000.0f, 
					0.0004f, 3.0f,
					glm::vec3(0,0,-50), 
					glm::vec3(0,1,0), 
					glm::vec3(0,0,0), 
					true);

	camera->setViewport(window->getWindowWidth(),window->getWindowHeight(),0.5f,0.5f);

	// Load accumulation shader for accumulating all the transparent matrials, as well as their alphas.
	GLSLProgram* defaultShader = new GLSLProgram();
	defaultShader->initShaderProgram("Vert.glsl","","","","Frag.glsl");

	// Load screen filling quad shader.
	GLSLProgram* screenFillingQuadShader = new GLSLProgram();
	screenFillingQuadShader->initShaderProgram("screenFillingQuadVert.glsl","","","","screenFillingQuadFrag.glsl");

	// Load accumulation shader for accumulating all the transparent matrials, as well as their alphas.
	GLSLProgram* accumTransparencyRevealageShader = new GLSLProgram();
	accumTransparencyRevealageShader->initShaderProgram("AccumTransparencyRevealageVert.glsl","","","","AccumTransparencyRevealageFrag.glsl");

	// Load Weighted Average shader, which will be used for final compositing (a variation of screen filling quad shader using multiple textures).
	GLSLProgram* newOITCoverageShader = new GLSLProgram();
	newOITCoverageShader->initShaderProgram("NewOITCoverageVert.glsl","","","","NewOITCoverageFrag.glsl");

	// Create screen filling quad.
	Quad* screenFillingQuad = new Quad(glm::vec3(-1.0,1.0,0), glm::vec3(-1.0,-1.0,0), glm::vec3(1.0,-1.0,0), glm::vec3(1.0,1.0,0), glm::vec3(0), 0, 0, 0);
	
	screenFillingQuad->initQuad();
	screenFillingQuad->setGLSLProgram(*newOITCoverageShader);

	TextureManager::GetInstance().loadTexture("../Content/Textures/Particle_Smoke/smoke_particle_red_base.png");
	TextureManager::GetInstance().loadTexture("../Content/Textures/Particle_Smoke/smoke_particle_grey_base_2.png");
	TextureManager::GetInstance().loadTexture("../Content/Textures/Particle_Smoke/smoke_particle_grey_base_3.png");

	Quad* quad1 = new Quad(glm::vec3(100+100,100+100,-1), glm::vec3(100+100,-100+100,-1), glm::vec3(-100+100,-100+100,-1), glm::vec3(-100+100,100+100,-1), glm::vec3(0), 10, 10, 0);
	quad1->initQuad();
	quad1->initDefaultTexture(255,0,0,89);
	quad1->setTexture(TextureManager::GetInstance().getTextureHandle("../Content/Textures/Particle_Smoke/smoke_particle_grey_base_3.png"));

	Quad* quad2 = new Quad(glm::vec3(100+100,100+100,-20), glm::vec3(100+100,-100+100,-20), glm::vec3(-100+100,-100+100,-20), glm::vec3(-100+100,100+100,-20), glm::vec3(0), 10, 10, 0);
	quad2->initQuad();
	quad2->initDefaultTexture(0,255,0,89);
	quad2->setTexture(TextureManager::GetInstance().getTextureHandle("../Content/Textures/Particle_Smoke/smoke_particle_grey_base_2.png"));

	Quad* quad3 = new Quad(glm::vec3(100+100,100+100,20), glm::vec3(100+100,-100+100,20), glm::vec3(-100+100,-100+100,20), glm::vec3(-100+100,100+100,20), glm::vec3(0), 10, 10, 0);
	quad3->initQuad();
	quad3->initDefaultTexture(0,0,255,89);
	quad3->setTexture(TextureManager::GetInstance().getTextureHandle("../Content/Textures/Particle_Smoke/smoke_particle_red_base.png"));

	Quad* quad4 = new Quad(glm::vec3(100+100,100+100,-40), glm::vec3(100+100,-100+100,-40), glm::vec3(-100+100,-100+100,-40), glm::vec3(-100+100,100+100,-40), glm::vec3(0), 10, 10, 0);
	quad4->initQuad();
	quad4->initDefaultTexture(255,0,127,50);

	Quad* quad5 = new Quad(glm::vec3(100+100,100+100,40), glm::vec3(100+100,-100+100,40), glm::vec3(-100+100,-100+100,40), glm::vec3(-100+100,100+100,40), glm::vec3(0), 10, 10, 0);
	quad5->initQuad();
	quad5->initDefaultTexture(255,127,0,50);

	ModelLoader* modelImporter = new ModelLoader();
	modelImporter->importModel("../Content/Models/crytek-sponza/sponza.obj", processFlagsOnModelImport);

	// Create and initialize model
	Model* model = new Model(glm::vec3(0,0,0), "../Content/Models/crytek-sponza/");
	model->loadModel(modelImporter->getScene());

	// Create framebuffers
	std::vector<unsigned int> activeColorAttachmentsOpaque;
	std::vector<unsigned int> activeColorAttachmentsTransparent;

	Framebuffer* opaqueFrameBuffer = new Framebuffer(window->getWindowWidth(),window->getWindowHeight());
	
	activeColorAttachmentsOpaque.push_back(0);

	opaqueFrameBuffer->setColorAttachment(0);

	//frameBuffer->setDepthAttachment();
	opaqueFrameBuffer->setDepthStencilTexture();

	opaqueFrameBuffer->unbind();

	Framebuffer* accumFrameBuffer = new Framebuffer(window->getWindowWidth(),window->getWindowHeight());
	
	activeColorAttachmentsTransparent.push_back(0);
	activeColorAttachmentsTransparent.push_back(1);

	accumFrameBuffer->setColorAttachment(0);
	accumFrameBuffer->setColorAttachment(1);

	//frameBuffer->setDepthAttachment();
	accumFrameBuffer->setDepthStencilTexture();

	accumFrameBuffer->unbind();

	// Additional textures to pass for the second transparency render pass.
	std::vector<GLuint> additionalTextureHandles;
	additionalTextureHandles.push_back(accumFrameBuffer->getColorAttachment(0));
	additionalTextureHandles.push_back(accumFrameBuffer->getColorAttachment(1));

	std::vector<GLuint> opaqueTextureHandle;
	opaqueTextureHandle.push_back(opaqueFrameBuffer->getColorAttachment(0));

	// Move this to "GraphicsWindow" 
	glfwSetCursorPos(window->getWindowHandle(), (double) (window->getWindowWidth()/2.0), (double) (window->getWindowHeight()/2.0));
	
	// Move this to "Camera"
	//glClearColor(0.4f,0.6f,0.94f,0.0f);
	glClearColor(0.0f,0.0f,0.0f,0.0f);

	const float clearColorWhite = 1.0f;
	const float clearColorBlack = 0.0f;

	// Sampler
	GLuint sampler = 0;
	glGenSamplers(1, &sampler);

	glSamplerParameteri(sampler, GL_TEXTURE_WRAP_S, GL_REPEAT);  
	glSamplerParameteri(sampler, GL_TEXTURE_WRAP_T, GL_REPEAT);
	glSamplerParameteri(sampler, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
	glSamplerParameteri(sampler, GL_TEXTURE_MIN_FILTER, GL_NEAREST);

	check_gl_error();

	// Render Loop
	while(!window->shouldClose())
	{
		//glClearColor(0.0f,0.0f,0.0f,0.0f);
		glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);

		glEnable(GL_DEPTH_TEST);
		glDepthFunc(GL_LEQUAL);
		glEnable(GL_CULL_FACE);
		glCullFace(GL_BACK);

		// Update camera
		camera->camControll(window->getWindowHandle());
		camera->update();
		
		// Update shader uniforms
		model->getCurrentGLSLProgram()->use();
		model->getCurrentGLSLProgram()->setUniform("lightPosition", camera->getCamPos());
		model->getCurrentGLSLProgram()->setUniform("camPosition", camera->getCamPos());
		model->getCurrentGLSLProgram()->setUniform("viewMatrix", camera->getVMatrix());
		model->getCurrentGLSLProgram()->setUniform("normalMatrix", camera->getTranspInvMVMatrix()); // Change this!
		model->getCurrentGLSLProgram()->setUniform("VPMatrix", camera->getVPMatrix());

		opaqueFrameBuffer->clean();
		opaqueFrameBuffer->bind();
		opaqueFrameBuffer->bindForRenderPass(activeColorAttachmentsOpaque);

		model->renderOpaque();
		//quad4->render();
		//quad5->render();

		//opaqueFrameBuffer->unbind();

		//// Blitting the opaque scene depth to propperly depth test the transparen against it.
		//opaqueFrameBuffer->bindForReading();

		//accumFrameBuffer->bindForWriting();
		//glBlitFramebuffer(0, 0, window->getWindowWidth(), window->getWindowHeight(), 0, 0, window->getWindowWidth(), window->getWindowHeight(), 
		//				  GL_DEPTH_BUFFER_BIT, GL_NEAREST);

		//opaqueFrameBuffer->unbind();

		//_______________________________________________________________________________________________________________________________________________________________________________
		// Acuumulation pass
		accumTransparencyRevealageShader->use();
		accumTransparencyRevealageShader->setUniform("VPMatrix", camera->getVPMatrix());

		model->setGLSLProgram(accumTransparencyRevealageShader);
		quad1->setGLSLProgram(*accumTransparencyRevealageShader);
		quad2->setGLSLProgram(*accumTransparencyRevealageShader);
		quad3->setGLSLProgram(*accumTransparencyRevealageShader);
		quad4->setGLSLProgram(*accumTransparencyRevealageShader);
		quad5->setGLSLProgram(*accumTransparencyRevealageShader);

		accumFrameBuffer->clean();
		accumFrameBuffer->bind();
		accumFrameBuffer->bindForRenderPass(activeColorAttachmentsTransparent);
		accumFrameBuffer->cleanColorAttachment(1,clearColorWhite);

		opaqueFrameBuffer->unbind();

		// Blitting the opaque scene depth to propperly depth test the transparen against it.
		opaqueFrameBuffer->bindForReading();

		accumFrameBuffer->bindForWriting();
		glBlitFramebuffer(0, 0, window->getWindowWidth(), window->getWindowHeight(), 0, 0, window->getWindowWidth(), window->getWindowHeight(), 
						  GL_DEPTH_BUFFER_BIT, GL_NEAREST);

		opaqueFrameBuffer->unbind();

		accumFrameBuffer->bind();
		accumFrameBuffer->bindForRenderPass(activeColorAttachmentsTransparent);

		glEnable(GL_BLEND);
		glBlendFunci(0, GL_ONE, GL_ONE);
		glBlendFunci(1, GL_ZERO, GL_ONE_MINUS_SRC_ALPHA);
		//glEnable(GL_DEPTH_TEST);
		glDepthMask(GL_FALSE);
		glDisable(GL_CULL_FACE);

		model->renderTransparent();
		quad1->render();
		quad2->render();
		quad3->render();
		//quad4->render();
		//quad5->render();

		accumFrameBuffer->unbind();

		model->setGLSLProgram(defaultShader);
		quad1->setGLSLProgram(*defaultShader);
		quad2->setGLSLProgram(*defaultShader);
		quad3->setGLSLProgram(*defaultShader);
		quad4->setGLSLProgram(*defaultShader);
		quad5->setGLSLProgram(*defaultShader);

		glDisable(GL_BLEND);
		//glEnable(GL_DEPTH_TEST);
		glDepthMask(GL_TRUE);
		glEnable(GL_CULL_FACE);
		glCullFace(GL_BACK);

		//_______________________________________________________________________________________________________________________________________________________________________________
		// Final compositing pass

		//screenFillingQuad->setGLSLProgram(*screenFillingQuadShader);
		//screenFillingQuad->getCurrentShaderProgram()->use();
		//screenFillingQuad->renderWithAdditionalTextures(opaqueTextureHandle,sampler);

		newOITCoverageShader->use();

		glDepthMask(GL_FALSE);
		glEnable(GL_BLEND);
		glBlendFunc(GL_ONE_MINUS_SRC_ALPHA, GL_SRC_ALPHA);

		screenFillingQuad->renderWithAdditionalTextures(additionalTextureHandles,sampler);

		glDepthMask(GL_TRUE);
		glDisable(GL_BLEND);
		//_______________________________________________________________________________________________________________________________________________________________________________

		// For debug!
		//screenFillingQuad->setGLSLProgram(*screenFillingQuadShader);
		//screenFillingQuad->getCurrentShaderProgram()->use();
		//screenFillingQuad->setTexture(opaqueFrameBuffer->getColorAttachment(0));
		//screenFillingQuad->render();

		accumFrameBuffer->clean();

		window->swapBuffers();

		glfwPollEvents();

		check_gl_error();
	}

	glfwTerminate();
	window->release();
	
	return 0;
}
Example #26
0
Model::Model(ID3D11Device* device, TextureManager& texMgr, const std::string& modelFilename, const std::string& texturePath)
{
	//std::vector<M3dMaterial> mats;
	std::vector<MaterialLoader> mats;

	//M3DLoader m3dLoader;
	//m3dLoader.LoadM3d(modelFilename, Vertices, Indices, Subsets, mats);

	ModelLoader loader;
	loader.Load(modelFilename, Vertices, Indices, Subsets, mats, SkinnedData);



	ModelMesh.SetVertices(device, &Vertices[0], Vertices.size());
	ModelMesh.SetIndices(device, &Indices[0], Indices.size());
	ModelMesh.SetSubsetTable(Subsets);

	SubsetCount = mats.size();

	TPM = mats[0].DiffuseMapNames.size();
	for(UINT i = 0; i < SubsetCount; ++i)
	{
		Mat.push_back(mats[i].Mat);

		for (int j = 0; j < mats[i].DiffuseMapNames.size(); ++j)
		{
			if (mats[i].DiffuseMapNames[j] != "")
			{
				ID3D11ShaderResourceView* diffuseMapSRV = texMgr.CreateTexture(texturePath + mats[i].DiffuseMapNames[j]);
				if (diffuseMapSRV)
					DiffuseMapSRV.push_back(diffuseMapSRV);
			}
		}

		for (int j = 0; j < mats[i].NormalMapNames.size(); ++j)
		{
			if (mats[i].NormalMapNames[j] != "")
			{
				ID3D11ShaderResourceView* normalMapSRV = texMgr.CreateTexture(texturePath + mats[i].NormalMapNames[j]);
				if (normalMapSRV)
					NormalMapSRV.push_back(normalMapSRV);
			}
		}
		/*
		if (mats[i].DiffuseMapName != "")
		{
			ID3D11ShaderResourceView* diffuseMapSRV = texMgr.CreateTexture(texturePath + mats[i].DiffuseMapName);
			if (diffuseMapSRV)
				DiffuseMapSRV.push_back(diffuseMapSRV);
		}

		if (mats[i].NormalMapName != "")
		{
			ID3D11ShaderResourceView* normalMapSRV = texMgr.CreateTexture(texturePath + mats[i].NormalMapName);
			if (normalMapSRV)
				NormalMapSRV.push_back(normalMapSRV);
		}*/
	}
	
	m_BoneBoxes = SkinnedData.CreateBoneBoxes(Vertices);

	if (m_BoneBoxes.size() == 0)
	{
		//BoundingSphere::CreateFromPoints(m_BoundingSphere, Vertices.size(), &Vertices[0].Pos, sizeof(Vertex::PosNormalTexTanSkinned));

		BoundingBox AABB;
		BoundingBox::CreateFromPoints(AABB, Vertices.size(), &Vertices[0].Pos, sizeof(Vertex::PosNormalTexTanSkinned));

		BoundingOrientedBox::CreateFromBoundingBox(m_BoundingOrientedBox, AABB);

		XMFLOAT3 Extents = m_BoundingOrientedBox.Extents;
		m_SmallestRadiusInBox =	( Extents.x > Extents.z ) ? Extents.z : Extents.x;

		BoundingSphere::CreateFromBoundingBox(m_BoundingSphere, m_BoundingOrientedBox);
	}

	else
	{
		AnimationClip* AC = SkinnedData.GetAnimation("ALL");

		if (AC)
		{
			UINT numKeyFrames = AC->BoneAnimations[0].Keyframes.size();

			std::vector<XMFLOAT3> bigBoxPoints;
			m_SmallestRadiusInBox = 99999;
			for (int i = 0; i < numKeyFrames; ++i)
			{
				float time = AC->BoneAnimations[0].Keyframes[i].TimePos;

				std::vector<XMFLOAT4X4> FinalTransforms(AC->BoneAnimations.size());
				SkinnedData.GetFinalTransforms("ALL", time, FinalTransforms);

				std::vector<DirectX::BoundingOrientedBox>	tempboxes(m_BoneBoxes.size());
				for (int i = 0; i < m_BoneBoxes.size(); ++i)
				{
					m_BoneBoxes[i].Transform(tempboxes[i], XMLoadFloat4x4(&FinalTransforms[i]));
				}

				std::vector<XMFLOAT3> points;
				for (int i = 0; i < tempboxes.size(); ++i)
				{
					XMFLOAT3 corners[BoundingOrientedBox::CORNER_COUNT];
					tempboxes[i].GetCorners(&corners[0]);

					for each (XMFLOAT3 point in corners)
					{
						points.push_back(point);
						bigBoxPoints.push_back(point);
					}
				}
				BoundingBox AABB;
				BoundingBox::CreateFromPoints(AABB, points.size(), &points[0], sizeof(XMFLOAT3));

				XMFLOAT3 Extents = AABB.Extents;
				m_SmallestRadiusInBox = min(m_SmallestRadiusInBox, min(min(Extents.x, Extents.z), Extents.y));
			}

			BoundingBox AABB;
			BoundingBox::CreateFromPoints(AABB, bigBoxPoints.size(), &bigBoxPoints[0], sizeof(XMFLOAT3));

			BoundingOrientedBox::CreateFromBoundingBox(m_BoundingOrientedBox, AABB);
			BoundingSphere::CreateFromBoundingBox(m_BoundingSphere, m_BoundingOrientedBox);
		}

		
		//m_SmallestRadiusInBox = 10;
		/*
		BoundingSphere::CreateFromBoundingBox(m_BoundingSphere, m_BoundingOrientedBox);
		BoundingOrientedBox::CreateFromBoundingBox(m_BoundingOrientedBox, AABB);
		BoundingSphere::CreateFromBoundingBox(m_BoundingSphere, m_BoundingOrientedBox);
		*/
	}
Example #27
0
void GeometryReader::run() {
    DependencyManager::get<StatTracker>()->decrementStat("PendingProcessing");
    CounterStat counter("Processing");
    PROFILE_RANGE_EX(resource_parse_geometry, "GeometryReader::run", 0xFF00FF00, 0, { { "url", _url.toString() } });
    auto originalPriority = QThread::currentThread()->priority();
    if (originalPriority == QThread::InheritPriority) {
        originalPriority = QThread::NormalPriority;
    }
    QThread::currentThread()->setPriority(QThread::LowPriority);
    Finally setPriorityBackToNormal([originalPriority]() {
        QThread::currentThread()->setPriority(originalPriority);
    });

    if (!_resource.data()) {
        return;
    }

    try {
        if (_data.isEmpty()) {
            throw QString("reply is NULL");
        }

        // Ensure the resource has not been deleted
        auto resource = _resource.toStrongRef();
        if (!resource) {
            qCWarning(modelnetworking) << "Abandoning load of" << _url << "; could not get strong ref";
            return;
        }

        if (_url.path().isEmpty()) {
            throw QString("url is invalid");
        }

        HFMModel::Pointer hfmModel;
        QVariantHash serializerMapping = _mapping.second;
        serializerMapping["combineParts"] = _combineParts;
        serializerMapping["deduplicateIndices"] = true;

        if (_url.path().toLower().endsWith(".gz")) {
            QByteArray uncompressedData;
            if (!gunzip(_data, uncompressedData)) {
                throw QString("failed to decompress .gz model");
            }
            // Strip the compression extension from the path, so the loader can infer the file type from what remains.
            // This is okay because we don't expect the serializer to be able to read the contents of a compressed model file.
            auto strippedUrl = _url;
            strippedUrl.setPath(_url.path().left(_url.path().size() - 3));
            hfmModel = _modelLoader.load(uncompressedData, serializerMapping, strippedUrl, "");
        } else {
            hfmModel = _modelLoader.load(_data, serializerMapping, _url, _webMediaType.toStdString());
        }

        if (!hfmModel) {
            throw QString("unsupported format");
        }

        if (hfmModel->meshes.empty() || hfmModel->joints.empty()) {
            throw QString("empty geometry, possibly due to an unsupported model version");
        }

        // Add scripts to hfmModel
        if (!serializerMapping.value(SCRIPT_FIELD).isNull()) {
            QVariantList scripts = serializerMapping.values(SCRIPT_FIELD);
            for (auto &script : scripts) {
                hfmModel->scripts.push_back(script.toString());
            }
        }

        // Do processing on the model
        baker::Baker modelBaker(hfmModel, _mapping.second, _mapping.first);
        modelBaker.run();

        auto processedHFMModel = modelBaker.getHFMModel();
        auto materialMapping = modelBaker.getMaterialMapping();

        QMetaObject::invokeMethod(resource.data(), "setGeometryDefinition",
                Q_ARG(HFMModel::Pointer, processedHFMModel), Q_ARG(MaterialMapping, materialMapping));
    } catch (const std::exception&) {
        auto resource = _resource.toStrongRef();
        if (resource) {
            QMetaObject::invokeMethod(resource.data(), "finishedLoading",
                Q_ARG(bool, false));
        }
    } catch (QString& e) {
        qCWarning(modelnetworking) << "Exception while loading model --" << e;
        auto resource = _resource.toStrongRef();
        if (resource) {
            QMetaObject::invokeMethod(resource.data(), "finishedLoading",
                                      Q_ARG(bool, false));
        }
    }
}
void testFwdKinConsistency(std::string modelFilePath)
{
    std::cout << "Testing " << modelFilePath << std::endl;


    // Load iDynTree model and compute a default traversal
    ModelLoader loader;
    loader.loadModelFromFile(modelFilePath);
    iDynTree::Model model = loader.model();
    iDynTree::Traversal traversal;
    model.computeFullTreeTraversal(traversal);

    // Load KDL tree
    KDL::Tree tree;
    treeFromUrdfFile(modelFilePath,tree);
    KDL::CoDyCo::UndirectedTree undirected_tree(tree);
    KDL::CoDyCo::Traversal kdl_traversal;
    undirected_tree.compute_traversal(kdl_traversal);

    // A KDL::Tree only supports 0 and 1 DOFs joints, and
    // KDL::Tree::getNrOfJoints does not count the 0 dof joints, so
    // it is actually equivalent to iDynTree::Model::getNrOfDOFs
    ASSERT_EQUAL_DOUBLE(tree.getNrOfJoints(),model.getNrOfDOFs());

    // Input : joint positions and base position with respect to world
    iDynTree::FreeFloatingPos baseJntPos(model);
    iDynTree::FreeFloatingVel baseJntVel(model);
    iDynTree::FreeFloatingAcc baseJntAcc(model);

    baseJntPos.worldBasePos() =  getRandomTransform();
    baseJntVel.baseVel() = getRandomTwist();
    baseJntAcc.baseAcc() =  getRandomTwist();

    for(unsigned int jnt=0; jnt < baseJntPos.getNrOfPosCoords(); jnt++)
    {
        baseJntPos.jointPos()(jnt) = getRandomDouble();
        baseJntVel.jointVel()(jnt) = getRandomDouble();
        baseJntAcc.jointAcc()(jnt) = getRandomDouble();
    }


    // Build a map between KDL joints and iDynTree joints because we are not sure
    // that the joint indices will match
    std::vector<int> kdl2idyntree_joints;
    kdl2idyntree_joints.resize(undirected_tree.getNrOfDOFs());

    for(unsigned int dofIndex=0; dofIndex < undirected_tree.getNrOfDOFs(); dofIndex++)
    {
        std::string dofName = undirected_tree.getJunction(dofIndex)->getName();
        int idyntreeJointIndex = model.getJointIndex(dofName);
        kdl2idyntree_joints[dofIndex] = idyntreeJointIndex;
    }


    KDL::JntArray jntKDL(undirected_tree.getNrOfDOFs());
    KDL::JntArray jntVelKDL(undirected_tree.getNrOfDOFs());
    KDL::JntArray jntAccKDL(undirected_tree.getNrOfDOFs());

    KDL::Frame  worldBaseKDL;
    KDL::Twist  baseVelKDL;
    KDL::Twist  baseAccKDL;

    ToKDL(baseJntPos,worldBaseKDL,jntKDL,kdl2idyntree_joints);
    ToKDL(baseJntVel,baseVelKDL,jntVelKDL,kdl2idyntree_joints);
    ToKDL(baseJntAcc,baseAccKDL,jntAccKDL,kdl2idyntree_joints);

    // Output : link (for iDynTree) or frame positions with respect to world
    std::vector<KDL::Frame> framePositions(undirected_tree.getNrOfLinks());

    iDynTree::LinkPositions linkPositions(model);


    // Build a map between KDL links and iDynTree links because we are not sure
    // that the link indices will match
    std::vector<int> idynTree2KDL_links;
    idynTree2KDL_links.resize(model.getNrOfLinks());

    for(unsigned int linkIndex=0; linkIndex < model.getNrOfLinks(); linkIndex++)
    {
        std::string linkName = model.getLinkName(linkIndex);
        int kdlLinkIndex = undirected_tree.getLink(linkName)->getLinkIndex();
        idynTree2KDL_links[linkIndex] = kdlLinkIndex;
    }

    // Compute position forward kinematics with old KDL code and with the new iDynTree code
    KDL::CoDyCo::getFramesLoop(undirected_tree,
                               jntKDL,
                               kdl_traversal,
                               framePositions,
                               worldBaseKDL);

    ForwardPositionKinematics(model,traversal,baseJntPos,linkPositions);

    // Check results
    for(unsigned int travEl = 0; travEl  < traversal.getNrOfVisitedLinks(); travEl++)
    {
        LinkIndex linkIndex = traversal.getLink(travEl)->getIndex();
        ASSERT_EQUAL_TRANSFORM_TOL(linkPositions(linkIndex),ToiDynTree(framePositions[idynTree2KDL_links[linkIndex]]),1e-1);
    }

    // Compution velocity & acceleration kinematics
    std::vector<KDL::Twist> kdlLinkVel(undirected_tree.getNrOfLinks());
    std::vector<KDL::Twist> kdlLinkAcc(undirected_tree.getNrOfLinks());
    KDL::CoDyCo::rneaKinematicLoop(undirected_tree,jntKDL,jntVelKDL,jntAccKDL,kdl_traversal,
                                                   baseVelKDL,baseAccKDL,kdlLinkVel,kdlLinkAcc);

    iDynTree::LinkVelArray linksVels(model);
    iDynTree::LinkAccArray linksAcc(model);

    ForwardVelAccKinematics(model,traversal,baseJntPos,baseJntVel,baseJntAcc,linksVels,linksAcc);

    // Check results
    for(unsigned int travEl = 0; travEl  < traversal.getNrOfVisitedLinks(); travEl++)
    {
        LinkIndex linkIndex = traversal.getLink(travEl)->getIndex();

        ASSERT_EQUAL_VECTOR(linksVels(linkIndex).asVector(),
                            ToiDynTree(kdlLinkVel[idynTree2KDL_links[linkIndex]]).asVector());
        ASSERT_EQUAL_VECTOR(linksAcc(linkIndex).asVector(),
                            ToiDynTree(kdlLinkAcc[idynTree2KDL_links[linkIndex]]).asVector());
    }

    // Compute position, velocity and acceleration
    LinkPositions linksPos_check(model);
    iDynTree::LinkVelArray linksVels_check(model);
    iDynTree::LinkAccArray linksAcc_check(model);

    ForwardPosVelAccKinematics(model,traversal,baseJntPos, baseJntVel, baseJntAcc,
                               linksPos_check,linksVels_check,linksAcc_check);

    for(unsigned int travEl = 0; travEl  < traversal.getNrOfVisitedLinks(); travEl++)
    {
        LinkIndex linkIndex = traversal.getLink(travEl)->getIndex();
        ASSERT_EQUAL_TRANSFORM(linkPositions(linkIndex),
                               linksPos_check(linkIndex));
        ASSERT_EQUAL_VECTOR(linksVels(linkIndex).asVector(),
                            linksVels_check(linkIndex).asVector());
        ASSERT_EQUAL_VECTOR(linksAcc(linkIndex).asVector(),
                             linksAcc(linkIndex).asVector());
    }

    // Compute torques (i.e. inverse dynamics)
    LinkNetExternalWrenches fExt(model);
    LinkInternalWrenches f(model);
    FreeFloatingGeneralizedTorques baseWrenchJointTorques(model);
    KDL::JntArray jntTorques(model.getNrOfDOFs());
    KDL::Wrench   baseWrench;

    std::vector<KDL::Wrench> fExtKDL(undirected_tree.getNrOfLinks());
    std::vector<KDL::Wrench> fKDL(undirected_tree.getNrOfLinks());

    // First set to zero all the fExtKDL, fKDL wrenches : then
    // the following loop will set the one that correspond to "real"
    // iDynTree links to the same value we used in iDynTree
    for(unsigned int linkKDL = 0; linkKDL < undirected_tree.getNrOfLinks(); linkKDL++)
    {
        fKDL[linkKDL]    = KDL::Wrench::Zero();
        fExtKDL[linkKDL] = KDL::Wrench::Zero();
    }

    for(unsigned int link = 0; link < model.getNrOfLinks(); link++ )
    {
        fExt(link) = getRandomWrench();
        fExtKDL[idynTree2KDL_links[link]] = ToKDL(fExt(link));
        fKDL[idynTree2KDL_links[link]] = KDL::Wrench::Zero();
    }

    bool ok = RNEADynamicPhase(model,traversal,
                               baseJntPos.jointPos(),
                               linksVels,linksAcc,fExt,f,baseWrenchJointTorques);

    int retVal = KDL::CoDyCo::rneaDynamicLoop(undirected_tree,jntKDL,kdl_traversal,
                                 kdlLinkVel,kdlLinkAcc,
                                 fExtKDL,fKDL,jntTorques,baseWrench);

    ASSERT_EQUAL_DOUBLE(ok,true);
    ASSERT_EQUAL_DOUBLE(retVal,0);

    /***
     * This check is commented out because KDL::CoDyCo::rneaDynamicLoop returned
     * a reverse baseWrench.. still need to be investigated.
     * (The - is necessary for consistency with the mass matrix..)
     *
     */
    //ASSERT_EQUAL_VECTOR(baseWrenchJointTorques.baseWrench().asVector(),
    //                    ToiDynTree(baseWrench).asVector());

    for(int link = 0; link < model.getNrOfLinks(); link++ )
    {
        ASSERT_EQUAL_VECTOR(f(link).asVector(),ToiDynTree(fKDL[idynTree2KDL_links[link]]).asVector());
    }

    for(int dof = 0; dof < model.getNrOfDOFs(); dof++ )
    {
        ASSERT_EQUAL_DOUBLE(jntTorques(dof),baseWrenchJointTorques.jointTorques()(kdl2idyntree_joints[dof]));
    }

    // Check mass matrix
    iDynTree::FreeFloatingMassMatrix massMatrix(model);
    iDynTree::LinkInertias crbis(model);
    ok = CompositeRigidBodyAlgorithm(model,traversal,
                                     baseJntPos.jointPos(),
                                     crbis,massMatrix);

    KDL::CoDyCo::FloatingJntSpaceInertiaMatrix massMatrixKDL(undirected_tree.getNrOfDOFs()+6);
    std::vector<KDL::RigidBodyInertia> Ic(undirected_tree.getNrOfLinks());

    retVal = KDL::CoDyCo::crba_floating_base_loop(undirected_tree,kdl_traversal,jntKDL,Ic,massMatrixKDL);

    ASSERT_IS_TRUE(ok);
    ASSERT_EQUAL_DOUBLE_TOL(retVal,0,1e-8);

    // Check composite rigid body inertias
    for(int link = 0; link < model.getNrOfLinks(); link++ )
    {
         ASSERT_EQUAL_MATRIX(crbis(link).asMatrix(),ToiDynTree(Ic[idynTree2KDL_links[link]]).asMatrix());
    }

    std::cerr << "iDynTree " << massMatrix.toString() << std::endl;
    std::cerr << "massMatrix " << massMatrixKDL.data << std::endl;


    // Check CRBA algorithm
    for(int ii=0; ii < model.getNrOfDOFs()+6; ii++ )
    {
        for( int jj=0; jj < model.getNrOfDOFs()+6; jj++ )
        {
            int idyntreeII = kdl2idyntreeFloatingDOFMapping(ii,kdl2idyntree_joints);
            int idyntreeJJ = kdl2idyntreeFloatingDOFMapping(jj,kdl2idyntree_joints);
            ASSERT_EQUAL_DOUBLE_TOL(massMatrix(idyntreeII,idyntreeJJ),massMatrixKDL(ii,jj),1e-8);
        }
    }

    return;
}
Example #29
0
void MyGLWidget::loadModel()
{
      // Lade die Modelle aus den Dateien in Datenstrukturen
      ModelLoader * model ;
      model = new ModelLoader() ;

      // Frosch
      bool res = model->loadObjectFromFile("Models/baby.obj");
      // Wenn erfolgreich, generiere VBO und Index-Array
      if (res) {
          // Frage zu erwartende Array-Längen ab
          vboLength[0] = model->lengthOfVBO(0,false,true);
          iboLength[0] = model->lengthOfIndexArray();
          // Generiere VBO und Index-Array
          vboData[0] = new GLfloat[vboLength[0]];
          indexData[0] = new GLuint[iboLength[0]];
          //model->genSimpleVBO(vboData[0]);
          model->genVBO(vboData[0],0,false,true);
          model->genIndexArray(indexData[0]);
      }
      else {
          // Modell konnte nicht geladen werden
          assert(0) ;
      }
      delete model ;

      // Planet
      model = new ModelLoader() ;
      //res = model->loadObjectFromFile("Models/sombrero.obj");
      res = model->loadObjectFromFile("Models/sphere_low.obj");
      // Wenn erfolgreich, generiere VBO und Index-Array
      if (res) {
          // Frage zu erwartende Array-Längen ab
          vboLength[1] = model->lengthOfVBO(0,false,true);
          iboLength[1] = model->lengthOfIndexArray();
          // Generiere VBO und Index-Array
          vboData[1] = new GLfloat[vboLength[1]];
          indexData[1] = new GLuint[iboLength[1]];
          model->genVBO(vboData[1],0,false,true);
          model->genIndexArray(indexData[1]);
      }
      else {
          // Modell konnte nicht geladen werden
          assert(0) ;
      }
      delete model ;

      // Sombrero
      model = new ModelLoader() ;
      res = model->loadObjectFromFile("Models/sombrero.obj");
      // Wenn erfolgreich, generiere VBO und Index-Array
      if (res) {
          // Frage zu erwartende Array-Längen ab
          vboLength[2] = model->lengthOfVBO(0,false,true);
          iboLength[2] = model->lengthOfIndexArray();
          // Generiere VBO und Index-Array
          vboData[2] = new GLfloat[vboLength[2]];
          indexData[2] = new GLuint[iboLength[2]];
          model->genVBO(vboData[2],0,false,true);
          model->genIndexArray(indexData[2]);
      }
      else {
          // Modell konnte nicht geladen werden
          assert(0) ;
      }
      delete model ;

      // Sombrero
      model = new ModelLoader() ;
      res = model->loadObjectFromFile("Models/sword.obj");
      // Wenn erfolgreich, generiere VBO und Index-Array
      if (res) {
          // Frage zu erwartende Array-Längen ab
          vboLength[3] = model->lengthOfVBO(0,false,true);
          iboLength[3] = model->lengthOfIndexArray();
          // Generiere VBO und Index-Array
          vboData[3] = new GLfloat[vboLength[3]];
          indexData[3] = new GLuint[iboLength[3]];
          model->genVBO(vboData[3],0,false,true);
          model->genIndexArray(indexData[3]);
      }
      else {
          // Modell konnte nicht geladen werden
          assert(0) ;
      }
      delete model ;

      // Sombrero
      model = new ModelLoader() ;
     //res = model->loadObjectFromFile("Models/vikinghelmet.obj");
      res = model->loadObjectFromFile("Models/Porygon.obj");
      // Wenn erfolgreich, generiere VBO und Index-Array
      if (res) {
          // Frage zu erwartende Array-Längen ab
          vboLength[4] = model->lengthOfVBO(0,false,true);
          iboLength[4] = model->lengthOfIndexArray();
          // Generiere VBO und Index-Array
          vboData[4] = new GLfloat[vboLength[4]];
          indexData[4] = new GLuint[iboLength[4]];
          model->genVBO(vboData[4],0,false,true);
          model->genIndexArray(indexData[4]);
      }
      else {
          // Modell konnte nicht geladen werden
          assert(0) ;
      }
      delete model ;

}
Example #30
0
int PASCAL WinMain(HINSTANCE hInstance, HINSTANCE /*hPrevInstance*/,
				   LPSTR lpCmdLine, int nCmdShow)
{
	ModelLoader* modelLoader;
	bool screenSaver = isScreenSaver();
	int retValue;
	STARTUPINFO startupInfo;
	bool fromConsole = false;

	//HMODULE hThumbs = LoadLibrary("LDViewThumbs.dll");
	//if (hThumbs != NULL)
	//{
	//	PFNDLLREGISTERSERVER pDllRegisterServer =
	//		(PFNDLLREGISTERSERVER)GetProcAddress(hThumbs, "DllRegisterServer");

	//	CoInitialize(NULL);
	//	if (pDllRegisterServer != NULL)
	//	{
	//		pDllRegisterServer();
	//	}
	//}
	memset(&startupInfo, 0, sizeof(startupInfo));
	startupInfo.cb = sizeof(startupInfo);
	GetStartupInfo(&startupInfo);
	if (startupInfo.lpTitle != NULL &&
		stringHasCaseInsensitivePrefix(startupInfo.lpTitle, "command line ")
		&& strcasestr(startupInfo.lpTitle, "ldview") != NULL)
	{
		runningWithConsole();
		fromConsole = true;
	}
#ifdef _DEBUG
	int _debugFlag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
	_debugFlag |= _CRTDBG_LEAK_CHECK_DF;
	_CrtSetDbgFlag(_debugFlag);
	_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_DEBUG);
	if (!fromConsole)
	{
		createConsole();
	}
//	MessageBox(NULL, "Attach a debugger now...", "Debug", MB_OK);
#endif // _DEBUG
	bool udok = setupUserDefaults(lpCmdLine, screenSaver,
		isRemovableDrive(hInstance));
	setupLocalStrings();
	if (TCUserDefaults::boolForKey(DEBUG_COMMAND_LINE_KEY, false, false))
	{
		std::string message = "Command Line:\n";

		message += lpCmdLine;
		MessageBox(NULL, message.c_str(), "LDView", MB_OK);
	}
	if (!udok && !TCUserDefaults::longForKey("IniFailureShown", 0, 0))
	{
		UCCHAR message[2048];
		UCSTR iniPath = mbstoucstring(TCUserDefaults::getIniPath());

		sucprintf(message, COUNT_OF(message),
			TCLocalStrings::get(_UC("IniFailure")), iniPath);
		CUIWindow::messageBoxUC(NULL, message, _UC("LDView"), MB_OK);
		delete iniPath;
		TCUserDefaults::setLongForKey(1, "IniFailureShown", false);
	}
	if (screenSaver)
	{
		if (strncasecmp(lpCmdLine, "/p", 2) == 0 ||
			strncasecmp(lpCmdLine, "-p", 2) == 0 ||
			strncasecmp(lpCmdLine, "p", 1) == 0)
		{
			// preview mode
			return doPreview(hInstance, lpCmdLine);
		}
		if (strncasecmp(lpCmdLine, "/c", 2) == 0 ||
			strncasecmp(lpCmdLine, "-c", 2) == 0 ||
			strncasecmp(lpCmdLine, "c", 1) == 0 ||
			strlen(lpCmdLine) == 0)
		{
			SSConfigure *configure;

			configure = new SSConfigure(hInstance);
#ifdef _DEBUG
			_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_DEBUG);
			createConsole();
#endif // _DEBUG
			configure->run();
			// configure mode
			return 1;
		}
		// This shouldn't be necessary, but I've received a report of a whole
		// bunch of copies of the LDView screensaver running at once.  This
		// might not fix things entirely, but it will at least prevent it
		// from launching multiple times concurrently.
		CreateMutex(NULL, FALSE, "LDView Screensaver");
		if (GetLastError() == ERROR_ALREADY_EXISTS)
		{
			return 0;
		}
	}
#ifdef _LOG_PERFORMANCE
	LARGE_INTEGER frequency;
	if (QueryPerformanceFrequency(&frequency))
	{
		debugPrintf("Frequency: %I64d\n", frequency.QuadPart);
	}
#endif // _LOG_PERFORMANCE
	OleInitialize(NULL);

	//Win7JumpListStuff();

	modelLoader = new ModelLoader(CUIWindow::getLanguageModule(), nCmdShow,
		screenSaver);
	retValue = mainLoop();
	modelLoader->release();
	return retValue;
} // WinMain