Material* SceneParser::parsePhongMaterial() { char token[MAX_PARSER_TOKEN_LENGTH]; Vec3f diffuseColor(1, 1, 1); Vec3f specularColor(0, 0, 0); float exponent = 1; getToken(token); assert(!strcmp(token, "{")); while (1) { getToken(token); if (!strcmp(token, "diffuseColor")) { diffuseColor = readVec3f(); } else if (!strcmp(token, "specularColor")) { specularColor = readVec3f(); } else if (!strcmp(token, "exponent")) { exponent = readFloat(); } else { assert(!strcmp(token, "}")); break; } } Material *answer = new PhongMaterial(diffuseColor, specularColor, exponent); return answer; }
Material * SceneParser::parseMaterial() { char token[MAX_PARSER_TOKEN_LENGTH]; char filename[MAX_PARSER_TOKEN_LENGTH]; filename[0] = 0; Vector3f diffuseColor(1,1,1), specularColor(0,0,0); float shininess=0; getToken(token); assert(!strcmp(token, "{")); while (true) { getToken(token); if (strcmp(token, "diffuseColor")==0) { diffuseColor = readVector3f(); } else if (strcmp(token, "specularColor")==0) { specularColor = readVector3f(); } else if (strcmp(token, "shininess")==0) { shininess = readFloat(); } else if (strcmp(token, "texture")==0) { getToken(filename); } else { assert(!strcmp(token, "}")); break; } } Material *answer = new Material(diffuseColor, specularColor, shininess); if(filename[0] !=0){ answer->loadTexture(filename); } return answer; }
bool Grid::intersect(const Ray &r, Hit &h, float tmin) { //Prepare the Material objects Vec3f diffuseColor(1, 1, 1); Vec3f specularColor(0, 0, 0); float exponent = 1; Vec3f reflectiveColor(0, 0, 0); Vec3f transparentColor(0, 0, 0); float indexOfRefraction = 1; PhongMaterial *m = new PhongMaterial(diffuseColor, specularColor, exponent, reflectiveColor, transparentColor, indexOfRefraction); //Start to do DDA MarchingInfo mi; initializeRayMarch(mi, r, tmin); bool hitSomething = false; int i, j, k; do { mi.getIndices(i, j, k); printf("The current point is:%d,%d,%d\n", i, j, k); if (mObjects[offset(i, j, k)].getNumObjects() > 0) { h.set(mi.get_tmin(), m, mi.getNormal(), r); return true; } mi.nextCell(); } while(i < mXSize && j < mYSize && k < mZSize); return false; }
color3 Ray::PhongColor(Light light, Material material, Fragment fragment) const { vec3 ambient = ambientColor(light, material); vec3 diffuse = diffuseColor(light, material, fragment); vec3 specular = specularColor(light, material, fragment); vec3 color = clamp(ambient + diffuse + specular, 0.0, 1.0); return color; }
Material* SceneParser::parseMaterial() { char token[MAX_PARSER_TOKEN_LENGTH]; Vec3f diffuseColor(1,1,1); getToken(token); assert (!strcmp(token, "{")); while (1) { getToken(token); if (!strcmp(token, "diffuseColor")) { diffuseColor = readVec3f(); } else { assert (!strcmp(token, "}")); break; } } Material *answer = new Material(diffuseColor); return answer; }
Material* SceneParser::parseMaterial() { char token[MAX_PARSER_TOKEN_LENGTH]; char filename[MAX_PARSER_TOKEN_LENGTH]; filename[0] = 0; Vector3f diffuseColor(1,1,1), specularColor(0,0,0); float shininess=0; float refractionIndex =0; getToken(token); assert (!strcmp(token, "{")); Noise *noise =0; while (1) { getToken(token); if (strcmp(token, "diffuseColor")==0) { diffuseColor = readVector3f(); } else if (strcmp(token, "specularColor")==0) { specularColor = readVector3f(); } else if (strcmp(token, "shininess")==0) { shininess = readFloat(); }else if(strcmp(token, "refractionIndex")==0){ refractionIndex = readFloat(); } else if (strcmp(token, "texture")==0) { getToken(filename); } ///unimplemented else if (strcmp(token, "bump")==0) { getToken(token); } else if(strcmp(token,"Noise")==0){ noise = parseNoise(); } else { assert (!strcmp(token, "}")); break; } } Material *answer = new Material(diffuseColor, specularColor, shininess,refractionIndex); if(filename[0] !=0){ answer->loadTexture(filename); } if(noise != 0){ answer->setNoise(*noise); delete noise; } return answer; }
// <Material // DEF="" ID // USE="" IDREF // ambientIntensity="0.2" SFFloat [inputOutput] // diffuseColor="0.8 0.8 0.8" SFColor [inputOutput] // emissiveColor="0 0 0" SFColor [inputOutput] // shininess="0.2" SFFloat [inputOutput] // specularColor="0 0 0" SFColor [inputOutput] // transparency="0" SFFloat [inputOutput] // /> void X3DImporter::ParseNode_Shape_Material() { std::string use, def; float ambientIntensity = 0.2f; float shininess = 0.2f; float transparency = 0; aiColor3D diffuseColor(0.8f, 0.8f, 0.8f); aiColor3D emissiveColor(0, 0, 0); aiColor3D specularColor(0, 0, 0); CX3DImporter_NodeElement* ne( nullptr ); MACRO_ATTRREAD_LOOPBEG; MACRO_ATTRREAD_CHECKUSEDEF_RET(def, use); MACRO_ATTRREAD_CHECK_RET("ambientIntensity", ambientIntensity, XML_ReadNode_GetAttrVal_AsFloat); MACRO_ATTRREAD_CHECK_RET("shininess", shininess, XML_ReadNode_GetAttrVal_AsFloat); MACRO_ATTRREAD_CHECK_RET("transparency", transparency, XML_ReadNode_GetAttrVal_AsFloat); MACRO_ATTRREAD_CHECK_REF("diffuseColor", diffuseColor, XML_ReadNode_GetAttrVal_AsCol3f); MACRO_ATTRREAD_CHECK_REF("emissiveColor", emissiveColor, XML_ReadNode_GetAttrVal_AsCol3f); MACRO_ATTRREAD_CHECK_REF("specularColor", specularColor, XML_ReadNode_GetAttrVal_AsCol3f); MACRO_ATTRREAD_LOOPEND; // if "USE" defined then find already defined element. if(!use.empty()) { MACRO_USE_CHECKANDAPPLY(def, use, ENET_Material, ne); } else { // create and if needed - define new geometry object. ne = new CX3DImporter_NodeElement_Material(NodeElement_Cur); if(!def.empty()) ne->ID = def; ((CX3DImporter_NodeElement_Material*)ne)->AmbientIntensity = ambientIntensity; ((CX3DImporter_NodeElement_Material*)ne)->Shininess = shininess; ((CX3DImporter_NodeElement_Material*)ne)->Transparency = transparency; ((CX3DImporter_NodeElement_Material*)ne)->DiffuseColor = diffuseColor; ((CX3DImporter_NodeElement_Material*)ne)->EmissiveColor = emissiveColor; ((CX3DImporter_NodeElement_Material*)ne)->SpecularColor = specularColor; // check for child nodes if(!mReader->isEmptyElement()) ParseNode_Metadata(ne, "Material"); else NodeElement_Cur->Child.push_back(ne);// add made object as child to current element NodeElement_List.push_back(ne);// add element to node element list because its a new object in graph }// if(!use.empty()) else }
QVector3D WhittedRenderer::trace(const Ray& primaryRay, int depth, const QList<Shape*>& shapes, const QList<Light*>& lights) { double minDist = std::numeric_limits<double>::max(); Shape* closestShape = nullptr; QVector3D shaded; if (m_grid->intersect(primaryRay, closestShape, minDist)) { auto material = closestShape->material(); shaded = material->ambientReflectivity() * m_ambientLightColor * material->colorVector(); QColor color = material ? material->color() : QColor(40, 40, 40); QVector3D diffuseColor(color.redF(), color.greenF(), color.blueF()); QVector4D hitPoint = primaryRay.along(minDist); QVector4D normalVector = closestShape->surfaceNormal(hitPoint, primaryRay); QVector4D viewVector = -primaryRay.direction(); foreach(Light* light, lights) { QVector3D emittance; QVector4D lightVector; light->sample(lightVector, emittance); lightVector = lightVector - hitPoint; float lightVectorLengthSquared = lightVector.lengthSquared(); float lightVectorLength = sqrt(lightVectorLengthSquared); lightVector.normalize(); Ray shadowRay(hitPoint, lightVector); double t; Shape* blockingShape; bool shadowRayHit = m_grid->intersect(shadowRay, blockingShape, t); if (!shadowRayHit || (shadowRayHit && (lightVectorLengthSquared < t * t))) { // Diffuse float dot = fmax(0.0f, QVector4D::dotProduct(lightVector, normalVector)) * material->diffuseReflectivity(); emittance *= 1 / (1 + 0.2 * lightVectorLength + 0.08 * lightVectorLengthSquared); shaded += dot * QVector3D(emittance.x() * diffuseColor.x(), emittance.y() * diffuseColor.y(), emittance.z() * diffuseColor.z()); // Specular if (material->specularReflectivity() > 0.0) { QVector4D reflectedLightVector = MathUtils::reflect(-lightVector, normalVector); // lightVector and normalVector are already normalized float dot = QVector4D::dotProduct(reflectedLightVector, viewVector); if (dot > 0.0) shaded += material->specularReflectivity() * pow(dot, material->shininess()) * emittance; } } }
Material* SceneParser::parseMaterial() { cout << "PARSING INDIVIDUAL MATERIAL" << endl; char token[MAX_PARSER_TOKEN_LENGTH]; Vector3f diffuseColor(1,1,1); float exponent = 1; getToken(token); assert (!strcmp(token, "{")); while (1) { getToken(token); if (!strcmp(token, "diffuseColor")) { diffuseColor = readVector3f(); } else { assert (!strcmp(token, "}")); break; } } Material *answer = new Material(diffuseColor); return answer; }
void SpotLight::apply() { const math::Matrix4x4& wt = cachedWorldTransform(); math::Vector3 wrotz = math::Vector3( wt(0,2),wt(1,2),wt(2,2) ); float wrotzlen = wrotz.length(); if ( wrotzlen > Float::MIN_VALUE ) { wrotz *= 1.f / wrotzlen; float intens = intensity(); gd::LightState ls; GdUtil::setLightState( ls, gd::LightState::LIGHT_SPOT, diffuseColor()*intens, specularColor()*intens, ambientColor()*intens, wt.translation(), wrotz, m_range, m_atten[0], m_atten[1], m_atten[2], 1.f, m_inner, m_outer ); gd::GraphicsDevice* dev = Context::device(); dev->addLight( ls ); } }
void DirectLight::apply() { const Matrix4x4& wt = cachedWorldTransform(); Vector3 wrotz = Vector3( wt(0,2),wt(1,2),wt(2,2) ); float wrotzlen = wrotz.length(); if ( wrotzlen > Float::MIN_VALUE ) { wrotz *= 1.f / wrotzlen; float intens = intensity(); gd::LightState ls; GdUtil::setLightState( ls, gd::LightState::LIGHT_DIRECT, diffuseColor()*intens, specularColor()*intens, ambientColor()*intens, wt.translation(), wrotz.normalize(), MAX_RANGE, 1.f, 0.f, 0.f, 1.f, MAX_CONE_ANGLE, MAX_CONE_ANGLE ); gd::GraphicsDevice* dev = Context::device(); dev->addLight( ls ); } }
void RobotEnvironment::generateRandomScene(unsigned int& numObstacles) { scene_ = std::make_shared<frapu::Scene>(); std::vector<frapu::ObstacleSharedPtr> obstacles(numObstacles); std::uniform_real_distribution<double> uniform_dist(-1.0, 4.0); std::uniform_real_distribution<double> uniform_distZ(3.0, 6.0); for (size_t i = 0; i < numObstacles; i++) { double rand_x = uniform_dist(randomEngine_); double rand_y = uniform_dist(randomEngine_); double rand_z = uniform_distZ(randomEngine_); frapu::TerrainSharedPtr terrain = std::make_shared<frapu::TerrainImpl>("t" + std::to_string(i), 0.0, 0.0, false, true); std::string box_name = "b" + std::to_string(i); obstacles[i] = std::make_shared<frapu::BoxObstacle>(box_name, rand_x, rand_y, rand_z, 0.25, 0.25, 0.25, terrain); std::vector<double> diffuseColor( {0.5, 0.5, 0.5, 0.5}); static_cast<frapu::ObstacleImpl*>(obstacles[obstacles.size() - 1].get())->setStandardColor(diffuseColor, diffuseColor); std::vector<double> dims( {rand_x, rand_y, rand_z, 0.25, 0.25, 0.25}); robot_->addBox(box_name, dims); } scene_->setObstacles(obstacles); cout << "random scene created " << obstacles.size(); }
/* Parse the "Materials" token */ void scene::parseMaterials() { char token[MAX_PARSER_TOKEN_LENGTH]; char texname[MAX_PARSER_TOKEN_LENGTH]; getToken(token); assert (!strcmp(token, "{")); /* Loop over each Material */ bool working=true; while (working) { getToken(token); if (!strcmp(token, "}")) { working = false; } else if (!strcmp(token, "Material")) { getToken(token); assert (!strcmp(token, "{")); texname[0] = '\0'; Vec3f diffuseColor(1,1,1); Vec3f specularColor(0,0,0); float shininess = 1; Vec3f transparentColor(0,0,0); Vec3f reflectiveColor(0,0,0); float indexOfRefraction = 1; while (1) { getToken(token); if (!strcmp(token, "textureFilename")) { getToken(token); strcpy(texname, token); } else if (!strcmp(token, "diffuseColor")) diffuseColor = readVec3f(); else if (!strcmp(token, "specularColor")) specularColor = readVec3f(); else if (!strcmp(token, "shininess")) shininess = readFloat(); else if (!strcmp(token, "transparentColor")) transparentColor = readVec3f(); else if (!strcmp(token, "reflectiveColor")) reflectiveColor = readVec3f(); else if (!strcmp(token, "indexOfRefraction")) indexOfRefraction = readFloat(); else { assert (!strcmp(token, "}")); break; } } material temp; temp.diffuseCol=diffuseColor; temp.specularCol=specularColor; temp.shininess=shininess; temp.transparentCol=transparentColor; temp.reflectiveCol=reflectiveColor; temp.refractionIndex=indexOfRefraction; if(strcmp(texname, "NULL")) temp.texture=jpeg_read(texname, NULL); else temp.texture=NULL; myMaterials.push_back(temp); } } }
void CVK::Node::load(std::string path) { // load a scene with ASSIMP Assimp::Importer importer; const aiScene* scene = importer.ReadFile(path, aiProcess_GenSmoothNormals | aiProcess_Triangulate); if(scene) printf("SUCCESS: Loaded Model from Path: \"%s\"\n", path.c_str()); else { printf("ERROR: Loading failed from Path: \"%s\"\n", path.c_str()); return; } std::vector<CVK::Material*> materials; // load all materials in this file for(unsigned int i=0; i < scene->mNumMaterials; i++) { aiMaterial* mat = scene->mMaterials[i]; aiColor3D diffColor (0.f,0.f,0.f); mat->Get(AI_MATKEY_COLOR_DIFFUSE, diffColor); aiColor3D specColor (0.f,0.f,0.f); mat->Get(AI_MATKEY_COLOR_SPECULAR, specColor); float shininess = 0.0f; mat->Get(AI_MATKEY_SHININESS, shininess); glm::vec3 diffuseColor(diffColor.r, diffColor.g, diffColor.b); glm::vec3 specularColor(specColor.r, specColor.g, specColor.b); aiString fileName; // filename mat->Get(AI_MATKEY_TEXTURE(aiTextureType_DIFFUSE, 0), fileName); std::string s = path.substr(0, path.rfind("/")) + "/"; s += fileName.data; //materials.push_back(new CVK::Material(glm::vec3(0.0,1.0,0.0), glm::vec3(0.0,0.0,1.0), 10)); if (fileName.length>0) materials.push_back(new CVK::Material( const_cast<char*> ( s.c_str() ), 1.f, 1.f, specularColor, shininess)); //should set kd and ks!! else materials.push_back(new CVK::Material(diffuseColor, specularColor, shininess)); } // load all meshes in this file for(unsigned int i=0; i < scene->mNumMeshes; i++) { aiMesh* mesh = scene->mMeshes[i]; CVK::Geometry* geometry = new CVK::Geometry(); // load geometry information of the current mesh for(unsigned int vCount = 0; vCount < mesh->mNumVertices; vCount++) { // vertices aiVector3D v = mesh->mVertices[vCount]; geometry->getVertices()->push_back( glm::vec4(v.x, v.y, v.z, 1.0f)); // normals if (mesh->HasNormals()) { v = mesh->mNormals[vCount]; geometry->getNormals()->push_back( glm::vec3(v.x, v.y, v.z)); } // texture coordinates if (mesh->HasTextureCoords(0)) { v = mesh->mTextureCoords[0][vCount]; geometry->getUVs()->push_back( glm::vec2(v.x, v.y)); } } for(unsigned int fCount = 0; fCount < mesh->mNumFaces; fCount++) { aiFace f = mesh->mFaces[fCount]; // index numbers for(unsigned int iCount = 0; iCount < f.mNumIndices; iCount++) { geometry->getIndex()->push_back(f.mIndices[iCount]); } } geometry->createBuffers(); // new child node with the geometry and a connection to material CVK::Node* child = new CVK::Node(); child->setGeometry(geometry); child->setMaterial(materials[mesh->mMaterialIndex]); addChild(child); } }
void TerrainShader::SetObjectParameters( Kiwi::Scene* scene, Kiwi::RenderTarget* renderTarget, Kiwi::IRenderable* renderable ) { assert( scene != 0 ); assert( renderTarget != 0 ); assert( renderable != 0 ); Kiwi::Renderer* renderer = scene->GetRenderer(); Kiwi::Camera* camera = renderTarget->GetViewport( 0 )->GetCamera(); Kiwi::Entity* entity = renderable->GetParentEntity(); Kiwi::Transform* transform = entity->GetTransform(); Kiwi::Mesh::Subset* meshSubset = renderable->GetCurrentMeshSubset(); DirectX::XMMATRIX world; DirectX::XMMATRIX view; DirectX::XMMATRIX projection; Kiwi::Matrix4ToXMMATRIX( transform->GetWorldMatrix(), world ); Kiwi::Matrix4ToXMMATRIX( camera->GetViewMatrix(), view ); Kiwi::Matrix4ToXMMATRIX( camera->GetProjectionMatrix(), projection ); //set the worldViewProject matrix DirectX::XMMATRIX wvp = world * view * projection; // lock the vertex object buffer so that it can be written to ID3D11Buffer* vobBuffer = m_vertexBuffers[0]; if( vobBuffer ) { Vertex_ObjectBuffer vertexBuffer = { wvp, world }; renderer->GetDeviceContext()->UpdateSubresource( vobBuffer, 0, NULL, &vertexBuffer, 0, 0 ); } else { throw Kiwi::Exception( L"DefaultShader::SetEntityParameters", L"[" + m_shaderName + L"] The vertex object buffer is null" ); } Kiwi::Color kDiffuseColor = meshSubset->material.GetColor( L"Diffuse" ); DirectX::XMFLOAT4 diffuseColor( kDiffuseColor.red, kDiffuseColor.green, kDiffuseColor.blue, kDiffuseColor.alpha ); DirectX::XMFLOAT4 isTextured( 0.0f, 0.0f, 0.0f, 0.0f ); static unsigned long lastTextureID = 0; //stores the ID of the last texture so we only switch textures when a new one needs to be set if( meshSubset->material.IsTextured() ) { isTextured.x = 1.0f; Kiwi::Texture* matTexture = meshSubset->material.GetTexture( L"Diffuse" ); ID3D11ShaderResourceView* matSRV = matTexture->GetShaderResourceView(); renderer->GetDeviceContext()->PSSetShaderResources( 0, 1, &matSRV ); } ID3D11Buffer* pobBuffer = m_pixelBuffers[0]; if( pobBuffer ) { Pixel_ObjectBuffer pixelBuffer = { diffuseColor, isTextured }; renderer->GetDeviceContext()->UpdateSubresource( pobBuffer, 0, NULL, &pixelBuffer, 0, 0 ); } else { throw Kiwi::Exception( L"DefaultShader::SetEntityParameters", L"[" + m_shaderName + L"] The pixel object buffer is null" ); } }
Color trace (const Ray& ray, std::set<IShape*>& sceneShapes, std::set<Light*>& sceneLights, int depth) { Color pixelColor (0.3); float near; Color color; Vector3D normal; IShape *shape = calculateIntersect (ray, sceneShapes, &near, normal, color); if (shape) { pixelColor = color; Point intersectionPoint = ray.calculate (near); Vector3D n; Color c; pixelColor = Color (0.0f); //Calculate illumination on intersected pixel for (auto light : sceneLights) { Vector3D lightDirection = (light->position () - intersectionPoint); float lightLenght = lightDirection.normalize (); const Ray shadowRay (intersectionPoint + normal * bias, lightDirection, lightLenght); float near = INFINITY; IShape *s = calculateIntersect (shadowRay, sceneShapes, &near, n, c); if (!s) //There is no object between the intersected pixel and this light. { float diffuseCoefficient = shape->diffuse (); float specularCoefficient = shape->specular (); pixelColor += ambientColor (color); if (diffuseCoefficient > 0.0f) pixelColor += diffuseColor (lightDirection, light, normal, color, diffuseCoefficient); if (specularCoefficient > 0.0f) pixelColor += specularColor (lightDirection, normal, ray, light, specularCoefficient); } else //Intersected pixel is shadowed!!! { pixelColor = color * 0.1; break; } } //Calculate the reflected color if ((shape->reflection () > 0) && depth <= MAX_DEPTH) { Vector3D reflDir = ray.direction () - normal * 2 * ray.direction ().dot (normal); reflDir.normalize (); Ray reflectionRay (intersectionPoint + normal * bias, reflDir); Color reflectionColor = trace (reflectionRay, sceneShapes, sceneLights, depth + 1); pixelColor += reflectionColor * shape->reflection (); } } pixelColor.clamp (); return pixelColor; }
MStatus anisotropicShaderNode::compute( const MPlug& plug, MDataBlock& block ) { if ((plug == aOutColor) || (plug.parent() == aOutColor)) { MFloatVector resultColor(0.0,0.0,0.0); MFloatVector diffuseColor( 0.0,0.0,0.0 ); MFloatVector specularColor( 0.0,0.0,0.0 ); MFloatVector ambientColor( 0.0,0.0,0.0 ); // get matrix MFloatMatrix& matrixOToW = block.inputValue( aMatrixOToW ).asFloatMatrix(); MFloatMatrix& matrixWToC = block.inputValue( aMatrixWToC ).asFloatMatrix(); // spin scratch around this vector (in object space ) MFloatVector& A = block.inputValue( aAxesVector ).asFloatVector(); A.normalize(); // spin scratch around this vector (in world space ) MFloatVector wa = A * matrixOToW; wa.normalize(); // spin scratch around this vector (in camera space ) MFloatVector ca = wa * matrixWToC; ca.normalize(); MFloatVector& surfacePoint = block.inputValue( aPointCamera ).asFloatVector(); // get sample surface shading parameters MFloatVector& N = block.inputValue( aNormalCamera ).asFloatVector(); MFloatVector& surfaceColor = block.inputValue( aColor ).asFloatVector(); float diffuseReflectivity = block.inputValue( aDiffuseReflectivity ).asFloat(); float specularCoeff = block.inputValue( aSpecularCoeff ).asFloat(); // get light list MArrayDataHandle lightData = block.inputArrayValue( aLightData ); int numLights = lightData.elementCount(); // iterate through light list and get ambient/diffuse values for( int count=0; count < numLights; count++ ) { MDataHandle currentLight = lightData.inputValue(); MFloatVector& lightIntensity = currentLight.child( aLightIntensity ).asFloatVector(); MFloatVector& lightDirection = currentLight.child( aLightDirection ).asFloatVector(); // find ambient component if( currentLight.child(aLightAmbient).asBool()) { ambientColor[0] += lightIntensity[0] * surfaceColor[0]; ambientColor[1] += lightIntensity[1] * surfaceColor[1]; ambientColor[2] += lightIntensity[2] * surfaceColor[2]; } float cosln = lightDirection * N; if( cosln > 0.0f ){ // illuminated! // find diffuse component if( currentLight.child(aLightDiffuse).asBool()) { float cosDif = cosln * diffuseReflectivity; diffuseColor[0] += lightIntensity[0] * cosDif * surfaceColor[0]; diffuseColor[1] += lightIntensity[1] * cosDif * surfaceColor[1]; diffuseColor[2] += lightIntensity[2] * cosDif * surfaceColor[2]; } // find specular component if( currentLight.child( aLightSpecular).asBool()){ MFloatVector& rayDirection = block.inputValue( aRayDirection ).asFloatVector(); MFloatVector viewDirection = -rayDirection; MFloatVector half = calcHalfVector( viewDirection, lightDirection ); // Beckmann function MFloatVector nA; if( fabs(1.0-fabs(N*ca)) <= 0.0001f ){ MFloatPoint oo( 0.0,0.0,0.0 ); MFloatPoint ow = oo * matrixOToW; MFloatPoint oc = ow * matrixWToC; MFloatVector origin( oc[0], oc[1], oc[2] ); nA = origin - surfacePoint; nA.normalize(); }else{ nA = ca; } MFloatVector x = N ^ nA; x.normalize(); MFloatVector y = N ^ x; y.normalize(); MFloatVector azimuthH = N ^ half; azimuthH = N ^ azimuthH; azimuthH.normalize(); float cos_phai = x * azimuthH; float sin_phai = 0.0; if( fabs(1 - cos_phai*cos_phai) < 0.0001 ){ sin_phai = 0.0; }else{ sin_phai = sqrtf( 1.0f - cos_phai*cos_phai ); } double co = pow( (half * N), 4.0f ); double t = tan( acos(half*N) ); t *= -t; float rough1 = block.inputValue( aRoughness1 ).asFloat(); float rough2 = block.inputValue( aRoughness2 ).asFloat(); double aaa = cos_phai / rough1; double bbb = sin_phai / rough2; t = t * ( aaa*aaa + bbb*bbb ); double D = pow( (1.0/((double)rough1*(double)rough2 * co)), t ); double aa = (2.0 * (N*half) * (N*viewDirection) ) / (viewDirection*half); double bb = (2.0 * (N*half) * (N*lightDirection) ) / (viewDirection*half); double cc = 1.0; double G = 0.0; G = MIN( aa, bb ); G = MIN( G, cc ); float s = (float) (D * G / (double)((N*lightDirection) * (N*viewDirection))); MFloatVector& specColor = block.inputValue( aSpecColor ).asFloatVector(); specularColor[0] += lightIntensity[0] * specColor[0] * s * specularCoeff; specularColor[1] += lightIntensity[1] * specColor[1] * s * specularCoeff; specularColor[2] += lightIntensity[2] * specColor[2] * s * specularCoeff; } } if( !lightData.next() ){ break; } } // result = specular + diffuse + ambient; resultColor = diffuseColor + specularColor + ambientColor; MFloatVector& transparency = block.inputValue( aInTransparency ).asFloatVector(); resultColor[0] *= ( 1.0f - transparency[0] ); resultColor[1] *= ( 1.0f - transparency[1] ); resultColor[2] *= ( 1.0f - transparency[2] ); // set ouput color attribute MDataHandle outColorHandle = block.outputValue( aOutColor ); MFloatVector& outColor = outColorHandle.asFloatVector(); outColor = resultColor; outColorHandle.setClean(); block.setClean( plug ); } else if ((plug == aOutTransparency) || (plug.parent() == aOutTransparency)) { MFloatVector& tr = block.inputValue( aInTransparency ).asFloatVector(); // set ouput color attribute MDataHandle outTransHandle = block.outputValue( aOutTransparency ); MFloatVector& outTrans = outTransHandle.asFloatVector(); outTrans = tr; block.setClean( plug ); } else return MS::kUnknownParameter; return MS::kSuccess; }
MaterialData ModelLoader::loadMaterial(unsigned int index, const aiMaterial* material) { Q_ASSERT(material != nullptr); MaterialData data = MaterialData(); data.name = "material_" + to_string(index); aiColor3D ambientColor(0.1f, 0.1f, 0.1f); aiColor3D diffuseColor(0.8f, 0.8f, 0.8f); aiColor3D specularColor(0.0f, 0.0f, 0.0f); aiColor3D emissiveColor(0.0f, 0.0f, 0.0f); int blendMode; int twoSided = 1; float opacity = 1.0f; float shininess = 0.0f; float shininessStrength = 1.0f; if(material->Get(AI_MATKEY_COLOR_AMBIENT, ambientColor) == AI_SUCCESS) { data.ambientColor.setX(ambientColor.r); data.ambientColor.setY(ambientColor.g); data.ambientColor.setZ(ambientColor.b); } if(material->Get(AI_MATKEY_COLOR_DIFFUSE, diffuseColor) == AI_SUCCESS) { data.diffuseColor.setX(diffuseColor.r); data.diffuseColor.setY(diffuseColor.g); data.diffuseColor.setZ(diffuseColor.b); } if(material->Get(AI_MATKEY_COLOR_SPECULAR, specularColor) == AI_SUCCESS) { data.specularColor.setX(specularColor.r); data.specularColor.setY(specularColor.g); data.specularColor.setZ(specularColor.b); } if(material->Get(AI_MATKEY_COLOR_EMISSIVE, emissiveColor) == AI_SUCCESS) { data.emissiveColor.setX(emissiveColor.r); data.emissiveColor.setY(emissiveColor.g); data.emissiveColor.setZ(emissiveColor.b); } if(material->Get(AI_MATKEY_TWOSIDED, twoSided) == AI_SUCCESS) { data.twoSided = twoSided; } if(material->Get(AI_MATKEY_OPACITY, opacity) == AI_SUCCESS) { data.ambientColor.setW(opacity); data.diffuseColor.setW(opacity); data.specularColor.setW(opacity); data.emissiveColor.setW(opacity); if(opacity < 1.0f) { data.alphaBlending = true; // Activate backface culling allows to avoid // cull artifacts when alpha blending is activated data.twoSided = 1; if(material->Get(AI_MATKEY_BLEND_FUNC, blendMode) == AI_SUCCESS) { if(blendMode == aiBlendMode_Additive) data.blendMode = aiBlendMode_Additive; else data.blendMode = aiBlendMode_Default; } } else { data.alphaBlending = false; data.blendMode = -1; } } if(material->Get(AI_MATKEY_SHININESS, shininess) == AI_SUCCESS) { data.shininess = shininess; } if(material->Get(AI_MATKEY_SHININESS_STRENGTH, shininessStrength) == AI_SUCCESS) { data.shininessStrength = shininessStrength; } return data; }
void RTRRadianceRenderer::renderPhoton( RTRVector3D location, RTRVector3D direction, QVector<Photon*> &result, RTRRenderElement *emissionElement, RTRColor lightColor, bool causticOnly) { RTRColor photonColor = lightColor; //if (sampler->generateRandomNumber() > qAbs(direction.z())) // return; bool refracInAir = true; RTRRenderElement* intersectElement = emissionElement; Photon::Type photonType = Photon::Type::DIRECT; for(int i = 0; i < 32; i++) { RTRRay ray(location, direction, RTRRay::CREATE_FROM_POINT_AND_DIRECTION); elementsCache->search(intersectElement, ray, intersectElement); if(intersectElement == nullptr) { //qDebug() << "No element"; /*if(i != 0) { result.append(photon); }*/ return; } RTRVector3D intersectPoint; RTRVector3D intersectNormal; RTRColor intersectColor; intersectElement->intersect(ray, intersectPoint, intersectNormal, intersectColor); double reflectionRate = intersectElement->material->reflectionRate; RTRColor mtlReflColor= intersectElement->material->reflectionColor; double mtlReflGloss = 1.0; RTRColor mtlSpecColor; double mtlRefracRate = intersectElement->material->refractionRate; double mtlRefracIndex = intersectElement->material->refractionIndex; RTRColor mtlRefracColor(1.0, 1.0, 1.0); double mtlRefracGloss = 1.0; double mtlDiffuseRate = 0.0; if (intersectElement->material->getPropertyType("reflection_glossiness") == RTRMaterial::TYPE_COLOR) mtlReflGloss = intersectElement->material->getColorAt("reflection_glossiness", 0, 0).r(); if (intersectElement->material->getPropertyType("specular") == RTRMaterial::TYPE_COLOR) mtlSpecColor = intersectElement->material->getColorAt("specular", 0, 0); if (intersectElement->material->getPropertyType("refraction_color") == RTRMaterial::TYPE_COLOR) mtlRefracColor = intersectElement->material->getColorAt("refraction_color", 0, 0); if (intersectElement->material->getPropertyType("refraction_glossiness") == RTRMaterial::TYPE_COLOR) mtlRefracGloss = intersectElement->material->getColorAt("refraction_glossiness", 0, 0).r(); mtlDiffuseRate = intersectElement->material->getColorAt("Kd", 0, 0).r(); //Decide which kind of intersection is happening if (intersectElement->material->emissionStrength > 0.001) { return; } if (reflectionRate > 0.00001 && rand() / (float)RAND_MAX < reflectionRate) { if (intersectNormal.dotProduct(ray.direction) < 0) { intersectNormal = intersectNormal * (-1.0); } RTRVector3D reflectionDirection(0.0, 0.0, 0.0); reflectionDirection = (intersectNormal * 2 * ray.direction.dotProduct(intersectNormal) - ray.direction)*-1; /*if (mtlReflGloss < 0.99999) { reflectionDirection.x() *= (1 + (qrand() / (double)RAND_MAX * 2 - 1)*(1 - mtlReflGloss)); reflectionDirection.y() *= (1 + (qrand() / (double)RAND_MAX * 2 - 1)*(1 - mtlReflGloss)); reflectionDirection.z() *= (1 + (qrand() / (double)RAND_MAX * 2 - 1)*(1 - mtlReflGloss)); }*/ location = intersectPoint; direction = reflectionDirection; photonColor = RTRColor( photonColor.r() * mtlReflColor.r(),photonColor.g() * mtlReflColor.g(),photonColor.b() * mtlReflColor.b()); if(photonType == Photon::Type::DIRECT || photonType == Photon::Type::SPECULAR) photonType = Photon::Type::SPECULAR; else photonType = Photon::Type::DIFFUSE_INTERREFLECTION; } else if (mtlRefracRate > 0.00001 && rand() / (float)RAND_MAX < mtlRefracRate) { double IOR = refracInAir ? mtlRefracIndex : 1 / mtlRefracIndex; RTRVector3D refractionNormal = intersectNormal; /*if (mtlRefracGloss < 0.99999) { refractionNormal.x() *= (1 + (qrand() / (double)RAND_MAX * 2 - 1)*(1 - mtlRefracGloss)); refractionNormal.y() *= (1 + (qrand() / (double)RAND_MAX * 2 - 1)*(1 - mtlRefracGloss)); refractionNormal.z() *= (1 + (qrand() / (double)RAND_MAX * 2 - 1)*(1 - mtlRefracGloss)); }*/ if (refractionNormal.dotProduct(ray.direction) > 0) refractionNormal = refractionNormal * (-1); double c = -ray.direction.dotProduct(refractionNormal); double r = IOR;// 1 / IOR; double temp = 1 - r*r*(1 - c*c); if(photonType == Photon::Type::DIRECT || photonType == Photon::Type::SPECULAR) photonType = Photon::Type::SPECULAR; else photonType = Photon::Type::DIFFUSE_INTERREFLECTION; if (temp > 0) { RTRVector3D refractionDirection = ray.direction * r + refractionNormal*(r*c - qSqrt(temp)); location = intersectPoint; direction = refractionDirection; refracInAir = !refracInAir; photonColor = RTRColor( photonColor.r() * mtlRefracColor.r(), photonColor.g() * mtlRefracColor.g(), photonColor.b() * mtlRefracColor.b() ); } else return; } else { if(photonType == Photon::Type::SPECULAR) photonType = Photon::Type::CAUSTIC; else if(photonType == Photon::Type::DIRECT) photonType = Photon::Type::DIFFUSE; else photonType = Photon::Type::DIFFUSE_INTERREFLECTION; if((causticOnly && photonType == Photon::Type::CAUSTIC) || (!causticOnly /*&& photonType != Photon::Type::CAUSTIC*/)) { Photon *photon = new Photon(); photon->color = photonColor; photon->direction = direction; photon->location = intersectPoint; photon->type = photonType; result.append(photon); } if(causticOnly) { return; } RTRVector3D nextPhotonDirection; //qDebug() << "N" << intersectNormal.x() << intersectNormal.y() << intersectNormal.z(); if(intersectNormal.dotProduct(direction) > 0) { intersectNormal = intersectNormal * -1.0; } for(;;) { nextPhotonDirection = sampler->generateRandomDirection(); double project = nextPhotonDirection.dotProduct(intersectNormal); if(project > sampler->generateRandomNumber()) break; //if (i == 10) return; } RTRColor diffuseColor(0.0, 0.0, 0.0); RTRColor specColor; double decay = nextPhotonDirection.dotProduct(intersectNormal); photonColor = intersectColor * photonColor; //qDebug() << "DIFFUSE"; location = intersectPoint; direction = nextPhotonDirection; //if(sampler->generateRandomNumber() > 0.9) //{ // return; //} //result.append(photon); } } }
// Execute OpenGL Material void GLC_Material::glExecute(float overwriteTransparency) { GLfloat pAmbientColor[4]= {ambientColor().redF(), ambientColor().greenF(), ambientColor().blueF(), overwriteTransparency}; GLfloat pDiffuseColor[4]= {diffuseColor().redF(), diffuseColor().greenF(), diffuseColor().blueF(), overwriteTransparency}; GLfloat pSpecularColor[4]= {specularColor().redF(), specularColor().greenF(), specularColor().blueF(), overwriteTransparency}; GLfloat pLightEmission[4]= {emissiveColor().redF(), emissiveColor().greenF(), emissiveColor().blueF(), overwriteTransparency}; const bool textureIsEnable= glIsEnabled(GL_TEXTURE_2D); if (m_pTexture != NULL) { if (!textureIsEnable) glEnable(GL_TEXTURE_2D); m_pTexture->glcBindTexture(); if (GLC_State::glslUsed()) { if (GLC_Shader::hasActiveShader()) { GLC_Shader::currentShaderHandle()->programShaderHandle()->setUniformValue("tex", GLint(0)); GLC_Shader::currentShaderHandle()->programShaderHandle()->setUniformValue("useTexture", true); } } } else { if (textureIsEnable) glDisable(GL_TEXTURE_2D); if (GLC_State::glslUsed()) { if (GLC_Shader::hasActiveShader()) { GLC_Shader::currentShaderHandle()->programShaderHandle()->setUniformValue("tex", GLint(0)); GLC_Shader::currentShaderHandle()->programShaderHandle()->setUniformValue("useTexture", false); } } } glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, pAmbientColor); glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, pDiffuseColor); glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, pSpecularColor); glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, pLightEmission); glMaterialfv(GL_FRONT_AND_BACK, GL_SHININESS, &m_Shininess); glColor4fv(pDiffuseColor); // OpenGL Error handler GLenum error= glGetError(); if (error != GL_NO_ERROR) { GLC_OpenGlException OpenGlException("GLC_Material::glExecute(float overwriteTransparency) ", error); throw(OpenGlException); } }
BxDF* XMLReader::LoadBxDF(QXmlStreamReader &xml_reader) { BxDF* result = NULL; //First check what type of material we're supposed to load QXmlStreamAttributes attribs(xml_reader.attributes()); QStringRef type = attribs.value(QString(), QString("type")); if(QStringRef::compare(type, QString("lambert")) == 0) { glm::vec3 diffuseColor(0.5f); QStringRef color = attribs.value(QString(), QString("diffuseColor")); if(QStringRef::compare(color, QString("")) != 0) { diffuseColor = ToVec3(color); } result = new LambertBxDF(diffuseColor); } else if(QStringRef::compare(type, QString("specularReflection")) == 0) { glm::vec3 refl_color(0.5f); QStringRef color = attribs.value(QString(), QString("reflectionColor")); if(QStringRef::compare(color, QString("")) != 0) { refl_color = ToVec3(color); } result = new SpecularReflectionBxDF(refl_color); } else if(QStringRef::compare(type, QString("blinnMicrofacet")) == 0) { glm::vec3 refl_color(0.5f); QStringRef color = attribs.value(QString(), QString("reflectionColor")); if(QStringRef::compare(color, QString("")) != 0) { refl_color = ToVec3(color); } result = new BlinnMicrofacetBxDF(refl_color); QStringRef exponent = attribs.value(QString(), QString("exponent")); if(QStringRef::compare(exponent, QString("")) != 0) { ((BlinnMicrofacetBxDF*)result)->exponent = exponent.toFloat(); } } else if(QStringRef::compare(type, QString("anisotropic")) == 0) { glm::vec3 refl_color(0.5f); QStringRef color = attribs.value(QString(), QString("reflectionColor")); if(QStringRef::compare(color, QString("")) != 0) { refl_color = ToVec3(color); } float exp1 = 4.0f; QStringRef e1 = attribs.value(QString(), QString("exponent1")); if(QStringRef::compare(e1, QString("")) != 0) { exp1 = e1.toFloat(); } float exp2 = 20.0f; QStringRef e2 = attribs.value(QString(), QString("exponent2")); if(QStringRef::compare(e2, QString("")) != 0) { exp2 = e2.toFloat(); } result = new AnisotropicBxDF(refl_color, exp1, exp2); } else if(QStringRef::compare(type, QString("phong")) == 0) { glm::vec3 diffuseColor(0.5f); QStringRef diffuse_color = attribs.value(QString(), QString("diffuseColor")); if(QStringRef::compare(diffuse_color, QString("")) != 0) { diffuseColor = ToVec3(diffuse_color); } glm::vec3 specularColor(1); QStringRef specular_color = attribs.value(QString(), QString("specularColor")); if(QStringRef::compare(specular_color, QString("")) != 0) { specularColor = ToVec3(specular_color); } float specularPower = 5.0f; QStringRef specular_power = attribs.value(QString(), QString("specularPower")); if(QStringRef::compare(specular_power, QString("")) != 0) { specularPower = specular_power.toFloat(); } result = new PhongBxDF(diffuseColor, specularColor, specularPower); } else if(QStringRef::compare(type, QString("transmission")) == 0) { float ei = 1.0f; float et = 1.0f; QStringRef eta_i = attribs.value(QString(), QString("etai")); if(QStringRef::compare(eta_i, QString("")) != 0) { ei = eta_i.toFloat(); } QStringRef eta_t = attribs.value(QString(), QString("etat")); if(QStringRef::compare(eta_i, QString("")) != 0) { et = eta_t.toFloat(); } glm::vec3 transmissionColor(1); QStringRef trans = attribs.value(QString(), QString("transmissionColor")); if(QStringRef::compare(trans, QString("")) != 0) { transmissionColor = ToVec3(trans); } result = new TransmissionBxDF(ei,et,transmissionColor); } else { std::cout << "Could not parse the BxDF!" << std::endl; return NULL; } result->name = attribs.value(QString(), QString("name")).toString(); return result; }
int main( int argc, char **argv ) { int width = 1024, height=768; float widthf = (float) width, heightf = (float) height; double t; float fps = 0.f; // Initialise GLFW if( !glfwInit() ) { fprintf( stderr, "Failed to initialize GLFW\n" ); exit( EXIT_FAILURE ); } // Force core profile on Mac OSX #ifdef __APPLE__ glfwOpenWindowHint(GLFW_OPENGL_VERSION_MAJOR, 3); glfwOpenWindowHint(GLFW_OPENGL_VERSION_MINOR, 2); glfwOpenWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); glfwOpenWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); #endif // Open a window and create its OpenGL context if( !glfwOpenWindow( width, height, 0,0,0,0, 24, 0, GLFW_WINDOW ) ) { fprintf( stderr, "Failed to open GLFW window\n" ); glfwTerminate(); exit( EXIT_FAILURE ); } glfwSetWindowTitle( "002_forward_a" ); // Core profile is flagged as experimental in glew #ifdef __APPLE__ glewExperimental = GL_TRUE; #endif GLenum err = glewInit(); if (GLEW_OK != err) { /* Problem: glewInit failed, something is seriously wrong. */ fprintf(stderr, "Error: %s\n", glewGetErrorString(err)); exit( EXIT_FAILURE ); } // Ensure we can capture the escape key being pressed below glfwEnable( GLFW_STICKY_KEYS ); // Enable vertical sync (on cards that support it) glfwSwapInterval( 1 ); GLenum glerr = GL_NO_ERROR; glerr = glGetError(); if (!imguiRenderGLInit(DroidSans_ttf, DroidSans_ttf_len)) { fprintf(stderr, "Could not init GUI renderer.\n"); exit(EXIT_FAILURE); } // Init viewer structures Camera camera; camera_defaults(camera); GUIStates guiStates; init_gui_states(guiStates); // GUI float intensity = 1.0; // Load images and upload textures GLuint textures[3]; glGenTextures(3, textures); int x; int y; int comp; unsigned char * diffuse = stbi_load("textures/spnza_bricks_a_diff.tga", &x, &y, &comp, 3); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, textures[0]); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, x, y, 0, GL_RGB, GL_UNSIGNED_BYTE, diffuse); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); fprintf(stderr, "Diffuse %dx%d:%d\n", x, y, comp); unsigned char * spec = stbi_load("textures/spnza_bricks_a_spec.tga", &x, &y, &comp, 1); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, textures[1]); glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, x, y, 0, GL_RED, GL_UNSIGNED_BYTE, spec); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); fprintf(stderr, "Spec %dx%d:%d\n", x, y, comp); // Try to load and compile shader ShaderGLSL shader; const char * shaderFile = "002/1.glsl"; //int status = load_shader_from_file(shader, shaderFile, ShaderGLSL::VERTEX_SHADER | ShaderGLSL::FRAGMENT_SHADER | ShaderGLSL::GEOMETRY_SHADER); int status = load_shader_from_file(shader, shaderFile, ShaderGLSL::VERTEX_SHADER | ShaderGLSL::FRAGMENT_SHADER); if ( status == -1 ) { fprintf(stderr, "Error on loading %s\n", shaderFile); exit( EXIT_FAILURE ); } // Apply shader GLuint program = shader.program; glUseProgram(program); GLuint projectionLocation = glGetUniformLocation(program, "Projection"); GLuint viewLocation = glGetUniformLocation(program, "View"); GLuint objectLocation = glGetUniformLocation(program, "Object"); GLuint timeLocation = glGetUniformLocation(program, "Time"); GLuint diffuseLocation = glGetUniformLocation(program, "Diffuse"); GLuint specLocation = glGetUniformLocation(program, "Spec"); GLuint intensityLocation = glGetUniformLocation(program, "Intensity"); GLuint cameraPositionLocation = glGetUniformLocation(program, "CameraPosition"); GLuint lightPositionLocation = glGetUniformLocation(program, "LightPosition"); GLuint lightIntensityLocation = glGetUniformLocation(program, "LightIntensity"); GLuint diffuseColorLocation = glGetUniformLocation(program, "DiffuseColor"); GLuint specularColorLocation = glGetUniformLocation(program, "SpecularColor"); GLuint specularFactorLocation = glGetUniformLocation(program, "SpecularFactor"); GLuint lightPositionLocation2 = glGetUniformLocation(program, "LightPosition2"); GLuint lightIntensityLocation2 = glGetUniformLocation(program, "LightIntensity2"); GLuint diffuseColorLocation2 = glGetUniformLocation(program, "DiffuseColor2"); GLuint specularColorLocation2 = glGetUniformLocation(program, "SpecularColor2"); GLuint specularFactorLocation2 = glGetUniformLocation(program, "SpecularFactor2"); GLuint spotLightExternalAngleLocation = glGetUniformLocation(program, "SpotLightExternalAngle"); GLuint spotLightInternalAngleLocation = glGetUniformLocation(program, "SpotLightInternalAngle"); // Load geometry int cube_triangleCount = 12; int cube_triangleList[] = {0, 1, 2, 2, 1, 3, 4, 5, 6, 6, 5, 7, 8, 9, 10, 10, 9, 11, 12, 13, 14, 14, 13, 15, 16, 17, 18, 19, 17, 20, 21, 22, 23, 24, 25, 26, }; float cube_uvs[] = {0.f, 0.f, 0.f, 1.f, 1.f, 0.f, 1.f, 1.f, 0.f, 0.f, 0.f, 1.f, 1.f, 0.f, 1.f, 1.f, 0.f, 0.f, 0.f, 1.f, 1.f, 0.f, 1.f, 1.f, 0.f, 0.f, 0.f, 1.f, 1.f, 0.f, 1.f, 1.f, 0.f, 0.f, 0.f, 1.f, 1.f, 0.f, 1.f, 0.f, 1.f, 1.f, 0.f, 1.f, 1.f, 1.f, 0.f, 0.f, 0.f, 0.f, 1.f, 1.f, 1.f, 0.f, }; float cube_vertices[] = {-0.5, -0.5, 0.5, 0.5, -0.5, 0.5, -0.5, 0.5, 0.5, 0.5, 0.5, 0.5, -0.5, 0.5, 0.5, 0.5, 0.5, 0.5, -0.5, 0.5, -0.5, 0.5, 0.5, -0.5, -0.5, 0.5, -0.5, 0.5, 0.5, -0.5, -0.5, -0.5, -0.5, 0.5, -0.5, -0.5, -0.5, -0.5, -0.5, 0.5, -0.5, -0.5, -0.5, -0.5, 0.5, 0.5, -0.5, 0.5, 0.5, -0.5, 0.5, 0.5, -0.5, -0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, -0.5, -0.5, -0.5, -0.5, -0.5, -0.5, 0.5, -0.5, 0.5, -0.5, -0.5, 0.5, -0.5, -0.5, -0.5, 0.5, -0.5, 0.5, 0.5 }; float cube_normals[] = {0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, }; int plane_triangleCount = 2; int plane_triangleList[] = {0, 1, 2, 2, 1, 3}; float plane_uvs[] = {0.f, 0.f, 0.f, 10.f, 10.f, 0.f, 10.f, 10.f}; float plane_vertices[] = {-50.0, -1.0, 50.0, 50.0, -1.0, 50.0, -50.0, -1.0, -50.0, 50.0, -1.0, -50.0}; float plane_normals[] = {0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0}; // Vertex Array Object GLuint vao[2]; glGenVertexArrays(2, vao); // Vertex Buffer Objects GLuint vbo[8]; glGenBuffers(8, vbo); // Cube glBindVertexArray(vao[0]); // Bind indices and upload data glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vbo[0]); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(cube_triangleList), cube_triangleList, GL_STATIC_DRAW); // Bind vertices and upload data glBindBuffer(GL_ARRAY_BUFFER, vbo[1]); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(GL_FLOAT)*3, (void*)0); glBufferData(GL_ARRAY_BUFFER, sizeof(cube_vertices), cube_vertices, GL_STATIC_DRAW); // Bind normals and upload data glBindBuffer(GL_ARRAY_BUFFER, vbo[2]); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(GL_FLOAT)*3, (void*)0); glBufferData(GL_ARRAY_BUFFER, sizeof(cube_normals), cube_normals, GL_STATIC_DRAW); // Bind uv coords and upload data glBindBuffer(GL_ARRAY_BUFFER, vbo[3]); glEnableVertexAttribArray(2); glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(GL_FLOAT)*2, (void*)0); glBufferData(GL_ARRAY_BUFFER, sizeof(cube_uvs), cube_uvs, GL_STATIC_DRAW); // Plane glBindVertexArray(vao[1]); // Bind indices and upload data glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vbo[4]); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(plane_triangleList), plane_triangleList, GL_STATIC_DRAW); // Bind vertices and upload data glBindBuffer(GL_ARRAY_BUFFER, vbo[5]); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(GL_FLOAT)*3, (void*)0); glBufferData(GL_ARRAY_BUFFER, sizeof(plane_vertices), plane_vertices, GL_STATIC_DRAW); // Bind normals and upload data glBindBuffer(GL_ARRAY_BUFFER, vbo[6]); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(GL_FLOAT)*3, (void*)0); glBufferData(GL_ARRAY_BUFFER, sizeof(plane_normals), plane_normals, GL_STATIC_DRAW); // Bind uv coords and upload data glBindBuffer(GL_ARRAY_BUFFER, vbo[7]); glEnableVertexAttribArray(2); glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(GL_FLOAT)*2, (void*)0); glBufferData(GL_ARRAY_BUFFER, sizeof(plane_uvs), plane_uvs, GL_STATIC_DRAW); // Unbind everything. Potentially illegal on some implementations glBindVertexArray(0); glBindBuffer(GL_ARRAY_BUFFER, 0); // Viewport glViewport( 0, 0, width, height ); // Default states glm::vec3 lightPosition(0.0, 1.0, 10); float lightIntensity = 1.0f; glm::vec3 diffuseColor(1.0, 1.0, 1.0); glm::vec3 specularColor(1.0, 1.0, 1.0); float specularFactor = 100.f; glm::vec3 lightPosition2(1.0, 0.0, 10); float lightIntensity2 = 1.0f; glm::vec3 diffuseColor2(1.0, 0.0, 0.0); glm::vec3 specularColor2(1.0, 1.0, 1.0); float specularFactor2 = 100.f; float spotLightInternal = M_PI/32; float spotLightExternal = M_PI/16; bool checkedLight1 = true; bool checkedLight2 = false; bool checkedLight3 = false; do { t = glfwGetTime(); glEnable(GL_DEPTH_TEST); // Mouse states int leftButton = glfwGetMouseButton( GLFW_MOUSE_BUTTON_LEFT ); int rightButton = glfwGetMouseButton( GLFW_MOUSE_BUTTON_RIGHT ); int middleButton = glfwGetMouseButton( GLFW_MOUSE_BUTTON_MIDDLE ); if( leftButton == GLFW_PRESS ) guiStates.turnLock = true; else guiStates.turnLock = false; if( rightButton == GLFW_PRESS ) guiStates.zoomLock = true; else guiStates.zoomLock = false; if( middleButton == GLFW_PRESS ) guiStates.panLock = true; else guiStates.panLock = false; // Camera movements int altPressed = glfwGetKey(GLFW_KEY_LSHIFT); if (!altPressed && (leftButton == GLFW_PRESS || rightButton == GLFW_PRESS || middleButton == GLFW_PRESS)) { int x; int y; glfwGetMousePos(&x, &y); guiStates.lockPositionX = x; guiStates.lockPositionY = y; } if (altPressed == GLFW_PRESS) { int mousex; int mousey; glfwGetMousePos(&mousex, &mousey); int diffLockPositionX = mousex - guiStates.lockPositionX; int diffLockPositionY = mousey - guiStates.lockPositionY; if (guiStates.zoomLock) { float zoomDir = 0.0; if (diffLockPositionX > 0) zoomDir = -1.f; else if (diffLockPositionX < 0 ) zoomDir = 1.f; camera_zoom(camera, zoomDir * GUIStates::MOUSE_ZOOM_SPEED); } else if (guiStates.turnLock) { camera_turn(camera, diffLockPositionY * GUIStates::MOUSE_TURN_SPEED, diffLockPositionX * GUIStates::MOUSE_TURN_SPEED); } else if (guiStates.panLock) { camera_pan(camera, diffLockPositionX * GUIStates::MOUSE_PAN_SPEED, diffLockPositionY * GUIStates::MOUSE_PAN_SPEED); } guiStates.lockPositionX = mousex; guiStates.lockPositionY = mousey; } // Get camera matrices glm::mat4 projection = glm::perspective(45.0f, widthf / heightf, 0.1f, 100.f); glm::mat4 worldToView = glm::lookAt(camera.eye, camera.o, camera.up); glm::mat4 objectToWorld; // Clear the front buffer glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Bind textures glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, textures[0]); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, textures[1]); // Bind shader glUseProgram(program); // Upload uniforms glUniformMatrix4fv(projectionLocation, 1, 0, glm::value_ptr(projection)); glUniformMatrix4fv(viewLocation, 1, 0, glm::value_ptr(worldToView)); glUniformMatrix4fv(objectLocation, 1, 0, glm::value_ptr(objectToWorld)); glUniform1f(timeLocation, t); glUniform3fv(cameraPositionLocation, 1, glm::value_ptr(camera.eye)); glUniform1f(intensityLocation, intensity); glUniform1i(diffuseLocation, 0); glUniform1i(specLocation, 1); glUniform3fv(lightPositionLocation, 1, glm::value_ptr(lightPosition)); glUniform1f(lightIntensityLocation, lightIntensity); glUniform3fv(diffuseColorLocation, 1, glm::value_ptr(diffuseColor)); glUniform3fv(specularColorLocation, 1, glm::value_ptr(specularColor)); glUniform1f(specularFactorLocation, specularFactor); glUniform3fv(lightPositionLocation2, 1, glm::value_ptr(lightPosition2)); glUniform1f(lightIntensityLocation2, lightIntensity2); glUniform3fv(diffuseColorLocation2, 1, glm::value_ptr(diffuseColor2)); glUniform3fv(specularColorLocation2, 1, glm::value_ptr(specularColor2)); glUniform1f(specularFactorLocation2, specularFactor2); glUniform1f(spotLightInternalAngleLocation, spotLightInternal); glUniform1f(spotLightExternalAngleLocation, spotLightExternal); // Render vaos glBindVertexArray(vao[0]); glDrawElementsInstanced(GL_TRIANGLES, cube_triangleCount * 3, GL_UNSIGNED_INT, (void*)0, 4); glBindVertexArray(vao[1]); glDrawElements(GL_TRIANGLES, plane_triangleCount * 3, GL_UNSIGNED_INT, (void*)0); #if 1 // Draw UI glDisable(GL_DEPTH_TEST); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glViewport(0, 0, width, height); unsigned char mbut = 0; int mscroll = 0; int mousex; int mousey; glfwGetMousePos(&mousex, &mousey); mousey = height - mousey; if( leftButton == GLFW_PRESS ) mbut |= IMGUI_MBUT_LEFT; imguiBeginFrame(mousex, mousey, mbut, mscroll); int logScroll = 0; char lineBuffer[512]; imguiBeginScrollArea("001", 0, 0, 200, height, &logScroll); sprintf(lineBuffer, "FPS %f", fps); imguiLabel(lineBuffer); int toggle = 0; toggle = imguiCollapse("Light1", "", checkedLight1); if(checkedLight1) { imguiIndent(); imguiIndent(); imguiLabel("Light Position"); imguiIndent(); imguiSlider("x", &lightPosition.x, -10, 10, 0.01); imguiSlider("y", &lightPosition.y, -10, 10, 0.01); imguiSlider("z", &lightPosition.z, -10, 10, 0.01); imguiUnindent(); imguiSlider("Light Intensity", &lightIntensity, 0, 3, 0.01); imguiLabel("Diffuse Color"); imguiIndent(); imguiSlider("r", &diffuseColor.x, 0, 1, 0.001); imguiSlider("g", &diffuseColor.y, 0, 1, 0.001); imguiSlider("b", &diffuseColor.z, 0, 1, 0.001); imguiUnindent(); imguiLabel("Specular Color"); imguiIndent(); imguiSlider("r", &specularColor.x, 0, 1, 0.001); imguiSlider("g", &specularColor.y, 0, 1, 0.001); imguiSlider("b", &specularColor.z, 0, 1, 0.001); imguiUnindent(); imguiSlider("Specular Intensity", &specularFactor, 0, 100, 1); imguiUnindent(); imguiUnindent(); } if (toggle) { checkedLight1 = !checkedLight1; } toggle = imguiCollapse("Light2", "", checkedLight2); if(checkedLight2) { imguiIndent(); imguiIndent(); imguiLabel("Light Position"); imguiIndent(); imguiSlider("x", &lightPosition2.x, -10, 10, 0.01); imguiSlider("y", &lightPosition2.y, -10, 10, 0.01); imguiSlider("z", &lightPosition2.z, -10, 10, 0.01); imguiUnindent(); imguiSlider("Light Intensity", &lightIntensity2, 0, 3, 0.01); imguiLabel("Diffuse Color"); imguiIndent(); imguiSlider("r", &diffuseColor2.x, 0, 1, 0.001); imguiSlider("g", &diffuseColor2.y, 0, 1, 0.001); imguiSlider("b", &diffuseColor2.z, 0, 1, 0.001); imguiUnindent(); imguiLabel("Specular Color"); imguiIndent(); imguiSlider("r", &specularColor2.x, 0, 1, 0.001); imguiSlider("g", &specularColor2.y, 0, 1, 0.001); imguiSlider("b", &specularColor2.z, 0, 1, 0.001); imguiUnindent(); imguiSlider("Specular Intensity", &specularFactor2, 0, 100, 1); imguiUnindent(); imguiUnindent(); } if (toggle) { checkedLight2 = !checkedLight2; } toggle = imguiCollapse("SpotLight", "", checkedLight3); if(checkedLight3) { imguiIndent(); imguiIndent(); imguiSlider("External Angle", &spotLightExternal, 0, 2, 0.01); imguiSlider("Internal Angle", &spotLightInternal, 0, 2, 0.01); imguiUnindent(); imguiUnindent(); } if (toggle) { checkedLight3 = !checkedLight3; } imguiEndScrollArea(); imguiEndFrame(); imguiRenderGLDraw(width, height); glDisable(GL_BLEND); #endif // Check for errors GLenum err = glGetError(); if(err != GL_NO_ERROR) { fprintf(stderr, "OpenGL Error : %s\n", gluErrorString(err)); } // Swap buffers glfwSwapBuffers(); } // Check if the ESC key was pressed or the window was closed while( glfwGetKey( GLFW_KEY_ESC ) != GLFW_PRESS && glfwGetWindowParam( GLFW_OPENED ) ); // Clean UI imguiRenderGLDestroy(); // Close OpenGL window and terminate GLFW glfwTerminate(); exit( EXIT_SUCCESS ); }
void Material::ExportMaterials(FbxScene* scene, FbxMesh* mesh, const ImporterMesh& importedMesh, const ImporterMaterial* importedMaterials) { for (int i = 0; i < importedMesh.material_count; i++) { FbxNode* node = mesh->GetNode(); FbxString materialName = importedMaterials[importedMesh.material_Id[i]].name; FbxString shadingName; FbxDouble3 diffuseColor(importedMaterials[importedMesh.material_Id[i]].diffuse[0], importedMaterials[importedMesh.material_Id[i]].diffuse[1], importedMaterials[importedMesh.material_Id[i]].diffuse[2]); FbxDouble3 ambientColor(importedMaterials[importedMesh.material_Id[i]].ambient[0], importedMaterials[importedMesh.material_Id[i]].ambient[1], importedMaterials[importedMesh.material_Id[i]].ambient[2]); FbxDouble3 emissiveColor(importedMaterials[importedMesh.material_Id[i]].incandescence[0], importedMaterials[importedMesh.material_Id[i]].incandescence[1], importedMaterials[importedMesh.material_Id[i]].incandescence[2]); FbxDouble3 transparencyColor(importedMaterials[importedMesh.material_Id[i]].transparency_color[0], importedMaterials[importedMesh.material_Id[i]].transparency_color[1], importedMaterials[importedMesh.material_Id[i]].transparency_color[2]); FbxDouble3 specularColor(importedMaterials[importedMesh.material_Id[i]].specular[0], importedMaterials[importedMesh.material_Id[i]].specular[1] , importedMaterials[importedMesh.material_Id[i]].specular[2]); const char* pathName = "C://Users/Litet/Documents/GitHub/SmallGameProject/FBX Export/FBX Export/"; // Lambert if (importedMaterials[importedMesh.material_Id[i]].mtrl_type == 0) { shadingName = "Lambert"; FbxSurfaceLambert* material = NULL; material= node->GetSrcObject<FbxSurfaceLambert>(0); material = FbxSurfaceLambert::Create(scene, materialName.Buffer()); materialName += i; material->Emissive.Set(emissiveColor); material->Ambient.Set(ambientColor); material->Diffuse.Set(diffuseColor); material->DiffuseFactor.Set(importedMaterials[importedMesh.material_Id[i]].diffuse_factor); material->TransparentColor.Set(transparencyColor); FbxNode* node = mesh->GetNode(); if (node) { node->AddMaterial(material); } // Diffuse Texture FbxFileTexture* texture = FbxFileTexture::Create(scene, "Diffuse Texture"); std::cout << "DAFUSE MAP LENGTH: " << importedMaterials[importedMesh.material_Id[i]].duffuse_map_length << std::endl; if (importedMaterials[importedMesh.material_Id[i]].duffuse_map_length > 0) { std::string tmp(pathName); tmp += importedMaterials[importedMesh.material_Id[i]].diffuse_map; texture->SetFileName(tmp.c_str()); texture->SetTextureUse(FbxTexture::eStandard); texture->SetMappingType(FbxTexture::eUV); texture->SetMaterialUse(FbxFileTexture::eModelMaterial); texture->SetSwapUV(false); texture->SetTranslation(0.0, 0.0); texture->SetScale(1.0, 1.0); texture->SetRotation(0.0, 0.0); if (material) material->Diffuse.ConnectSrcObject(texture); } // Normal Texture texture = FbxFileTexture::Create(scene, "Normal Texture"); if (importedMaterials[importedMesh.material_Id[i]].normal_map_length > 0) { texture->SetFileName(importedMaterials[importedMesh.material_Id[i]].normal_map); texture->SetTextureUse(FbxTexture::eStandard); texture->SetMappingType(FbxTexture::eUV); texture->SetMaterialUse(FbxFileTexture::eModelMaterial); texture->SetSwapUV(false); texture->SetTranslation(0.0, 0.0); texture->SetScale(1.0, 1.0); texture->SetRotation(0.0, 0.0); if (material) material->NormalMap.ConnectSrcObject(texture); } } // Phong else { shadingName = "Phong"; FbxSurfacePhong* material = NULL; material = node->GetSrcObject<FbxSurfacePhong>(0); material = FbxSurfacePhong::Create(scene, materialName.Buffer()); materialName += i; material->Emissive.Set(emissiveColor); material->Ambient.Set(ambientColor); material->Diffuse.Set(diffuseColor); material->DiffuseFactor.Set(importedMaterials[importedMesh.material_Id[i]].diffuse_factor); material->TransparentColor.Set(transparencyColor); material->Specular.Set(specularColor); // No need... super boost? //material->SpecularFactor.Set(importedMaterials[importedMesh.material_Id[i]].specular_factor * 100); material->Shininess.Set(importedMaterials[importedMesh.material_Id[i]].specular_factor); material->Reflection.Set(FbxDouble3(importedMaterials[importedMesh.material_Id[i]].reflection[0], importedMaterials[importedMesh.material_Id[i]].reflection[1], importedMaterials[importedMesh.material_Id[i]].reflection[2])); // Bugged...? material->ReflectionFactor.Set(FbxDouble(importedMaterials[importedMesh.material_Id[i]].reflection_factor)); cout << importedMaterials[importedMesh.material_Id[i]].shininess << endl; FbxNode* node = mesh->GetNode(); if (node) { node->AddMaterial(material); } // Diffuse Texture FbxFileTexture* texture = FbxFileTexture::Create(scene, "Diffuse Texture"); if (importedMaterials[importedMesh.material_Id[i]].duffuse_map_length > 0) { texture->SetFileName(importedMaterials[importedMesh.material_Id[i]].diffuse_map); texture->SetTextureUse(FbxTexture::eStandard); texture->SetMappingType(FbxTexture::eUV); texture->SetMaterialUse(FbxFileTexture::eModelMaterial); texture->SetSwapUV(false); texture->SetTranslation(0.0, 0.0); texture->SetScale(1.0, 1.0); texture->SetRotation(0.0, 0.0); if (material) material->Diffuse.ConnectSrcObject(texture); } // Specular Texture texture = FbxFileTexture::Create(scene, "Specular Texture"); if (importedMaterials[importedMesh.material_Id[i]].specular_map_length > 0) { texture->SetFileName(importedMaterials[importedMesh.material_Id[i]].specular_map); texture->SetTextureUse(FbxTexture::eStandard); texture->SetMappingType(FbxTexture::eUV); texture->SetMaterialUse(FbxFileTexture::eModelMaterial); texture->SetSwapUV(false); texture->SetTranslation(0.0, 0.0); texture->SetScale(1.0, 1.0); texture->SetRotation(0.0, 0.0); if (material) material->Specular.ConnectSrcObject(texture); } // Normal Texture texture = FbxFileTexture::Create(scene, "Normal Texture"); if (importedMaterials[importedMesh.material_Id[i]].normal_map_length > 0) { texture->SetFileName(importedMaterials[importedMesh.material_Id[i]].normal_map); texture->SetTextureUse(FbxTexture::eStandard); texture->SetMappingType(FbxTexture::eUV); texture->SetMaterialUse(FbxFileTexture::eModelMaterial); texture->SetSwapUV(false); texture->SetTranslation(0.0, 0.0); texture->SetScale(1.0, 1.0); texture->SetRotation(0.0, 0.0); if (material) material->NormalMap.ConnectSrcObject(texture); } } } }