/* note: we can know the texture unit index by getting parent then finding it in the list of children */ void SGScriptTranslator::translateTextureUnit(ScriptCompiler* compiler, const AbstractNodePtr &node) { ObjectAbstractNode *obj = static_cast<ObjectAbstractNode*>(node.get()); TextureUnitState* texState = any_cast<TextureUnitState*>(obj->parent->context); Pass* pass = texState->getParent(); Technique* technique = pass->getParent(); Material* material = technique->getParent(); ShaderGenerator* shaderGenerator = ShaderGenerator::getSingletonPtr(); String dstTechniqueSchemeName = obj->name; bool techniqueCreated; // Make sure the scheme name is valid - use default if none exists. if (dstTechniqueSchemeName.empty()) dstTechniqueSchemeName = ShaderGenerator::DEFAULT_SCHEME_NAME; //check if technique already created techniqueCreated = shaderGenerator->hasShaderBasedTechnique(material->getName(), material->getGroup(), technique->getSchemeName(), dstTechniqueSchemeName); if (techniqueCreated == false) { // Create the shader based technique. techniqueCreated = shaderGenerator->createShaderBasedTechnique(material->getName(), material->getGroup(), technique->getSchemeName(), dstTechniqueSchemeName, shaderGenerator->getCreateShaderOverProgrammablePass()); } // Case technique successfully created. if (techniqueCreated) { //Attempt to get the render state which might have been created by the pass parsing mGeneratedRenderState = shaderGenerator->getRenderState(dstTechniqueSchemeName, material->getName(), material->getGroup(), pass->getIndex()); // Go over all the render state properties. for(AbstractNodeList::iterator i = obj->children.begin(); i != obj->children.end(); ++i) { if((*i)->type == ANT_PROPERTY) { PropertyAbstractNode *prop = static_cast<PropertyAbstractNode*>((*i).get()); SubRenderState* subRenderState = ShaderGenerator::getSingleton().createSubRenderState(compiler, prop, texState, this); if (subRenderState) { addSubRenderState(subRenderState, dstTechniqueSchemeName, material->getName(), material->getGroup(), pass->getIndex()); } } else { processNode(compiler, *i); } } mGeneratedRenderState = NULL; } }
// update state of all objects void GameState::updateObjectState() { // get elapsed ms since last update int elapsedms = glutGet(GLUT_ELAPSED_TIME) - _lastupdate; if (_playermovestate & MoveStateLeft) _playership->translate(glm::vec3(-0.01f, 0.0f, 0.0f)); if (_playermovestate & MoveStateRight) _playership->translate(glm::vec3( 0.01f, 0.0f, 0.0f)); if (_playermovestate & MoveStateUp) _playership->translate(glm::vec3( 0.0f, 0.01f, 0.0f)); if (_playermovestate & MoveStateDown) _playership->translate(glm::vec3( 0.0f, -0.01f, 0.0f)); if (_playermovestate & (MoveStateLeft | MoveStateRight | MoveStateUp | MoveStateDown)) { // player moving, create exhaust createEffect(ParticleSystemType::PlayerExhaust, _playership->getPosition()); } // update all objects' state. If one enemy changes direction, // make all enemies change direction (space invaders!) // also randomly fire projectiles from enemies bool keepDirection = true; for (size_t i=0; i<_enemyships.size(); i++) { auto enemy = _enemyships[i]; float factor = _enemyships.size() / 32.0; float speed = 0.0001 + 0.0005 * (1.0-factor); enemy->setSpeed(speed); if (enemy->update(elapsedms) == false) keepDirection = false; int ms = enemy->getTimeSinceLastProjectile(); if (ms < 0) { enemy->setTimeToNextProjectile(_rng.genUniformInt()); } else if (ms > enemy->getTimeToNextProjectile()) { fireProjectile(enemy->getPosition(), glm::vec3(0.0f, -1.0f, 0.0f), 0.1, 0.0003, true); int delta = (int)(_rng.genUniformInt() * factor); enemy->setTimeToNextProjectile((delta<0? 100: delta)); } //createEffect(ParticleSystemType::EnemyExhaust, _enemyships[i]->getPosition()); // bad performance } if (!keepDirection) { for (size_t i=0; i<_enemyships.size(); i++) _enemyships[i]->changeDirection(); } _playership->update(elapsedms); // Update position of enemy projectiles and check for collisions with player auto epp = _enemyprojectiles.begin(); while (epp != _enemyprojectiles.end()) { shared_ptr<Projectile> projectile = *epp; projectile->update(elapsedms); if (!projectile->intersects(_playership)) { ++epp; continue; } // GAME OVER createEffect(ParticleSystemType::Death, _playership->getPosition()); createEffect(ParticleSystemType::DeathFollowup, _playership->getPosition()); _scene.removeObject(_playership); _scene.removeObject(projectile); epp = _enemyprojectiles.erase(epp); // Hack! Move him out of the way so enemy projectiles don't keep colliding _playership->translate(glm::vec3(10,0,0)); _gameover = true; break; } // Check if player shot down any enemies, also clean up // _playerprojectiles list if previously destroyed projectiles still exist auto ppitr = _playerprojectiles.begin(); while (ppitr != _playerprojectiles.end()) { shared_ptr<Projectile> projectile = *ppitr; // Remove projectiles that have flown off the screen if (projectile->update(elapsedms)) { _scene.removeObject(projectile); ppitr = _playerprojectiles.erase(ppitr); continue; } bool impact = false; auto eitr = _enemyships.begin(); while (eitr != _enemyships.end()) { shared_ptr<Spaceship> enemy = *eitr; if (!enemy || !projectile->intersects(enemy)) { ++eitr; continue; } // BOOM! Destroy enemy ship & projectile createEffect(ParticleSystemType::Explosion, enemy->getPosition()); _scene.removeObject(enemy); _scene.removeObject(projectile); eitr = _enemyships.erase(eitr); ppitr = _playerprojectiles.erase(ppitr); impact = true; break; } if (!impact) ++ppitr; } // check if player ship collides with enemy ship // turn the enemy red if we touch Box3D box = _playership->getBoundingBox().getBounds(); for (size_t i=0; i<_enemyships.size(); i++) { box = _enemyships[i]->getBoundingBox().getBounds(); if (_playership->intersects(_enemyships[i])) { Material m; m.setAmbient(glm::vec3(0.3, 0.2, 0.2)); m.setDiffuse(glm::vec3(0.8, 0.3, 0.3)); m.setSpecular(glm::vec3(0.8, 0.8, 0.8)); m.setShininess(100.0); _enemyships[i]->setMaterial(m); _enemyships[i]->rotate(glm::vec3(0, 0, 0), 2.0f); } } // update particle systems auto ppp = _particlesystems.begin(); while (ppp != _particlesystems.end()) { shared_ptr<ParticleSystem> ps = *ppp; if (ps->update(elapsedms)) { ++ppp; continue; } // system needs to be removed ps->hide(); ppp = _particlesystems.erase(ppp); } // set new last update time _lastupdate = glutGet(GLUT_ELAPSED_TIME); }
void CreateSceneSample::initialize() { // Create the font for drawing the framerate. _font = Font::create("res/ui/arial.gpb"); // Create a new empty scene. _scene = Scene::create(); // Create the camera. Camera* camera = Camera::createPerspective(45.0f, getAspectRatio(), 1.0f, 10.0f); Node* cameraNode = _scene->addNode("camera"); // Attach the camera to a node. This determines the position of the camera. cameraNode->setCamera(camera); // Make this the active camera of the scene. _scene->setActiveCamera(camera); SAFE_RELEASE(camera); // Move the camera to look at the origin. cameraNode->translate(0, 1, 5); cameraNode->rotateX(MATH_DEG_TO_RAD(-11.25f)); // Create a white light. Light* light = Light::createDirectional(0.75f, 0.75f, 0.75f); Node* lightNode = _scene->addNode("light"); lightNode->setLight(light); // Release the light because the node now holds a reference to it. SAFE_RELEASE(light); lightNode->rotateX(MATH_DEG_TO_RAD(-45.0f)); // Create the cube mesh and model. Mesh* cubeMesh = createCubeMesh(); Model* cubeModel = Model::create(cubeMesh); // Release the mesh because the model now holds a reference to it. SAFE_RELEASE(cubeMesh); // Create the material for the cube model and assign it to the first mesh part. Material* material = cubeModel->setMaterial("res/shaders/textured.vert", "res/shaders/textured.frag", "DIRECTIONAL_LIGHT_COUNT 1"); // These parameters are normally set in a .material file but this example sets them programmatically. // Bind the uniform "u_worldViewProjectionMatrix" to use the WORLD_VIEW_PROJECTION_MATRIX from the scene's active camera and the node that the model belongs to. material->setParameterAutoBinding("u_worldViewProjectionMatrix", "WORLD_VIEW_PROJECTION_MATRIX"); material->setParameterAutoBinding("u_inverseTransposeWorldViewMatrix", "INVERSE_TRANSPOSE_WORLD_VIEW_MATRIX"); // Set the ambient color of the material. material->getParameter("u_ambientColor")->setValue(Vector3(0.2f, 0.2f, 0.2f)); // Bind the light's color and direction to the material. material->getParameter("u_directionalLightColor[0]")->setValue(lightNode->getLight()->getColor()); material->getParameter("u_directionalLightDirection[0]")->bindValue(lightNode, &Node::getForwardVectorWorld); // Load the texture from file. Texture::Sampler* sampler = material->getParameter("u_diffuseTexture")->setValue("res/png/crate.png", true); sampler->setFilterMode(Texture::LINEAR_MIPMAP_LINEAR, Texture::LINEAR); material->getStateBlock()->setCullFace(true); material->getStateBlock()->setDepthTest(true); material->getStateBlock()->setDepthWrite(true); _cubeNode = _scene->addNode("cube"); _cubeNode->setModel(cubeModel); _cubeNode->rotateY(MATH_PIOVER4); SAFE_RELEASE(cubeModel); }
//-------------------------------------------------------------------------------------- void FBXScene::ProcessMaterials(FbxScene* pScene) { for( int i = 0; i < pScene->GetMaterialCount(); ++i ) { Material* pMaterial = new Material(i); FbxSurfaceMaterial* pFBXMaterial = pScene->GetMaterial(i); FbxProperty diffuseTextureProperty = pFBXMaterial->FindProperty(FbxSurfaceMaterial::sDiffuse); if( diffuseTextureProperty.IsValid() ) { FbxFileTexture* pDiffuseTexture = diffuseTextureProperty.GetSrcObject<FbxFileTexture>(0); if( pDiffuseTexture ) { std::string strFileName = pDiffuseTexture->GetFileName(); if( strFileName.length() == 0 ) strFileName = pDiffuseTexture->GetRelativeFileName(); strFileName = GetFileFromPath(strFileName); pMaterial->SetDiffuseTextureName(strFileName); } } FbxProperty normalTextureProperty = pFBXMaterial->FindProperty(FbxSurfaceMaterial::sNormalMap); if( normalTextureProperty.IsValid() ) { FbxFileTexture* pNormalTexture = normalTextureProperty.GetSrcObject<FbxFileTexture>(0); if( pNormalTexture ) { std::string strFileName = pNormalTexture->GetFileName(); if( strFileName.length() == 0 ) strFileName = pNormalTexture->GetRelativeFileName(); strFileName = GetFileFromPath(strFileName); pMaterial->SetNormalTextureName(strFileName); } } FbxSurfaceLambert* pLambert = FbxCast<FbxSurfaceLambert>(pFBXMaterial); FbxSurfacePhong* pPhong = FbxCast<FbxSurfacePhong>(pFBXMaterial); BTHFBX_VEC3 AmbientColor2; BTHFBX_VEC3 EmissiveColor2; BTHFBX_VEC3 DiffuseColor2; BTHFBX_VEC3 SpecularColor2; float fSpecularPower = 1.0f; float fTransparency = 1.0f; if( pLambert ) { AmbientColor2 = GetMaterialColor2(pLambert->Ambient, pLambert->AmbientFactor); EmissiveColor2 = GetMaterialColor2(pLambert->Emissive, pLambert->EmissiveFactor); DiffuseColor2 = GetMaterialColor2(pLambert->Diffuse, pLambert->DiffuseFactor); FbxPropertyT<FbxDouble> FBXTransparencyProperty = pLambert->TransparencyFactor; if( FBXTransparencyProperty.IsValid() ) fTransparency = (float)FBXTransparencyProperty.Get(); } if( pPhong ) { SpecularColor2 = GetMaterialColor2(pPhong->Specular, pPhong->SpecularFactor); FbxPropertyT<FbxDouble> FBXSpecularPowerProperty = pPhong->Shininess; if( FBXSpecularPowerProperty.IsValid() ) fSpecularPower = (float)FBXSpecularPowerProperty.Get(); } pMaterial->SetAmbientColor2(AmbientColor2); pMaterial->SetEmissiveColor2(EmissiveColor2); pMaterial->SetDiffuseColor2(DiffuseColor2); pMaterial->SetSpecularColor2(SpecularColor2); pMaterial->SetSpecularPower(fSpecularPower); pMaterial->SetTransparency(fTransparency); pMaterial->AddTexturePath( GetFilePath(this->mFilename) + "/" ); m_Materials.push_back(pMaterial); m_FBXMaterials.push_back(pFBXMaterial); } }
RenderingMesh* COLRenderWidget::createRenderingMesh(Mesh* mesh) { Matrix4 fModelMat = Matrix4::Identity; MeshFrame* frame = mesh->getFrame(); if (frame) { fModelMat = fModelMat * frame->getAbsoluteModelMatrix(); } RenderingPrimitiveFormat rpf; switch (mesh->getVertexFormat()) { case VertexFormatPoints: rpf = RenderingPrimitivePoints; break; case VertexFormatLines: rpf = RenderingPrimitiveLines; break; case VertexFormatTriangles: rpf = RenderingPrimitiveTriangles; break; case VertexFormatTriangleStrips: rpf = RenderingPrimitiveTriangleStrip; break; } //uint32_t flags = RenderingMesh::EnableShaderPluginUniformBuffers | RenderingMesh::HasTransparency; uint32_t flags = RenderingMesh::EnableShaderPluginUniformBuffers; DefaultRenderingMesh* rm = new DefaultRenderingMesh ( rpf, flags, mesh->getVertexCount(), 0, NULL, 0, mesh->getDataBuffer(), mesh->getIndexBuffer(), mesh->getVertexOffset(), mesh->getVertexStride(), mesh->getSubmeshIDOffset(), mesh->getSubmeshIDStride(), mesh->getNormalOffset(), mesh->getNormalStride(), mesh->getTexCoordOffset(), mesh->getTexCoordStride(), mesh->getVertexColorOffset(), mesh->getVertexColorStride(), -1, 0, -1, 0 ); rm->setModelMatrix(fModelMat); for (Mesh::SubmeshIterator sit = mesh->getSubmeshBegin() ; sit != mesh->getSubmeshEnd() ; sit++) { Submesh* submesh = *sit; Material* mat = submesh->getMaterial(); GLuint oglTex = 0; uint8_t r = 255; uint8_t g = 255; uint8_t b = 255; uint8_t a = 255; if (mat) { mat->getColor(r, g, b, a); } RenderingSubmesh* sm = new RenderingSubmesh(rm, submesh->getIndexCount(), submesh->getIndexOffset(), oglTex); sm->setMaterialColor(r, g, b, a); } return rm; }
void STKAnimatedMesh::updateNoGL() { scene::IMesh* m = getMeshForCurrentFrame(); if (m) Box = m->getBoundingBox(); else { Log::error("animated mesh", "Animated Mesh returned no mesh to render."); return; } if (!isMaterialInitialized) { video::IVideoDriver* driver = SceneManager->getVideoDriver(); const u32 mb_count = m->getMeshBufferCount(); for (u32 i = 0; i < mb_count; ++i) { scene::IMeshBuffer* mb = Mesh->getMeshBuffer(i); if (!mb) continue; scene::SSkinMeshBuffer* ssmb = NULL; video::E_VERTEX_TYPE prev_type = mb->getVertexType(); if (m_skinned_mesh) { ssmb = dynamic_cast<scene::SSkinMeshBuffer*>(mb); ssmb->VertexType = video::EVT_SKINNED_MESH; } bool affected = false; RenderInfo* cur_ri = m_mesh_render_info; if (!m_all_parts_colorized && mb && cur_ri) { if (m_mesh_render_info && !m_mesh_render_info->isStatic()) { // Convert to static render info for each mesh buffer assert(m_mesh_render_info->getNumberOfHue() == mb_count); const float hue = m_mesh_render_info->getDynamicHue(i); if (hue > 0.0f) { cur_ri = new RenderInfo(hue); m_static_render_info.push_back(cur_ri); affected = true; } else { cur_ri = NULL; } } else { // Test if material is affected by static hue change Material* m = material_manager->getMaterialFor(mb ->getMaterial().getTexture(0), mb); if (m->isColorizable()) affected = true; } } assert(cur_ri ? cur_ri->isStatic() : true); GLmeshes.push_back(allocateMeshBuffer(mb, m_debug_name, affected || m_all_parts_colorized || (cur_ri && cur_ri->isTransparent()) ? cur_ri : NULL)); if (m_skinned_mesh) ssmb->VertexType = prev_type; } for (u32 i = 0; i < m->getMeshBufferCount(); ++i) { scene::IMeshBuffer* mb = Mesh->getMeshBuffer(i); if (!mb) continue; scene::SSkinMeshBuffer* ssmb = NULL; video::E_VERTEX_TYPE prev_type = mb->getVertexType(); if (m_skinned_mesh) { ssmb = dynamic_cast<scene::SSkinMeshBuffer*>(mb); ssmb->VertexType = video::EVT_SKINNED_MESH; } video::E_MATERIAL_TYPE type = mb->getMaterial().MaterialType; f32 MaterialTypeParam = mb->getMaterial().MaterialTypeParam; video::IMaterialRenderer* rnd = driver->getMaterialRenderer(type); if (!isObject(type)) { #ifdef DEBUG Log::warn("material", "Unhandled (animated) material type : %d", type); #endif continue; } GLMesh &mesh = GLmeshes[i]; video::E_VERTEX_TYPE vt = mb->getVertexType(); Material* material = material_manager->getMaterialFor(mb->getMaterial().getTexture(0), mb); if (rnd->isTransparent()) { TransparentMaterial TranspMat = getTransparentMaterialFromType(type, vt, MaterialTypeParam, material); TransparentMesh[TranspMat].push_back(&mesh); } else if (mesh.m_render_info != NULL && mesh.m_render_info->isTransparent()) { if (mesh.VAOType == video::EVT_SKINNED_MESH) TransparentMesh[TM_TRANSLUCENT_SKN].push_back(&mesh); else if (mesh.VAOType == video::EVT_TANGENTS) TransparentMesh[TM_TRANSLUCENT_TAN].push_back(&mesh); else TransparentMesh[TM_TRANSLUCENT_STD].push_back(&mesh); } else { Material::ShaderType MatType = getMeshMaterialFromType(type, vt, material, NULL); MeshSolidMaterial[MatType].push_back(&mesh); } if (m_skinned_mesh) ssmb->VertexType = prev_type; } isMaterialInitialized = true; } for (u32 i = 0; i < m->getMeshBufferCount(); ++i) { scene::IMeshBuffer* mb = Mesh->getMeshBuffer(i); if (mb != NULL) { // Test if texture matrix needs to be updated every frame const core::matrix4& mat = getMaterial(i).getTextureMatrix(0); if (mat.isIdentity() && !m_got_animated_matrix) continue; else { m_got_animated_matrix = true; GLmeshes[i].texture_trans.X = mat[8]; GLmeshes[i].texture_trans.Y = mat[9]; } } } }
/** * Gets the sample material for a workspace and displays its properties in the tree. */ void MantidSampleMaterialDialog::updateMaterial() { MatrixWorkspace_sptr ws = AnalysisDataService::Instance().retrieveWS<MatrixWorkspace>(m_wsName.toStdString()); if(!ws) return; const Material material = ws->sample().getMaterial(); m_uiForm.treeMaterialProperties->clear(); QTreeWidgetItem *item; QTreeWidgetItem *subItem; QTreeWidgetItem *subSubItem; item = new QTreeWidgetItem(); item->setText(0, "Formula"); item->setText(1, QString::fromStdString(material.name())); m_uiForm.treeMaterialProperties->addTopLevelItem(item); item = new QTreeWidgetItem(); item->setText(0, "Number Density"); item->setText(1, QString::number(material.numberDensity())); m_uiForm.treeMaterialProperties->addTopLevelItem(item); item = new QTreeWidgetItem(); item->setText(0, "Temperature"); item->setText(1, QString::number(material.temperature())); m_uiForm.treeMaterialProperties->addTopLevelItem(item); item = new QTreeWidgetItem(); item->setText(0, "Pressure"); item->setText(1, QString::number(material.pressure())); m_uiForm.treeMaterialProperties->addTopLevelItem(item); item = new QTreeWidgetItem(); item->setText(0, "Cross Sections"); m_uiForm.treeMaterialProperties->addTopLevelItem(item); subItem = new QTreeWidgetItem(); subItem->setText(0, "Absorption"); subItem->setText(1, QString::number(material.absorbXSection())); item->addChild(subItem); subItem = new QTreeWidgetItem(); subItem->setText(0, "Scattering"); item->addChild(subItem); // Expand the Cross Sections section item->setExpanded(true); subSubItem = new QTreeWidgetItem(); subSubItem->setText(0, "Total"); subSubItem->setText(1, QString::number(material.totalScatterXSection())); subItem->addChild(subSubItem); subSubItem = new QTreeWidgetItem(); subSubItem->setText(0, "Coherent"); subSubItem->setText(1, QString::number(material.cohScatterXSection())); subItem->addChild(subSubItem); subSubItem = new QTreeWidgetItem(); subSubItem->setText(0, "Incoherent"); subSubItem->setText(1, QString::number(material.incohScatterXSection())); subItem->addChild(subSubItem); // Expand the Scattering section subItem->setExpanded(true); }
MaterialXMLExportDialog::MaterialXMLExportDialog(MaterialListModel* model, QWidget *parent) : QDialog(parent), model_(model), allItemsChecked_(true), exportMode_(ANSYS) { QVBoxLayout * layout = new QVBoxLayout(this); layout->setContentsMargins(1, 1, 1, 1); setLayout(layout); materialView_ = new QTableWidget(model_->getMaterialCount(), 2, this); materialView_->setHorizontalHeaderItem(0, new QTableWidgetItem(tr("Material"))); materialView_->setColumnWidth(0, 400); materialView_->setHorizontalHeaderItem(1, new QTableWidgetItem(tr("Description"))); materialView_->setSelectionBehavior(QAbstractItemView::SelectItems); materialView_->setSelectionMode(QAbstractItemView::NoSelection); materialView_->setAcceptDrops(false); materialView_->setDropIndicatorShown(false); materialView_->setDragDropMode(QAbstractItemView::NoDragDrop); materialView_->setAlternatingRowColors(true); materialView_->horizontalHeader()->setStretchLastSection(true); connect(materialView_->horizontalHeader(), SIGNAL(sectionDoubleClicked(int)), this, SLOT(headerViewDoubleClicked(int))); materialView_->setMinimumWidth(700); materialView_->setMinimumHeight(400); int row = 0; const std::vector<Material*>& list = model_->getMaterials(); for (std::vector<Material*>::const_iterator it = list.begin(); it!=list.end(); ++it) { Material *mat = *it; QTableWidgetItem * item; item = new MaterialTableItem(mat, QTableWidgetItem::UserType+100); item->setText(mat->getName()); item->setCheckState(Qt::Checked); item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsUserCheckable); materialView_->setItem(row, 0, item); item = new QTableWidgetItem(mat->getDescription()); item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled); materialView_->setItem(row, 1, item); row++; } layout->addWidget(materialView_); QWidget *buttons = new QWidget(this); QHBoxLayout *buttonLayout = new QHBoxLayout(buttons); buttonLayout->setContentsMargins(1, 1, 1, 1); buttons->setLayout(buttonLayout); buttonLayout->addWidget(new QLabel(tr("Export Mode:"), buttons)); QButtonGroup* group = new QButtonGroup(buttons); connect(group, SIGNAL(buttonClicked(QAbstractButton*)), this, SLOT(modeChanged(QAbstractButton*))); modeANSYSbutton_ = new QRadioButton("ANSYS", buttons); modeANSYSbutton_->setMinimumHeight(1.2*modeANSYSbutton_->minimumSizeHint().height()); //group->addButton(modeANSYSbutton_, 0); buttonLayout->addWidget(modeANSYSbutton_); modeANSYSbutton_->setChecked(true); modeMATMLbutton_ = new QRadioButton("MatML", buttons); modeMATMLbutton_->setMinimumHeight(1.2*modeMATMLbutton_->minimumSizeHint().height()); //group->addButton(modeMATMLbutton_, 1); buttonLayout->addWidget(modeMATMLbutton_); layout->addWidget(buttons); buttons = new QWidget(this); buttonLayout = new QHBoxLayout(buttons); buttonLayout->setContentsMargins(1,1,1,1); buttons->setLayout(buttonLayout); buttonLayout->addSpacerItem(new QSpacerItem(10, 10, QSizePolicy::Expanding)); QPushButton *button; button = new QPushButton(tr("Export"), buttons); //button->setFlat(true); button->setDefault(false); connect(button, SIGNAL(clicked()), this, SLOT(exportMaterials())); buttonLayout->addWidget(button); button = new QPushButton(tr("Cancel"), buttons); //button->setFlat(true); button->setDefault(true); connect(button, SIGNAL(clicked()), this, SLOT(reject())); buttonLayout->addWidget(button); layout->addWidget(buttons); updateGeometry(); }
/** Initialises the track object based on the specified XML data. * \param xml_node The XML data. * \param parent The parent scene node. * \param model_def_loader Used to load level-of-detail nodes. */ void TrackObject::init(const XMLNode &xml_node, scene::ISceneNode* parent, ModelDefinitionLoader& model_def_loader, TrackObject* parent_library) { m_init_xyz = core::vector3df(0,0,0); m_init_hpr = core::vector3df(0,0,0); m_init_scale = core::vector3df(1,1,1); m_enabled = true; m_initially_visible = false; m_presentation = NULL; m_animator = NULL; m_parent_library = parent_library; m_physical_object = NULL; xml_node.get("id", &m_id ); xml_node.get("model", &m_name ); xml_node.get("xyz", &m_init_xyz ); xml_node.get("hpr", &m_init_hpr ); xml_node.get("scale", &m_init_scale); xml_node.get("enabled", &m_enabled ); m_interaction = "static"; xml_node.get("interaction", &m_interaction); xml_node.get("lod_group", &m_lod_group); m_is_driveable = false; xml_node.get("driveable", &m_is_driveable); bool lod_instance = false; xml_node.get("lod_instance", &lod_instance); m_soccer_ball = false; xml_node.get("soccer_ball", &m_soccer_ball); std::string type; xml_node.get("type", &type ); m_type = type; m_initially_visible = true; xml_node.get("if", &m_visibility_condition); if (m_visibility_condition == "false") { m_initially_visible = false; } if (!m_initially_visible) setEnabled(false); if (xml_node.getName() == "particle-emitter") { m_type = "particle-emitter"; m_presentation = new TrackObjectPresentationParticles(xml_node, parent); } else if (xml_node.getName() == "light") { m_type = "light"; m_presentation = new TrackObjectPresentationLight(xml_node, parent); } else if (xml_node.getName() == "library") { xml_node.get("name", &m_name); m_presentation = new TrackObjectPresentationLibraryNode(this, xml_node, model_def_loader); if (parent_library != NULL) { Track::getCurrentTrack()->addMetaLibrary(parent_library, this); } } else if (type == "sfx-emitter") { // FIXME: at this time sound emitters are just disabled in multiplayer // otherwise the sounds would be constantly heard if (race_manager->getNumLocalPlayers() < 2) m_presentation = new TrackObjectPresentationSound(xml_node, parent); } else if (type == "action-trigger") { std::string action; xml_node.get("action", &action); m_name = action; //adds action as name so that it can be found by using getName() m_presentation = new TrackObjectPresentationActionTrigger(xml_node, parent_library); } else if (type == "billboard") { m_presentation = new TrackObjectPresentationBillboard(xml_node, parent); } else if (type=="cutscene_camera") { m_presentation = new TrackObjectPresentationEmpty(xml_node); } else { // Colorization settings std::string model_name; xml_node.get("model", &model_name); #ifndef SERVER_ONLY if (CVS->isGLSL()) { scene::IMesh* mesh = NULL; // Use the first material in mesh to determine hue Material* colorized = NULL; if (model_name.size() > 0) { mesh = irr_driver->getMesh(model_name); if (mesh != NULL) { for (u32 j = 0; j < mesh->getMeshBufferCount(); j++) { SP::SPMeshBuffer* mb = static_cast<SP::SPMeshBuffer*> (mesh->getMeshBuffer(j)); std::vector<Material*> mbs = mb->getAllSTKMaterials(); for (Material* m : mbs) { if (m->isColorizable() && m->hasRandomHue()) { colorized = m; break; } } if (colorized != NULL) { break; } } } } else { std::string group_name = ""; xml_node.get("lod_group", &group_name); // Try to get the first mesh from lod groups mesh = model_def_loader.getFirstMeshFor(group_name); if (mesh != NULL) { for (u32 j = 0; j < mesh->getMeshBufferCount(); j++) { SP::SPMeshBuffer* mb = static_cast<SP::SPMeshBuffer*> (mesh->getMeshBuffer(j)); std::vector<Material*> mbs = mb->getAllSTKMaterials(); for (Material* m : mbs) { if (m->isColorizable() && m->hasRandomHue()) { colorized = m; break; } } if (colorized != NULL) { break; } } } } // If at least one material is colorizable, add RenderInfo for it if (colorized != NULL) { const float hue = colorized->getRandomHue(); if (hue > 0.0f) { m_render_info = std::make_shared<RenderInfo>(hue); } } } #endif scene::ISceneNode *glownode = NULL; bool is_movable = false; if (lod_instance) { m_type = "lod"; TrackObjectPresentationLOD* lod_node = new TrackObjectPresentationLOD(xml_node, parent, model_def_loader, m_render_info); m_presentation = lod_node; LODNode* node = (LODNode*)lod_node->getNode(); if (type == "movable" && parent != NULL) { // HACK: unparent movables from their parent library object if any, // because bullet provides absolute transforms, not transforms relative // to the parent object node->updateAbsolutePosition(); core::matrix4 absTransform = node->getAbsoluteTransformation(); node->setParent(irr_driver->getSceneManager()->getRootSceneNode()); node->setPosition(absTransform.getTranslation()); node->setRotation(absTransform.getRotationDegrees()); node->setScale(absTransform.getScale()); } glownode = node->getAllNodes()[0]; } else { m_type = "mesh"; m_presentation = new TrackObjectPresentationMesh(xml_node, m_enabled, parent, m_render_info); scene::ISceneNode* node = ((TrackObjectPresentationMesh *)m_presentation)->getNode(); if (type == "movable" && parent != NULL) { // HACK: unparent movables from their parent library object if any, // because bullet provides absolute transforms, not transforms relative // to the parent object node->updateAbsolutePosition(); core::matrix4 absTransform = node->getAbsoluteTransformation(); node->setParent(irr_driver->getSceneManager()->getRootSceneNode()); node->setPosition(absTransform.getTranslation()); // Doesn't seem necessary to set rotation here, TODO: not sure why //node->setRotation(absTransform.getRotationDegrees()); node->setScale(absTransform.getScale()); is_movable = true; } glownode = node; } std::string render_pass; xml_node.get("renderpass", &render_pass); if (m_interaction != "ghost" && m_interaction != "none" && render_pass != "skybox" ) { m_physical_object = PhysicalObject::fromXML(type == "movable", xml_node, this); } if (parent_library != NULL) { if (is_movable) parent_library->addMovableChild(this); else parent_library->addChild(this); } video::SColor glow; if (xml_node.get("glow", &glow) && glownode) { float r, g, b; r = glow.getRed() / 255.0f; g = glow.getGreen() / 255.0f; b = glow.getBlue() / 255.0f; SP::SPMeshNode* spmn = dynamic_cast<SP::SPMeshNode*>(glownode); if (spmn) { spmn->setGlowColor(video::SColorf(r, g, b)); } } bool is_in_shadowpass = true; if (xml_node.get("shadow-pass", &is_in_shadowpass) && glownode) { SP::SPMeshNode* spmn = dynamic_cast<SP::SPMeshNode*>(glownode); if (spmn) { spmn->setInShadowPass(is_in_shadowpass); } } bool forcedbloom = false; if (xml_node.get("forcedbloom", &forcedbloom) && forcedbloom && glownode) { float power = 1; xml_node.get("bloompower", &power); btClamp(power, 0.5f, 10.0f); irr_driver->addForcedBloomNode(glownode, power); } } if (type == "animation" || xml_node.hasChildNamed("curve")) { m_animator = new ThreeDAnimation(xml_node, this); } reset(); if (!m_initially_visible) setEnabled(false); if (parent_library != NULL && !parent_library->isEnabled()) setEnabled(false); } // TrackObject
/** * @brief Create a duplicate of the Material. * @return a pointer to the clone */ Material* Material::clone(){ Material* clone = new Material(getId()); clone->setNumEnergyGroups(_num_groups); for (int i=0; i < _num_groups; i++) { clone->setSigmaTByGroup((double)_sigma_t[i], i+1); clone->setSigmaAByGroup((double)_sigma_a[i], i+1); clone->setSigmaFByGroup((double)_sigma_f[i], i+1); clone->setNuSigmaFByGroup((double)_nu_sigma_f[i], i+1); clone->setChiByGroup((double)_chi[i], i+1); for (int j=0; j < _num_groups; j++) clone->setSigmaSByGroup( (double)getSigmaSByGroupInline(i,j), i+1, j+1); if (_dif_coef != NULL) clone->setDifCoefByGroup((double)_dif_coef[i], i+1); if (_buckling != NULL) clone->setBucklingByGroup((double)_buckling[i], i+1); for (int j=0; j < 4; j++) { if (_dif_hat != NULL) clone->setDifHatByGroup((double)_dif_hat[i*4+j], i+1, j); if (_dif_tilde != NULL) clone->setDifTildeByGroup((double)_dif_tilde[i*4+j], i+1, j); } } return clone; }
Colour* rayTrace(const Colour& ambient, const Point3D& eye, Ray ray, SceneNode* root, const std::list<Light*>& lights, int level, double fogDist){ if(level <= 0) return NULL; Intersection* i = root->intersect(ray); bool fogOn = true; if(fogDist <= 0) fogOn = false; if(i != NULL){ Colour color(0,0,0); Colour fog(0.8,0.8,0.8); Colour diffuse(0,0,0), specular(0,0,0); Material* material = i->getMaterial(); Vector3D n = i->getNormal(); n.normalize(); Point3D p = i->getPoint(); Vector3D v = eye - p; v.normalize(); for (std::list<Light*>::const_iterator I = lights.begin(); I != lights.end(); ++I) { Light light = **I; Vector3D l = light.position - p; l.normalize(); Vector3D r = 2*l*n*n - l; r.normalize(); // shadows Ray lightRay = Ray(p, l); Intersection* lightIsc = root->intersect(lightRay); if(lightIsc == NULL){ // add light contribution //std::cerr << "light" << std::endl; if(n*l > 0) diffuse = diffuse + material->getDiffuse() * (l*n) * light.colour; if(r*v > 0) specular = specular + material->getSpecular() * pow((r*v), material->getShininess()) * light.colour; } } //secondaty rays Vector3D r = 2*v*n*n - v; r.normalize(); Ray refRay(p, r); Colour* reflectedColor = rayTrace(ambient, eye, refRay, root, lights, level-1, fogDist); if(reflectedColor != NULL){ if(n*r > 0) diffuse = diffuse + material->getDiffuse() * (r*n) * material->getReflectivity() * (*reflectedColor); if(r*v > 0) specular = specular + material->getSpecular() * pow((r*v), material->getShininess()) * material->getReflectivity() * (*reflectedColor); } color = ambient*material->getColor() + diffuse + specular; if(fogOn){ double dist = i->getT()/fogDist; if(dist>1) dist=1; color = (1-dist)*color + dist*fog; } return new Colour(color); } return NULL; }
TRef<Geo> Execute(const Matrix& mat, GroupGeo* pgroup) { ZString strName = pgroup->GetName(); if (!strName.IsEmpty()) { if ( strName.Find("frm-") == 0 && (!pgroup->AnyChildGroups()) ) { Vector vecPosition = mat.Transform(Vector(0, 0, 0)); Vector vecForward = mat.TransformDirection(Vector(0, 0, -1)); Vector vecUp = mat.TransformDirection(Vector(0, 1, 0)); strName = strName.RightOf(4); if (strName.Find("SS") != -1) { // // a strobe light // ValueList* plist = pgroup->GetList(); if (plist->GetCount() == 1) { MaterialGeo* pmatGeo; CastTo(pmatGeo, plist->GetFirst()); Material* pmaterial = pmatGeo->GetMaterial(); AddLight(strName, pmaterial->GetDiffuse(), vecPosition); } else { AddLight(strName, Color(1, 1, 1), vecPosition); } return Geo::GetEmpty(); } else if ( strName.Find("thrust") != -1 || strName.Find("smoke") != -1 || strName.Find("rocket") != -1 ) { // // this is an engine // m_pframes->GetList().PushFront( FrameData(strName, vecPosition, vecForward, vecUp) ); return Geo::GetEmpty(); } else if ( (strName.Find("weapon") != -1) || (strName.Find("wepatt") != -1) || (strName.Find("wepemt") != -1) || (strName.Find("wepmnt") != -1) || (strName.Find("trail") != -1) ) { // // This is an attachment point // m_pframes->GetList().PushFront( FrameData(strName, vecPosition, vecForward, vecUp) ); return Geo::GetEmpty(); } else if ( (strName.Find("garage") != -1) ) { // // This is a garage we need to leave the frame in the graph // m_pframes->GetList().PushFront( FrameData(strName, vecPosition, vecForward, vecUp) ); } } } return NULL; }
void LODNode::OnRegisterSceneNode() { if (!isVisible()) return; if (m_nodes.size() == 0) return; // TODO: optimize this, there is no need to check every frame scene::ICameraSceneNode* curr_cam = irr_driver->getSceneManager()->getActiveCamera(); // Assumes all children are at the same location const int dist = (int)((getPosition() + m_nodes[0]->getPosition()).getDistanceFromSQ( curr_cam->getPosition() )); bool shown = false; for (unsigned int n=0; n<m_detail.size(); n++) { if (dist < m_detail[n]) { m_nodes[n]->updateAbsolutePosition(); m_nodes[n]->OnRegisterSceneNode(); shown = true; break; } } //printf("m_group_name = %s, m_nodes.size() = %i\n, type is mesh = %i\n", m_group_name.c_str(), (int)m_nodes.size(), // m_nodes[0]->getType() == scene::ESNT_MESH); // support an optional, mostly hard-coded fade-in/out effect for objects with a single level if (m_nodes.size() == 1 && (m_nodes[0]->getType() == scene::ESNT_MESH || m_nodes[0]->getType() == scene::ESNT_ANIMATED_MESH)) { if (m_previous_visibility == WAS_HIDDEN && shown) { scene::IMesh* mesh; if (m_nodes[0]->getType() == scene::ESNT_MESH) { scene::IMeshSceneNode* node = (scene::IMeshSceneNode*)(m_nodes[0]); mesh = node->getMesh(); } else { assert(m_nodes[0]->getType() == scene::ESNT_ANIMATED_MESH); scene::IAnimatedMeshSceneNode* node = (scene::IAnimatedMeshSceneNode*)(m_nodes[0]); assert(node != NULL); mesh = node->getMesh(); } for (unsigned int n=0; n<mesh->getMeshBufferCount(); n++) { scene::IMeshBuffer* mb = mesh->getMeshBuffer(n); video::ITexture* t = mb->getMaterial().getTexture(0); if (t == NULL) continue; Material* m = material_manager->getMaterialFor(t, mb); if (m != NULL) { m->onMadeVisible(mb); } } } else if (m_previous_visibility == WAS_SHOWN && !shown) { scene::IMesh* mesh; if (m_nodes[0]->getType() == scene::ESNT_MESH) { scene::IMeshSceneNode* node = (scene::IMeshSceneNode*)(m_nodes[0]); mesh = node->getMesh(); } else { assert(m_nodes[0]->getType() == scene::ESNT_ANIMATED_MESH); scene::IAnimatedMeshSceneNode* node = (scene::IAnimatedMeshSceneNode*)(m_nodes[0]); assert(node != NULL); mesh = node->getMesh(); } for (unsigned int n=0; n<mesh->getMeshBufferCount(); n++) { scene::IMeshBuffer* mb = mesh->getMeshBuffer(n); video::ITexture* t = mb->getMaterial().getTexture(0); if (t == NULL) continue; Material* m = material_manager->getMaterialFor(t, mb); if (m != NULL) { m->onHidden(mb); } } } else if (m_previous_visibility == FIRST_PASS && !shown) { scene::IMesh* mesh; if (m_nodes[0]->getType() == scene::ESNT_MESH) { scene::IMeshSceneNode* node = (scene::IMeshSceneNode*)(m_nodes[0]); mesh = node->getMesh(); } else { assert(m_nodes[0]->getType() == scene::ESNT_ANIMATED_MESH); scene::IAnimatedMeshSceneNode* node = (scene::IAnimatedMeshSceneNode*)(m_nodes[0]); assert(node != NULL); mesh = node->getMesh(); } for (unsigned int n=0; n<mesh->getMeshBufferCount(); n++) { scene::IMeshBuffer* mb = mesh->getMeshBuffer(n); video::ITexture* t = mb->getMaterial().getTexture(0); if(!t) continue; Material* m = material_manager->getMaterialFor(t, mb); if (m != NULL) { m->isInitiallyHidden(mb); } } } } m_previous_visibility = (shown ? WAS_SHOWN : WAS_HIDDEN); // If this node has children other than the LOD nodes, draw them core::list<ISceneNode*>::Iterator it; for (it = Children.begin(); it != Children.end(); it++) { if (m_nodes_set.find(*it) == m_nodes_set.end()) { assert(*it != NULL); if ((*it)->isVisible()) { (*it)->OnRegisterSceneNode(); } } } }
void PaymentDialog::setModel(QAbstractItemModel *model, int mode, Entity *view) { paymentModel = (PaymentModel *) model; this->mode = mode; this->view = view; payment = new Payment(); int id; if (mode == OTHER) { payModelF->setFilterRole(PayModel::otherRole); payModelF->setMatchValue(true); ui->table->hide(); adjustSize(); return; } else if (mode == ORDER) { id = view->fields["ordr_id"].toInt(); payModelF->setFilterRole(PayModel::orderRole); payModelF->setMatchValue(true); QString info = QString::fromUtf8("Заказ №%1 ").arg(id); setupInfo(info); ui->total->setMoney(Money(view->fields["ordr_debt"])); setupTable(id, Pay::ORDER); } else if (mode == MATERIAL) { id = view->fields["material_id"].toInt(); Material *material = (Material *) view; payModelF->setFilterRole(PayModel::materialRole); payModelF->setMatchValue(true); QString info = QString::fromUtf8("%1 %2 %3") .arg(material->getProductName()) .arg(material->getStockName()) .arg(material->getParametr()); setupInfo(info); ui->total->setMoney(Money(view->fields["material_debt"])); QString invoice = view->fields["material_invoice"].toString(); ui->invoice->setInvoice(invoice); setupTable(id, Pay::MATERIAL); } else if (mode == DEPOSIT) { id = view->fields["payment_field_id"].toInt(); Payment *depositPayment = (Payment *) view; int type = depositPayment->getPayType(); int paymentId = view->fields["payment_id"].toInt(); if (type == Pay::ORDER ) { payModelF->setFilterRole(PayModel::debtOrderRole); setupTable(paymentId, Pay::ORDER); } else if (type == Pay::MATERIAL ) { payModelF->setFilterRole(PayModel::debtMaterialRole); setupTable(paymentId, Pay::MATERIAL); } else if (type == Pay::OTHER ) { payModelF->setFilterRole(PayModel::debtOtherRole); setupTable(paymentId, Pay::OTHER); } payModelF->setMatchValue(true); QString info = QString::fromUtf8("Относится к платежу %1.") .arg(paymentId); setupInfo(info); int cents = abs(view->fields["payment_debt"].toInt()); ui->total->setMoney(Money(cents)); QString invoice = view->fields["payment_invoice"].toString(); ui->invoice->setInvoice(invoice); } payment->fields["payment_field_id"] = id; }
AEResult GameLightsUpdate::ShadowLightRenderGameObject(GameObject* gameObject, const glm::mat4& lightView, const glm::mat4& lightProj) { AEAssert(gameObject != nullptr); if (gameObject == nullptr) { return AEResult::NullParameter; } if (gameObject->HasMeshGOC() && gameObject->HasMaterialGOCs()) { Mesh* mesh = gameObject->GetMeshGOC()->GetMeshResource(); if (mesh != nullptr) { ConstantBuffer* cb = nullptr; Material* mat = nullptr; bool hasAnimation = gameObject->HasMeshAnimationGOC(); if (hasAnimation) { mat = m_VarianceSkinningShadowMaterial; ShaderProperties* vsProps = m_VarianceSkinningShadowMaterial->GetVSProps(); cb = vsProps->GetConstantBuffer(AE_CB_WORLD_VIEW_PROJ_NAME); ConstantBuffer* cbBones = vsProps->GetConstantBuffer(AE_CB_BONES_NAME); if (cbBones != nullptr) { AnimationPlayer* player = gameObject->GetMeshAnimationGOC()->GetAnimationPlayer(); cbBones->SetValue(AE_CB_BONE_TRANSFORMS_VAR_NAME, player->GetBoneTransforms(), sizeof(glm::mat4) * AE_MAX_BONES); } } else { mat = m_VarianceShadowMaterial; ShaderProperties* vsProps = m_VarianceShadowMaterial->GetVSProps(); cb = vsProps->GetConstantBuffer(AE_CB_WORLD_VIEW_PROJ_NAME); } cb->SetValueT<glm::mat4>(AE_CB_WORLD_VAR_NAME, gameObject->GetWorldTransform()); cb->SetValueT<glm::mat4>(AE_CB_VIEW_VAR_NAME, lightView); cb->SetValueT<glm::mat4>(AE_CB_PROJECTION_VAR_NAME, lightProj); AETODO("check return"); mat->Apply(); for (uint32_t i = 0; i < mesh->GetNumberMeshParts(); i++) { MeshPart* meshPart = mesh->GetMeshPart(i); m_GraphicDevice->SetVertexBuffer(meshPart->GetVertexBuffer()); m_GraphicDevice->SetIndexBuffer(meshPart->GetIndexBuffer()); m_GraphicDevice->SetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); m_GraphicDevice->DrawIndexed(0, 0, meshPart->GetIndexBuffer()->GetSize()); } AETODO("check return"); mat->UnApply(); } } for (auto goIt : *gameObject) { ShadowLightRenderGameObject(goIt.second, lightView, lightProj); } return AEResult::Ok; }
int main() { sf::ContextSettings settings; settings.majorVersion = 4; settings.minorVersion = 3; settings.depthBits = 24; settings.stencilBits = 8; settings.antialiasingLevel = 0; sf::Window window(sf::VideoMode(800, 600), "SMOG Test", sf::Style::Close, settings); sf::ContextSettings actualSettings = window.getSettings(); std::cout << "Window created:\n" << "\tMajor Version: " << actualSettings.majorVersion << "\n" << "\tMinor Version: " << actualSettings.minorVersion << "\n" << "\tDepth Bits : " << actualSettings.depthBits << "\n" << "\tStencil Bits : " << actualSettings.stencilBits << "\n" << "\tAntialiasing : " << actualSettings.antialiasingLevel << std::endl; window.setVerticalSyncEnabled(true); initialiseGlew(); sf::Vector2u windowSize = window.getSize(); Viewport viewport(windowSize.x, windowSize.y); TextureCache::RegisterLoader<SFML_TextureLoader>(); Scene scene; // FrameBuffer frameBuffer(800, 600); // frameBuffer.addTarget("diffuse", 4, Texture::UNSIGNED_BYTE_8); GBuffer gbuffer; // Scene setup for (int i = 0; i < 4; ++i) { SceneObject& sceneObject = scene.createSceneObject(); RenderableComponent& rendComp = sceneObject.createComponent<RenderableComponent>(); rendComp.renderable.reset(new Triangle); #if 1 rendComp.material = Material::Load("install/share/materials/textured.mtl"); #else std::stringstream ss; ss << "install/share/materials/color" << i << ".mtl"; #if 1 rendComp.material = Material::Load(ss.str()); #else rendComp.material = Material::Load("install/share/materials/color.mtl"); rendComp.material.set("color", RGB( (i == 0 || i == 1) ? 1.0f : 0.0f, (i == 0 || i == 2) ? 1.0f : 0.0f, (i == 0 || i == 3) ? 1.0f : 0.0f)); rendComp.material.save(ss.str()); #endif #endif sceneObject.transform().position = Vector3( (i % 2) ? 0.5f : -0.5f, (i > 1) ? 0.5f : -0.5f, 0.0f); sceneObject.transform().scale = Vector3(0.5f, 0.5f, 1.0f); } Material material = Material::Load("install/share/materials/debug_gbuffer.mtl"); Quad quad; // Main loop while (window.isOpen()) { sf::Event event; while (window.pollEvent(event)) { if (event.type == sf::Event::Closed) { window.close(); break; } else if (event.type == sf::Event::Resized) { viewport.resize(event.size.width, event.size.height); } } // Update scene.update(0.0f); // Bind the frame buffer //frameBuffer.bind(); gbuffer.writeTo(); glEnable(GL_DEPTH_TEST); glDepthMask(true); glDisable(GL_BLEND); glClearColor(0.0f, 0.0f, 0.0f, 0.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Draw for(SceneObjects::iterator sit = scene.begin(); sit != scene.end(); ++sit) { Components::iterator_range range = sit->components<RenderableComponent>(); for(Components::iterator cit = range.begin; cit != range.end; ++cit) { cit->as<RenderableComponent>().draw(); } } glUseProgram(0); //frameBuffer.unbind(); //frameBuffer.bindForRead(); gbuffer.readFrom(); glDisable(GL_DEPTH_TEST); glDepthMask(false); glEnable(GL_BLEND); glBlendFunc(GL_ONE, GL_ONE); glClearColor(0.0f, 0.0f, 0.0f, 0.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); material.program().use(); //frameBuffer.bindTargets(material.program()); material.program().set("diffuse", Texture(gbuffer.target(GBuffer::kDiffuse))); quad.draw(); glUseProgram(0); gbuffer.finish(); //frameBuffer.unbind(); window.display(); #if 1 checkGLErrors(); #endif } uchar pixels[800*600*4]; // const Texture& target = frameBuffer.target("diffuse"); // target.bind(); uint target = gbuffer.target(GBuffer::kDiffuse); glBindTexture(GL_TEXTURE_2D, target); glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_UNSIGNED_BYTE, &pixels); glBindTexture(GL_TEXTURE_2D, 0); // target.unbind(); sf::Image image; image.create(800, 600, pixels); image.saveToFile("screenshot.png"); TextureCache::CleanUp(); #if 1 checkGLErrors(); #endif return 0; }
bool FBXLoader::GetMaterial(KFbxGeometry* g, Object* o) { int m_count; KFbxNode* n; m_count = 0; n = NULL; if (g) { n = g->GetNode(); if (n) m_count = n->GetMaterialCount(); } if (m_count > 0) { KFbxPropertyDouble3 double3; KFbxPropertyDouble1 double1; KFbxColor col; Material* mat; int i; i = 0; while (i < m_count) { KFbxSurfaceMaterial* _mat; const KFbxImplementation* imp; KString imp_type; _mat = n->GetMaterial(i); mat = new (std::nothrow) Material; if (mat == NULL) { std::cout << "[FbxLoader]{__GetMaterial} Error: Can not allocate memory \n"; return (false); } mat->SetName((char*)_mat->GetName()); imp = GetImplementation(_mat, ImplementationHLSL); imp_type = "HLSL"; if (!imp) { imp = GetImplementation(_mat, ImplementationCGFX); imp_type = "CGFX"; } if (_mat->GetClassId().Is(KFbxSurfacePhong::ClassId)) { double3 = ((KFbxSurfacePhong*)_mat)->Ambient; col.Set(double3.Get()[0], double3.Get()[1], double3.Get()[2]); Color Amb(double3); mat->SetAmbient(Amb); double3 = ((KFbxSurfacePhong*)_mat)->Diffuse; col.Set(double3.Get()[0], double3.Get()[1], double3.Get()[2]); Color Diff(double3); mat->SetDiffuse(Diff); double3 = ((KFbxSurfacePhong*)_mat)->Specular; col.Set(double3.Get()[0], double3.Get()[1], double3.Get()[2]); Color Spec(double3); mat->SetSpecular(Spec); double3 = ((KFbxSurfacePhong*)_mat)->Emissive; col.Set(double3.Get()[0], double3.Get()[1], double3.Get()[2]); Color Em(double3); mat->SetEmissive(Em); double1 = ((KFbxSurfacePhong*)_mat)->TransparencyFactor; mat->SetOpacity(1.0 - double1.Get()); double1 = ((KFbxSurfacePhong*)_mat)->Shininess; mat->SetShininess(double1.Get()); double1 = ((KFbxSurfacePhong*)_mat)->ReflectionFactor; mat->SetReflection(1.0 - double1.Get()); mat->SetShadingModel(1); } else if (_mat->GetClassId().Is(KFbxSurfaceLambert::ClassId)) { double3 = ((KFbxSurfaceLambert*)_mat)->Ambient; col.Set(double3.Get()[0], double3.Get()[1], double3.Get()[2]); Color Amb(double3); mat->SetAmbient(Amb); double3 = ((KFbxSurfaceLambert*)_mat)->Diffuse; col.Set(double3.Get()[0], double3.Get()[1], double3.Get()[2]); Color Diff(double3); mat->SetDiffuse(Diff); double3 = ((KFbxSurfaceLambert*)_mat)->Emissive; col.Set(double3.Get()[0], double3.Get()[1], double3.Get()[2]); Color Em(double3); mat->SetEmissive(Em); double1 = ((KFbxSurfaceLambert*)_mat)->TransparencyFactor; mat->SetOpacity(1.0 - double1.Get()); mat->SetShadingModel(2); } o->AddMaterial(mat); ++i; } } return (true); }
Material *MaterialManager::materialFromXMLNode(TiXmlNode *node) { String mname = node->ToElement()->Attribute("name"); TiXmlNode* pChild, *pChild2,*pChild3; Shader *materialShader; ShaderBinding *newShaderBinding; vector<Shader*> materialShaders; vector<ShaderBinding*> newShaderBindings; vector<ShaderRenderTarget*> renderTargets; Material *newMaterial = new Material(mname); for (pChild3 = node->FirstChild(); pChild3 != 0; pChild3 = pChild3->NextSibling()) { if(strcmp(pChild3->Value(), "rendertargets") == 0) { if(pChild3->ToElement()->Attribute("type")) { if(strcmp(pChild3->ToElement()->Attribute("type"), "rgba_fp16") == 0) { newMaterial->fp16RenderTargets = true; } } for (pChild = pChild3->FirstChild(); pChild != 0; pChild = pChild->NextSibling()) { if(strcmp(pChild->Value(), "rendertarget") == 0) { ShaderRenderTarget *newTarget = new ShaderRenderTarget; newTarget->id = pChild->ToElement()->Attribute("id"); newTarget->width = CoreServices::getInstance()->getRenderer()->getXRes(); newTarget->height = CoreServices::getInstance()->getRenderer()->getYRes(); newTarget->sizeMode = ShaderRenderTarget::SIZE_MODE_PIXELS; if(pChild->ToElement()->Attribute("width") && pChild->ToElement()->Attribute("height")) { newTarget->width = atof(pChild->ToElement()->Attribute("width")); newTarget->height = atof(pChild->ToElement()->Attribute("height")); if(pChild->ToElement()->Attribute("sizeMode")) { if(strcmp(pChild->ToElement()->Attribute("sizeMode"), "normalized") == 0) { if(newTarget->width > 1.0f) newTarget->width = 1.0f; if(newTarget->height > 1.0f) newTarget->height = 1.0f; newTarget->width = ((Number)CoreServices::getInstance()->getRenderer()->getXRes()) * newTarget->width; newTarget->height = ((Number)CoreServices::getInstance()->getRenderer()->getYRes()) * newTarget->height; } } } // Texture *newTexture = CoreServices::getInstance()->getMaterialManager()->createNewTexture(newTarget->width, newTarget->height, true); Texture *newTexture, *temp; CoreServices::getInstance()->getRenderer()->createRenderTextures(&newTexture, &temp, (int)newTarget->width, (int)newTarget->height, newMaterial->fp16RenderTargets); newTexture->setResourceName(newTarget->id); //CoreServices::getInstance()->getResourceManager()->addResource(newTexture); newTarget->texture = newTexture; renderTargets.push_back(newTarget); } } } } for (pChild3 = node->FirstChild(); pChild3 != 0; pChild3 = pChild3->NextSibling()) { if(strcmp(pChild3->Value(), "specularValue") == 0) { newMaterial->specularValue = atof(pChild3->ToElement()->GetText()); } if(strcmp(pChild3->Value(), "specularStrength") == 0) { newMaterial->specularStrength = atof(pChild3->ToElement()->GetText()); } if(strcmp(pChild3->Value(), "specularColor") == 0) { String value = pChild3->ToElement()->GetText(); vector<String> values = value.split(" "); if(values.size() == 4) { newMaterial->specularColor.setColor(atof(values[0].c_str()), atof(values[1].c_str()), atof(values[2].c_str()),atof(values[3].c_str())); } else { Logger::log("Error: Incorrect number of values for specularColor (%d provided)!\n", values.size()); } } if(strcmp(pChild3->Value(), "diffuseColor") == 0) { String value = pChild3->ToElement()->GetText(); vector<String> values = value.split(" "); if(values.size() == 4) { newMaterial->diffuseColor.setColor(atof(values[0].c_str()), atof(values[1].c_str()), atof(values[2].c_str()),atof(values[3].c_str())); } else { Logger::log("Error: Incorrect number of values for diffuseColor (%d provided)!\n", values.size()); } } if(strcmp(pChild3->Value(), "shader") == 0) { materialShader = setShaderFromXMLNode(pChild3); if(materialShader) { newShaderBinding = materialShader->createBinding(); materialShaders.push_back(materialShader); newShaderBindings.push_back(newShaderBinding); for (pChild = pChild3->FirstChild(); pChild != 0; pChild = pChild->NextSibling()) { if(strcmp(pChild->Value(), "params") == 0) { for (pChild2 = pChild->FirstChild(); pChild2 != 0; pChild2 = pChild2->NextSibling()) { if(strcmp(pChild2->Value(), "param") == 0){ String pname = pChild2->ToElement()->Attribute("name"); String ptype = pChild2->ToElement()->Attribute("type"); String pvalue = pChild2->ToElement()->Attribute("value"); newShaderBinding->addParam(ptype, pname, pvalue); } } } if(strcmp(pChild->Value(), "targettextures") == 0) { for (pChild2 = pChild->FirstChild(); pChild2 != 0; pChild2 = pChild2->NextSibling()) { if(strcmp(pChild2->Value(), "targettexture") == 0){ RenderTargetBinding* newBinding = new RenderTargetBinding; newBinding->id = pChild2->ToElement()->Attribute("id"); newBinding->name = ""; if(pChild2->ToElement()->Attribute("name")) { newBinding->name = pChild2->ToElement()->Attribute("name"); } String mode = pChild2->ToElement()->Attribute("mode"); if(strcmp(mode.c_str(), "in") == 0) { newBinding->mode = RenderTargetBinding::MODE_IN; } else { newBinding->mode = RenderTargetBinding::MODE_OUT; } newShaderBinding->addRenderTargetBinding(newBinding); //Texture *texture = (Texture*)CoreServices::getInstance()->getResourceManager()->getResource(Resource::RESOURCE_TEXTURE, newBinding->id); // newBinding->texture = texture; for(int l=0; l < renderTargets.size(); l++) { if(renderTargets[l]->id == newBinding->id) { printf("Assigning texture to %s\n", newBinding->id.c_str()); newBinding->texture = renderTargets[l]->texture; newBinding->width = renderTargets[l]->width; newBinding->height = renderTargets[l]->height; } } if(newBinding->mode == RenderTargetBinding::MODE_IN) { newShaderBinding->addTexture(newBinding->name, newBinding->texture); } } } } if(strcmp(pChild->Value(), "textures") == 0) { for (pChild2 = pChild->FirstChild(); pChild2 != 0; pChild2 = pChild2->NextSibling()) { if(strcmp(pChild2->Value(), "texture") == 0){ String tname = ""; if(pChild2->ToElement()->Attribute("name")) { tname = pChild2->ToElement()->Attribute("name"); } newShaderBinding->addTexture(tname, (Texture*)CoreServices::getInstance()->getResourceManager()->getResource(Resource::RESOURCE_TEXTURE, pChild2->ToElement()->GetText())); } if(strcmp(pChild2->Value(), "cubemap") == 0){ String tname = ""; if(pChild2->ToElement()->Attribute("name")) { tname = pChild2->ToElement()->Attribute("name"); } newShaderBinding->addCubemap(tname, (Cubemap*)CoreServices::getInstance()->getResourceManager()->getResource(Resource::RESOURCE_CUBEMAP, pChild2->ToElement()->GetText())); } } } } } } } for(int i=0; i< materialShaders.size(); i++) { newMaterial->addShader(materialShaders[i],newShaderBindings[i]); } for(int i=0; i< renderTargets.size(); i++) { newMaterial->addShaderRenderTarget(renderTargets[i]); } return newMaterial; }
void Leitor::salvar(Topology* cena, std::string nomeArquivo){ cout<<"Iniciando exportação de arquivo."<<endl; //Caso o arquivo não termine com .obj, ele adiciona ao nome string sufixo=""; int tamanhoString = nomeArquivo.size(); for(int i=tamanhoString-4;i<tamanhoString;i++){ sufixo = sufixo + nomeArquivo[i]; } if (sufixo != ".obj"){ nomeArquivo = nomeArquivo + ".obj"; } Leitor::salvarMaterial(cena,nomeArquivo); FILE* arquivo; //Cria o arquivo: arquivo = fopen(nomeArquivo.c_str(),"w"); //Imprimir comentários iniciais: fprintf(arquivo,"#BRrender 2.0 - Trabalho de Computacao Grafica - OBJ File: '%s'\n",nomeArquivo.c_str()); //Imprimir mtllib, que vai ser sempre o mesmo nome mais o .mtl string prefixoMTL=""; string sufixoMTL=".mtl"; string nomeRealMTL=""; int tamanhoStringMTL = nomeArquivo.size(); for(int i=0;i<tamanhoStringMTL-4;i++){ prefixoMTL = prefixoMTL + nomeArquivo[i]; } nomeRealMTL = prefixoMTL + sufixoMTL; fprintf(arquivo, "mtllib %s\n",nomeRealMTL.c_str()); int nObjetos = cena->ObjectNumber; ListMaterial *materiais = cena->Materials; //Para cada objeto: for (int i = 0; i < nObjetos; i++){ //Imprime o nome do objeto: fprintf(arquivo,"o %s\n",cena->ObjectArray[i]->getName().c_str()); //Imprimir os vértices: ListVertex *verticesDoObjeto = cena->ObjectArray[i]->getListVertex(); for (int k = 0; k < verticesDoObjeto->numberVertex(); k++){ Vertex *verticeAtual = verticesDoObjeto->getVertex(k); fprintf(arquivo,"v %lf %lf %lf\n", verticeAtual->getCoordinateXd(),verticeAtual->getCoordinateYd(),verticeAtual->getCoordinateZd()); } ListFace *facesDoObjeto = cena->ObjectArray[i]->getListFace(); for (int k = 0; k < facesDoObjeto->numberFaces(); k++){ Material *materialAtual; Face *faceAtual = facesDoObjeto->getFace(k); if (materialAtual != faceAtual->getMaterial()){ materialAtual = faceAtual->getMaterial(); fprintf(arquivo,"usemtl %s\n",materialAtual->getName().c_str()); } Vertex *vertice1 = faceAtual->getVertice1(); Vertex *vertice2 = faceAtual->getVertice2(); Vertex *vertice3 = faceAtual->getVertice3(); int indiceV1; int indiceV2; int indiceV3; int nTotalVertices = cena->VertexNumber; for (int j = 0; j < nTotalVertices; j++){ if (vertice1 == cena->VertexArray[j]){ indiceV1 = j+1; //O "+1" se dá pois o índice de faces no obj começa do 1 } if (vertice2 == cena->VertexArray[j]){ indiceV2 = j+1; } if (vertice3 == cena->VertexArray[j]){ indiceV3 = j+1; } } fprintf(arquivo,"f %d %d %d\n", indiceV1, indiceV2,indiceV3); } } fclose(arquivo); cout << "Arquivos exportados com sucesso!\n"; }
void MainApplication::initScene() { m_components.clear(); m_debugComponents.clear(); g_world = SoftBodyWorld(); g_body = 0; // Create wood material Material * woodMaterial = new Material(Shader::find("shader")); woodMaterial->setTexture(new Texture("resources/wood.bmp")); // Load bowl model MeshObject * bowl = new MeshObject(MeshFactory::FromFile("resources/bowl.ply"), woodMaterial); bowl->transform().translate(glm::vec3(0.0f, 2.0f, 0.0f)); bowl->transform().update(); // Load low-poly model of bowl for collision detection Mesh * lowpoly = MeshFactory::FromFile("resources/bowl-low.ply"); MeshCollider * bowlCollider = new MeshCollider(bowl); bowlCollider->m_mesh = lowpoly; bowlCollider->m_bvh = BVH::constructFromMesh(lowpoly); CollisionDetector::instance()->addCollider(bowlCollider); m_components.push_back(bowl); // Create cloth material Material * clothMaterial = new Material(Shader::find("shader")); clothMaterial->setTexture(new Texture("resources/cloth.bmp")); clothMaterial->setDiffuseColor(glm::vec4(0.8f, 0.8f, 0.8f, 1.0f)); clothMaterial->setAmbientColor(glm::vec4(0.3f, 0.3f, 0.3f, 1.0f)); clothMaterial->setSpecularColor(glm::vec4(0.5f, 0.5f, 0.5f, 1.0f)); // Create cloth mesh with attached soft body information MeshObject * cloth = SoftBody::createCloth(clothMaterial, &g_world, &g_body); cloth->transform().translate(glm::vec3(-2.5f, 5.0f, -2.5f)); cloth->transform().update(); m_components.push_back(cloth); // Create material for apple Material * appleMaterial = new Material(Shader::find("shader")); appleMaterial->setDiffuseColor(glm::vec4(0.9f)); appleMaterial->setTexture(new Texture("resources/apple.bmp")); // Load apple model from file MeshObject * apple = new MeshObject(MeshFactory::FromFile("resources/apple.ply"), appleMaterial); apple->transform().translate(glm::vec3(0.0f, 3.0f, 10.0f)); apple->transform().scale(glm::vec3(0.5f)); // Create a mathematical sphere collider for the apple SphereCollider * sphereCollider = new SphereCollider(apple); CollisionDetector::instance()->addCollider(sphereCollider); m_components.push_back(apple); // Create animator that animates the apple KeyframeAnimator<glm::vec3> * anim = new KeyframeAnimator<glm::vec3>(apple, new LinearInterpolator<glm::vec3>, apple->transform().position()); anim->addKeyframe(0.0f, glm::vec3(0.0f, 3.0f, 10.0f)); anim->addKeyframe(20000.0f, glm::vec3(0.0f, 3.0f, -10.0f)); anim->addKeyframe(40000.0f, glm::vec3(0.0f, 3.0f, 10.0f)); m_ballAnimator = anim; // Create some debug spheres for the BVH int level = 0; while (true) { ComponentCollection components = addDrawDebug(bowlCollider, level); if (components.empty()) break; m_debugComponents[level] = components; level++; } }
void TriangleShape::generate() { /**************************************************************** * * * Vertices * * * **************************************************************** */ // check if all 3 points are present, otherwise use default method to calculate vertices if(!genVer) { vertices = new Vec3Array(3); (*vertices)[0].set(p1); (*vertices)[1].set(p2); (*vertices)[2].set(p3); } else if (genVer) { vertices = new Vec3Array(); // top point Vec3d v1(center.x(), center.y(), center.z()+length/2); // bottom left point Vec3d v2((center.x()-cos(120)*length/2), center.y(), (center.z()-sin(-60)*length/2)); // bottom right point Vec3d v3((center.x()-cos(60)*length/2), center.y(), (center.z()-sin(-60)*length/2)); vertices->push_back(center); vertices->push_back(v1); vertices->push_back(center); vertices->push_back(v2); vertices->push_back(center); vertices->push_back(v3); vertices->push_back(center); vertices->push_back(v1); } setVertexArray(vertices); /**************************************************************** * * * normals * * * **************************************************************** */ Vec3Array* normals = new Vec3Array(1); (*normals)[0].set(1.0f, 1.0f, 0.0f); setNormalArray(normals); setNormalBinding(Geometry::BIND_OVERALL); /**************************************************************** * * * colors * * * **************************************************************** */ if (!genVer) { colors = new Vec4Array(3); (*colors)[0].set(color1.x(), color1.y(), color1.z(), color1.w()); (*colors)[1].set(color2.x(), color2.y(), color2.z(), color2.w()); (*colors)[2].set(color3.x(), color3.y(), color3.z(), color3.w()); addPrimitiveSet(new DrawArrays(PrimitiveSet::TRIANGLES, 0, 3)); } else { colors = new Vec4Array(); colors->push_back(color1); colors->push_back(color2); colors->push_back(color1); colors->push_back(color2); colors->push_back(color1); colors->push_back(color2); colors->push_back(color1); colors->push_back(color2); addPrimitiveSet(new DrawArrays(PrimitiveSet::TRIANGLE_STRIP, 0, 8)); } setColorArray(colors); setColorBinding(Geometry::BIND_PER_VERTEX); /**************************************************************** * * * stateset and material * * * **************************************************************** */ StateSet* state = getOrCreateStateSet(); state->setMode(GL_BLEND,StateAttribute::ON|StateAttribute::OVERRIDE); Material* mat = new Material(); mat->setAlpha(Material::FRONT_AND_BACK, 0.1); mat->setColorMode(Material::AMBIENT_AND_DIFFUSE); state->setAttributeAndModes(mat,StateAttribute::ON | StateAttribute::OVERRIDE); /**************************************************************** * * * blending * * * **************************************************************** */ BlendFunc* bf = new BlendFunc(BlendFunc::SRC_ALPHA, BlendFunc::ONE_MINUS_SRC_ALPHA ); state->setAttributeAndModes(bf); state->setRenderingHint(StateSet::TRANSPARENT_BIN); state->setMode(GL_LIGHTING, StateAttribute::ON); setStateSet(state); }
/*************************************************************** * Function: ANIMCreateSinglePageGeodeAnimation() ***************************************************************/ void ANIMCreateSinglePageGeodeAnimation(const string& texfilename, Geode **flipUpGeode, Geode **flipDownGeode, AnimationPathCallback **flipUpCallback, AnimationPathCallback **flipDownCallback) { /* coordinates of page object */ Vec3 topleft = Vec3(-0.19, 0, 0); Vec3 bottomleft = Vec3(-0.19, 0, -0.28); Vec3 bottomright = Vec3( 0.19, 0, -0.28); Vec3 topright = Vec3( 0.19, 0, 0); Vec3 start = Vec3(0, -0.004, 0); Vec3 end = Vec3(0, 0.008, 0); float pageH = 0.28, pageW = 0.38; /* create page pain geometry */ *flipUpGeode = new Geode; *flipDownGeode = new Geode; Geometry *pageGeometry = new Geometry(); Vec3Array* vertices = new Vec3Array; Vec2Array* texcoords = new Vec2Array(4); Vec3Array* normals = new Vec3Array; vertices->push_back(topleft); (*texcoords)[0].set(0, 1); vertices->push_back(bottomleft); (*texcoords)[1].set(0, 0); vertices->push_back(bottomright); (*texcoords)[2].set(1, 0); vertices->push_back(topright); (*texcoords)[3].set(1, 1); for (int i = 0; i < 4; i++) { normals->push_back(Vec3(0, -1, 0)); } DrawElementsUInt* rectangle = new DrawElementsUInt(PrimitiveSet::POLYGON, 0); rectangle->push_back(0); rectangle->push_back(1); rectangle->push_back(2); rectangle->push_back(3); pageGeometry->addPrimitiveSet(rectangle); pageGeometry->setVertexArray(vertices); pageGeometry->setTexCoordArray(0, texcoords); pageGeometry->setNormalArray(normals); pageGeometry->setNormalBinding(Geometry::BIND_PER_VERTEX); (*flipUpGeode)->addDrawable(pageGeometry); (*flipDownGeode)->addDrawable(pageGeometry); /* apply image textures to page geodes */ Image* imgFloorplan = osgDB::readImageFile(texfilename); int imgW = imgFloorplan->s(); int imgH = imgFloorplan->t(); Texture2D* texFloorplan = new Texture2D(imgFloorplan); texFloorplan->setWrap(Texture::WRAP_S, Texture::CLAMP); texFloorplan->setWrap(Texture::WRAP_T, Texture::CLAMP); float imgRatio = (float) imgW / imgH; float pageRatio = pageW / pageH; if (imgRatio <= pageRatio) { (*texcoords)[0].set((1.0 - pageRatio / imgRatio) * 0.5, 1); (*texcoords)[1].set((1.0 - pageRatio / imgRatio) * 0.5, 0); (*texcoords)[2].set((1.0 + pageRatio / imgRatio) * 0.5, 0); (*texcoords)[3].set((1.0 + pageRatio / imgRatio) * 0.5, 1); } else { (*texcoords)[0].set(0, (1.0 + imgRatio / pageRatio) * 0.5); (*texcoords)[1].set(0, (1.0 - imgRatio / pageRatio) * 0.5); (*texcoords)[2].set(1, (1.0 - imgRatio / pageRatio) * 0.5); (*texcoords)[3].set(1, (1.0 + imgRatio / pageRatio) * 0.5); } Material *transmaterial = new Material; transmaterial->setDiffuse(Material::FRONT_AND_BACK, Vec4(1, 1, 1, 1)); transmaterial->setAlpha(Material::FRONT_AND_BACK, 0.8f); Material *solidmaterial = new Material; solidmaterial->setDiffuse(Material::FRONT_AND_BACK, Vec4(1, 1, 1, 1)); solidmaterial->setAlpha(Material::FRONT_AND_BACK, 1.0f); StateSet *flipUpStateSet = (*flipUpGeode)->getOrCreateStateSet(); flipUpStateSet->setTextureAttributeAndModes(0, texFloorplan, StateAttribute::ON); flipUpStateSet->setMode(GL_BLEND, StateAttribute::OVERRIDE | StateAttribute::ON ); flipUpStateSet->setRenderingHint(StateSet::TRANSPARENT_BIN); flipUpStateSet->setAttributeAndModes(transmaterial, StateAttribute::OVERRIDE | StateAttribute::ON); StateSet *flipDownStateSet = (*flipDownGeode)->getOrCreateStateSet(); flipDownStateSet->setTextureAttributeAndModes(0, texFloorplan, StateAttribute::ON); flipDownStateSet->setMode(GL_BLEND, StateAttribute::OVERRIDE | StateAttribute::ON ); flipDownStateSet->setRenderingHint(StateSet::TRANSPARENT_BIN); flipDownStateSet->setAttributeAndModes(solidmaterial, StateAttribute::OVERRIDE | StateAttribute::ON); /* create page flipping animation call backs */ AnimationPath* animationPathFlipUp = new AnimationPath; AnimationPath* animationPathFlipDown = new AnimationPath; animationPathFlipUp->setLoopMode(AnimationPath::NO_LOOPING); animationPathFlipDown->setLoopMode(AnimationPath::NO_LOOPING); Vec3 flipUpOffset, flipDownOffset; Quat flipUpQuat, flipDownQuat; Vec3 offsetstep = (end - start) / ANIM_SKETCH_BOOK_PAGE_FLIP_SAMPS; float anglestep = M_PI * 2 / ANIM_SKETCH_BOOK_PAGE_FLIP_SAMPS; float timestep = 1.0f / ANIM_SKETCH_BOOK_PAGE_FLIP_SAMPS; for (int i = 0; i < ANIM_SKETCH_BOOK_PAGE_FLIP_SAMPS + 1; i++) { float val = i * timestep; flipUpOffset = start + offsetstep * i; flipDownOffset = end - offsetstep * i; flipUpQuat = Quat(i * anglestep, Vec3(-1, 0, 0)); flipDownQuat = Quat(i * anglestep, Vec3(1, 0, 0)); animationPathFlipUp->insert(val, AnimationPath::ControlPoint(flipUpOffset, flipUpQuat, Vec3(1, 1, 1))); animationPathFlipDown->insert(val, AnimationPath::ControlPoint(flipDownOffset, flipDownQuat, Vec3(1, 1, 1))); } *flipUpCallback = new AnimationPathCallback(animationPathFlipUp, 0.0, 1.0f / ANIM_SKETCH_BOOK_PAGE_FLIP_TIME); *flipDownCallback = new AnimationPathCallback(animationPathFlipDown, 0.0, 1.0f / ANIM_SKETCH_BOOK_PAGE_FLIP_TIME); }
void Model::draw(bool wireframe) { unsigned int partCount = _mesh->getPartCount(); if (partCount == 0) { // No mesh parts (index buffers). if (_material) { Technique* technique = _material->getTechnique(); unsigned int passCount = technique->getPassCount(); for (unsigned int i = 0; i < passCount; ++i) { Pass* pass = technique->getPass(i); pass->bind(); GL_ASSERT( glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0) ); if (wireframe && (_mesh->getPrimitiveType() == Mesh::TRIANGLES || _mesh->getPrimitiveType() == Mesh::TRIANGLE_STRIP)) { unsigned int vertexCount = _mesh->getVertexCount(); for (unsigned int j = 0; j < vertexCount; j += 3) { GL_ASSERT( glDrawArrays(GL_LINE_LOOP, j, 3) ); } } else { GL_ASSERT( glDrawArrays(_mesh->getPrimitiveType(), 0, _mesh->getVertexCount()) ); } pass->unbind(); } } } else { for (unsigned int i = 0; i < partCount; ++i) { MeshPart* part = _mesh->getPart(i); // Get the material for this mesh part. Material* material = getMaterial(i); if (material) { Technique* technique = material->getTechnique(); unsigned int passCount = technique->getPassCount(); for (unsigned int j = 0; j < passCount; ++j) { Pass* pass = technique->getPass(j); pass->bind(); GL_ASSERT( glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, part->_indexBuffer) ); if (wireframe && (_mesh->getPrimitiveType() == Mesh::TRIANGLES || _mesh->getPrimitiveType() == Mesh::TRIANGLE_STRIP)) { unsigned int indexCount = part->getIndexCount(); unsigned int indexSize = 0; switch (part->getIndexFormat()) { case Mesh::INDEX8: indexSize = 1; break; case Mesh::INDEX16: indexSize = 2; break; case Mesh::INDEX32: indexSize = 4; break; } for (unsigned int k = 0; k < indexCount; k += 3) { GL_ASSERT( glDrawElements(GL_LINE_LOOP, 3, part->getIndexFormat(), ((const GLvoid*)(k*indexSize))) ); } } else { GL_ASSERT( glDrawElements(part->getPrimitiveType(), part->getIndexCount(), part->getIndexFormat(), 0) ); } pass->unbind(); } } } } }
void InitScene() { Logger::log("Creating Material\n\n"); // Generate a box material Material *boxMaterial = new Material(); // Load textures for this material Texture::create(CRATE_PCX,"crate1"); // Apply the textures as layer 0, 1, 2 boxMaterial->bindTexture(0,Texture::getTextureId("crate1"),TEXTURE_DIFF); // Create the box structure and bind our material to each face makeBox(boxObj,1.0,boxMaterial); // Create a UV Mapper UVMapper myUVMapper; // Set the projection type to cubic myUVMapper.setProjection(UV_PROJECTION_CUBIC); // Match the scale of our box myUVMapper.setScale(XYZ(1.0,1.0,1.0)); // Apply the UV map to the material we bound to our box object myUVMapper.apply(boxObj,boxMaterial); // Now cache the object onto the card for best performance. boxObj.cache(true); MeshRenderer tmpShader; mkLandscape(); //CreateTower(2,4,2,XYZ(-1.5,5,-1.5),XYZ(1,1,1)); // Set up the global ambient factor // Light::setGlobalAmbient(RGB(0.1,0.1,0.1)); // Set up our light for (int i = 0; i < NUM_LIGHTS; i++) { myLights[i].setType(LIGHT_POINT); myLights[i].diffuse = RGB((float)rand()/(float)RAND_MAX,(float)rand()/(float)RAND_MAX,(float)rand()/(float)RAND_MAX); myLights[i].setCutoff(20); myScene.bind(myLights[i]); } // Set up our camera (targeted, looking at 0,0,0) myCamera.setType(CAMERA_TARGET); myCamera.position = XYZ(-8.0,8.0,-8.0); //myCamera.target = XYZ(0,5,0); targetObj.setPosition(XYZ(0,0,0)); myCamera.bindTarget(&targetObj); myCamera.setClip(0.01,100); // Bind the light and camera myScene.bind(myCamera); /* myLightR.position = XYZ(cos(10*2.0)*8.0, 6, sin(10*2.0)*8.0); myLightG.position = XYZ(cos(10 )*4.0, 6, sin(10 )*4.0); myLightB.position = XYZ(cos(10*-1.5)*10.0,6, sin(10*-1.5)*10.0); */ }
bool Loader_obj::load_model_data(Model& mdl, QString path){ QStringList pathlist = path.split("/",QString::KeepEmptyParts); //KeepEmptyParts QString model_name = pathlist.last(); //LOAD MESH DATA QFile file(path); if (!file.open (QIODevice::ReadOnly)) { qDebug(" Model import: Error 1: Model file could not be loaded..."); return false; } QTextStream stream ( &file ); QString line; QString mtllib; QString current_mesh; QMap<QString,QVector<int> >mesh_faces; QMap<QString,QString> mesh_mtl; QMap<QString,Material* > mtln_mtl; QVector<Vector3> model_vertices; QVector<Vector3> model_vertex_normals; QVector<Vector3> model_vertex_texture_coordinates; while( !stream.atEnd() ) { line = stream.readLine(); QStringList list = line.split(QRegExp("\\s+"),QString::SkipEmptyParts); //SkipEmptyParts if(!list.empty()){ if(list.first() == "mtllib"){ mtllib = list.last(); } else if(list.first() == "v"){ model_vertices.append(Vector3( list.value(1).toFloat(), list.value(2).toFloat(), list.value(3).toFloat())); } else if(list.first() == "vn"){ model_vertex_normals.append(Vector3( list.value(1).toFloat(), list.value(2).toFloat(), list.value(3).toFloat())); } else if(list.first() == "vt"){ model_vertex_texture_coordinates.append(Vector3( list.value(1).toFloat(), list.value(2).toFloat(), list.value(3).toFloat())); } else if(list.first() == "g"){ current_mesh = list.value(1); } else if(list.first() == "usemtl"){ mesh_mtl[current_mesh] = list.value(1); } else if(list.first() == "f"){ QStringList face_part_1_list = list.value(1).split("/",QString::SkipEmptyParts); //SkipEmptyParts QStringList face_part_2_list = list.value(2).split("/",QString::SkipEmptyParts); //SkipEmptyParts QStringList face_part_3_list = list.value(3).split("/",QString::SkipEmptyParts); //SkipEmptyParts mesh_faces[current_mesh].append(face_part_1_list.value(0).toInt()); mesh_faces[current_mesh].append(face_part_1_list.value(1).toInt()); mesh_faces[current_mesh].append(face_part_1_list.value(2).toInt()); mesh_faces[current_mesh].append(face_part_2_list.value(0).toInt()); mesh_faces[current_mesh].append(face_part_2_list.value(1).toInt()); mesh_faces[current_mesh].append(face_part_2_list.value(2).toInt()); mesh_faces[current_mesh].append(face_part_3_list.value(0).toInt()); mesh_faces[current_mesh].append(face_part_3_list.value(1).toInt()); mesh_faces[current_mesh].append(face_part_3_list.value(2).toInt()); } } } file.close(); //LOAD MTL DATA pathlist.removeAt(pathlist.length()-1); QString mtl_path = pathlist.join("/") + "/" + mtllib; QString tex_path = pathlist.join("/") + "/"; QFile mtlfile(mtl_path); if (!mtlfile.open (QIODevice::ReadOnly)) { qDebug(" Model import: Error 2: Model material file could not be loaded..."); return false; } QTextStream mtlstream ( &mtlfile ); QString mtlline; QString current_mtl; QMap<QString,Vector3> mtl_ambient_c; //Ka QMap<QString,Vector3> mtl_diffuse_c; //Kd QMap<QString,Vector3> mtl_specular_c; //Ks QMap<QString,float> mtl_specular_ns; //Ns QMap<QString,float> mtl_transparency_d; //d QMap<QString,float> mtl_transparency_tr; //Tr QMap<QString,Vector3> mtl_transparency_tf; //Tf QMap<QString,QString> mtl_ambient_map; //map_Ka QMap<QString,QString> mtl_diffuse_map; //map_Kd QMap<QString,QString> mtl_specular_map; //map_Ks QMap<QString,QString> mtl_bump_map; //map_bump QMap<QString,int> mtl_illumination; //illum //stream while( !mtlstream.atEnd() ) { mtlline = mtlstream.readLine(); QStringList list = mtlline.split(QRegExp("\\s+"),QString::SkipEmptyParts); //SkipEmptyParts if(!list.empty()){ if(list.first() == "newmtl"){ current_mtl = list.last(); } else if(list.first() == "Ka"){ mtl_ambient_c[current_mtl] = Vector3(list.value(1).toFloat(), list.value(2).toFloat(), list.value(3).toFloat()); } else if(list.first() == "Kd"){ mtl_diffuse_c[current_mtl] = Vector3(list.value(1).toFloat(), list.value(2).toFloat(), list.value(3).toFloat()); } else if(list.first() == "Ks"){ mtl_specular_c[current_mtl] = Vector3(list.value(1).toFloat(), list.value(2).toFloat(), list.value(3).toFloat()); } else if(list.first() == "Ns"){ mtl_specular_ns[current_mtl] = list.value(1).toFloat(); } else if(list.first() == "d"){ mtl_transparency_d[current_mtl] = list.value(1).toFloat(); } else if(list.first() == "Tr"){ mtl_transparency_tr[current_mtl] = list.value(1).toFloat(); } else if(list.first() == "Tf"){ mtl_transparency_tf[current_mtl] = Vector3(list.value(1).toFloat(), list.value(2).toFloat(), list.value(3).toFloat()); } else if(list.first() == "map_Ka"){ mtl_ambient_map[current_mtl] = list.value(1).split("\\",QString::SkipEmptyParts).last().toUtf8(); } else if(list.first() == "map_Kd"){ mtl_diffuse_map[current_mtl] = list.value(1).split("\\",QString::SkipEmptyParts).last().toUtf8(); } else if(list.first() == "map_Ks"){ mtl_specular_map[current_mtl] = list.value(1).split("\\",QString::SkipEmptyParts).last().toUtf8(); } else if((list.first() == "map_bump") || (list.first() == "bump")){ mtl_bump_map[current_mtl] = list.value(1).split("\\",QString::SkipEmptyParts).last().toUtf8(); } else if(list.first() == "illum"){ mtl_illumination[current_mtl] = list.value(1).toInt(); } } } //stream end //CREATE MTLS (if needed...) //using diffues mat cause its the major map used (other maps are optional)... QList<QString> mtl_names = mtl_diffuse_c.keys(); for(int i = 0; i < mtl_names.length(); i++){ Material* mtl = new Material(mtl_names.value(i),tex_path); mtl->set_ambient_c(mtl_ambient_c[mtl_names.value(i)]); mtl->set_diffuse_c(mtl_diffuse_c[mtl_names.value(i)]); mtl->set_specular_c(mtl_specular_c[mtl_names.value(i)]); mtl->set_specular_ns(mtl_specular_ns[mtl_names.value(i)]); mtl->set_transparency_d(mtl_transparency_d[mtl_names.value(i)]); mtl->set_transparency_tr(mtl_transparency_tr[mtl_names.value(i)]); mtl->set_transparency_tf(mtl_transparency_tf[mtl_names.value(i)]); mtl->set_ambient_map_name(mtl_ambient_map[mtl_names.value(i)]); mtl->set_diffuse_map_name(mtl_diffuse_map[mtl_names.value(i)]); mtl->set_specular_map_name(mtl_specular_map[mtl_names.value(i)]); mtl->set_bump_map_name(mtl_bump_map[mtl_names.value(i)]); mtl->set_illumination(mtl_illumination[mtl_names.value(i)]); //init texture maps //as this function gets called in a thread we need to do this in main... /* mtl->load_ambient_map(tex_path + mtl_ambient_map[mtl_names.value(i)]); mtl->load_diffuse_map(tex_path + mtl_diffuse_map[mtl_names.value(i)]); mtl->load_specular_map(tex_path + mtl_specular_map[mtl_names.value(i)]); mtl->load_bump_map(tex_path + mtl_bump_map[mtl_names.value(i)]); */ mtl->set_ambient_map_path(tex_path + mtl_ambient_map[mtl_names.value(i)]); mtl->set_diffuse_map_path(tex_path + mtl_diffuse_map[mtl_names.value(i)]); mtl->set_specular_map_path(tex_path + mtl_specular_map[mtl_names.value(i)]); mtl->set_bump_map_path(tex_path + mtl_bump_map[mtl_names.value(i)]); mtl->loadData(); /* qDebug(" MTL ambient m: " + mtl->get_ambient_map_name().toUtf8()); qDebug(" MTL diffuse m: " + mtl->get_diffuse_map_name().toUtf8()); qDebug(" MTL specular m: " + mtl->get_specular_map_name().toUtf8()); qDebug(" MTL bump m: " + mtl->get_bump_map_name().toUtf8()); */ mtln_mtl[mtl_names.value(i)] = mtl; } //CREATE MESHS (if needed...) //QMap<QString,QVector<QVector3D> > mesh_faces; //QMap<QString,QString> mesh_mtl; //QVector<QVector3D> model_vertices; //QVector<QVector3D> model_vertex_normals; //QVector<QVector3D> model_vertex_texture_coordinates; //using mesh_mtl to iterate ... QList<QString> mesh_names = mesh_mtl.keys(); for(int i = 0; i < mesh_names.length(); i++){ //min/max vertex pos on all 3 axis GLfloat v_min_x = 0.0f; GLfloat v_max_x = 0.0f; GLfloat v_min_y = 0.0f; GLfloat v_max_y = 0.0f; GLfloat v_min_z = 0.0f; GLfloat v_max_z = 0.0f; int triangle_count = mesh_faces[mesh_names.value(i)].size() / 3 / 3; //qDebug(" Triangles: %i",triangle_count); GLfloat* vertices = new GLfloat[mesh_faces[mesh_names.value(i)].size()]; GLfloat* texcoords = new GLfloat[mesh_faces[mesh_names.value(i)].size()]; //should be wrong ... 108/3*2 is right ... GLfloat* normals = new GLfloat[mesh_faces[mesh_names.value(i)].size()]; //qDebug("Mesh..."); for(int j = 0; j < mesh_faces[mesh_names.value(i)].size(); j+=9){ // 1 v/vt/vn 2 v/vt/vn 3 v/vt/vn // v Vector3 vertex1 = model_vertices.value(mesh_faces[mesh_names.value(i)].value(j) -1); vertices[j] = (GLfloat) vertex1.x(); vertices[j+1] = (GLfloat) vertex1.y(); vertices[j+2] = (GLfloat) vertex1.z(); Vector3 vertex2 = model_vertices.value(mesh_faces[mesh_names.value(i)].value(j+3)-1); vertices[3+j] = (GLfloat) vertex2.x(); vertices[3+j+1] = (GLfloat) vertex2.y(); vertices[3+j+2] = (GLfloat) vertex2.z(); Vector3 vertex3 = model_vertices.value(mesh_faces[mesh_names.value(i)].value(j+6)-1); vertices[6+j] = (GLfloat) vertex3.x(); vertices[6+j+1] = (GLfloat) vertex3.y(); vertices[6+j+2] = (GLfloat) vertex3.z(); //get the min/max vertex pos on all 3 axis //x axis v_min_x = min_value(v_min_x,vertex1.x()); v_min_x = min_value(v_min_x,vertex2.x()); v_min_x = min_value(v_min_x,vertex3.x()); v_max_x = max_value(v_max_x,vertex1.x()); v_max_x = max_value(v_max_x,vertex2.x()); v_max_x = max_value(v_max_x,vertex3.x()); //y axis v_min_y = min_value(v_min_y,vertex1.y()); v_min_y = min_value(v_min_y,vertex2.y()); v_min_y = min_value(v_min_y,vertex3.y()); v_max_y = max_value(v_max_y,vertex1.y()); v_max_y = max_value(v_max_y,vertex2.y()); v_max_y = max_value(v_max_y,vertex3.y()); //z axis v_min_z = min_value(v_min_z,vertex1.z()); v_min_z = min_value(v_min_z,vertex2.z()); v_min_z = min_value(v_min_z,vertex3.z()); v_max_z = max_value(v_max_z,vertex1.z()); v_max_z = max_value(v_max_z,vertex2.z()); v_max_z = max_value(v_max_z,vertex3.z()); // vt (t value inverted) Vector3 texcoord1 = model_vertex_texture_coordinates.value(mesh_faces[mesh_names.value(i)].value(j+1)-1); texcoords[j] = (GLfloat) texcoord1.x(); texcoords[j+1] = (GLfloat) -texcoord1.y(); texcoords[j+2] = (GLfloat) texcoord1.z(); Vector3 texcoord2 = model_vertex_texture_coordinates.value(mesh_faces[mesh_names.value(i)].value(j+4)-1); texcoords[3+j] = (GLfloat) texcoord2.x(); texcoords[3+j+1] = (GLfloat) -texcoord2.y(); texcoords[3+j+2] = (GLfloat) texcoord2.z(); Vector3 texcoord3 = model_vertex_texture_coordinates.value(mesh_faces[mesh_names.value(i)].value(j+7)-1); texcoords[6+j] = (GLfloat) texcoord3.x(); texcoords[6+j+1] = (GLfloat) -texcoord3.y(); texcoords[6+j+2] = (GLfloat) texcoord3.z(); // vn Vector3 normal1 = model_vertex_normals.value(mesh_faces[mesh_names.value(i)].value(j+2)-1); normal1.normalize(); //normalize normals[j] = (GLfloat) normal1.x(); normals[j+1] = (GLfloat) normal1.y(); normals[j+2] = (GLfloat) normal1.z(); Vector3 normal2 = model_vertex_normals.value(mesh_faces[mesh_names.value(i)].value(j+5)-1); normal2.normalize(); //normalize normals[3+j] = (GLfloat) normal2.x(); normals[3+j+1] = (GLfloat) normal2.y(); normals[3+j+2] = (GLfloat) normal2.z(); Vector3 normal3 = model_vertex_normals.value(mesh_faces[mesh_names.value(i)].value(j+8)-1); normal3.normalize(); //normalize normals[6+j] = (GLfloat) normal3.x(); normals[6+j+1] = (GLfloat) normal3.y(); normals[6+j+2] = (GLfloat) normal3.z(); } Vector3 vert1(v_min_x, v_min_y, v_min_z); Vector3 vert2(v_max_x, v_max_y, v_max_z); Vector3 bounding_sphere_pos((v_min_x + v_max_x)/2.0f, (v_min_y + v_max_y)/2.0f, (v_min_z + v_max_z)/2.0f); double bounding_sphere_radius = vert1.distance(vert2) / 2.0f; //bounding_sphere_radius = 10.0; //Create Mesh and add it to the Mesh-list of the model. Mesh* mesh = new Mesh(mesh_names.value(i), triangle_count, vertices, texcoords, normals, mtln_mtl.value(mesh_mtl.value(mesh_names.value(i)))); mesh->setBoundingSpherePos(bounding_sphere_pos); mesh->setBoundingSphereRadius(bounding_sphere_radius); //meshs.append(mesh); mdl.add_mesh(mesh); } mdl.set_path(path); return true; }
void Mesh::render(int renderMode, int glMode){ int group_name = 0; int currentID = 0; glBindTexture(GL_TEXTURE_2D, currentID); if (glMode == GL_LINE_LOOP) { renderVerts(); if (renderMode == GL_SELECT) return; } for(Group* g : groups){ if(renderMode == GL_SELECT && glMode == GL_POLYGON){ glLoadName(group_name++); } if(!g->getVisible()){ continue; } string mtlName = g->getMtl(); if(!mtlName.empty()){ Material* mtl = getMtl(mtlName); glMaterialfv(GL_FRONT, GL_SPECULAR, mtl->getSpecular()); glMaterialfv(GL_FRONT, GL_AMBIENT, mtl->getAmbient()); glMaterialfv(GL_FRONT, GL_DIFFUSE, mtl->getDiffuse()); glMaterialf(GL_FRONT, GL_SHININESS, mtl->getShininess()); int tID = mtl->getID(); if(tID != currentID){ currentID = tID; glBindTexture(GL_TEXTURE_2D, currentID); } } int face_name = 0; glColor3f(1.0, 1.0, 1.0); for(Face* f : g->getFaces()){ if (f == face_selected.face) glColor3f(0.603922f, 0.803922f, 0.196078f); vector<int> v = f->getVerts(); vector<int> n = f->getNorms(); vector<int> t = f->getTexts(); bool hasNorm = !n.empty(); bool hasText = !t.empty(); int nv = v.size(); if (renderMode == GL_SELECT && glMode == GL_POLYGON) glPushName(face_name++); glBegin(glMode); for(int x = 0; x < nv; ++x){ if(hasNorm) { glNormal3fv(norms[n[x]].getCoords()); } if(hasText){ glTexCoord2fv(texts[t[x]].getCoords()); } glVertex3fv(verts[v[x]].getCoords()); } glEnd(); if (renderMode == GL_SELECT && glMode == GL_POLYGON) glPopName(); if (f == face_selected.face) glColor3f(1.0, 1.0, 1.0); } } }
Scene& GlassModelExample::createMaterials(Scene& scene) { std::cout << "Creating materials..." << std::endl; Material* mat = NULL; mat = new Material("white", Color(1,1,1)); mat->setSpecularIntensity(1.0); mat->setSpecularGlossiness(32); scene.addElement(mat); mat = new Material("glass", Color(0.04,0.02,0.04)); mat->setReflection(true); mat->setRefraction(true); mat->setIOR(1.3); mat->setAbsorption(10); mat->setSpecularIntensity(0.15); mat->setSpecularGlossiness(64); scene.addElement(mat); mat = new Material("glossy_glass", Color(0.04,0.02,0.04)); mat->setReflection(true); mat->setRefraction(true); mat->setIOR(1.3); mat->setAbsorption(0); mat->setSpecularIntensity(0.2); mat->setSpecularGlossiness(64); mat->setGlossy(true); mat->setGlossyRoughness(0.01); scene.addElement(mat); mat = NULL; return scene; }
void ParticleEmitter::setParticleType(const ParticleKind* type) { assert(m_magic_number == 0x58781325); bool is_new_type = (m_particle_type != type); if (is_new_type) { if (m_node != NULL) { m_node->removeAll(); m_node->removeAllAffectors(); m_emitter->drop(); } else { if (m_is_glsl) m_node = ParticleSystemProxy::addParticleNode(m_is_glsl, type->randomizeInitialY()); else m_node = irr_driver->addParticleNode(); if (m_is_glsl) { bool additive = (type->getMaterial()->getShaderType() == Material::SHADERTYPE_ADDITIVE); static_cast<ParticleSystemProxy *>(m_node)->setAlphaAdditive(additive); } } if (m_parent != NULL) { m_node->setParent(m_parent); } m_particle_type = type; } m_emission_decay_rate = type->getEmissionDecayRate(); Material* material = type->getMaterial(); const float minSize = type->getMinSize(); const float maxSize = type->getMaxSize(); const int lifeTimeMin = type->getMinLifetime(); const int lifeTimeMax = type->getMaxLifetime(); assert(maxSize >= minSize); assert(lifeTimeMax >= lifeTimeMin); #ifdef DEBUG if (material != NULL) { video::ITexture* tex = material->getTexture(); assert(tex != NULL); const io::SNamedPath& name = tex->getName(); const io::path& tpath = name.getPath(); std::string debug_name = std::string("particles(") + tpath.c_str() + ")"; m_node->setName(debug_name.c_str()); } #endif m_min_rate = (float)type->getMinRate(); m_max_rate = (float)type->getMaxRate(); if (is_new_type) { video::SMaterial& mat0 = m_node->getMaterial(0); m_node->setPosition(m_position.toIrrVector()); if (material != NULL) { assert(material->getTexture() != NULL); material->setMaterialProperties(&mat0, NULL); m_node->setMaterialTexture(0, material->getTexture()); mat0.ZWriteEnable = !material->isTransparent(); // disable z-buffer writes if material is transparent // fallback for old render engine if (material->getShaderType() == Material::SHADERTYPE_ADDITIVE) mat0.MaterialType = video::EMT_TRANSPARENT_ADD_COLOR; else if (material->getShaderType() == Material::SHADERTYPE_ALPHA_BLEND) mat0.MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL; else if (material->getShaderType() == Material::SHADERTYPE_ALPHA_TEST) mat0.MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF; } else { std::string help = file_manager->getAsset(FileManager::GUI, "main_help.png"); m_node->setMaterialTexture(0, irr_driver->getTexture(help)); } // velocity in m/ms core::vector3df velocity(m_particle_type->getVelocityX(), m_particle_type->getVelocityY(), m_particle_type->getVelocityZ()); switch (type->getShape()) { case EMITTER_POINT: { m_emitter = m_node->createPointEmitter(velocity, type->getMinRate(), type->getMaxRate(), type->getMinColor(), type->getMinColor(), lifeTimeMin, lifeTimeMax, m_particle_type->getAngleSpread() /* angle */ ); break; } case EMITTER_BOX: { const float box_size_x = type->getBoxSizeX()/2.0f; const float box_size_y = type->getBoxSizeY()/2.0f; m_emitter = m_node->createBoxEmitter(core::aabbox3df(-box_size_x, -box_size_y, -0.6f, box_size_x, box_size_y, -0.6f - type->getBoxSizeZ()), velocity, type->getMinRate(), type->getMaxRate(), type->getMinColor(), type->getMinColor(), lifeTimeMin, lifeTimeMax, m_particle_type->getAngleSpread() ); #if VISUALIZE_BOX_EMITTER if (m_parent != NULL) { for (int x=0; x<2; x++) { for (int y=0; y<2; y++) { for (int z=0; z<2; z++) { m_visualisation.push_back( irr_driver->getSceneManager()->addSphereSceneNode(0.05f, 16, m_parent, -1, core::vector3df((x ? box_size_x : -box_size_x), (y ? box_size_y : -box_size_y), -0.6 - (z ? 0 : type->getBoxSizeZ()))) ); } } } } #endif break; } case EMITTER_SPHERE: { m_emitter = m_node->createSphereEmitter(core::vector3df(0.0f,0.0f,0.0f) /* center */, m_particle_type->getSphereRadius(), velocity, type->getMinRate(), type->getMaxRate(), type->getMinColor(), type->getMinColor(), lifeTimeMin, lifeTimeMax, m_particle_type->getAngleSpread() ); break; } default: { Log::error("ParticleEmitter", "Unknown shape"); return; } } } else { m_emitter->setMinParticlesPerSecond(int(m_min_rate)); m_emitter->setMaxParticlesPerSecond(int(m_max_rate)); } m_emitter->setMinStartSize(core::dimension2df(minSize, minSize)); m_emitter->setMaxStartSize(core::dimension2df(maxSize, maxSize)); if (is_new_type) { m_node->setEmitter(m_emitter); // this grabs the emitter scene::IParticleFadeOutAffector *af = m_node->createFadeOutParticleAffector(video::SColor(0, 255, 255, 255), type->getFadeoutTime()); m_node->addAffector(af); af->drop(); if (type->getGravityStrength() != 0) { scene::IParticleGravityAffector *gaf = m_node->createGravityAffector(core::vector3df(00.0f, type->getGravityStrength(), 0.0f), type->getForceLostToGravityTime()); m_node->addAffector(gaf); gaf->drop(); } const float fas = type->getFadeAwayStart(); const float fae = type->getFadeAwayEnd(); if (fas > 0.0f && fae > 0.0f) { FadeAwayAffector* faa = new FadeAwayAffector(fas*fas, fae*fae); m_node->addAffector(faa); faa->drop(); } if (type->hasScaleAffector()) { if (m_is_glsl) { static_cast<ParticleSystemProxy *>(m_node)->setIncreaseFactor(type->getScaleAffectorFactorX()); } else { core::vector2df factor = core::vector2df(type->getScaleAffectorFactorX(), type->getScaleAffectorFactorY()); scene::IParticleAffector* scale_affector = new ScaleAffector(factor); m_node->addAffector(scale_affector); scale_affector->drop(); } } if (type->getMinColor() != type->getMaxColor()) { if (m_is_glsl) { video::SColor color_from = type->getMinColor(); static_cast<ParticleSystemProxy *>(m_node)->setColorFrom(color_from.getRed() / 255.0f, color_from.getGreen() / 255.0f, color_from.getBlue() / 255.0f); video::SColor color_to = type->getMaxColor(); static_cast<ParticleSystemProxy *>(m_node)->setColorTo(color_to.getRed() / 255.0f, color_to.getGreen() / 255.0f, color_to.getBlue() / 255.0f); } else { video::SColor color_from = type->getMinColor(); core::vector3df color_from_v = core::vector3df(float(color_from.getRed()), float(color_from.getGreen()), float(color_from.getBlue())); video::SColor color_to = type->getMaxColor(); core::vector3df color_to_v = core::vector3df(float(color_to.getRed()), float(color_to.getGreen()), float(color_to.getBlue())); ColorAffector* affector = new ColorAffector(color_from_v, color_to_v); m_node->addAffector(affector); affector->drop(); } } const float windspeed = type->getWindSpeed(); if (windspeed > 0.01f) { WindAffector *waf = new WindAffector(windspeed); m_node->addAffector(waf); waf->drop(); // TODO: wind affector for GLSL particles } const bool flips = type->getFlips(); if (flips) { if (m_is_glsl) static_cast<ParticleSystemProxy *>(m_node)->setFlip(); } } } // setParticleType
Material *MaterialManager::materialFromXMLNode(TiXmlNode *node) { TiXmlElement *nodeElement = node->ToElement(); if (!nodeElement) return NULL; // Skip comment nodes String mname = nodeElement->Attribute("name"); TiXmlNode* pChild, *pChild2,*pChild3; Shader *materialShader; ShaderBinding *newShaderBinding; vector<Shader*> materialShaders; vector<ShaderBinding*> newShaderBindings; vector<ShaderRenderTarget*> renderTargets; Material *newMaterial = new Material(mname); if(nodeElement->Attribute("blendingMode")) { newMaterial->blendingMode = atoi(nodeElement->Attribute("blendingMode")); } for (pChild3 = node->FirstChild(); pChild3 != 0; pChild3 = pChild3->NextSibling()) { TiXmlElement *pChild3Element = pChild3->ToElement(); if (!pChild3Element) continue; // Skip comment nodes if(strcmp(pChild3->Value(), "rendertargets") == 0) { if(pChild3Element->Attribute("type")) { if(strcmp(pChild3Element->Attribute("type"), "rgba_fp16") == 0) { newMaterial->fp16RenderTargets = true; } } for (pChild = pChild3->FirstChild(); pChild != 0; pChild = pChild->NextSibling()) { TiXmlElement *pChildElement = pChild->ToElement(); if (!pChildElement) continue; // Skip comment nodes if(strcmp(pChild->Value(), "rendertarget") == 0) { ShaderRenderTarget *newTarget = new ShaderRenderTarget; newTarget->id = pChildElement->Attribute("id"); newTarget->width = CoreServices::getInstance()->getRenderer()->getXRes(); newTarget->height = CoreServices::getInstance()->getRenderer()->getYRes(); newTarget->sizeMode = ShaderRenderTarget::SIZE_MODE_PIXELS; if(pChildElement->Attribute("width") && pChildElement->Attribute("height")) { newTarget->width = atof(pChildElement->Attribute("width")); newTarget->height = atof(pChildElement->Attribute("height")); if(pChildElement->Attribute("sizeMode")) { if(strcmp(pChildElement->Attribute("sizeMode"), "normalized") == 0) { if(newTarget->width > 1.0f) newTarget->width = 1.0f; if(newTarget->height > 1.0f) newTarget->height = 1.0f; newTarget->width = ((Number)CoreServices::getInstance()->getRenderer()->getXRes()) * newTarget->width; newTarget->height = ((Number)CoreServices::getInstance()->getRenderer()->getYRes()) * newTarget->height; } } } // Texture *newTexture = CoreServices::getInstance()->getMaterialManager()->createNewTexture(newTarget->width, newTarget->height, true); Texture *newTexture, *temp; CoreServices::getInstance()->getRenderer()->createRenderTextures(&newTexture, &temp, (int)newTarget->width, (int)newTarget->height, newMaterial->fp16RenderTargets); newTexture->setResourceName(newTarget->id); //CoreServices::getInstance()->getResourceManager()->addResource(newTexture); newTarget->texture = newTexture; renderTargets.push_back(newTarget); } } } } for (pChild3 = node->FirstChild(); pChild3 != 0; pChild3 = pChild3->NextSibling()) { TiXmlElement *pChild3Element = pChild3->ToElement(); if (!pChild3Element) continue; // Skip comment nodes if(strcmp(pChild3->Value(), "shader") == 0) { materialShader = setShaderFromXMLNode(pChild3); if(materialShader) { newShaderBinding = materialShader->createBinding(); materialShaders.push_back(materialShader); newShaderBindings.push_back(newShaderBinding); for (pChild = pChild3->FirstChild(); pChild != 0; pChild = pChild->NextSibling()) { TiXmlElement *pChildElement = pChild->ToElement(); if (!pChildElement) continue; // Skip comment nodes if(strcmp(pChild->Value(), "params") == 0) { for (pChild2 = pChild->FirstChild(); pChild2 != 0; pChild2 = pChild2->NextSibling()) { TiXmlElement *pChild2Element = pChild2->ToElement(); if (!pChild2Element) continue; // Skip comment nodes if(strcmp(pChild2->Value(), "param") == 0){ String pname = pChild2Element->Attribute("name"); if(!CoreServices::getInstance()->getRenderer()->getDataPointerForName(pname)) { String pvalue = pChild2Element->Attribute("value"); int type = materialShader->getExpectedParamType(pname); LocalShaderParam *param = newShaderBinding->addParam(type, pname); if(param) { switch(type) { case ProgramParam::PARAM_NUMBER: { param->setNumber(atof(pvalue.c_str())); } break; case ProgramParam::PARAM_VECTOR2: { std::vector<String> values = pvalue.split(" "); if(values.size() == 2) { param->setVector2(Vector2(atof(values[0].c_str()), atof(values[1].c_str()))); } else { printf("Material parameter error: A Vector2 must have 2 values (%d provided)!\n", (int)values.size()); } } break; case ProgramParam::PARAM_VECTOR3: { std::vector<String> values = pvalue.split(" "); if(values.size() == 3) { param->setVector3(Vector3(atof(values[0].c_str()), atof(values[1].c_str()), atof(values[2].c_str()))); } else { printf("Material parameter error: A Vector3 must have 3 values (%d provided)!\n", (int)values.size()); } } break; case ProgramParam::PARAM_COLOR: { std::vector<String> values = pvalue.split(" "); if(values.size() == 4) { param->setColor(Color(atof(values[0].c_str()), atof(values[1].c_str()), atof(values[2].c_str()), atof(values[3].c_str()))); } else { printf("Material parameter error: A Vector3 must have 3 values (%d provided)!\n", (int)values.size()); } } break; } } } } } } if(strcmp(pChild->Value(), "targettextures") == 0) { for (pChild2 = pChild->FirstChild(); pChild2 != 0; pChild2 = pChild2->NextSibling()) { TiXmlElement *pChild2Element = pChild2->ToElement(); if (!pChild2Element) continue; // Skip comment nodes if(strcmp(pChild2->Value(), "targettexture") == 0){ RenderTargetBinding* newBinding = new RenderTargetBinding; newBinding->id = pChild2Element->Attribute("id"); newBinding->name = ""; if(pChild2Element->Attribute("name")) { newBinding->name = pChild2Element->Attribute("name"); } String mode = pChild2Element->Attribute("mode"); if(strcmp(mode.c_str(), "in") == 0) { newBinding->mode = RenderTargetBinding::MODE_IN; } else { newBinding->mode = RenderTargetBinding::MODE_OUT; } newShaderBinding->addRenderTargetBinding(newBinding); //Texture *texture = (Texture*)CoreServices::getInstance()->getResourceManager()->getResource(Resource::RESOURCE_TEXTURE, newBinding->id); // newBinding->texture = texture; for(int l=0; l < renderTargets.size(); l++) { if(renderTargets[l]->id == newBinding->id) { printf("Assigning texture to %s\n", newBinding->id.c_str()); newBinding->texture = renderTargets[l]->texture; newBinding->width = renderTargets[l]->width; newBinding->height = renderTargets[l]->height; } } if(newBinding->mode == RenderTargetBinding::MODE_IN) { newShaderBinding->addTexture(newBinding->name, newBinding->texture); } } } } if(strcmp(pChild->Value(), "textures") == 0) { for (pChild2 = pChild->FirstChild(); pChild2 != 0; pChild2 = pChild2->NextSibling()) { TiXmlElement *pChild2Element = pChild2->ToElement(); if (!pChild2Element) continue; // Skip comment nodes if(strcmp(pChild2->Value(), "texture") == 0){ String tname = ""; if(pChild2Element->Attribute("name")) { tname = pChild2Element->Attribute("name"); } Texture *texture = CoreServices::getInstance()->getMaterialManager()->createTextureFromFile(pChild2Element->GetText()); newShaderBinding->addTexture(tname,texture); // newShaderBinding->addTexture(tname, (Texture*)CoreServices::getInstance()->getResourceManager()->getResource(Resource::RESOURCE_TEXTURE, pChild2Element->GetText())); } if(strcmp(pChild2->Value(), "cubemap") == 0){ String tname = ""; if(pChild2Element->Attribute("name")) { tname = pChild2Element->Attribute("name"); } newShaderBinding->addCubemap(tname, (Cubemap*)CoreServices::getInstance()->getResourceManager()->getResource(Resource::RESOURCE_CUBEMAP, pChild2Element->GetText())); } } } } } } } for(int i=0; i< materialShaders.size(); i++) { newMaterial->addShader(materialShaders[i],newShaderBindings[i]); } for(int i=0; i< renderTargets.size(); i++) { newMaterial->addShaderRenderTarget(renderTargets[i]); } return newMaterial; }
//----------------------------------------------------------------------------- void SGScriptTranslator::translatePass(ScriptCompiler* compiler, const AbstractNodePtr &node) { ObjectAbstractNode *obj = static_cast<ObjectAbstractNode*>(node.get()); Pass* pass = any_cast<Pass*>(obj->parent->context); Technique* technique = pass->getParent(); Material* material = technique->getParent(); ShaderGenerator* shaderGenerator = ShaderGenerator::getSingletonPtr(); String dstTechniqueSchemeName = obj->name; bool techniqueCreated; // Make sure the scheme name is valid - use default if none exists. if (dstTechniqueSchemeName.empty()) dstTechniqueSchemeName = ShaderGenerator::DEFAULT_SCHEME_NAME; // Create the shader based technique. techniqueCreated = shaderGenerator->createShaderBasedTechnique(material->getName(), material->getGroup(), technique->getSchemeName(), dstTechniqueSchemeName, shaderGenerator->getCreateShaderOverProgrammablePass()); // Case technique successfully created. if (techniqueCreated) { // Go over all the render state properties. for(AbstractNodeList::iterator i = obj->children.begin(); i != obj->children.end(); ++i) { if((*i)->type == ANT_PROPERTY) { PropertyAbstractNode *prop = static_cast<PropertyAbstractNode*>((*i).get()); // Handle light count property. if (prop->name == "light_count") { if (prop->values.size() != 3) { compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line); } else { int lightCount[3]; if (false == SGScriptTranslator::getInts(prop->values.begin(), prop->values.end(), lightCount, 3)) { compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line); } else { shaderGenerator->createScheme(dstTechniqueSchemeName); RenderState* renderState = shaderGenerator->getRenderState(dstTechniqueSchemeName, material->getName(), material->getGroup(), pass->getIndex()); renderState->setLightCount(lightCount); renderState->setLightCountAutoUpdate(false); } } } // Handle the rest of the custom properties. else { SubRenderState* subRenderState = ShaderGenerator::getSingleton().createSubRenderState(compiler, prop, pass, this); if (subRenderState) { addSubRenderState(subRenderState, dstTechniqueSchemeName, material->getName(), material->getGroup(), pass->getIndex()); } } } else { processNode(compiler, *i); } } mGeneratedRenderState = NULL; } }