Beispiel #1
0
void CharacterModel::deactivateShader(void)
{
    for(UInt32 i = 0; i < getMaterials().size(); ++i)
    {
        ChunkMaterialPtr m = getMaterials(i);
        
        beginEditCP(m);
        m->subChunk(getShader());
        endEditCP(m);
    }
}
	void ModelRenderProcessor::deleteModelFromGpu(string modelPath) {
		auto model = loader->getModelBy(modelPath);
		auto materials = model->getMaterials();
		for(auto& i : materials) {
			auto program = loader->getProgramBy(i.getProgramName());
			auto programName = program->getName();
			
			if(!hasMaterialWithProgram(programName))
				deleteProgramFromGpu(programName);
		}

		vector<Mesh3d>& meshes = model->getMeshes();
		unordered_map<uint32_t, string> texturesToRemove;
		for(auto& s : meshes) {
			string mName = model->getUniqueMeshName(s);
			deleteGeometryFromGpu(mName);
			
			Texture2d& texture = model->getTextureBy(s);
			texturesToRemove.emplace(s.getMaterialId(), texture.getPath());
		}

		for(auto& s : texturesToRemove) {
			deleteTextureFromGpu(s.second);
		}
	}
	bool ModelRenderProcessor::hasMaterialWithProgram(std::string name) {
		for(auto& i : idToObject) {
			View& object = i.second;
			auto model = loader->getModelBy(object.getPath());
			auto materials = model->getMaterials();
			for(auto& j : materials) {
				if(j.getProgramName() == name)
					return true;
			}
		}
		return false;
	}
void FBXModel::loadMeshes(KFbxNode* node, const GraphicsDevice& device, KFbxGeometryConverter& converter)
{
	const char* name = node->GetName();

	if (node->GetNodeAttribute())
	{
		KFbxNodeAttribute::EAttributeType attributeType = node->GetNodeAttribute()->GetAttributeType();

		if (attributeType == KFbxNodeAttribute::eMESH)
		{
			KFbxMesh* kfbxMesh = converter.TriangulateMesh((KFbxMesh*)node->GetNodeAttribute());

			VertexCollection vertices = getVertices(kfbxMesh);
			MaterialCollection materials = getMaterials(device, node);

			unsigned long numFaces = kfbxMesh->GetPolygonCount();
			unsigned long numVertices = kfbxMesh->GetControlPointsCount();
				
			Mesh mesh = Mesh::create(device, numFaces, numVertices, FBXVertex::vertexElements, D3DXMESH_MANAGED | D3DXMESH_32BIT);

			mesh.getVertexBuffer().setData(vertices);
			mesh.getIndexBuffer().setData(kfbxMesh->GetPolygonVertices(), kfbxMesh->GetPolygonVertexCount());

			KFbxLayerElementArrayTemplate<int>* materialIndices;
			kfbxMesh->GetMaterialIndices(&materialIndices);

			unsigned long* buffer = mesh.lockAttributeBuffer();

			for(int i = 0; i < kfbxMesh->GetPolygonCount(); ++i)
				buffer[i] = materialIndices->GetAt(i);
			
			mesh.unlockAttributeBuffer();
				
			Mesh::Adjacency adjacency = mesh.generateAdjacency();

			mesh.clean(D3DXCLEAN_SIMPLIFICATION, adjacency);
			mesh.optimizeInplace(D3DXMESHOPT_COMPACT | D3DXMESHOPT_ATTRSORT | D3DXMESHOPT_VERTEXCACHE, adjacency);
			mesh.computeNormals(adjacency);
			

			meshes[name] = FBXMesh(mesh, materials, name);
		}
	}

	for (int i = 0; i < node->GetChildCount(); i++)
		loadMeshes(node->GetChild(i), device, converter);
}
Beispiel #5
0
float PhysActor_PhysX::GetRestitution()
{
	float result = 0.0f;
	bool result_set = false;

	auto nbShapes = impl->physActor->getNbShapes();

	if (nbShapes <= 0)
		return result;

	physx::PxShape** shapes = new physx::PxShape*[nbShapes];
	impl->physActor->getShapes(shapes, nbShapes);

	for (size_t i = 0; i < nbShapes && !result_set; ++i)
	{
		auto shape = shapes[i];
		if (!shape)
			continue;

		auto nbMaterials = shape->getNbMaterials();

		if (nbMaterials <= 0)
			continue;

		physx::PxMaterial** materials = new physx::PxMaterial*[nbMaterials];
		shape->getMaterials(materials, nbMaterials);

		if (materials[0])
		{
			physx::PxMaterial* material = materials[0];

			result = material->getRestitution();
			result_set = true;
		}

		delete[] materials;
	}

	delete[] shapes;

	return result;
}
	void ModelRenderProcessor::loadModelToGpu(string modelPath) {
		auto model = loader->getModelBy(modelPath);
		auto materials = model->getMaterials();
		for(auto& i : materials) {
			auto program = loader->getProgramBy(i.getProgramName());
			auto programName = program->getName();
			if(!hasMaterialWithProgram(programName))
				loadProgramToGpu(programName, program);
		}

		vector<Mesh3d>& meshes = model->getMeshes();
		for(auto& s : meshes) {
			string meshName = model->getUniqueMeshName(s);

			loadGeometryToGpu(meshName, s.getRawVertices(), s.getIndices());

			Texture2d& texture = model->getTextureBy(s);
			loadTextureToGpu(texture);

			auto& buffer = meshToBuffer.at(meshName);
			buffer.texture = textureToId.at(texture.getPath());
		}
	}
Beispiel #7
0
void PhysActor_PhysX::SetRestitution(float restitution)
{
	auto nbShapes = impl->physActor->getNbShapes();

	if (nbShapes <= 0)
		return;

	physx::PxShape** shapes = new physx::PxShape*[nbShapes];
	impl->physActor->getShapes(shapes, nbShapes);

	for (size_t i = 0; i < nbShapes; ++i)
	{
		auto shape = shapes[i];
		if (!shape)
			continue;

		auto nbMaterials = shape->getNbMaterials();

		if (nbMaterials <= 0)
			continue;

		physx::PxMaterial** materials = new physx::PxMaterial*[nbMaterials];
		shape->getMaterials(materials, nbMaterials);

		if (materials[0])
		{
			physx::PxMaterial* material = materials[0];

			material->setRestitution(restitution);
		}

		delete[] materials;
	}

	delete[] shapes;
}
/*************************************************************************************
** Description: This is a virtual function that calculates the cost of a regular
** customer project.
**************************************************************************************/
double RegularProject::billAmount()
{
	return (80.0 * getHours()) + getMaterials() + getTransportation(); //return the total cost of the project
}
Beispiel #9
0
void CharacterModel::convertMaterials(std::string configfile)
{
    getMaterials().clear();
    UInt32 mcnt = 0;
    PathHandler ph;
    
    ph.setBaseFile(configfile.c_str());
       
    for(int mid = 0; mid < _coreModel->getCoreMaterialCount(); mid++)
    {
        CalCoreMaterial *coremat = _coreModel->getCoreMaterial(mid);
        SimpleMaterialPtr mat = SimpleMaterial::create();

        beginEditCP(mat);

        CalCoreMaterial::Color &calamb = coremat->getAmbientColor();
        CalCoreMaterial::Color &caldif = coremat->getDiffuseColor();
        CalCoreMaterial::Color &calspec = coremat->getSpecularColor();

        mat->setAmbient(Color3f(calamb.red / 255.0f, calamb.green / 255.0f, calamb.blue / 255.0f));
        mat->setDiffuse(Color3f(caldif.red / 255.0f, caldif.green / 255.0f, caldif.blue / 255.0f));
        mat->setSpecular(Color3f(calspec.red / 255.0f, calspec.green / 255.0f, calspec.blue / 255.0f));
        
        mat->setShininess(coremat->getShininess() * 100.f);
        mat->setLit(true);
        mat->setColorMaterial(GL_NONE);
        
        for(int mapId = 0; mapId < coremat->getMapCount(); mapId++)
        {
            std::string file = coremat->getMapFilename(mapId);
            std::string pfile = ph.findFile(file.c_str());
            SINFO << "Loading texture '" << pfile << "'..." << endLog;

            ImagePtr img = Image::create();
            
             if(!img->read(pfile.c_str()))
            {
                SWARNING << "CharacterModel::convertMaterials: error "
                         << "loading image " << file << endLog;
            }
            else
            {
                // amz with my test scene paladin.cfg all textures were
                // upside down so I disabled the vertical flipping perhaps
                // they fixed the bug in Cal3D?
#if 0
                beginEditCP(img);
                {
                // For some reason Cal3D expects textures upside down ???
                UInt32 bpl = img->getBpp() * img->getWidth();
                UChar8 *t = img->getData(), 
                       *b = t + (img->getHeight() - 1) * bpl,
                        dum;

                for(UInt32 y = img->getHeight() / 2; y > 0; --y)
                {
                    for(UInt32 x = bpl; x > 0; --x, ++t, ++b)
                    {
                        dum = *t;
                        *t = *b;
                        *b = dum;
                    }
                    b -= bpl * 2;
                }
                }
                endEditCP(img);
#endif
                
                TextureChunkPtr tex = TextureChunk::create();
                
                beginEditCP(tex);
                tex->setImage(img);
                tex->setEnvMode(GL_MODULATE);
                endEditCP(tex);
                
                mat->addChunk(tex);
            }
        }
            
        endEditCP(mat);
        
        coremat->setUserData((Cal::UserData)mcnt);
        getMaterials().push_back(mat);
        mcnt ++;
    }    
}
void MeshResourceMarker::onNewMessage(const MarkerConstPtr& old_message, const MarkerConstPtr& new_message)
{
  ROS_ASSERT(new_message->type == visualization_msgs::Marker::MESH_RESOURCE);

  bool need_color = false;

  scene_node_->setVisible(false);

  if( !entity_ ||
      old_message->mesh_resource != new_message->mesh_resource ||
      old_message->mesh_use_embedded_materials != new_message->mesh_use_embedded_materials )
  {
    reset();

    if (new_message->mesh_resource.empty())
    {
      return;
    }

    if (loadMeshFromResource(new_message->mesh_resource).isNull())
    {
      std::stringstream ss;
      ss << "Mesh resource marker [" << getStringID() << "] could not load [" << new_message->mesh_resource << "]";
      if ( owner_ )
      {
        owner_->setMarkerStatus(getID(), StatusProperty::Error, ss.str());
      }
      ROS_DEBUG("%s", ss.str().c_str());
      return;
    }

    static uint32_t count = 0;
    std::stringstream ss;
    ss << "mesh_resource_marker_" << count++;
    std::string id = ss.str();
    entity_ = context_->getSceneManager()->createEntity(id, new_message->mesh_resource);
    scene_node_->attachObject(entity_);
    need_color = true;

    // create a default material for any sub-entities which don't have their own.
    ss << "Material";
    Ogre::MaterialPtr default_material = Ogre::MaterialManager::getSingleton().create( ss.str(), ROS_PACKAGE_NAME );
    default_material->setReceiveShadows(false);
    default_material->getTechnique(0)->setLightingEnabled(true);
    default_material->getTechnique(0)->setAmbient( 0.5, 0.5, 0.5 );
    materials_.insert( default_material );

    if ( new_message->mesh_use_embedded_materials )
    {
      // make clones of all embedded materials so selection works correctly
      S_MaterialPtr materials = getMaterials();

      S_MaterialPtr::iterator it;
      for ( it = materials.begin(); it!=materials.end(); it++ )
      {
        if( (*it)->getName() != "BaseWhiteNoLighting" )
        {
          Ogre::MaterialPtr new_material = (*it)->clone( id + (*it)->getName() );
          materials_.insert( new_material );
        }
      }

      // make sub-entities use cloned materials
      for (uint32_t i = 0; i < entity_->getNumSubEntities(); ++i)
      {
        std::string mat_name = entity_->getSubEntity(i)->getMaterialName();
        if( mat_name != "BaseWhiteNoLighting" )
        {
          entity_->getSubEntity(i)->setMaterialName( id + mat_name );
        }
        else
        {
          // BaseWhiteNoLighting is the default material Ogre uses
          // when it sees a mesh with no material.  Here we replace
          // that with our default_material which gets colored with
          // new_message->color.
          entity_->getSubEntity(i)->setMaterial( default_material );
        }
      }
    }
    else
    {
      entity_->setMaterial( default_material );
    }

    context_->getSelectionManager()->removeObject(coll_);
    coll_ = context_->getSelectionManager()->createCollisionForEntity(entity_, SelectionHandlerPtr(new MarkerSelectionHandler(this, MarkerID(new_message->ns, new_message->id))), coll_);
  }

  if( need_color ||
      old_message->color.r != new_message->color.r ||
      old_message->color.g != new_message->color.g ||
      old_message->color.b != new_message->color.b ||
      old_message->color.a != new_message->color.a )
  {
    float r = new_message->color.r;
    float g = new_message->color.g;
    float b = new_message->color.b;
    float a = new_message->color.a;

    // Old way was to ignore the color and alpha when using embedded
    // materials, which meant you could leave them unset, which means
    // 0.  Since we now USE the color and alpha values, leaving them
    // all 0 will mean the object will be invisible.  Therefore detect
    // the situation where RGBA are all 0 and treat that the same as
    // all 1 (full white).
    if( new_message->mesh_use_embedded_materials && r == 0 && g == 0 && b == 0 && a == 0 )
    {
      r = 1; g = 1; b = 1; a = 1;
    }

    Ogre::SceneBlendType blending;
    bool depth_write;

    if ( a < 0.9998 )
    {
      blending = Ogre::SBT_TRANSPARENT_ALPHA;
      depth_write = false;
    }
    else
    {
      blending = Ogre::SBT_REPLACE;
      depth_write = true;
    }

    S_MaterialPtr::iterator it;
    for( it = materials_.begin(); it != materials_.end(); it++ )
    {    
      Ogre::Technique* technique = (*it)->getTechnique( 0 );

      technique->setAmbient( r*0.5, g*0.5, b*0.5 );
      technique->setDiffuse( r, g, b, a );
      technique->setSceneBlending( blending );
      technique->setDepthWriteEnabled( depth_write );
    }
  }

  Ogre::Vector3 pos, scale;
  Ogre::Quaternion orient;
  transform(new_message, pos, orient, scale);

  scene_node_->setVisible(true);
  setPosition(pos);
  setOrientation(orient);

  // In Ogre, mesh surface normals are not normalized if object is not
  // scaled.  This forces the surface normals to be renormalized by
  // invisibly tweaking the scale.
  if( scale.x == 1.0 && scale.y == 1.0 && scale.z == 1.0 )
  {
    scale.z = 1.0001;
  }
  scene_node_->setScale(scale);
}
Beispiel #11
0
void MeshResourceMarker::onNewMessage(const MarkerConstPtr& old_message, const MarkerConstPtr& new_message)
{
  ROS_ASSERT(new_message->type == visualization_msgs::Marker::MESH_RESOURCE);

  // flag indicating if the mesh material color needs to be updated
  bool update_color = false;

  scene_node_->setVisible(false);

  if (!entity_ ||
      old_message->mesh_resource != new_message->mesh_resource ||
      old_message->mesh_use_embedded_materials != new_message->mesh_use_embedded_materials)
  {
    reset();

    if (new_message->mesh_resource.empty())
    {
      return;
    }

    if (loadMeshFromResource(new_message->mesh_resource).isNull())
    {
      std::stringstream ss;
      ss << "Mesh resource marker [" << getStringID() << "] could not load [" << new_message->mesh_resource << "]";
      if (owner_)
      {
        owner_->setMarkerStatus(getID(), StatusProperty::Error, ss.str());
      }
      ROS_DEBUG("%s", ss.str().c_str());
      return;
    }

    static uint32_t count = 0;
    std::stringstream ss;
    ss << "mesh_resource_marker_" << count++;
    std::string id = ss.str();
    entity_ = context_->getSceneManager()->createEntity(id, new_message->mesh_resource);
    scene_node_->attachObject(entity_);

    // create a default material for any sub-entities which don't have their own.
    ss << "Material";
    Ogre::MaterialPtr default_material = Ogre::MaterialManager::getSingleton().create(ss.str(), ROS_PACKAGE_NAME);
    default_material->setReceiveShadows(false);
    default_material->getTechnique(0)->setLightingEnabled(true);
    default_material->getTechnique(0)->setAmbient(0.5, 0.5, 0.5);
    materials_.insert(default_material);

    if (new_message->mesh_use_embedded_materials)
    {
      // make clones of all embedded materials so selection works correctly
      S_MaterialPtr materials = getMaterials();

      S_MaterialPtr::iterator it;
      for (it = materials.begin(); it != materials.end(); it++)
      {
        if ((*it)->getName() != "BaseWhiteNoLighting")
        {
          Ogre::MaterialPtr new_material = (*it)->clone(id + (*it)->getName());
          materials_.insert(new_material);
        }
      }

      // make sub-entities use cloned materials
      for (uint32_t i = 0; i < entity_->getNumSubEntities(); ++i)
      {
        std::string mat_name = entity_->getSubEntity(i)->getMaterialName();
        if (mat_name != "BaseWhiteNoLighting")
        {
          entity_->getSubEntity(i)->setMaterialName(id + mat_name);
        }
        else
        {
          // BaseWhiteNoLighting is the default material Ogre uses
          // when it sees a mesh with no material.  Here we replace
          // that with our default_material which gets colored with
          // new_message->color.
          entity_->getSubEntity(i)->setMaterial(default_material);
        }
      }
    }
    else
    {
      entity_->setMaterial(default_material);
    }

    // add a pass to every material to perform the color tinting
    S_MaterialPtr::iterator material_it;
    for (material_it = materials_.begin(); material_it != materials_.end(); material_it++)
    {
      Ogre::Technique* technique = (*material_it)->getTechnique(0);
      color_tint_passes_.push_back(technique->createPass());
    }

    // always update color on resource change
    update_color = true;

    handler_.reset(new MarkerSelectionHandler(this, MarkerID(new_message->ns, new_message->id), context_));
    handler_->addTrackedObject(entity_);
  }
  else
  {
    // underlying mesh resource has not changed but if the color has
    //  then we need to update the materials color
    if (!old_message
        || old_message->color.r != new_message->color.r
        || old_message->color.g != new_message->color.g
        || old_message->color.b != new_message->color.b
        || old_message->color.a != new_message->color.a)
    {
      update_color = true;
    }
  }

  // update material color
  //  if the mesh_use_embedded_materials is true and color is non-zero
  //  then the color will be used to tint the embedded materials
  if (update_color)
  {
    float r = new_message->color.r;
    float g = new_message->color.g;
    float b = new_message->color.b;
    float a = new_message->color.a;

    Ogre::SceneBlendType blending;
    bool depth_write;

    if (a < 0.9998)
    {
      blending = Ogre::SBT_TRANSPARENT_ALPHA;
      depth_write = false;
    }
    else
    {
      blending = Ogre::SBT_REPLACE;
      depth_write = true;
    }

    for (std::vector<Ogre::Pass*>::iterator it = color_tint_passes_.begin();
         it != color_tint_passes_.end();
         ++it)
    {
      (*it)->setAmbient(0.5 * r, 0.5 * g, 0.5 * b);
      (*it)->setDiffuse(r, g, b, a);
      (*it)->setSceneBlending(blending);
      (*it)->setDepthWriteEnabled(depth_write);
      (*it)->setLightingEnabled(true);
    }
  }

  Ogre::Vector3 pos, scale;
  Ogre::Quaternion orient;
  transform(new_message, pos, orient, scale);

  scene_node_->setVisible(true);
  setPosition(pos);
  setOrientation(orient);

  scene_node_->setScale(scale);
}