Exemple #1
0
//Init 
bool cScene::Init(const std::string &lacNameId, const std::string &lacFile)
{
  macFile = lacFile;
  mbLoaded = false;

  //Create an instance of the importer class
  Assimp::Importer lImporter;

  //Load the scene
  const aiScene* lpScene = lImporter.ReadFile( macFile.c_str(),
  aiProcess_CalcTangentSpace |
  aiProcess_Triangulate      |
  aiProcess_JoinIdenticalVertices |
  aiProcess_SortByPType);

  // If the import failed, report it
  if (!lpScene)
  {
    printf( lImporter.GetErrorString() );
    return false;
  }

  
  ProcessScene(lpScene);
  lImporter.FreeScene();
  mbLoaded = true;
  return true;
}
void SpotLightDemo::Initialize()
{
	glEnable(GL_DEPTH_TEST);
	program.AddShaderFile(ShaderType::Vertex, "Assets/Shaders/Vertex/spotlight.vert");
	program.AddShaderFile(ShaderType::Fragment, "Assets/Shaders/Fragment/spotlight.frag");
	program.Build();

	using std::unique_ptr;
	monkey = std::unique_ptr<GameObject>(new GameObject());
	monkey->GetTransform()->SetPosition({ 0.0f,0.0f,-5.0f });
	monkey->Update();
	light.color = glm::vec3(0.4f, 0.5f, 0.7f);
	light.position = glm::vec3(2.0f, 0.0f, -1.0f);
	light.direction = glm::normalize( glm::vec3(0.0f, 0.0f, -5.0f ) - light.position);
	light.cutOffAngle = 12.0f;
	light.exponent = 5.0f;

	program.AddUniformBlock({ "TransformBlock",{
		{ "TransformBlock.view", &camera->GetView()[0][0],sizeof(camera->GetView()) },
		{ "TransformBlock.projection", &camera->GetProjection()[0][0],sizeof(camera->GetProjection()) },
		{"TransformBlock.eyePosition", &camera->GetPosition()[0],sizeof(camera->GetPosition())},
	} });

	program.AddUniformBlock({ "LightBlock", {
		{ "LightBlock.color", &light.color.x,sizeof(light.color) },
		{ "LightBlock.position", &light.position.x,sizeof(light.position) },
		{ "LightBlock.direction", &light.direction.x,sizeof(light.direction) },
		{ "LightBlock.exponent", &light.exponent,sizeof(light.exponent) },
		{ "LightBlock.cutOffAngle", &light.cutOffAngle,sizeof(light.cutOffAngle) },
	} });
	
	Assimp::Importer importer;
	auto scene = importer.ReadFile("Assets/Models/Obj/monkey.obj", aiProcess_Triangulate);
	if (scene && scene->HasMeshes())
	{
		mesh = std::unique_ptr<MeshComponent>(new MeshComponent(monkey.get()));
		mesh->Initialize(scene->mMeshes[0], program, {
			{ "world",  UniformType::MAT4,&monkey->GetWorld()[0][0] },
			{ "material.ambient",UniformType::VEC3, &mesh->GetMaterial().ambient[0] },
			{ "material.diffuse",UniformType::VEC3, &mesh->GetMaterial().diffuse[0] } ,
			{ "material.specular", UniformType::VEC4, &mesh->GetMaterial().specular[0] }
		});

		monkey->AddComponent(mesh.get());
		mesh->GetMaterial().ambient = glm::vec3(0.2f, 0.4f, 0.7f);
		mesh->GetMaterial().diffuse = glm::vec3(0.8f, 0.1f, 0.1f);
		mesh->GetMaterial().specular = glm::vec4(0.3f, 0.7f, 0.3f,10.0f);
	}
	importer.FreeScene();
}
void LoadingObjDemo::InitializeObj(string filePath)
{
	Assimp::Importer importer;
	auto scene = importer.ReadFile(filePath.c_str(),
		aiProcess_Triangulate | aiProcess_GenSmoothNormals | aiProcess_FlipUVs );
	if (scene)
	{
		auto mesh = scene->mMeshes[0];
		gameObject = std::unique_ptr<GameObject>(new GameObject());
		meshComponent = std::unique_ptr<MeshComponent>(new MeshComponent(gameObject.get()));
		meshComponent->Initialize(mesh, program, {
			{ "model", UniformType::MAT4,&gameObject->GetWorld()[0][0] }
		});
		gameObject->GetTransform()->SetPosition(glm::vec3(0, 0, -10));
	}
	importer.FreeScene();
}
Exemple #4
0
ScenePtr ModelLoader::loadScene(const std::string & path) {
	//Création de la scène
	ScenePtr scene(new Scene);
	SceneObjectPtr &rootObject = scene->getRootObject();

	//Chargement du modèle dans assimp
	Assimp::Importer importer;
	const aiScene *aiScene = importer.ReadFile(path, aiProcess_Triangulate | aiProcess_FlipUVs | aiProcess_CalcTangentSpace);
	if (!aiScene) {
		throw std::runtime_error(importer.GetErrorString());
	}
	importer.ApplyPostProcessing(aiProcess_GenNormals);

	if (!aiScene || aiScene->mFlags == AI_SCENE_FLAGS_INCOMPLETE || !aiScene->mRootNode) {
		cout << "ERROR::ASSIMP::" << importer.GetErrorString() << endl;
		return ScenePtr(nullptr);
	}
	m_directory = path.substr(0, path.find_last_of('/'));

	processNode(aiScene, scene, aiScene->mRootNode, rootObject, glm::mat4());

	importer.FreeScene();
	return std::move(scene);
}
Exemple #5
0
void KeCloseScene()
{
    /* Close this mesh currently in memory */
    importer.FreeScene();
}
void FrameBufferDemo::Initialize()
{
	fboProgram.AddShaderFile(ShaderType::Vertex,"Assets/Shaders/Vertex/fbo.vert");
	fboProgram.AddShaderFile(ShaderType::Fragment,"Assets/Shaders/Fragment/fbo.frag");
	fboProgram.Build();

	textureProgram.AddShaderFile(ShaderType::Vertex, "Assets/Shaders/Vertex/texture.vert");
	textureProgram.AddShaderFile(ShaderType::Fragment, "Assets/Shaders/Fragment/texture.frag");
	textureProgram.Build();
	
	textureProgram.AddUniformBlock({ "TransformBlock", {
		{ "TransformBlock.view", &camera->GetView()[0][0], sizeof(camera->GetView()) },
		{ "TransformBlock.projection", &camera->GetProjection()[0][0], sizeof(camera->GetProjection()) },
	} });

	fboProgram.AddUniformBlock({ "TransformBlock",{
		{ "TransformBlock.view", &camera->GetView()[0][0], sizeof(camera->GetView()) },
		{ "TransformBlock.projection", &camera->GetProjection()[0][0], sizeof(camera->GetProjection()) },
	} });


	input->addBinding(GLFW_KEY_LEFT, [this](InputInfo info) {
		camera->MoveLeft();
		fboProgram.UpdateUniformBlock("TransformBlock");
		textureProgram.UpdateUniformBlock("TransformBlock");
	});

	input->addBinding(GLFW_KEY_RIGHT, [this](InputInfo info) {
		camera->MoveRight();
		fboProgram.UpdateUniformBlock("TransformBlock");
		textureProgram.UpdateUniformBlock("TransformBlock");
	});


	input->addBinding(GLFW_KEY_UP, [this](InputInfo info) {
		camera->MoveForward();
		textureProgram.UpdateUniformBlock("TransformBlock");
		fboProgram.UpdateUniformBlock("TransformBlock");
	});

	input->addBinding(GLFW_KEY_DOWN, [this](InputInfo info) {
		camera->MoveBack();
		textureProgram.UpdateUniformBlock("TransformBlock");
		fboProgram.UpdateUniformBlock("TransformBlock");
	});


	glGenFramebuffers(1, &fboHandle);
	glBindFramebuffer(GL_FRAMEBUFFER, fboHandle);

	glGenTextures(1, &renderTargetTexture);
	glActiveTexture(GL_TEXTURE0);
	glBindTexture(GL_TEXTURE_2D, renderTargetTexture);
	glTexStorage2D(GL_TEXTURE_2D, 1, GL_RGBA8, 512, 512);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, renderTargetTexture,0);

	glGenRenderbuffers(1, &depthBufferTexture);
	glBindRenderbuffer(GL_RENDERBUFFER, depthBufferTexture);
	glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, 512, 512);

	GLenum drawBufs[] = { GL_COLOR_ATTACHMENT0 };
	glDrawBuffers(1, drawBufs);

	glBindFramebuffer(GL_FRAMEBUFFER, 0);

	Assimp::Importer importer;
	auto cubeScene = importer.ReadFile("Assets/Models/Obj/box.obj", aiProcess_Triangulate);
	cube = std::unique_ptr<GameObject>(new GameObject());
	cube->GetTransform()->SetPosition({ 0.0f,0.0f,-5.0f });
	cube->GetTransform()->SetScale({ 20.0f,20.0f,20.0f });
	cube->Update();
	if (cubeScene && cubeScene->HasMeshes())
	{
		cubeMesh = std::unique_ptr<MeshComponent>(new MeshComponent(cube.get()));
		cubeMesh->Initialize(cubeScene->mMeshes[0], fboProgram, {
			{"world", UniformType::MAT4, &cube->GetWorld()[0][0]},
		});
		cubeMesh->AddTexture({ renderTargetTexture,GL_TEXTURE_2D, renderer->GetSampler(SamplerType::Linear).sampler });
	}

	auto monkeyScene = importer.ReadFile("Assets/Models/Obj/monkey.obj", aiProcess_Triangulate);
	monkey = std::unique_ptr<GameObject>(new GameObject());
	monkey->GetTransform()->SetPosition({ 2.0f,0.0f,-2.0f });
	monkey->Update();
	if (monkeyScene && monkeyScene->HasMeshes())
	{
		monkeyMesh = std::unique_ptr<MeshComponent>(new MeshComponent(monkey.get()));
		monkeyMesh->Initialize(monkeyScene->mMeshes[0], textureProgram, {
			{"world", UniformType::MAT4, &monkey->GetWorld()[0][0]}
		});
		monkeyMesh->AddTexture("Assets/Textures/brick.jpg");
	}

	importer.FreeScene();
}
    bool AssimpModelImporter::Load(const std::string& Filename)
    {
        // Assimp Importer
        Assimp::Importer Importer;
        
        // Load Model
        assimp_model = Importer.ReadFile(Filename.c_str(),aiProcessPreset_TargetRealtime_Fast | aiProcess_OptimizeMeshes | aiProcess_JoinIdenticalVertices | aiProcess_LimitBoneWeights | aiProcess_FlipUVs | aiProcess_CalcTangentSpace);

        // Path Relative to Model File
        std::string RelativePath = Filename.substr(0,Filename.find_last_of("/")+1);

        if (!assimp_model)
        {
            echo("Failed To Import Model: " + Filename + " ERROR: " + Importer.GetErrorString());
            return false;
        } else {
            
            // Build Skeleton
            // initial bone count
            boneCount = 0;
            // Get Skeleton
            GetBone(assimp_model->mRootNode);
            
            for (uint32 i=0;i<assimp_model->mNumMeshes;i++)
            {
                // loop through meshes
                const aiMesh* mesh = assimp_model->mMeshes[i];

                // create submesh
                SubMesh subMesh;
                
                // set submesh id
                subMesh.ID = i;
                
                // set name
                subMesh.Name = mesh->mName.data;
                
                for (uint32 t = 0; t < mesh->mNumFaces;t++) {
                    const aiFace* face = &mesh->mFaces[t];
                    subMesh.tIndex.push_back(face->mIndices[0]);
                    subMesh.tIndex.push_back(face->mIndices[1]);
                    subMesh.tIndex.push_back(face->mIndices[2]);
                }

                // get posisitons
                if (mesh->HasPositions())
                {
                    subMesh.hasVertex = true;
                    subMesh.tVertex.resize(mesh->mNumVertices);
                    memcpy(&subMesh.tVertex[0],&mesh->mVertices[0],mesh->mNumVertices*sizeof(Vec3));
                } else subMesh.hasVertex = false;

                // get normals
                if (mesh->HasNormals())
                {                    
                    subMesh.hasNormal = true;
                    subMesh.tNormal.resize(mesh->mNumVertices);
                    memcpy(&subMesh.tNormal[0],&mesh->mNormals[0],mesh->mNumVertices*sizeof(Vec3));
                } else subMesh.hasNormal = false;

                // get texcoords
                if (mesh->HasTextureCoords(0))
                {               
                    subMesh.hasTexcoord = true;
                    for (uint32 k = 0; k < mesh->mNumVertices;k++) 
                    {
                        subMesh.tTexcoord.push_back(Vec2(mesh->mTextureCoords[0][k].x,mesh->mTextureCoords[0][k].y));                            
                    }
                } else subMesh.hasTexcoord = false;

                // get tangent
                if (mesh->HasTangentsAndBitangents())
                {
                    subMesh.hasTangentBitangent = true;
                    subMesh.tTangent.resize(mesh->mNumVertices);
                    subMesh.tBitangent.resize(mesh->mNumVertices);
                    memcpy(&subMesh.tTangent[0],&mesh->mTangents[0],mesh->mNumVertices*sizeof(Vec3));
                    memcpy(&subMesh.tBitangent[0],&mesh->mBitangents[0],mesh->mNumVertices*sizeof(Vec3));
                } else subMesh.hasTangentBitangent = false;

                // get vertex colors
                if (mesh->HasVertexColors(0))
                {
                    subMesh.hasVertexColor = true;
                    subMesh.tVertexColor.resize(mesh->mNumVertices);
                    memcpy(&subMesh.tVertexColor[0],&mesh->mColors[0],mesh->mNumVertices*sizeof(Vec4));
                } else subMesh.hasVertexColor = false;

                // get vertex weights
                if (mesh->HasBones())
                {
                    // Set Flag
                    subMesh.hasBones = true;
                    
                    // Create Bone's Sub Mesh Internal ID
                    uint32 count = 0;
                    for (uint32 k = 0; k < mesh->mNumBones; k++)
                    {
                        // Save Offset Matrix
                        Matrix _offsetMatrix;
                        _offsetMatrix.m[0]  = mesh->mBones[k]->mOffsetMatrix.a1; _offsetMatrix.m[1]  = mesh->mBones[k]->mOffsetMatrix.b1;  _offsetMatrix.m[2]   = mesh->mBones[k]->mOffsetMatrix.c1; _offsetMatrix.m[3]  = mesh->mBones[k]->mOffsetMatrix.d1;
                        _offsetMatrix.m[4]  = mesh->mBones[k]->mOffsetMatrix.a2; _offsetMatrix.m[5]  = mesh->mBones[k]->mOffsetMatrix.b2;  _offsetMatrix.m[6]   = mesh->mBones[k]->mOffsetMatrix.c2; _offsetMatrix.m[7]  = mesh->mBones[k]->mOffsetMatrix.d2;
                        _offsetMatrix.m[8]  = mesh->mBones[k]->mOffsetMatrix.a3; _offsetMatrix.m[9]  = mesh->mBones[k]->mOffsetMatrix.b3;  _offsetMatrix.m[10]  = mesh->mBones[k]->mOffsetMatrix.c3; _offsetMatrix.m[11] = mesh->mBones[k]->mOffsetMatrix.d3;
                        _offsetMatrix.m[12] = mesh->mBones[k]->mOffsetMatrix.a4; _offsetMatrix.m[13] = mesh->mBones[k]->mOffsetMatrix.b4;  _offsetMatrix.m[14]  = mesh->mBones[k]->mOffsetMatrix.c4; _offsetMatrix.m[15] = mesh->mBones[k]->mOffsetMatrix.d4;

                        uint32 boneID = GetBoneID(mesh->mBones[k]->mName.data);
                        subMesh.BoneOffsetMatrix[boneID] = _offsetMatrix;
                        subMesh.MapBoneIDs[boneID] = count;
                        count++;
                    }
                    
                    // Add Bones and Weights to SubMesh Structure, based on Internal IDs
                    for (uint32 j = 0; j < mesh->mNumVertices; j++)
                    {
                        // get values
                        std::vector<uint32> boneID(4,0);
                        std::vector<f32> weightValue(4,0.f);
                        
                        uint32 count = 0;
                        for (uint32 k = 0; k < mesh->mNumBones; k++) 
                        {
                            for (uint32 l = 0; l < mesh->mBones[k]->mNumWeights; l++)
                            {
                                if (mesh->mBones[k]->mWeights[l].mVertexId == j)
                                {
                                    // Convert Bone ID to Internal of the Sub Mesh
                                    boneID[count] = subMesh.MapBoneIDs[GetBoneID(mesh->mBones[k]->mName.data)];
                                    // Add Bone Weight
                                    weightValue[count] = mesh->mBones[k]->mWeights[l].mWeight;
                                    count++;
                                }
                            }
                        }
                        subMesh.tBonesID.push_back(Vec4((f32)boneID[0],(f32)boneID[1],(f32)boneID[2],(f32)boneID[3]));
                        subMesh.tBonesWeight.push_back(Vec4(weightValue[0],weightValue[1],weightValue[2],weightValue[3]));                        
                    }
                    
                } else subMesh.hasBones = false;
                
                // Get SubMesh Material ID
                subMesh.materialID = mesh->mMaterialIndex;
                
                // add to submeshes vector
                subMeshes.push_back(subMesh);
            }
            
            // Build Materials List
            for (uint32 i=0;i<assimp_model->mNumMaterials;++i)
            {
                MaterialProperties material;
                // Get Material
                const aiMaterial* pMaterial = assimp_model->mMaterials[i];
                material.id = i;
                
                aiString name;
                pMaterial->Get(AI_MATKEY_NAME, name);
                material.Name.resize(name.length);
                memcpy(&material.Name[0], name.data, name.length);
                
                aiColor3D color;
				material.haveColor = false;
                if (pMaterial->Get(AI_MATKEY_COLOR_DIFFUSE, color)==AI_SUCCESS) 
                {
                    material.haveColor = true;
                    material.Color = Vec4(color.r, color.g, color.b, 1.0);                
                }
				material.haveAmbient = false;
                if (pMaterial->Get(AI_MATKEY_COLOR_AMBIENT, color)==AI_SUCCESS) 
                {
                    material.haveAmbient = true;
                    material.Ambient = Vec4(color.r, color.g, color.b, 1.0);                                
                }
				material.haveSpecular = false;
                if (pMaterial->Get(AI_MATKEY_COLOR_SPECULAR, color)==AI_SUCCESS) 
                {
                    material.haveSpecular = true;
                    material.Specular = Vec4(color.r, color.g, color.b, 1.0);
                }
                material.haveEmissive = false;
                if (pMaterial->Get(AI_MATKEY_COLOR_EMISSIVE, color)==AI_SUCCESS) 
                {
                    material.haveEmissive = true;
                    material.Emissive = Vec4(color.r, color.g, color.b, 1.0);
                }
                
                bool flag = false;
                pMaterial->Get(AI_MATKEY_ENABLE_WIREFRAME, flag);
                material.WireFrame = flag;

                flag = false;
                pMaterial->Get(AI_MATKEY_TWOSIDED, flag);
                material.Twosided = flag;
                
                f32 value = 1.0f;
                pMaterial->Get(AI_MATKEY_OPACITY, value);
                material.Opacity = value;
                
                value = 0.0f;
                pMaterial->Get(AI_MATKEY_SHININESS, value);
                material.Shininess = value;
                
                value = 0.0f;
                pMaterial->Get(AI_MATKEY_SHININESS_STRENGTH, value);
                material.ShininessStrength = value;                
                // Save Properties                
                
                aiString path;
                aiReturn texFound;

                // Diffuse
                texFound = assimp_model->mMaterials[i]->GetTexture(aiTextureType_DIFFUSE, 0, &path);
                if (texFound==AI_SUCCESS)
                {
                    material.haveColorMap = true;
                    material.colorMap.resize(path.length);
                    memcpy(&material.colorMap[0],&path.data,path.length);
                    std::replace(material.colorMap.begin(), material.colorMap.end(),'\\','/');
                }
                
                // Bump Map
                texFound = assimp_model->mMaterials[i]->GetTexture(aiTextureType_NORMALS, 0, &path);
                if (texFound==AI_SUCCESS)
                {
                    material.haveNormalMap = true;
                    material.normalMap.resize(path.length);
                    memcpy(&material.normalMap[0],&path.data,path.length);
                    std::replace(material.normalMap.begin(), material.normalMap.end(),'\\','/');
                } else {
                    // Height Map
                    texFound = assimp_model->mMaterials[i]->GetTexture(aiTextureType_HEIGHT, 0, &path);
                    if (texFound==AI_SUCCESS)
                    {
                        material.haveNormalMap = true;
                        material.normalMap.resize(path.length);
                        memcpy(&material.normalMap[0],&path.data,path.length);
                        std::replace(material.normalMap.begin(), material.normalMap.end(),'\\','/');
                    }
                }
                // Specular
                texFound = assimp_model->mMaterials[i]->GetTexture(aiTextureType_SPECULAR, 0, &path);
                if (texFound==AI_SUCCESS)
                {
                    material.haveSpecularMap = true;
                    material.specularMap.resize(path.length);
                    memcpy(&material.specularMap[0],&path.data,path.length);
                    std::replace(material.specularMap.begin(), material.specularMap.end(),'\\','/');
                }
                // Add Material to List
                materials.push_back(material);
            }
        }
		Importer.FreeScene();

        return true;
    }
void DiffuseDemo::Initialize()
{
	glEnable(GL_DEPTH_TEST);
	glClearColor(0.4f, 0.7f, 0.2f, 1.0f);

	program.Initialize();
	program.AddShaderFile(ShaderType::Vertex, "Assets/Shaders/Vertex/diffuseLight.vert");
	program.AddShaderFile(ShaderType::Fragment, "Assets/Shaders/Fragment/diffuseLight.frag");
	program.Build();

	light.position = glm::vec3(5.0f, 5.0f, -5.0f);
	light.color = glm::vec3(0.0f, 0.5f, 0.5f);

	
	program.AddUniformBlock({
		"TransformBlock",{
			{ "TransformBlock.view", &camera->GetView()[0][0],sizeof(camera->GetView()) },
			{ "TransformBlock.projection", &camera->GetProjection()[0][0],sizeof(camera->GetProjection()) }
		}
	});

	program.AddUniformBlock({
		"LightBlock", {
			{ "LightBlock.position", &light.position[0],sizeof(light.position) },
			{ "LightBlock.color", &light.color[0],sizeof(light.color) }
		}
	});
	
	monkeyObject = std::unique_ptr<GameObject>(new GameObject());
	boxObject = std::unique_ptr<GameObject>(new GameObject());


	monkeyObject->GetTransform()->SetPosition(glm::vec3(0, 0, -5));
	monkeyObject->GetTransform()->Update();

	boxObject->GetTransform()->SetPosition(glm::vec3(2, 2, -7));
	boxObject->GetTransform()->Update();

	program.AddUniform("view", &camera->GetView()[0][0], UniformType::MAT4);
	program.AddUniform("projection", &camera->GetProjection()[0][0], UniformType::MAT4);

	Assimp::Importer importer;
	auto monkeyScene = importer.ReadFile("Assets/Models/Obj/monkey.obj", aiProcess_Triangulate);
	if (monkeyScene)
	{
		monkey = std::unique_ptr<MeshComponent>(new MeshComponent(monkeyObject.get()));
		monkey->Initialize(monkeyScene->mMeshes[0], program, {
			{ "world",  UniformType::MAT4,&monkeyObject->GetWorld()[0][0] },
			{ "diffuse", UniformType::VEC3,&monkey->GetMaterial().diffuse[0] }
		});
		monkeyObject->AddComponent(monkey.get());
	}
	importer.FreeScene();

	auto boxScene = importer.ReadFile("Assets/Models/Obj/box.obj", aiProcess_Triangulate);
	if (boxScene)
	{
		box = std::unique_ptr<MeshComponent>(new MeshComponent(boxObject.get()));
		box->Initialize(boxScene->mMeshes[0], program, {
			{ "world",UniformType::MAT4,&boxObject->GetWorld()[0][0] },
			{ "diffuse", UniformType::VEC3,&box->GetMaterial().diffuse[0] }
		});
		box->GetMaterial().diffuse = glm::vec3(0.2f, 0.7f, 0.5);
		boxObject->AddComponent(box.get());
	}

	importer.FreeScene();

}
Exemple #9
0
    MeshData(const string& name)
    {
      static Assimp::Importer importer;
      D3DInfo& d3d = *D3DInfo::CurrentInstance();

      // Read the mesh data from file using Asset Importer.
      const aiScene* scene = importer.ReadFile(config::Meshes + name, ImportSetting);
      if (!scene || !scene->mNumMeshes)
      {
        Warn("Mesh read failed for " + name);
        return;
      }

      const aiMesh* mesh = scene->mMeshes[0];
      WarnIf(scene->mNumMeshes > 1, "Mesh " + name + " has more sub-meshes than are currently supported");
      
      // Verify mesh texture coordinates and tangents.
      bool hasTexCoords = true;
      if (!mesh->HasTextureCoords(0))
      {
        hasTexCoords = false;
        Warn("Mesh " + name + " doesn't have texture coordinates");
      }
      bool hasTangents = true;
      if (!mesh->HasTangentsAndBitangents())
      {
        hasTangents = false;
        Warn("Mesh " + name + " doesn't have tangents/bitangents");
      }

      float minFloat = numeric_limits<float>::min();
      float maxFloat = numeric_limits<float>::max();
      boundingBox.max = { minFloat, minFloat, minFloat };
      boundingBox.min = { maxFloat, maxFloat, maxFloat };

      // Copy all vertices.
      vertices.resize(mesh->mNumVertices);
      for (size_t i = 0; i < mesh->mNumVertices; ++i)
      {
        vertices[i].position  = reinterpret_cast<const float3&>(mesh->mVertices[i]);
        vertices[i].normal = reinterpret_cast<const float3&>(mesh->mNormals[i]);
        if (hasTexCoords)
        {
          vertices[i].tex = reinterpret_cast<const float2&>(mesh->mTextureCoords[0][i]);
        }
        if (hasTangents)
        {
          vertices[i].tangent = reinterpret_cast<const float3&>(mesh->mTangents[i]);
          vertices[i].bitangent = reinterpret_cast<const float3&>(mesh->mBitangents[i]);
        }

        // Determine the min and max extents of the mesh.
        if (vertices[i].position.x < boundingBox.min.x) boundingBox.min.x = vertices[i].position.x;
        if (vertices[i].position.y < boundingBox.min.y) boundingBox.min.y = vertices[i].position.y;
        if (vertices[i].position.z < boundingBox.min.z) boundingBox.min.z = vertices[i].position.z;
        if (vertices[i].position.x > boundingBox.max.x) boundingBox.max.x = vertices[i].position.x;
        if (vertices[i].position.y > boundingBox.max.y) boundingBox.max.y = vertices[i].position.y;
        if (vertices[i].position.z > boundingBox.max.z) boundingBox.max.z = vertices[i].position.z;
      }

      // Calculate the centroid of the mesh: centroid = min + ((max - min) / 2)
      XMVECTOR minVector = XMLoadFloat3(&boundingBox.min);
      XMVECTOR cornerToCorner = XMVectorSubtract(XMLoadFloat3(&boundingBox.max), minVector);
      XMStoreFloat3(
        &boundingBox.centroid, 
        XMVectorAdd(
          minVector, 
          XMVectorScale(cornerToCorner, 0.5f)));

      // Center the mesh on (0,0,0) by subtracting the centroid position from all vertex positions.
      for (auto& vertex : vertices)
      {
        vertex.position.x -= boundingBox.centroid.x;
        vertex.position.y -= boundingBox.centroid.y;
        vertex.position.z -= boundingBox.centroid.z;
      }

      // Copy all indices.
      indices.resize(mesh->mNumFaces * 3);
      for (size_t i = 0; i < mesh->mNumFaces; ++i)
      {
        indices[i * 3 + 0] = mesh->mFaces[i].mIndices[0];
        indices[i * 3 + 1] = mesh->mFaces[i].mIndices[1];
        indices[i * 3 + 2] = mesh->mFaces[i].mIndices[2];
      }

      // Free the loaded scene.
      importer.FreeScene();

      // Create the index buffer.
      D3D11_BUFFER_DESC bufferDesc;
      bufferDesc.BindFlags = D3D11_BIND_INDEX_BUFFER;
      bufferDesc.ByteWidth = indices.size() * sizeof(indices[0]);
      bufferDesc.CPUAccessFlags = 0;
      bufferDesc.MiscFlags = 0;
      bufferDesc.StructureByteStride = 0;
      bufferDesc.Usage = D3D11_USAGE_IMMUTABLE;
      D3D11_SUBRESOURCE_DATA initData;
      initData.pSysMem = indices.data();
      initData.SysMemPitch = 0;
      initData.SysMemSlicePitch = 0;
      DX(d3d.Device->CreateBuffer(&bufferDesc, &initData, indexBuffer));

      // Create the vertex buffer.
      bufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
      bufferDesc.ByteWidth = vertices.size() * sizeof(vertices[0]);
      initData.pSysMem = vertices.data();
      DX(d3d.Device->CreateBuffer(&bufferDesc, &initData, vertexBuffer));

      // Create the constant buffer.
      D3D11_BUFFER_DESC cbDesc;
      ZeroMemory(&cbDesc, sizeof(cbDesc));
      cbDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
      cbDesc.ByteWidth = sizeof(ObjectConstants);
      cbDesc.Usage = D3D11_USAGE_DEFAULT;
      DX(d3d.Device->CreateBuffer(&cbDesc, nullptr, constantBuffer));
    }
void MultiLightDemo::Initialize()
{
	glEnable(GL_DEPTH_TEST);
	glClearColor(0.3f, 0.2f, 0.7f, 1.0f);
	program.AddShaderFile(ShaderType::Vertex, "Assets/Shaders/Vertex/multiLight.vert");
	program.AddShaderFile(ShaderType::Fragment, "Assets/Shaders/Fragment/multiLight.frag");
	program.Build();

	program.AddUniformBlock({ "TransformBlock",{
		{ "TransformBlock.view",&camera->GetView()[0][0], sizeof(camera->GetView()) },
		{ "TransformBlock.projection",&camera->GetProjection()[0][0], sizeof(camera->GetProjection()) },
		{ "TransformBlock.eyePosition",&camera->GetPosition()[0], sizeof(camera->GetPosition()) },
	} });

	lights[0].position = glm::vec3(0.0f, 0.0f, -2.0f);
	lights[1].position = glm::vec3(-2.0f, -3.0f, -2.0f);
	lights[2].position = glm::vec3(4.0f, 7.0f, -2.0f);

	lights[0].color = glm::vec3(0.9f,0.5f,0.3f);
	lights[1].color = glm::vec3(0.2f,0.9f,0.2f);
	lights[2].color = glm::vec3(0.2f,0.4f,0.9f);
	
	program.AddUniform("lights[0].position", &lights[0].position[0], UniformType::VEC3);
	program.AddUniform("lights[0].color", &lights[0].color[0], UniformType::VEC3);
	program.AddUniform("lights[1].position", &lights[1].position[0], UniformType::VEC3);
	program.AddUniform("lights[1].color", &lights[1].color[0], UniformType::VEC3);
	program.AddUniform("lights[2].position", &lights[2].position[0], UniformType::VEC3);
	program.AddUniform("lights[2].color", &lights[2].color[0], UniformType::VEC3);

	input->addBinding(GLFW_KEY_LEFT, [this](InputInfo info) {
		camera->MoveLeft();
		program.UpdateUniformBlock("TransformBlock");
	});

	input->addBinding(GLFW_KEY_RIGHT, [this](InputInfo info) {
		camera->MoveRight();
		program.UpdateUniformBlock("TransformBlock");
	});


	input->addBinding(GLFW_KEY_UP, [this](InputInfo info) {
		camera->MoveForward();
		program.UpdateUniformBlock("TransformBlock");
	});

	input->addBinding(GLFW_KEY_DOWN, [this](InputInfo info) {
		camera->MoveBack();
		program.UpdateUniformBlock("TransformBlock");
	});


	//program.AddUniform("light[0].position", &lights[0].position[0], UniformType::VEC3);
	//program.AddUniform("light[0].color", &lights[0].color[0], UniformType::VEC3);
	//program.AddUniform("light[1].position", &lights[1].position[0], UniformType::VEC3);
	//program.AddUniform("light[1].color", &lights[1].color[0], UniformType::VEC3);
	//program.AddUniform("light[2].position", &lights[2].position[0], UniformType::VEC3);
	//program.AddUniform("light[2].color", &lights[2].color[0], UniformType::VEC3);

	using std::unique_ptr;
	monkey = unique_ptr<GameObject>(new GameObject());
	monkey->GetTransform()->SetPosition({ 0.0f,0.0f,-5.0f });
	monkey->Update();
	Assimp::Importer importer;
	auto scene = importer.ReadFile("Assets/Models/Obj/monkey.obj", aiProcess_Triangulate);
	if (scene && scene->HasMeshes())
	{
		mesh = unique_ptr<MeshComponent>(new MeshComponent(monkey.get()));
		mesh->Initialize(scene->mMeshes[0], program, {
			{ "world", UniformType::MAT4, &monkey->GetWorld()[0][0] },
			{ "material.ambient", UniformType::VEC3, &mesh->GetMaterial().ambient[0] },
			{ "material.diffuse", UniformType::VEC3, &mesh->GetMaterial().diffuse[0] },
			{ "material.specular", UniformType::VEC4, &mesh->GetMaterial().specular[0] },
		});
		monkey->AddComponent(mesh.get());
	}

	mesh->GetMaterial().ambient = glm::vec3(0.6f, 0.7f, 0.1f);
	mesh->GetMaterial().diffuse = glm::vec3(0.5f, 0.2f, 0.8f);
	mesh->GetMaterial().specular = glm::vec4(0.3f, 0.2f, 0.2f, 10.0f);
	importer.FreeScene();

}
Exemple #11
0
void ke_close_scene()
{
    /* Close this mesh currently in memory */
    importer.FreeScene();
}