Ejemplo n.º 1
0
	void DefaultSceneRenderer::render(task_t &task) {
		glClearColor(0.9f, 0.9f, 0.9f, 1.f); // default background color

		glEnable(GL_DEPTH_TEST);
		glDepthFunc(GL_LESS);

		auto size = task.size;

		if (size == size2i(0, 0)) return;

		initFBO(size);

		glViewport(0, 0, size.w, size.h);

		// draw material properties to scene buffer
		glBindFramebuffer(GL_DRAW_FRAMEBUFFER, m_fbo_scene);
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);


		// draw everything in the draw queue
		//
		for (; !task.drawQueue.empty(); task.drawQueue.pop()) {
			auto d = task.drawQueue.top();
			// Bind shader program
			// Bind material properties
			// Bind Geometry
			// Then render

			material_ptr m = d->material();
			m->shader->bind();
			m->bind(task.projectionMatrix, task.zfar);
			d->draw();
		}

		static GLuint prog_deferred0 = 0;
		if (!prog_deferred0) {
			prog_deferred0 = gecom::makeShaderProgram("330 core", { GL_VERTEX_SHADER, GL_GEOMETRY_SHADER, GL_FRAGMENT_SHADER }, shader_deferred0_source);
		}

		glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
		glDisable(GL_DEPTH_TEST);
		glUseProgram(prog_deferred0);

		glActiveTexture(GL_TEXTURE0);
		glBindTexture(GL_TEXTURE_2D, m_tex_scene_depth);
		glActiveTexture(GL_TEXTURE1);
		glBindTexture(GL_TEXTURE_2D, m_tex_scene_color);
		glActiveTexture(GL_TEXTURE2);
		glBindTexture(GL_TEXTURE_2D, m_tex_scene_normal);

		glUniform1i(glGetUniformLocation(prog_deferred0, "sampler_depth"), 0);
		glUniform1i(glGetUniformLocation(prog_deferred0, "sampler_color"), 1);
		glUniform1i(glGetUniformLocation(prog_deferred0, "sampler_normal"), 2);

		draw_dummy();

		glUseProgram(0);
		glBindFramebuffer(GL_READ_FRAMEBUFFER, m_fbo_scene);
		glBlitFramebuffer(0, 0, size.w, size.h, 0, 0, size.w, size.h, GL_DEPTH_BUFFER_BIT, GL_NEAREST);
		glBindFramebuffer(GL_READ_FRAMEBUFFER, 0);

		// glEnable(GL_DEPTH_TEST);
		// glDepthFunc(GL_LEQUAL);
		// s.physicsSystem().debugDraw(s);
	}
Ejemplo n.º 2
0
  vec3 spotDirection;
};

lightSource light0 = lightSource(
    vec4(0.0,  1.0,  2.0, 1.0),
    vec4(1.0, 1.0, 1.0, 1.0),
    0.0, 1.0, 0.0,
    80.0, 20.0,
    vec3(-1.0, -0.5, -1.0)
);
 
struct material
{
  vec4 diffuse;
};
material mymaterial = material(vec4(1.0, 0.8, 0.8, 1.0));
 
void main(void)
{
  mat4 mvp = p*v*m;
  vec3 normalDirection = normalize(m_3x3_inv_transp * v_normal);
  vec3 lightDirection;
  float attenuation;
 
  if (light0.position.w == 0.0) // directional light
    {
      attenuation = 1.0; // no attenuation
      lightDirection = normalize(vec3(light0.position));
    }
  else // point or spot light (or other kind of light)
    {
Ejemplo n.º 3
0
bool ccPlane::setAsTexture(QImage image)
{
    if (image.isNull())
    {
        ccLog::Warning("[ccPlane::setAsTexture] Invalid texture image!");
        return false;
    }

    //texture coordinates
    TextureCoordsContainer* texCoords = getTexCoordinatesTable();
    if (!texCoords)
    {
        texCoords = new TextureCoordsContainer();
        if (!texCoords->reserve(4))
        {
            //not enough memory
            ccLog::Warning("[ccPlane::setAsTexture] Not enough memory!");
            delete texCoords;
            return false;
        }

        //create default texture coordinates
        float TA[2] = { 0.0f, 0.0f };
        float TB[2] = { 0.0f, 1.0f };
        float TC[2] = { 1.0f, 1.0f };
        float TD[2] = { 1.0f, 0.0f };
        texCoords->addElement(TA);
        texCoords->addElement(TB);
        texCoords->addElement(TC);
        texCoords->addElement(TD);

        setTexCoordinatesTable(texCoords);
    }

    if (!hasPerTriangleTexCoordIndexes())
    {
        if (!reservePerTriangleTexCoordIndexes())
        {
            //not enough memory
            ccLog::Warning("[ccPlane::setAsTexture] Not enough memory!");
            setTexCoordinatesTable(0);
            removePerTriangleMtlIndexes();
            return false;
        }

        //set default texture indexes
        addTriangleTexCoordIndexes(0,2,1);
        addTriangleTexCoordIndexes(0,3,2);
    }

    if (!hasPerTriangleMtlIndexes())
    {
        if (!reservePerTriangleMtlIndexes())
        {
            //not enough memory
            ccLog::Warning("[ccPlane::setAsTexture] Not enough memory!");
            setTexCoordinatesTable(0);
            removePerTriangleTexCoordIndexes();
            return false;
        }

        //set default material indexes
        addTriangleMtlIndex(0);
        addTriangleMtlIndex(0);
    }

    //set material
    if (!getMaterialSet())
        setMaterialSet(new ccMaterialSet());
    ccMaterialSet* materialSet = const_cast<ccMaterialSet*>(getMaterialSet());
    assert(materialSet);
    //remove old material (if any)
    materialSet->clear();
    //add new material
    {
        ccMaterial::Shared material(new ccMaterial("texture"));
        material->setTexture(image,QString(),false);
        materialSet->addMaterial(material);
    }

    showMaterials(true);

    return true;
}
ccMesh* DistanceMapGenerationTool::ConvertConicalMapToMesh(	const QSharedPointer<Map>& map,
															bool counterclockwise,
															QImage mapTexture/*=QImage()*/)
{
	if (!map)
		return 0;

	unsigned meshVertCount = map->xSteps * map->ySteps;
	unsigned meshFaceCount = (map->xSteps-1) * (map->ySteps-1) * 2;
	ccPointCloud* cloud = new ccPointCloud();
	ccMesh* mesh = new ccMesh(cloud);
	mesh->addChild(cloud);
	if (!cloud->reserve(meshVertCount) || !mesh->reserve(meshFaceCount))
	{
		//not enough memory
		delete mesh;
		return 0;
	}

	//compute projection constant
	double nProj = ConicalProjectN(map->yMin,map->yMax) * map->conicalSpanRatio;
	assert(nProj >= -1.0 && nProj <= 1.0);

	//create vertices
	{
		double cwSign = (counterclockwise ? -1.0 : 1.0);
		for (unsigned j=0; j<map->xSteps; ++j)
		{
			//longitude
			double lon_rad = static_cast<double>(j)/static_cast<double>(map->xSteps) * (2.0*M_PI);

			double theta = nProj * (lon_rad - M_PI); //-Pi shift so that the map is well centered
			double sin_theta = sin(theta);
			double cos_theta = cos(theta);

			for (unsigned i=0; i<map->ySteps; ++i)
			{
				double lat_rad = map->yMin + static_cast<double>(i) * map->yStep;
				double r = ConicalProject(lat_rad, map->yMin, nProj);

				CCVector3 Pxyz( static_cast<PointCoordinateType>(cwSign * r * sin_theta),
								static_cast<PointCoordinateType>(-r * cos_theta),
								0);
				cloud->addPoint(Pxyz);
			}
		}
	}

	//create facets
	{
		for (unsigned j=0; j+1<map->xSteps; ++j)
		{
			for (unsigned i=0; i+1<map->ySteps; ++i)
			{
				unsigned vertA = j*map->ySteps + i;
				unsigned vertB = vertA + map->ySteps;
				unsigned vertC = vertB + 1;
				unsigned vertD = vertA + 1;

				mesh->addTriangle(vertB,vertC,vertD);
				mesh->addTriangle(vertB,vertD,vertA);
			}
		}
	}

	//do we have a texture as well?
	if (true/*!mapTexture.isNull()*/) //we force tex. coordinates and indexes creation!
	{
		//texture coordinates
		TextureCoordsContainer* texCoords = new TextureCoordsContainer();
		if (!texCoords->reserve(meshVertCount))
		{
			//not enough memory to finish the job!
			delete texCoords;
			return mesh;
		}

		//create default texture coordinates
		for (unsigned j=0; j<map->xSteps; ++j)
		{
			float T[2] = { static_cast<float>(j)/static_cast<float>(map->xSteps-1), 0.0f };
			for (unsigned i=0; i<map->ySteps; ++i)
			{
				T[1] = static_cast<float>(i)/static_cast<float>(map->ySteps-1);
				texCoords->addElement(T);
			}
		}

		if (!mesh->reservePerTriangleTexCoordIndexes())
		{
			//not enough memory to finish the job!
			delete texCoords;
			return mesh;
		}
		
		//set texture indexes
		{
			for (unsigned j=0; j+1<map->xSteps; ++j)
			{
				for (unsigned i=0; i+1<map->ySteps; ++i)
				{
					unsigned vertA = j*map->ySteps + i;
					unsigned vertB = vertA + map->ySteps;
					unsigned vertC = vertB + 1;
					unsigned vertD = vertA + 1;

					mesh->addTriangleTexCoordIndexes(vertB,vertC,vertD);
					mesh->addTriangleTexCoordIndexes(vertB,vertD,vertA);
				}
			}
		}
	
		//set material indexes
		if (!mesh->reservePerTriangleMtlIndexes())
		{
			//not enough memory to finish the job!
			delete texCoords;
			mesh->removePerTriangleTexCoordIndexes();
			return mesh;
		}
		for (unsigned i=0; i<meshFaceCount; ++i)
			mesh->addTriangleMtlIndex(0);

		//set material
		{
			ccMaterial::Shared material(new ccMaterial("texture"));
			material->setTexture(mapTexture, QString(), false);

			ccMaterialSet* materialSet = new ccMaterialSet();
			materialSet->addMaterial(material);

			mesh->setMaterialSet(materialSet);
		}

		mesh->setTexCoordinatesTable(texCoords);
		mesh->showMaterials(true);
		mesh->setVisible(true);
	}

	return mesh;
}
Ejemplo n.º 5
0
void materialBlueGreen() {
  material(Vector4(0,0.1,0.1,1),Vector3(0,0.3,0.7),Vector3(0,0.8,0.2),200);
}
void assemble_postvars_rhs (EquationSystems& es,
                      const std::string& system_name)
{

  const Real E    = es.parameters.get<Real>("E");
  const Real NU    = es.parameters.get<Real>("NU");
  const Real KPERM    = es.parameters.get<Real>("KPERM");
  
	Real sum_jac_postvars=0;
	
	Real av_pressure=0;
	Real total_volume=0;

#include "assemble_preamble_postvars.cpp"

  for ( ; el != end_el; ++el)
    {    
 
      const Elem* elem = *el;

      dof_map.dof_indices (elem, dof_indices);
      dof_map.dof_indices (elem, dof_indices_u, u_var);
      dof_map.dof_indices (elem, dof_indices_v, v_var);
      dof_map.dof_indices (elem, dof_indices_p, p_var);
      dof_map.dof_indices (elem, dof_indices_x, x_var);
      dof_map.dof_indices (elem, dof_indices_y, y_var);
      #if THREED
      dof_map.dof_indices (elem, dof_indices_w, w_var);
      dof_map.dof_indices (elem, dof_indices_z, z_var);
      #endif

      const unsigned int n_dofs   = dof_indices.size();
      const unsigned int n_u_dofs = dof_indices_u.size(); 
      const unsigned int n_v_dofs = dof_indices_v.size();
      const unsigned int n_p_dofs = dof_indices_p.size();
      const unsigned int n_x_dofs = dof_indices_x.size(); 
      const unsigned int n_y_dofs = dof_indices_y.size();
      #if THREED
      const unsigned int n_w_dofs = dof_indices_w.size();
      const unsigned int n_z_dofs = dof_indices_z.size();
      #endif
      
      fe_disp->reinit  (elem);
      fe_vel->reinit  (elem);
      fe_pres->reinit (elem);

      Ke.resize (n_dofs, n_dofs);
      Fe.resize (n_dofs);

      Kuu.reposition (u_var*n_u_dofs, u_var*n_u_dofs, n_u_dofs, n_u_dofs);
      Kuv.reposition (u_var*n_u_dofs, v_var*n_u_dofs, n_u_dofs, n_v_dofs);
      Kup.reposition (u_var*n_u_dofs, p_var*n_u_dofs, n_u_dofs, n_p_dofs);
      Kux.reposition (u_var*n_u_dofs, p_var*n_u_dofs + n_p_dofs , n_u_dofs, n_x_dofs);
      Kuy.reposition (u_var*n_u_dofs, p_var*n_u_dofs + n_p_dofs+n_x_dofs , n_u_dofs, n_y_dofs);
      #if THREED
      Kuw.reposition (u_var*n_u_dofs, w_var*n_u_dofs, n_u_dofs, n_w_dofs);
      Kuz.reposition (u_var*n_u_dofs, p_var*n_u_dofs + n_p_dofs+2*n_x_dofs , n_u_dofs, n_z_dofs);
      #endif

      Kvu.reposition (v_var*n_v_dofs, u_var*n_v_dofs, n_v_dofs, n_u_dofs);
      Kvv.reposition (v_var*n_v_dofs, v_var*n_v_dofs, n_v_dofs, n_v_dofs);
      Kvp.reposition (v_var*n_v_dofs, p_var*n_v_dofs, n_v_dofs, n_p_dofs);
      Kvx.reposition (v_var*n_v_dofs, p_var*n_u_dofs + n_p_dofs , n_v_dofs, n_x_dofs);
      Kvy.reposition (v_var*n_v_dofs, p_var*n_u_dofs + n_p_dofs+n_x_dofs , n_v_dofs, n_y_dofs);
      #if THREED
      Kvw.reposition (v_var*n_u_dofs, w_var*n_u_dofs, n_v_dofs, n_w_dofs);
      Kuz.reposition (v_var*n_u_dofs, p_var*n_u_dofs + n_p_dofs+2*n_x_dofs , n_u_dofs, n_z_dofs);
      #endif

      #if THREED
      Kwu.reposition (w_var*n_w_dofs, u_var*n_v_dofs, n_v_dofs, n_u_dofs);
      Kwv.reposition (w_var*n_w_dofs, v_var*n_v_dofs, n_v_dofs, n_v_dofs);
      Kwp.reposition (w_var*n_w_dofs, p_var*n_v_dofs, n_v_dofs, n_p_dofs);
      Kwx.reposition (w_var*n_w_dofs, p_var*n_u_dofs + n_p_dofs , n_v_dofs, n_x_dofs);
      Kwy.reposition (w_var*n_w_dofs, p_var*n_u_dofs + n_p_dofs+n_x_dofs , n_v_dofs, n_y_dofs);
      Kww.reposition (w_var*n_w_dofs, w_var*n_u_dofs, n_v_dofs, n_w_dofs);
      Kwz.reposition (w_var*n_w_dofs, p_var*n_u_dofs + n_p_dofs+2*n_x_dofs , n_u_dofs, n_z_dofs);
      #endif

      Kpu.reposition (p_var*n_u_dofs, u_var*n_u_dofs, n_p_dofs, n_u_dofs);
      Kpv.reposition (p_var*n_u_dofs, v_var*n_u_dofs, n_p_dofs, n_v_dofs);
      Kpp.reposition (p_var*n_u_dofs, p_var*n_u_dofs, n_p_dofs, n_p_dofs);
      Kpx.reposition (p_var*n_v_dofs, p_var*n_u_dofs + n_p_dofs , n_p_dofs, n_x_dofs);
      Kpy.reposition (p_var*n_v_dofs, p_var*n_u_dofs + n_p_dofs+n_x_dofs , n_p_dofs, n_y_dofs);
      #if THREED
      Kpw.reposition (p_var*n_u_dofs, w_var*n_u_dofs, n_p_dofs, n_w_dofs);
      Kpz.reposition (p_var*n_u_dofs, p_var*n_u_dofs + n_p_dofs+2*n_x_dofs , n_p_dofs, n_z_dofs);
      #endif

      Kxu.reposition (p_var*n_u_dofs + n_p_dofs, u_var*n_u_dofs, n_x_dofs, n_u_dofs);
      Kxv.reposition (p_var*n_u_dofs + n_p_dofs, v_var*n_u_dofs, n_x_dofs, n_v_dofs);
      Kxp.reposition (p_var*n_u_dofs + n_p_dofs, p_var*n_u_dofs, n_x_dofs, n_p_dofs);
      Kxx.reposition (p_var*n_u_dofs + n_p_dofs, p_var*n_u_dofs + n_p_dofs , n_x_dofs, n_x_dofs);
      Kxy.reposition (p_var*n_u_dofs + n_p_dofs, p_var*n_u_dofs + n_p_dofs+n_x_dofs , n_x_dofs, n_y_dofs);
      #if THREED
      Kxw.reposition (p_var*n_u_dofs + n_p_dofs, w_var*n_u_dofs, n_x_dofs, n_w_dofs);
      Kxz.reposition (p_var*n_u_dofs + n_p_dofs, p_var*n_u_dofs + n_p_dofs+2*n_x_dofs , n_x_dofs, n_z_dofs);
      #endif


      Kyu.reposition (p_var*n_u_dofs + n_p_dofs+n_x_dofs, u_var*n_u_dofs, n_y_dofs, n_u_dofs);
      Kyv.reposition (p_var*n_u_dofs + n_p_dofs+n_x_dofs, v_var*n_u_dofs, n_y_dofs, n_v_dofs);
      Kyp.reposition (p_var*n_u_dofs + n_p_dofs+n_x_dofs, p_var*n_u_dofs, n_y_dofs, n_p_dofs);
      Kyx.reposition (p_var*n_u_dofs + n_p_dofs+n_x_dofs, p_var*n_u_dofs + n_p_dofs , n_y_dofs, n_x_dofs);
      Kyy.reposition (p_var*n_u_dofs + n_p_dofs+n_x_dofs, p_var*n_u_dofs + n_p_dofs+n_x_dofs , n_y_dofs, n_y_dofs);
      #if THREED
      Kyw.reposition (p_var*n_u_dofs + n_p_dofs+n_x_dofs, w_var*n_u_dofs, n_x_dofs, n_w_dofs);
      Kyz.reposition (p_var*n_u_dofs + n_p_dofs+n_x_dofs, p_var*n_u_dofs + n_p_dofs+2*n_x_dofs , n_x_dofs, n_z_dofs);
      #endif

      #if THREED
      Kzu.reposition (p_var*n_u_dofs + n_p_dofs+2*n_x_dofs, u_var*n_u_dofs, n_y_dofs, n_u_dofs);
      Kzv.reposition (p_var*n_u_dofs + n_p_dofs+2*n_x_dofs, v_var*n_u_dofs, n_y_dofs, n_v_dofs);
      Kzp.reposition (p_var*n_u_dofs + n_p_dofs+2*n_x_dofs, p_var*n_u_dofs, n_y_dofs, n_p_dofs);
      Kzx.reposition (p_var*n_u_dofs + n_p_dofs+2*n_x_dofs, p_var*n_u_dofs + n_p_dofs , n_y_dofs, n_x_dofs);
      Kzy.reposition (p_var*n_u_dofs + n_p_dofs+2*n_x_dofs, p_var*n_u_dofs + n_p_dofs+n_x_dofs , n_y_dofs, n_y_dofs);
      Kzw.reposition (p_var*n_u_dofs + n_p_dofs+2*n_x_dofs, w_var*n_u_dofs, n_x_dofs, n_w_dofs);
      Kzz.reposition (p_var*n_u_dofs + n_p_dofs+2*n_x_dofs, p_var*n_u_dofs + n_p_dofs+2*n_x_dofs , n_x_dofs, n_z_dofs);
      #endif



      Fu.reposition (u_var*n_u_dofs, n_u_dofs);
      Fv.reposition (v_var*n_u_dofs, n_v_dofs);
      Fp.reposition (p_var*n_u_dofs, n_p_dofs);
      Fx.reposition (p_var*n_u_dofs + n_p_dofs, n_x_dofs);
      Fy.reposition (p_var*n_u_dofs + n_p_dofs+n_x_dofs, n_y_dofs);
      #if THREED
      Fw.reposition (w_var*n_u_dofs, n_w_dofs);
      Fz.reposition (p_var*n_u_dofs + n_p_dofs+2*n_x_dofs, n_y_dofs);
      #endif
    
	    std::vector<unsigned int> undefo_index;
		  PoroelasticConfig material(dphi,psi);

		
      // Now we will build the element matrix.
      for (unsigned int qp=0; qp<qrule.n_points(); qp++)
        {       
		  
		  
		  Number   p_solid = 0.;

		  grad_u_mat(0) = grad_u_mat(1) = grad_u_mat(2) = 0;
		
		  for (unsigned int d = 0; d < dim; ++d) {
			std::vector<Number> u_undefo;
			std::vector<Number> u_undefo_ref;

			//Fills the vector di with the global degree of freedom indices for the element. :dof_indicies
			
			

			
			Last_non_linear_soln.get_dof_map().dof_indices(elem, undefo_index,d);
			Last_non_linear_soln.current_local_solution->get(undefo_index, u_undefo);
			reference.current_local_solution->get(undefo_index, u_undefo_ref);

			for (unsigned int l = 0; l != n_u_dofs; l++){
			   grad_u_mat(d).add_scaled(dphi[l][qp], u_undefo[l]+u_undefo_ref[l]); 
			}
		  }
          
		  for (unsigned int l=0; l<n_p_dofs; l++)
		  {
			p_solid += psi[l][qp]*Last_non_linear_soln.current_local_solution->el(dof_indices_p[l]);
		}
		
		Point rX;
		material.init_for_qp(rX,grad_u_mat, p_solid, qp,0, p_solid,es);
		Real J=material.J;
		 Real I_1=material.I_1;
		 Real I_2=material.I_2;
		 Real I_3=material.I_3;
		 RealTensor sigma=material.sigma;
		 
		 av_pressure=av_pressure + p_solid*JxW[qp];
		 
		 /*
		 		 		std::cout<<"grad_u_mat(0)" << grad_u_mat(0) <<std::endl;

		 		std::cout<<" J " << J <<std::endl;

		std::cout<<" sigma " << sigma <<std::endl;
		*/
		 Real sigma_sum_sq=pow(sigma(0,0)*sigma(0,0)+sigma(0,1)*sigma(0,1)+sigma(0,2)*sigma(0,2)+sigma(1,0)*sigma(1,0)+sigma(1,1)*sigma(1,1)+sigma(1,2)*sigma(1,2)+sigma(2,0)*sigma(2,0)+sigma(2,1)*sigma(2,1)+sigma(2,2)*sigma(2,2),0.5);
		 
		// std::cout<<" J " << J <<std::endl;


		 sum_jac_postvars=sum_jac_postvars+JxW[qp];
 

		
		for (unsigned int i=0; i<n_u_dofs; i++){
          Fu(i) += I_1*JxW[qp]*phi[i][qp];
          Fv(i) += I_2*JxW[qp]*phi[i][qp];
          Fw(i) += I_3*JxW[qp]*phi[i][qp];

	        Fx(i) += sigma_sum_sq*JxW[qp]*phi[i][qp];
          Fy(i) += J*JxW[qp]*phi[i][qp];
          Fz(i) += 0*JxW[qp]*phi[i][qp];
    }
    
    
 
		for (unsigned int i=0; i<n_p_dofs; i++){
            Fp(i) += J*JxW[qp]*psi[i][qp];
		}
    
          

          
          
} // end qp





  system.rhs->add_vector(Fe, dof_indices);

  system.matrix->add_matrix (Ke, dof_indices);

} // end of element loop
  
	
    system.matrix->close();
    system.rhs->close();



    std::cout<<"Assemble postvars rhs->l2_norm () "<<system.rhs->l2_norm ()<<std::endl;

		
	 std::cout<<"sum_jac   "<< sum_jac_postvars <<std::endl;
	 
	  std::cout<<"av_pressure   "<< av_pressure/sum_jac_postvars <<std::endl;

  return;
}
Ejemplo n.º 7
0
pbool PBackground::unpack(const PXmlElement* xmlElement)
{
    PASSERT(xmlElement->isValid());

    const pchar *textureName = xmlElement->attribute("texture");
    if (textureName != P_NULL)
    {
        PResourceManager *resourceManager = scene()->context()->module<PResourceManager>("resource-manager");

        m_texture = resourceManager->getTexture(textureName);
        if (m_texture != P_NULL)
        {
            m_texture->retain();
        }
        material()->parameter("texture") = m_texture;
    }
    else
    {
        PLOG_ERROR("Failed to find the texture for PBackground in this xml node.");
        return false;
    }

    const pchar *p = P_NULL;

    const pchar *textureInfoValue = xmlElement->attribute("texinfo");
    if (textureInfoValue != P_NULL)
    {
        pfloat32 sx, sy;
        pfloat32 x, y;

        if ((p = pStringUnpackFloat(p, &sx)) != P_NULL &&
            (p = pStringUnpackFloat(p, &sy)) != P_NULL &&
            (p = pStringUnpackFloat(p, &x)) != P_NULL &&
            (p = pStringUnpackFloat(p, &y)) != P_NULL)
        {
	        m_textureInfo[0] = sx;
            m_textureInfo[1] = sy;
	        m_textureInfo[2] = x;
            m_textureInfo[3] = y;
        }
    }

    const pchar *sizeValue = xmlElement->attribute("size");
    if (sizeValue != P_NULL)
    {
        pfloat32 sx, sy;

        if ((p = pStringUnpackFloat(p, &sx)) != P_NULL &&
            (p = pStringUnpackFloat(p, &sy)) != P_NULL)
        {
	        m_sizeInfo[0] = sx;
            m_sizeInfo[1] = sy;
        }
    }

    const pchar *layoutValue = xmlElement->attribute("layout");
    pchar vLayout[16];
    pchar hLayout[16];
    if ((p = pStringUnpackString(layoutValue, hLayout)) != P_NULL && 
        (p = pStringUnpackString(layoutValue, vLayout)) != P_NULL)
    {
        puint32 layout = 0;

        if (pstrcmp(vLayout, "top") == 0)
        {
            layout |= LAYOUT_TOP;
        }
        else if (pstrcmp(vLayout, "middle") == 0)
        {
            layout |= LAYOUT_MIDDLE;
        }
        else if (pstrcmp(vLayout, "bottom") == 0)
        {
            layout |= LAYOUT_BOTTOM;
        }
        else if (pstrcmp(vLayout, "left") == 0)
        {
            layout |= LAYOUT_LEFT;
        }
        else if (pstrcmp(vLayout, "center") == 0)
        {
            layout |= LAYOUT_CENTER;
        }
        else if (pstrcmp(vLayout, "right") == 0)
        {
            layout |= LAYOUT_RIGHT;
        }
    
        setLayout(layout);
    }

    m_dirty = true;

    return true;
}
Ejemplo n.º 8
0
 void Box::getDimensionsMaterials (std::vector<ldouble>& dimensions, std::vector<Math::DiagMatrix3<cldouble> >& materials) const {
   dimensions.push_back (size ().x ().value ());
   dimensions.push_back (size ().y ().value ());
   dimensions.push_back (size ().z ().value ());
   materials.push_back (material ());
 }
Ejemplo n.º 9
0
 void Sphere::getDimensionsMaterials (std::vector<ldouble>& dimensions, std::vector<Math::DiagMatrix3<cldouble> >& materials) const {
   dimensions.push_back (radius ().value () * 2);
   materials.push_back (material ());
 }
Ejemplo n.º 10
0
int main(){
	
	std::vector <int> mat(0);
	std::vector <int> cat(0); 
	std::vector <double> cx(0);
	std::vector <double> cy(0);
	std::vector <double> cz(0);
	std::vector <std::string> type(0);
	std::vector <std::string> filenames(0);
	
	// open coordinate file
	std::ifstream coord_file;
	coord_file.open("atoms-coords.cfg");

	// read in file header
	std::string dummy;
	
	getline(coord_file,dummy);
	//std::cout << dummy << std::endl;

	getline(coord_file,dummy);
	//std::cout << dummy << std::endl;

	getline(coord_file,dummy);
	//std::cout << dummy << std::endl;

	getline(coord_file,dummy);
	//std::cout << dummy << std::endl;

	getline(coord_file,dummy);
	//std::cout << dummy << std::endl;

	// get number of atoms
	unsigned int n_atoms;
	getline(coord_file,dummy);
	//std::cout << dummy << std::endl;	
	dummy.erase (dummy.begin(), dummy.begin()+17);
	n_atoms=atoi(dummy.c_str());

	getline(coord_file,dummy);
	//std::cout << dummy << std::endl;

	// get number of subsidiary files
	unsigned int n_files;
	getline(coord_file,dummy);
	//std::cout << dummy << std::endl;	
	dummy.erase (dummy.begin(), dummy.begin()+22);
	n_files=atoi(dummy.c_str());

	for(int file=0; file<n_files; file++){
		getline(coord_file,dummy);
		filenames.push_back(dummy);
		//std::cout << filenames[file] << std::endl;
	}

	getline(coord_file,dummy);
	//std::cout << dummy << std::endl;

	unsigned int n_local_atoms;
	getline(coord_file,dummy);
	//std::cout << dummy << std::endl;	
	n_local_atoms=atoi(dummy.c_str());
	
	// resize arrays
	mat.resize(n_atoms);
	cat.resize(n_atoms); 
	cx.resize(n_atoms);
	cy.resize(n_atoms);
	cz.resize(n_atoms);
	type.resize(n_atoms);
	
	unsigned int counter=0;
	
	// finish reading master file coordinates
	for(int i=0;i<n_local_atoms;i++){
		coord_file >> mat[counter] >> cat[counter] >> cx[counter] >> cy[counter] >> cz[counter] >> type[counter];
		counter++;
	}
	
	// close master file
	coord_file.close();
	
	// now read subsidiary files
	for(int file=0; file<n_files; file++){
		std::ifstream infile;
		infile.open(filenames[file].c_str());
		
		// read number of atoms in this file
		getline(infile,dummy);
		n_local_atoms=atoi(dummy.c_str());
		for(int i=0;i<n_local_atoms;i++){
			infile >> mat[counter] >> cat[counter] >> cx[counter] >> cy[counter] >> cz[counter] >> type[counter];
			counter++;
		}
		// close subsidiary file
		infile.close();
	}
	
	// check for correct read in of coordinates
	if(counter!=n_atoms) std::cerr << "Error in reading in coordinates" << std::endl;

	// Loop over all possible spin config files
	int ios = 0;
	int spinfile_counter=0;
	
	while(ios==0){
		
		std::stringstream file_sstr;
		file_sstr << "atoms-";
		file_sstr << std::setfill('0') << std::setw(8) << spinfile_counter;
		file_sstr << ".cfg";
		std::string cfg_file = file_sstr.str();
		//const char* cfg_filec = cfg_file.c_str();

		std::ifstream spinfile;
		spinfile.open(cfg_file.c_str());

		if(spinfile.is_open()){
		
			std::cout << "Processing file: " << cfg_file << std::endl;
			
		// Read in file header
		getline(spinfile,dummy);
			
	//std::cout << dummy << std::endl;

	getline(spinfile,dummy);
	//std::cout << dummy << std::endl;

	getline(spinfile,dummy);
	//std::cout << dummy << std::endl;

	getline(spinfile,dummy);
	//std::cout << dummy << std::endl;

	getline(spinfile,dummy);
	//std::cout << dummy << std::endl;

	// get number of atoms
	unsigned int n_spins;
	getline(spinfile,dummy);
	//std::cout << dummy << std::endl;	
	dummy.erase (dummy.begin(), dummy.begin()+17);
	n_spins=atoi(dummy.c_str());
	if(n_spins!=n_atoms) std::cerr << "Error! - mismatch between number of atoms in coordinate and spin files" << std::endl;
	
	getline(spinfile,dummy); // sys dimensions
	//std::cout << dummy << std::endl;
	char const field_delim = '\t';
	dummy.erase (dummy.begin(), dummy.begin()+18);
	std::istringstream ss(dummy);
	std::vector<double> val(0);
	for (std::string num; getline(ss, num, field_delim); ) {
		val.push_back(atof(num.c_str()));
		//std::cout << num << "\t" << val << std::endl;
	}
	double dim[3] = {val[0],val[1],val[2]};
	//std::cout << dim[0] << "\t" << dim[1] << "\t" << dim[2] << std::endl;

	getline(spinfile,dummy); // coord file

	getline(spinfile,dummy); // time
	//std::cout << dummy << std::endl;	
	dummy.erase (dummy.begin(), dummy.begin()+5);
	double time = atof(dummy.c_str());

	getline(spinfile,dummy); // field
	//std::cout << dummy << std::endl;	
	dummy.erase (dummy.begin(), dummy.begin()+6);
	double field = atof(dummy.c_str());

	getline(spinfile,dummy); // temp
	//std::cout << dummy << std::endl;	
	dummy.erase (dummy.begin(), dummy.begin()+12);
	double temperature = atof(dummy.c_str());
	
	// magnetisation
	getline(spinfile,dummy);
	dummy.erase (dummy.begin(), dummy.begin()+14);
	std::istringstream ss2(dummy);
	val.resize(0);
	for (std::string num; getline(ss2, num, field_delim); ) {
		val.push_back(atof(num.c_str()));
		//std::cout << num << "\t" << val << std::endl;
	}
	double mx = val[0];
	double my = val[1];
	double mz = val[2];
	
	// get number of materials
	unsigned int n_mat;
	getline(spinfile,dummy);
	//std::cout << dummy << std::endl;	
	dummy.erase (dummy.begin(), dummy.begin()+20);
	n_mat=atoi(dummy.c_str());

	std::vector <material_t> material(n_mat); 
	for(int imat=0;imat<n_mat;imat++){
		getline(spinfile,dummy);
		//dummy.erase (dummy.begin(), dummy.begin()+22);
		std::istringstream ss(dummy);
		std::vector<double> val(0);
		for (std::string num; getline(ss, num, field_delim); ) {
			val.push_back(atof(num.c_str()));
		}
		material[imat].mu_s = val[0];
		material[imat].mx = val[1];
		material[imat].my = val[2];
		material[imat].mz = val[3];
		material[imat].magm = val[4];
		//std::cout << material[imat].mu_s << "\t" << material[imat].mx << "\t" << material[imat].my << "\t"  << material[imat].mz << "\t"  << material[imat].magm << std::endl;
	}
	
	// line
	getline(spinfile,dummy);
	//std::cout << dummy << std::endl;
	
	// get number of subsidiary files
	unsigned int n_files;
	getline(spinfile,dummy);
	//std::cout << dummy << std::endl;	
	dummy.erase (dummy.begin(), dummy.begin()+22);
	n_files=atoi(dummy.c_str());
	filenames.resize(0);
	
	for(int file=0; file<n_files; file++){
		getline(spinfile,dummy);
		filenames.push_back(dummy);
		//std::cout << filenames[file] << std::endl;
	}

	getline(spinfile,dummy);
	//std::cout << dummy << std::endl;

	unsigned int n_local_atoms;
	getline(spinfile,dummy);
	//std::cout << dummy << std::endl;	
	n_local_atoms=atoi(dummy.c_str());

	// Open Povray Include File
	std::stringstream incpov_file_sstr;
	incpov_file_sstr << "atoms-";
	incpov_file_sstr << std::setfill('0') << std::setw(8) << spinfile_counter;
	incpov_file_sstr << ".inc";
	std::string incpov_file = incpov_file_sstr.str();
	
	// Open Povray Output file
	std::stringstream pov_file_sstr;
	pov_file_sstr << "atoms-";
	pov_file_sstr << std::setfill('0') << std::setw(8) << spinfile_counter;
	pov_file_sstr << ".pov";
	std::string pov_file = pov_file_sstr.str();

	std::ofstream pfile;
	pfile.open(pov_file.c_str());
	
	// Ouput povray file header
			double size, mag_vec;
			double vec[3];

			size = sqrt(dim[0]*dim[0] + dim[1]*dim[1] + dim[2]*dim[2]);
			vec[0] = (1.0/dim[0]);
			vec[1] = (1.0/dim[1]);
			vec[2] = (1.0/dim[2]);
			mag_vec = sqrt(vec[0]*vec[0]+vec[1]*vec[1]+vec[2]*vec[2]);
			vec[0]/=mag_vec;
			vec[1]/=mag_vec;
			vec[2]/=mag_vec;

			pfile << "#include \"colors.inc\"" << std::endl;
			pfile << "#include \"metals.inc\""	<< std::endl;
			pfile << "#include \"screen.inc\""	<< std::endl;
			pfile << "#declare LX=" << dim[0]*0.5 << ";" << std::endl;
			pfile << "#declare LY=" << dim[1]*0.5 << ";" << std::endl;
			pfile << "#declare LZ=" << dim[2]*0.5 << ";" << std::endl;
			pfile << "#declare CX=" << size*vec[0]*6.0 << ";" << std::endl;
			pfile << "#declare CY=" << size*vec[1]*6.0 << ";" << std::endl;
			pfile << "#declare CZ=" << size*vec[2]*6.0 << ";" << std::endl;
	 		pfile << "#declare ref=0.4;" << std::endl;
			pfile << "global_settings { assumed_gamma 2.0 }" << std::endl;
			pfile << "background { color Gray30 }" << std::endl;

			pfile << "Set_Camera(<CX,CY,CZ>, <LX,LY,LZ>, 15)" << std::endl;
			pfile << "Set_Camera_Aspect(4,3)" << std::endl;
			pfile << "Set_Camera_Sky(<0,0,1>)" << std::endl;
			pfile << "light_source { <2*CX, 2*CY, 2*CZ> color White}" << std::endl;

			for(int imat=0;imat<n_mat;imat++){
				pfile << "#declare sscale"<< imat << "=2.0;" << std::endl;
				pfile << "#declare rscale"<< imat << "=1.2;" << std::endl;
				pfile << "#declare cscale"<< imat << "=3.54;" << std::endl;
				pfile << "#declare cones"<< imat << "=0;" << std::endl;
				pfile << "#declare arrows"<< imat << "=1;" << std::endl;
				pfile << "#declare spheres"<< imat << "=1;" << std::endl;
				pfile << "#declare cubes" << imat << "=0;" << std::endl;
				pfile << "#declare spincolors"<< imat << "=1;" << std::endl;
				pfile << "#declare spincolor"<< imat << "=pigment {color rgb < 0.1 0.1 0.1 >};" << std::endl;
				pfile << "#macro spinm"<< imat << "(cx,cy,cz,sx,sy,sz, cr,cg,cb)" << std::endl;
				pfile << "union{" << std::endl;
				pfile << "#if(spheres" << imat << ") sphere {<cx,cy,cz>,0.5*rscale"<< imat << "} #end" << std::endl;
				pfile << "#if(cubes" << imat << ") box {<cx-cscale"<< imat << "*0.5,cy-cscale" << imat << "*0.5,cz-cscale"<< imat << "*0.5>,<cx+cscale"<< imat << "*0.5,cy+cscale" << imat << "*0.5,cz+cscale"<< imat << "*0.5>} #end" << std::endl;
				pfile << "#if(cones"<< imat << ") cone {<cx+0.5*sx*sscale0,cy+0.5*sy*sscale"<< imat << ",cz+0.5*sz*sscale"<< imat << ">,0.0 <cx-0.5*sx*sscale"<< imat << ",cy-0.5*sy*sscale"<< imat << ",cz-0.5*sz*sscale"<< imat << ">,sscale0*0.5} #end" << std::endl;
				pfile << "#if(arrows" << imat << ") cylinder {<cx+sx*0.5*sscale"<< imat <<",cy+sy*0.5*sscale"<< imat <<",cz+sz*0.5*sscale"<< imat <<
							">,<cx-sx*0.5*sscale"<< imat <<",cy-sy*0.5*sscale"<< imat <<",cz-sz*0.5*sscale"<< imat <<">,sscale"<< imat <<"*0.12}";
				pfile << "cone {<cx+sx*0.5*1.6*sscale"<< imat <<",cy+sy*0.5*1.6*sscale"<< imat <<",cz+sz*0.5*1.6*sscale"<< imat <<">,sscale"<< imat <<"*0.0 <cx+sx*0.5*sscale"<< imat <<
							",cy+sy*0.5*sscale"<< imat <<",cz+sz*0.5*sscale"<< imat <<">,sscale"<< imat <<"*0.2} #end" << std::endl;
				pfile << "#if(spincolors"<< imat << ") texture { pigment {color rgb <cr cg cb>}finish {reflection {ref} diffuse 1 ambient 0}}" << std::endl;
				pfile << "#else texture { spincolor"<< imat << " finish {reflection {ref} diffuse 1 ambient 0}} #end" << std::endl;
				pfile << "}" << std::endl;
				pfile << "#end" << std::endl;
				
				
			}
			pfile << "#include \"" << incpov_file_sstr.str() << "\"" << std::endl;
	
		pfile.close();


	std::ofstream incpfile;
	incpfile.open(incpov_file.c_str());
	
	double sx,sy,sz,red,green,blue,ireal;
	unsigned int si=0;
	
	// Read in spin coordinates and output to povray file
	for(int i=0; i<n_local_atoms;i++){
		spinfile >> sx >> sy >> sz;
		rgb(sz,red,green,blue);
		incpfile << "spinm"<< mat[si] << "(" << cx[si] << "," << cy[si] << "," << cz[si] << "," 
		<< sx << "," << sy << "," << sz << "," << red << "," << green << "," << blue << ")" << std::endl;
		si++;
		
	}
	
		// close master file
	spinfile.close();
	
	// now read subsidiary files
	for(int file=0; file<n_files; file++){
		std::ifstream infile;
		infile.open(filenames[file].c_str());
		
		// read number of atoms in this file
		getline(infile,dummy);
		n_local_atoms=atoi(dummy.c_str());
		for(int i=0;i<n_local_atoms;i++){
			infile >> sx >> sy >> sz;
			rgb(sz,red,green,blue);
			incpfile << "spinm"<< mat[si] << "(" << cx[si] << "," << cy[si] << "," << cz[si] << "," 
			<< sx << "," << sy << "," << sz << "," << red << "," << green << "," << blue << ")" << std::endl;
			si++;
			
		}
		// close subsidiary file
		infile.close();
	}
	
	// close povray inc file
	incpfile.close();
	
	
		spinfile_counter++;
		}
		else ios=1;
Ejemplo n.º 11
0
//------------------------------------------------------------------------------
int main( int argc, char * argv[] )
{
    // basic attributes of the computation
    const unsigned    geomDeg   = 1;
    const unsigned    fieldDegU = 2;
    const unsigned    fieldDegP = 1;
    const unsigned    tiOrder   = 2;   // order of time integrator
    const base::Shape shape     = base::QUAD;

    //typedef  base::time::BDF<tiOrder> MSM;
    typedef base::time::AdamsMoulton<tiOrder> MSM;

    // time stepping method determines the history size
    const unsigned nHist = MSM::numSteps;

    
    const std::string inputFile = "terz.inp";
    double E, nu, alpha, c0, k, H, F, tMax;
    unsigned numSteps, numIntervals;
    {
        base::io::PropertiesParser pp;
        pp.registerPropertiesVar( "E",     E     );
        pp.registerPropertiesVar( "nu",    nu    );
        pp.registerPropertiesVar( "alpha", alpha );
        pp.registerPropertiesVar( "c0",    c0    );
        pp.registerPropertiesVar( "k",     k     );
        pp.registerPropertiesVar( "H",     H     );
        pp.registerPropertiesVar( "F",     F     );

        pp.registerPropertiesVar( "tMax",         tMax  );
        pp.registerPropertiesVar( "numSteps",     numSteps );
        pp.registerPropertiesVar( "numIntervals", numIntervals );

        // Read variables from the input file
        std::ifstream inp( inputFile.c_str() );
        VERIFY_MSG( inp.is_open(), "Cannot open input file" );
        pp.readValues( inp );
        inp.close( );

    }

    const double deltaT = tMax / static_cast<double>( numSteps );

    // usage message
    if ( argc != 2 ) {
        std::cout << "Usage:  " << argv[0] << "  mesh.smf \n";
        return 0;
    }

    const std::string meshFile = boost::lexical_cast<std::string>( argv[1] );

    

    // Analytic solution
    Terzaghi terzaghi( E, nu, alpha, c0, k, H, F );
    

    //--------------------------------------------------------------------------
    // define a mesh
    typedef base::Unstructured<shape,geomDeg>    Mesh;
    const unsigned dim = Mesh::Node::dim;

    // create a mesh and read from input
    Mesh mesh;
    {
        std::ifstream smf( meshFile.c_str() );
        base::io::smf::readMesh( smf, mesh );
        smf.close();
    }

    // quadrature objects for volume and surface
    const unsigned kernelDegEstimate = 3;
    typedef base::Quadrature<kernelDegEstimate,shape> Quadrature;
    Quadrature quadrature;
    typedef base::SurfaceQuadrature<kernelDegEstimate,shape> SurfaceQuadrature;
    SurfaceQuadrature surfaceQuadrature;

    // Create a displacement field
    const unsigned    doFSizeU = dim;
    typedef base::fe::Basis<shape,fieldDegU>           FEBasisU;
    typedef base::Field<FEBasisU,doFSizeU,nHist>       Displacement;
    typedef Displacement::DegreeOfFreedom              DoFU;
    Displacement displacement;

    // Create a pressure field
    const unsigned    doFSizeP = 1;
    typedef base::fe::Basis<shape,fieldDegP>           FEBasisP;
    typedef base::Field<FEBasisP,doFSizeP,nHist>       Pressure;
    typedef Pressure::DegreeOfFreedom                  DoFP;
    Pressure pressure;

    // generate DoFs from mesh
    base::dof::generate<FEBasisU>( mesh, displacement );
    base::dof::generate<FEBasisP>( mesh, pressure );

    // Creates a list of <Element,faceNo> pairs along the boundary
    base::mesh::MeshBoundary meshBoundary;
    meshBoundary.create( mesh.elementsBegin(), mesh.elementsEnd() );

    // Create a boundary mesh from this list
    typedef base::mesh::CreateBoundaryMesh<Mesh::Element> CreateBoundaryMesh;
    typedef CreateBoundaryMesh::BoundaryMesh BoundaryMesh;
    BoundaryMesh boundaryMesh;
    {
        CreateBoundaryMesh::apply( meshBoundary.begin(),
                                   meshBoundary.end(),
                                   mesh, boundaryMesh );
    }



    // material object
    typedef mat::hypel::StVenant Material;
    Material material( mat::Lame::lambda( E, nu), mat::Lame::mu( E, nu ) );

    typedef base::asmb::FieldBinder<Mesh,Displacement,Pressure> Field;
    Field field( mesh, displacement, pressure );

    typedef Field::TupleBinder<1,1>::Type TopLeft;
    typedef Field::TupleBinder<1,2>::Type TopRight;
    typedef Field::TupleBinder<2,1>::Type BotLeft;
    typedef Field::TupleBinder<2,2>::Type BotRight;

    // surface displacement field
    typedef base::asmb::SurfaceFieldBinder<BoundaryMesh,Displacement> SurfaceFieldBinder;
    SurfaceFieldBinder surfaceFieldBinder( boundaryMesh, displacement );
    typedef SurfaceFieldBinder::TupleBinder<1>::Type SFTB;
    
    // kernel objects
    typedef solid::HyperElastic<Material,TopLeft::Tuple> HyperElastic;
    HyperElastic hyperElastic( material );

    typedef fluid::PressureGradient<TopRight::Tuple> GradP;
    GradP gradP;

    //typedef fluid::VelocityDivergence<FieldPUUTuple> DivU;
    //DivU divU( true ); // * alpha
    typedef PoroDivU<BotLeft::Tuple> DivU;
    DivU divU( alpha );

    typedef heat::Laplace<BotRight::Tuple> Laplace;
    Laplace laplace( k );

    // constrain the boundary
    base::dof::constrainBoundary<FEBasisU>( meshBoundary.begin(),
                                            meshBoundary.end(),
                                            mesh, displacement, 
                                            boost::bind( &dirichletU<dim,DoFU>, _1, _2, 1.0 ) );
    
    base::dof::constrainBoundary<FEBasisP>( meshBoundary.begin(),
                                            meshBoundary.end(),
                                            mesh, pressure, 
                                            boost::bind( &dirichletP<dim,DoFP>, _1, _2, H ) );


    // Number the degrees of freedom
    const std::size_t numDoFsU =
        base::dof::numberDoFsConsecutively( displacement.doFsBegin(), displacement.doFsEnd() );
    std::cout << "# Number of displacement dofs " << numDoFsU << std::endl;
    const std::size_t numDoFsP =
        base::dof::numberDoFsConsecutively( pressure.doFsBegin(), pressure.doFsEnd(), numDoFsU );
    std::cout << "# Number of pressure     dofs " << numDoFsP << std::endl;


    // write VTK file
    writeVTK( mesh, displacement, pressure, meshFile, 0 );

    
    for ( unsigned n = 0; n < numSteps; n++ ) {

        const double time = (n+1) * deltaT;
        std::cout << time << "  ";

        // initialise current displacement to zero (linear elasticity)
        std::for_each( displacement.doFsBegin(), displacement.doFsEnd(),
                       boost::bind( &DoFU::clearValue, _1 ) );

        // Create a solver object
        typedef base::solver::Eigen3           Solver;
        Solver solver( numDoFsU + numDoFsP );

        //------------------------------------------------------------------
        base::asmb::stiffnessMatrixComputation<TopLeft>( quadrature, solver, 
                                                         field, hyperElastic );

        base::asmb::stiffnessMatrixComputation<TopRight>( quadrature, solver,
                                                          field, gradP );

        base::asmb::stiffnessMatrixComputation<BotRight>( quadrature, solver,
                                                          field, laplace);

        // time integration terms
        base::time::computeReactionTerms<BotLeft,MSM>( divU, quadrature, solver,
                                                       field, deltaT, n );

        base::time::computeInertiaTerms<BotRight,MSM>( quadrature, solver,
                                                       field, deltaT, n, c0 );
        
        base::time::computeResidualForceHistory<BotRight,MSM>( laplace, 
                                                               quadrature, solver,
                                                               field, n );


        // Neumann boundary condition
        base::asmb::neumannForceComputation<SFTB>( surfaceQuadrature, solver, surfaceFieldBinder,
                                                   boost::bind( &neumannBC<dim>, _1, _2,
                                                                H, F ) );


        // Finalise assembly
        solver.finishAssembly();

        // Solve
        solver.superLUSolve();
            
        // distribute results back to dofs
        base::dof::setDoFsFromSolver( solver, displacement );
        base::dof::setDoFsFromSolver( solver, pressure );
        
        // push history
        std::for_each( displacement.doFsBegin(), displacement.doFsEnd(),
                       boost::bind( &DoFU::pushHistory, _1 ) );
        std::for_each( pressure.doFsBegin(), pressure.doFsEnd(),
                       boost::bind( &DoFP::pushHistory, _1 ) );


        // write VTK file
        writeVTK( mesh, displacement, pressure, meshFile, n+1 );
        
        // Finished time steps
        //--------------------------------------------------------------------------

        const std::pair<double,double> approx = probe( mesh, displacement, pressure );

        const double p = terzaghi.pressure( H/2., time );
        const double u = terzaghi.displacement( H/2., time );
        
        std::cout << u  << "  " << approx.first << "  "
                  << p  << "  " << approx.second << '\n';
    }
    
    return 0;
}
Ejemplo n.º 12
0
static SGNODE* getColor( IFSG_SHAPE& shape, int colorIdx )
{
    IFSG_APPEARANCE material( shape );

    static int cidx = 1;
    int idx;

    if( colorIdx == -1 )
        idx = cidx;
    else
        idx = colorIdx;

    switch( idx )
    {
    case 0:
        // green for PCB
        material.SetSpecular( 0.13, 0.81, 0.22 );
        material.SetDiffuse( 0.13, 0.81, 0.22 );
        // default ambient intensity
        material.SetShininess( 0.3 );

        break;

    case 1:
        // magenta
        material.SetSpecular( 0.8, 0.0, 0.8 );
        material.SetDiffuse( 0.6, 0.0, 0.6 );
        // default ambient intensity
        material.SetShininess( 0.3 );

        break;

    case 2:
        // red
        material.SetSpecular( 0.69, 0.14, 0.14 );
        material.SetDiffuse( 0.69, 0.14, 0.14 );
        // default ambient intensity
        material.SetShininess( 0.3 );

        break;

    case 3:
        // orange
        material.SetSpecular( 1.0, 0.44, 0.0 );
        material.SetDiffuse( 1.0, 0.44, 0.0 );
        // default ambient intensity
        material.SetShininess( 0.3 );

        break;

    case 4:
        // yellow
        material.SetSpecular( 0.93, 0.94, 0.16 );
        material.SetDiffuse( 0.93, 0.94, 0.16 );
        // default ambient intensity
        material.SetShininess( 0.3 );

        break;

    case 5:
        // blue
        material.SetSpecular( 0.1, 0.11, 0.88 );
        material.SetDiffuse( 0.1, 0.11, 0.88 );
        // default ambient intensity
        material.SetShininess( 0.3 );

        break;

    default:
        // violet
        material.SetSpecular( 0.32, 0.07, 0.64 );
        material.SetDiffuse( 0.32, 0.07, 0.64 );
        // default ambient intensity
        material.SetShininess( 0.3 );

        break;
    }

    if( ( colorIdx == -1 ) && ( ++cidx > NCOLORS ) )
        cidx = 1;

    return material.GetRawPtr();
};
Ejemplo n.º 13
0
uint32_t objToBin(const uint8_t* _objData
                  , bx::WriterSeekerI* _writer
                  , uint32_t _packUv
                  , uint32_t _packNormal
                  , bool _ccw
                  , bool _flipV
                  , bool _hasTangent
                  , float _scale
                 )
{
    int64_t parseElapsed = -bx::getHPCounter();
    int64_t triReorderElapsed = 0;

    const int64_t begin = _writer->seek();

    Vector3Array positions;
    Vector3Array normals;
    Vector3Array texcoords;
    Index3Map indexMap;
    TriangleArray triangles;
    BgfxGroupArray groups;

    uint32_t num = 0;

    MeshGroup group;
    group.m_startTriangle = 0;
    group.m_numTriangles = 0;
    group.m_name = "";
    group.m_material = "";

    char commandLine[2048];
    uint32_t len = sizeof(commandLine);
    int argc;
    char* argv[64];
    const char* next = (const char*)_objData;
    do
    {
        next = bx::tokenizeCommandLine(next, commandLine, len, argc, argv, BX_COUNTOF(argv), '\n');
        if (0 < argc)
        {
            if (0 == strcmp(argv[0], "#") )
            {
                if (2 < argc
                        &&  0 == strcmp(argv[2], "polygons") )
                {
                }
            }
            else if (0 == strcmp(argv[0], "f") )
            {
                Triangle triangle;
                memset(&triangle, 0, sizeof(Triangle) );

                const int numNormals   = (int)normals.size();
                const int numTexcoords = (int)texcoords.size();
                const int numPositions = (int)positions.size();
                for (uint32_t edge = 0, numEdges = argc-1; edge < numEdges; ++edge)
                {
                    Index3 index;
                    index.m_texcoord = 0;
                    index.m_normal = 0;
                    index.m_vertexIndex = -1;

                    char* vertex = argv[edge+1];
                    char* texcoord = strchr(vertex, '/');
                    if (NULL != texcoord)
                    {
                        *texcoord++ = '\0';

                        char* normal = strchr(texcoord, '/');
                        if (NULL != normal)
                        {
                            *normal++ = '\0';
                            const int nn = atoi(normal);
                            index.m_normal = (nn < 0) ? nn+numNormals : nn-1;
                        }

                        const int tex = atoi(texcoord);
                        index.m_texcoord = (tex < 0) ? tex+numTexcoords : tex-1;
                    }

                    const int pos = atoi(vertex);
                    index.m_position = (pos < 0) ? pos+numPositions : pos-1;

                    uint64_t hash0 = index.m_position;
                    uint64_t hash1 = uint64_t(index.m_texcoord)<<20;
                    uint64_t hash2 = uint64_t(index.m_normal)<<40;
                    uint64_t hash = hash0^hash1^hash2;

                    CS_STL::pair<Index3Map::iterator, bool> result = indexMap.insert(CS_STL::make_pair(hash, index) );
                    if (!result.second)
                    {
                        Index3& oldIndex = result.first->second;
                        BX_UNUSED(oldIndex);
                        BX_CHECK(oldIndex.m_position == index.m_position
                                 && oldIndex.m_texcoord == index.m_texcoord
                                 && oldIndex.m_normal == index.m_normal
                                 , "Hash collision!"
                                );
                    }

                    switch (edge)
                    {
                    case 0:
                    case 1:
                    case 2:
                        triangle.m_index[edge] = hash;
                        if (2 == edge)
                        {
                            if (_ccw)
                            {
                                std::swap(triangle.m_index[1], triangle.m_index[2]);
                            }
                            triangles.push_back(triangle);
                        }
                        break;

                    default:
                        if (_ccw)
                        {
                            triangle.m_index[2] = triangle.m_index[1];
                            triangle.m_index[1] = hash;
                        }
                        else
                        {
                            triangle.m_index[1] = triangle.m_index[2];
                            triangle.m_index[2] = hash;
                        }
                        triangles.push_back(triangle);
                        break;
                    }
                }
            }
            else if (0 == strcmp(argv[0], "g") )
            {
                if (1 >= argc)
                {
                    CS_PRINT("Error parsing *.obj file.\n");
                    return 0;
                }
                group.m_name = argv[1];
            }
            else if (*argv[0] == 'v')
            {
                group.m_numTriangles = (uint32_t)(triangles.size() ) - group.m_startTriangle;
                if (0 < group.m_numTriangles)
                {
                    groups.push_back(group);
                    group.m_startTriangle = (uint32_t)(triangles.size() );
                    group.m_numTriangles = 0;
                }

                if (0 == strcmp(argv[0], "vn") )
                {
                    Vector3 normal;
                    normal.x = (float)atof(argv[1]);
                    normal.y = (float)atof(argv[2]);
                    normal.z = (float)atof(argv[3]);

                    normals.push_back(normal);
                }
                else if (0 == strcmp(argv[0], "vp") )
                {
                    static bool once = true;
                    if (once)
                    {
                        once = false;
                        CS_PRINT("warning: 'parameter space vertices' are unsupported.\n");
                    }
                }
                else if (0 == strcmp(argv[0], "vt") )
                {
                    Vector3 texcoord;
                    texcoord.x = (float)atof(argv[1]);
                    texcoord.y = 0.0f;
                    texcoord.z = 0.0f;
                    switch (argc)
                    {
                    case 4:
                        texcoord.z = (float)atof(argv[3]);
                    // fallthrough
                    case 3:
                        texcoord.y = (float)atof(argv[2]);
                        break;

                    default:
                        break;
                    }

                    texcoords.push_back(texcoord);
                }
                else
                {
                    float px = (float)atof(argv[1]);
                    float py = (float)atof(argv[2]);
                    float pz = (float)atof(argv[3]);
                    float pw = 1.0f;
                    if (argc > 4)
                    {
                        pw = (float)atof(argv[4]);
                    }

                    float invW = _scale/pw;
                    px *= invW;
                    py *= invW;
                    pz *= invW;

                    Vector3 pos;
                    pos.x = px;
                    pos.y = py;
                    pos.z = pz;

                    positions.push_back(pos);
                }
            }
            else if (0 == strcmp(argv[0], "usemtl") )
            {
                std::string material(argv[1]);

                if (material != group.m_material)
                {
                    group.m_numTriangles = (uint32_t)(triangles.size() ) - group.m_startTriangle;
                    if (0 < group.m_numTriangles)
                    {
                        groups.push_back(group);
                        group.m_startTriangle = (uint32_t)(triangles.size() );
                        group.m_numTriangles = 0;
                    }
                }

                group.m_material = material;
            }
// unsupported tags
//              else if (0 == strcmp(argv[0], "mtllib") )
//              {
//              }
//              else if (0 == strcmp(argv[0], "o") )
//              {
//              }
//              else if (0 == strcmp(argv[0], "s") )
//              {
//              }
        }

        ++num;
    }
    while ('\0' != *next);

    group.m_numTriangles = (uint32_t)(triangles.size() ) - group.m_startTriangle;
    if (0 < group.m_numTriangles)
    {
        groups.push_back(group);
        group.m_startTriangle = (uint32_t)(triangles.size() );
        group.m_numTriangles = 0;
    }

    int64_t now = bx::getHPCounter();
    parseElapsed += now;
    int64_t convertElapsed = -now;

    std::sort(groups.begin(), groups.end(), GroupSortByMaterial() );

    bool hasColor = false;
    bool hasNormal;
    bool hasTexcoord;
    {
        Index3Map::const_iterator it = indexMap.begin();
        hasNormal   = 0 != it->second.m_normal;
        hasTexcoord = 0 != it->second.m_texcoord;

        if (!hasTexcoord
                &&  texcoords.size() == positions.size() )
        {
            hasTexcoord = true;

            for (Index3Map::iterator it = indexMap.begin(), itEnd = indexMap.end(); it != itEnd; ++it)
            {
                it->second.m_texcoord = it->second.m_position;
            }
        }

        if (!hasNormal
                &&  normals.size() == positions.size() )
        {
            hasNormal = true;

            for (Index3Map::iterator it = indexMap.begin(), itEnd = indexMap.end(); it != itEnd; ++it)
            {
                it->second.m_normal = it->second.m_position;
            }
        }
    }

    bgfx::VertexDecl decl;
    decl.begin();
    decl.add(bgfx::Attrib::Position, 3, bgfx::AttribType::Float);

    if (hasColor)
    {
        decl.add(bgfx::Attrib::Color0, 4, bgfx::AttribType::Uint8, true);
    }

    if (hasTexcoord)
    {
        switch (_packUv)
        {
        default:
        case 0:
            decl.add(bgfx::Attrib::TexCoord0, 2, bgfx::AttribType::Float);
            break;

        case 1:
            decl.add(bgfx::Attrib::TexCoord0, 2, bgfx::AttribType::Half);
            break;
        }
    }

    if (hasNormal)
    {
        _hasTangent &= hasTexcoord;

        switch (_packNormal)
        {
        default:
        case 0:
            decl.add(bgfx::Attrib::Normal, 3, bgfx::AttribType::Float);
            if (_hasTangent)
            {
                decl.add(bgfx::Attrib::Tangent, 4, bgfx::AttribType::Float);
            }
            break;

        case 1:
            decl.add(bgfx::Attrib::Normal, 4, bgfx::AttribType::Uint8, true, true);
            if (_hasTangent)
            {
                decl.add(bgfx::Attrib::Tangent, 4, bgfx::AttribType::Uint8, true, true);
            }
            break;
        }
    }
    decl.end();

    uint32_t stride = decl.getStride();
    uint8_t* vertexData = new uint8_t[triangles.size() * 3 * stride];
    uint16_t* indexData = new uint16_t[triangles.size() * 3];
    int32_t numVertices = 0;
    int32_t numIndices = 0;
    int32_t numPrimitives = 0;

    uint8_t* vertices = vertexData;
    uint16_t* indices = indexData;

    std::string material = groups.begin()->m_material;

    BgfxPrimitiveArray primitives;

    Primitive prim;
    prim.m_startVertex = 0;
    prim.m_startIndex  = 0;

    uint32_t positionOffset = decl.getOffset(bgfx::Attrib::Position);
    uint32_t color0Offset   = decl.getOffset(bgfx::Attrib::Color0);

    uint32_t ii = 0;
    for (BgfxGroupArray::const_iterator groupIt = groups.begin(); groupIt != groups.end(); ++groupIt, ++ii)
    {
        for (uint32_t tri = groupIt->m_startTriangle, end = tri + groupIt->m_numTriangles; tri < end; ++tri)
        {
            if (material != groupIt->m_material
                    ||  65533 < numVertices)
            {
                prim.m_numVertices = numVertices - prim.m_startVertex;
                prim.m_numIndices = numIndices - prim.m_startIndex;
                if (0 < prim.m_numVertices)
                {
                    primitives.push_back(prim);
                }

                triReorderElapsed -= bx::getHPCounter();
                for (BgfxPrimitiveArray::const_iterator primIt = primitives.begin(); primIt != primitives.end(); ++primIt)
                {
                    const Primitive& prim = *primIt;
                    triangleReorder(indexData + prim.m_startIndex, prim.m_numIndices, numVertices, 32);
                }
                triReorderElapsed += bx::getHPCounter();

                if (_hasTangent)
                {
                    calculateTangents(vertexData, numVertices, decl, indexData, numIndices);
                }

                write(_writer
                      , vertexData
                      , numVertices
                      , decl
                      , indexData
                      , numIndices
                      , material.c_str()
                      , primitives.data()
                      , (uint32_t)primitives.size()
                     );
                primitives.clear();

                for (Index3Map::iterator indexIt = indexMap.begin(); indexIt != indexMap.end(); ++indexIt)
                {
                    indexIt->second.m_vertexIndex = -1;
                }

                vertices = vertexData;
                indices = indexData;
                numVertices = 0;
                numIndices = 0;
                prim.m_startVertex = 0;
                prim.m_startIndex = 0;
                ++numPrimitives;

                material = groupIt->m_material;
            }

            Triangle& triangle = triangles[tri];
            for (uint32_t edge = 0; edge < 3; ++edge)
            {
                uint64_t hash = triangle.m_index[edge];
                Index3& index = indexMap[hash];
                if (index.m_vertexIndex == -1)
                {
                    index.m_vertexIndex = numVertices++;

                    float* position = (float*)(vertices + positionOffset);
                    memcpy(position, &positions[index.m_position], 3*sizeof(float) );

                    if (hasColor)
                    {
                        uint32_t* color0 = (uint32_t*)(vertices + color0Offset);
                        *color0 = rgbaToAbgr(numVertices%255, numIndices%255, 0, 0xff);
                    }

                    if (hasTexcoord)
                    {
                        float uv[2];
                        memcpy(uv, &texcoords[index.m_texcoord], 2*sizeof(float) );

                        if (_flipV)
                        {
                            uv[1] = -uv[1];
                        }

                        bgfx::vertexPack(uv, true, bgfx::Attrib::TexCoord0, decl, vertices);
                    }

                    if (hasNormal)
                    {
                        float normal[4];
                        bx::vec3Norm(normal, (float*)&normals[index.m_normal]);
                        bgfx::vertexPack(normal, true, bgfx::Attrib::Normal, decl, vertices);
                    }

                    vertices += stride;
                }

                *indices++ = (uint16_t)index.m_vertexIndex;
                ++numIndices;
            }
        }

        if (0 < numVertices)
        {
            prim.m_numVertices = numVertices - prim.m_startVertex;
            prim.m_numIndices = numIndices - prim.m_startIndex;
            bx::strlcpy(prim.m_name, groupIt->m_name.c_str(), 128);
            primitives.push_back(prim);
            prim.m_startVertex = numVertices;
            prim.m_startIndex = numIndices;
        }

        //CS_PRINT("%3d: s %5d, n %5d, %s\n"
        //    , ii
        //    , groupIt->m_startTriangle
        //    , groupIt->m_numTriangles
        //    , groupIt->m_material.c_str()
        //    );
    }

    if (0 < primitives.size() )
    {
        triReorderElapsed -= bx::getHPCounter();
        for (BgfxPrimitiveArray::const_iterator primIt = primitives.begin(); primIt != primitives.end(); ++primIt)
        {
            const Primitive& prim = *primIt;
            triangleReorder(indexData + prim.m_startIndex, prim.m_numIndices, numVertices, 32);
        }
        triReorderElapsed += bx::getHPCounter();

        if (_hasTangent)
        {
            calculateTangents(vertexData, numVertices, decl, indexData, numIndices);
        }

        write(_writer, vertexData, numVertices, decl, indexData, numIndices, material.c_str(), primitives.data(), (uint32_t)primitives.size());
    }

    delete [] indexData;
    delete [] vertexData;

    now = bx::getHPCounter();
    convertElapsed += now;

    const int64_t end = _writer->seek();
    const uint32_t dataSize = uint32_t(end-begin);
    CS_PRINT("size: %u\n", dataSize);

    CS_PRINT("parse %f [s]\ntri reorder %f [s]\nconvert %f [s]\n# %d, g %d, p %d, v %d, i %d\n"
             , double(parseElapsed)/bx::getHPFrequency()
             , double(triReorderElapsed)/bx::getHPFrequency()
             , double(convertElapsed)/bx::getHPFrequency()
             , num
             , uint32_t(groups.size() )
             , numPrimitives
             , numVertices
             , numIndices
            );

    return dataSize;
}
Ejemplo n.º 14
0
MaterialPtr EarthScene::createMaterial( const QString& colorFileName,
                                        const QString& specularFileName,
                                        const QString& nightlightsFileName )
{
    // Create a material and set the shaders
    MaterialPtr material( new Material );
    material->setShaders( ":/shaders/earth.vert",
                          ":/shaders/earth.frag" );

    // Create a diffuse color texture
    TexturePtr texture0( new Texture( Texture::Texture2D ) );
    texture0->create();
    texture0->bind();
    texture0->setImage( QImage( colorFileName ) );
    texture0->generateMipMaps();

    // Create a specular texture map
    TexturePtr texture1( new Texture( Texture::Texture2D ) );
    texture1->create();
    texture1->bind();
    texture1->setImage( QImage( specularFileName ) );
    texture1->generateMipMaps();

    // Create a nighttime lights texture
    TexturePtr texture2( new Texture( Texture::Texture2D ) );
    texture2->create();
    texture2->bind();
    texture2->setImage( QImage( nightlightsFileName ) );
    texture2->generateMipMaps();

#if !defined(Q_OS_MAC)
    // Create a sampler. This can be shared by many textures
    SamplerPtr sampler( new Sampler );
    sampler->create();
    sampler->setWrapMode( Sampler::DirectionS, GL_CLAMP_TO_EDGE );
    sampler->setWrapMode( Sampler::DirectionT, GL_CLAMP_TO_EDGE );
    sampler->setMinificationFilter( GL_LINEAR_MIPMAP_LINEAR );
    sampler->setMagnificationFilter( GL_LINEAR );

    // Associate the textures with the first 2 texture units
    material->setTextureUnitConfiguration( 0, texture0, sampler, QByteArrayLiteral( "dayColor" ) );
    material->setTextureUnitConfiguration( 1, texture1, sampler, QByteArrayLiteral( "specularMap" ) );
    material->setTextureUnitConfiguration( 2, texture2, sampler, QByteArrayLiteral( "nightColor" ) );
#else
    texture0->bind();
    texture0->setWrapMode( Texture::DirectionS, GL_CLAMP_TO_EDGE );
    texture0->setWrapMode( Texture::DirectionT, GL_CLAMP_TO_EDGE );
    texture0->setMinificationFilter( GL_LINEAR_MIPMAP_LINEAR );
    texture0->setMagnificationFilter( GL_LINEAR );

    texture1->bind();
    texture1->setWrapMode( Texture::DirectionS, GL_CLAMP_TO_EDGE );
    texture1->setWrapMode( Texture::DirectionT, GL_CLAMP_TO_EDGE );
    texture1->setMinificationFilter( GL_LINEAR_MIPMAP_LINEAR );
    texture1->setMagnificationFilter( GL_LINEAR );

    texture2->bind();
    texture2->setWrapMode( Texture::DirectionS, GL_CLAMP_TO_EDGE );
    texture2->setWrapMode( Texture::DirectionT, GL_CLAMP_TO_EDGE );
    texture2->setMinificationFilter( GL_LINEAR_MIPMAP_LINEAR );
    texture2->setMagnificationFilter( GL_LINEAR );

    // Associate the textures with the first 2 texture units
    material->setTextureUnitConfiguration( 0, texture0, QByteArrayLiteral( "dayColor" ) );
    material->setTextureUnitConfiguration( 1, texture1, QByteArrayLiteral( "specularMap" ) );
    material->setTextureUnitConfiguration( 2, texture2, QByteArrayLiteral( "nightColor" ) );
#endif

    return material;
}
Ejemplo n.º 15
0
void VideoNode::setCurrentFrame(GstBuffer* buffer)
{
    Q_ASSERT (m_materialType == MaterialTypeVideo);
    static_cast<VideoMaterial*>(material())->setCurrentFrame(buffer);
    markDirty(DirtyMaterial);
}
Ejemplo n.º 16
0
/** Compute the elastic (large!) deformation of a block of material.
 *  See problem description in ref06::PulledSheetProblem for a the boundary
 *  conditions. The problem is non-linear and therefore a Newton method is
 *  used. Moreover, the applied load (displacement or traction) is divided into
 *  load steps.
 *
 *  New features:
 *  - vectorial problem: DoFs are not scalar anymore
 *  - hyper-elasticity
 *
 */
int ref06::compressible( int argc, char * argv[] )
{
    // basic attributes of the computation
    const unsigned    geomDeg  = 1;
    const unsigned    fieldDeg = 2;
    const base::Shape shape    = base::HyperCubeShape<SPACEDIM>::value;

    // typedef mat::hypel::StVenant Material;
    typedef mat::hypel::NeoHookeanCompressible Material;

    // usage message
    if ( argc != 3 ) {
        std::cout << "Usage:  " << argv[0] << "  mesh.smf input.dat \n";
        return 0;
    }

    // read name of input file
    const std::string meshFile  = boost::lexical_cast<std::string>( argv[1] );
    const std::string inputFile = boost::lexical_cast<std::string>( argv[2] );

    // read from input file
    double E, nu, pull, traction, tolerance;
    unsigned maxIter, loadSteps;
    bool dispControlled;
    {    
        //Feed properties parser with the variables to be read
        base::io::PropertiesParser prop;
        prop.registerPropertiesVar( "E",                E );
        prop.registerPropertiesVar( "nu",               nu );
        prop.registerPropertiesVar( "pull",             pull );
        prop.registerPropertiesVar( "maxIter",          maxIter );
        prop.registerPropertiesVar( "loadSteps",        loadSteps );
        prop.registerPropertiesVar( "traction",         traction );
        prop.registerPropertiesVar( "dispControlled",   dispControlled );
        prop.registerPropertiesVar( "tolerance",        tolerance );

        // Read variables from the input file
        std::ifstream inp( inputFile.c_str()  );
        VERIFY_MSG( inp.is_open(), "Cannot open input file" );
        prop.readValues( inp );
        inp.close( );

        // Make sure all variables have been found
        if ( not prop.isEverythingRead() ) {
            prop.writeUnread( std::cerr );
            VERIFY_MSG( false, "Could not find above variables" );
        }
    }

    // find base name from mesh file
    const std::string baseName = base::io::baseName( meshFile, ".smf" );

    //--------------------------------------------------------------------------
    // define a mesh
    typedef base::Unstructured<shape,geomDeg>    Mesh;
    const unsigned dim = Mesh::Node::dim;

    // create a mesh and read from input
    Mesh mesh;
    {
        std::ifstream smf( meshFile.c_str() );
        base::io::smf::readMesh( smf, mesh );
        smf.close();
    }

    // quadrature objects for volume and surface
    const unsigned kernelDegEstimate = 3;
    typedef base::Quadrature<kernelDegEstimate,shape> Quadrature;
    Quadrature quadrature;
    typedef base::SurfaceQuadrature<kernelDegEstimate,shape> SurfaceQuadrature;
    SurfaceQuadrature surfaceQuadrature;

    // Create a field
    const unsigned    doFSize = dim;
    typedef base::fe::Basis<shape,fieldDeg>        FEBasis;
    typedef base::Field<FEBasis,doFSize>           Field;
    typedef Field::DegreeOfFreedom                 DoF;
    Field field;

    // generate DoFs from mesh
    base::dof::generate<FEBasis>( mesh, field );

    // Creates a list of <Element,faceNo> pairs along the boundary
    base::mesh::MeshBoundary meshBoundary;
    meshBoundary.create( mesh.elementsBegin(), mesh.elementsEnd() );

    // Create a boundary mesh from this list
    typedef base::mesh::BoundaryMeshBinder<Mesh::Element>::Type BoundaryMesh;
    BoundaryMesh boundaryMesh;
    {
        // Create a real mesh object from this list
        base::mesh::generateBoundaryMesh( meshBoundary.begin(),
                                          meshBoundary.end(),
                                          mesh, boundaryMesh );
    }

    // initial pull = (total amount) / (number of steps)
    const double firstPull = pull / static_cast<double>( loadSteps );

    // constrain the boundary
    base::dof::constrainBoundary<FEBasis>( meshBoundary.begin(),
                                           meshBoundary.end(),
                                           mesh, field, 
                                           boost::bind(
                                               &ref06::PulledSheet<dim>::dirichletBC<DoF>,
                                               _1, _2, dispControlled, firstPull ) );

    // Bind the fields together
    typedef base::asmb::FieldBinder<Mesh,Field> FieldBinder;
    FieldBinder fieldBinder( mesh, field );
    typedef FieldBinder::TupleBinder<1,1>::Type FTB;

    typedef base::asmb::SurfaceFieldBinder<BoundaryMesh,Field> SurfaceFieldBinder;
    SurfaceFieldBinder surfaceFieldBinder( boundaryMesh, field );
    typedef SurfaceFieldBinder::TupleBinder<1>::Type SFTB;

    // material object
    Material material( mat::Lame::lambda( E, nu), mat::Lame::mu( E, nu ) );

    // matrix kernel
    typedef solid::HyperElastic<Material,FTB::Tuple> HyperElastic;
    HyperElastic hyperElastic( material );
            
    // Number the degrees of freedom
    const std::size_t numDofs =
        base::dof::numberDoFsConsecutively( field.doFsBegin(), field.doFsEnd() );
    std::cout << "# Number of dofs " << numDofs << std::endl;

    // create table for writing the convergence behaviour of the nonlinear solves
    base::io::Table<4>::WidthArray widths = {{ 2, 5, 5, 15 }};
    base::io::Table<4> table( widths );
    table % "Step" % "Iter" % "|F|"  % "|x|";
    std::cout << "#" << table;

    // write a vtk file
    ref06::writeVTKFile( baseName, 0, mesh, field, material );


    //--------------------------------------------------------------------------
    // Loop over load steps
    //--------------------------------------------------------------------------
    for ( unsigned step = 0; step < loadSteps; step++ ) {

        // rescale constraints in every load step: (newValue / oldValue)
        const double  pullFactor =
            (step == 0 ?
             static_cast<double>( step+1 ) :
             static_cast<double>( step+1 )/ static_cast<double>(step) );

        // scale constraints
        base::dof::scaleConstraints( field, pullFactor );

        //----------------------------------------------------------------------
        // Nonlinear iterations
        //----------------------------------------------------------------------
        unsigned iter = 0;
        while ( iter < maxIter ) {

            table % step % iter;
    
            // Create a solver object
            typedef base::solver::Eigen3           Solver;
            Solver solver( numDofs );

            // apply traction boundary condition, if problem is not disp controlled
            if ( not dispControlled ) {
                
                // value of applied traction
                const double tractionFactor =
                    traction * 
                    static_cast<double>(step+1) / static_cast<double>( loadSteps );

                // apply traction load
                base::asmb::neumannForceComputation<SFTB>(
                    surfaceQuadrature, solver,
                    surfaceFieldBinder,
                    boost::bind( &ref06::PulledSheet<dim>::neumannBC,
                                 _1, _2, tractionFactor ) );
            }

            // residual forces
            base::asmb::computeResidualForces<FTB>( quadrature, solver,
                                                    fieldBinder,
                                                    hyperElastic );
            
            // Compute element stiffness matrices and assemble them
            base::asmb::stiffnessMatrixComputation<FTB>( quadrature, solver,
                                                         fieldBinder,
                                                         hyperElastic );

            // Finalise assembly
            solver.finishAssembly();

            // norm of residual 
            const double conv1 = solver.norm();
            table % conv1;

            // convergence via residual norm
            if ( conv1 < tolerance * E ) { // note the tolerance multiplier
                std::cout << table;
                break;
            }

            // Solve
            //solver.choleskySolve();
            solver.cgSolve();
            
            // distribute results back to dofs
            base::dof::addToDoFsFromSolver( solver, field );

            // norm of displacement increment
            const double conv2 = solver.norm();
            table % conv2;
            std::cout << table;
            iter++;
            
            // convergence via increment
            if ( conv2 < tolerance ) break;
        }
        // Finished non-linear iterations
        //----------------------------------------------------------------------

        // warning
        if ( iter == maxIter ) {
            std::cout << "# (WW) Step " << step << " has not converged within "
                      << maxIter << " iterations \n";
        }

        // write a vtk file
        ref06::writeVTKFile( baseName, step+1, mesh, field, material );
        
    }
    // Finished load steps
    //--------------------------------------------------------------------------
    
    return 0;
}
Ejemplo n.º 17
0
void VideoNode::updateColors(int brightness, int contrast, int hue, int saturation)
{
    Q_ASSERT (m_materialType == MaterialTypeVideo);
    static_cast<VideoMaterial*>(material())->updateColors(brightness, contrast, hue, saturation);
    markDirty(DirtyMaterial);
}
Ejemplo n.º 18
0
bool ThrowAbility::use() {
   if (isOnCooldown()) {
      return false;
   }

   SPtr<Scene> scene = gameObject.getScene().lock();
   if (!scene) {
      return false;
   }

   const glm::vec3 &position = gameObject.getCameraComponent().getCameraPosition();
   const glm::vec3 &front = gameObject.getCameraComponent().getFrontVector();
   const glm::vec3 &right = gameObject.getCameraComponent().getRightVector();

   SPtr<GameObject> projectile(std::make_shared<GameObject>());
   projectile->setPosition(position + front + right * 0.25f);
   projectile->setScale(glm::vec3(PROJECTILE_SCALE));

   // Graphics
   SPtr<Model> playerModel = gameObject.getGraphicsComponent().getModel();
   SPtr<Mesh> mesh = Context::getInstance().getAssetManager().loadMesh("meshes/rock_attack.obj");
   glm::vec3 color(1.0f, 0.75f, 0.15f);
   PlayerLogicComponent *playerLogic = dynamic_cast<PlayerLogicComponent*>(&gameObject.getLogicComponent());
   if (playerLogic) {
      color = playerLogic->getColor();
   }
   SPtr<Material> material(std::make_shared<PhongMaterial>(color * 0.2f, color * 0.6f, glm::vec3(0.2f), color * 0.2f, 50.0f));
   SPtr<Model> model(std::make_shared<Model>(playerModel->getShaderProgram(), mesh));
   model->attachMaterial(material);
   projectile->setGraphicsComponent(std::make_shared<GeometricGraphicsComponent>(*projectile));
   projectile->getGraphicsComponent().setModel(model);

   // Physics
   projectile->setPhysicsComponent(std::make_shared<MeshPhysicsComponent>(*projectile, 0.05f, CollisionGroup::Projectiles, CollisionGroup::Everything));
   btRigidBody *projectileRigidBody = dynamic_cast<btRigidBody*>(projectile->getPhysicsComponent().getCollisionObject());
   projectileRigidBody->setFriction(1.0f);
   projectileRigidBody->setRollingFriction(0.25f);
   projectileRigidBody->setRestitution(0.5f);
   projectileRigidBody->applyCentralForce(toBt(front * 100.0f));

   // Logic
   SPtr<ProjectileLogicComponent> logic(std::make_shared<ProjectileLogicComponent>(*projectile));
   WPtr<GameObject> wProjectile(projectile);
   GameObject &creator = gameObject;
   logic->setCollisionCallback([wProjectile, color, &creator](GameObject &gameObject, const btCollisionObject *objectCollidedWidth, const float dt) {
      if (objectCollidedWidth == creator.getPhysicsComponent().getCollisionObject()) {
         return;
      }

      SPtr<Scene> scene = gameObject.getScene().lock();
      if (!scene) {
         return;
      }

      SPtr<GameObject> projectile = wProjectile.lock();
      if (!projectile) {
         return;
      }

      scene->removeObject(projectile);

      SPtr<GameObject> explosion(createExplosion(projectile->getPosition(), 1.0f, color));
      scene->addLight(explosion);
      scene->addObject(explosion);
   });
   projectile->setLogicComponent(logic);

   // Audio
   SPtr<AudioComponent> audioComponent(std::make_shared<AudioComponent>(*projectile));
   audioComponent->registerSoundEvent(Event::SET_SCENE, SoundGroup::THROW);
   projectile->setAudioComponent(audioComponent);

   scene->addObject(projectile);

   resetTimeSinceLastUse();

   return true;
}
Ejemplo n.º 19
0
MaterialID ResourceManagerImpl::new_material_from_file(const unicode& path) {
    //Load the material
    auto mat = material(new_material());
    window().loader_for(path.encode())->into(*mat);
    return mat->id();
}
Ejemplo n.º 20
0
	void Seal::construct()
	{
		imaged = nullptr;
		piece_size(200.0f);
		z = 0.0f;
		set_scale(1.0f);
		radian = 0.0f;

		material().Diffuse.a = 1.0f;
		material().Diffuse.r = 1.0f;
		material().Diffuse.g = 1.0f;
		material().Diffuse.b = 1.0f;

		material().Ambient.a = 1.0f;
		material().Ambient.r = 1.0f;
		material().Ambient.g = 1.0f;
		material().Ambient.b = 1.0f;

		material().Specular.a = 0.0f;
		material().Specular.r = 0.0f;
		material().Specular.g = 0.0f;
		material().Specular.b = 0.0f;

		material().Emissive.a = 0.0f;
		material().Emissive.r = 0.0f;
		material().Emissive.g = 0.0f;
		material().Emissive.b = 0.0f;

		material().Power = 1.0f;

		computed_world_mat = false;
	}
ccMesh* DistanceMapGenerationTool::ConvertProfileToMesh(ccPolyline* profile,
														const ccGLMatrix& cloudToSurface,
														bool counterclockwise,
														unsigned angularSteps/*=36*/,
														QImage mapTexture/*=QImage()*/)
{
	if (!profile || angularSteps < 3)
	{
		return 0;
	}

	//profile vertices
	CCLib::GenericIndexedCloudPersist* profileVertices = profile->getAssociatedCloud();
	unsigned profVertCount = profileVertices->size();
	if (profVertCount < 2)
	{
		return 0;
	}

	//profile meta-data
	ProfileMetaData profileDesc;
	if (!GetPoylineMetaData(profile, profileDesc))
	{
		assert(false);
		return 0;
	}

	unsigned char Z = static_cast<unsigned char>(profileDesc.revolDim);
	//we deduce the 2 other ('horizontal') dimensions
	const unsigned char X = (Z < 2 ? Z+1 : 0);
	const unsigned char Y = (X < 2 ? X+1 : 0);

	unsigned meshVertCount = profVertCount * angularSteps;
	unsigned meshFaceCount = (profVertCount-1) * angularSteps * 2;
	ccPointCloud* cloud = new ccPointCloud("vertices");
	ccMesh* mesh = new ccMesh(cloud);
	if (!cloud->reserve(meshVertCount) || !mesh->reserve(meshFaceCount))
	{
		//not enough memory
		delete cloud;
		delete mesh;
		return 0;
	}

	ccGLMatrix surfaceToCloud = cloudToSurface.inverse();

	//create vertices
	{
		double cwSign = (counterclockwise ? -1.0 : 1.0);
		for (unsigned j=0; j<angularSteps; ++j)
		{
			double angle_rad = static_cast<double>(j)/angularSteps * (2*M_PI);

			CCVector3d N(sin(angle_rad) * cwSign,
						 cos(angle_rad),
						 0);

			for (unsigned i=0; i<profVertCount; ++i)
			{
				const CCVector3* P = profileVertices->getPoint(i);
				double radius = static_cast<double>(P->x);

				CCVector3 Pxyz;
				Pxyz.u[X] = static_cast<PointCoordinateType>(radius * N.x);
				Pxyz.u[Y] = static_cast<PointCoordinateType>(radius * N.y);
				Pxyz.u[Z] = P->y + profileDesc.heightShift;

				surfaceToCloud.apply(Pxyz);

				cloud->addPoint(Pxyz);
			}
		}
		mesh->addChild(cloud);
	}

	PointCoordinateType h0 = profileVertices->getPoint(0)->y;
	PointCoordinateType dH = profileVertices->getPoint(profVertCount-1)->y - h0;
	bool invertedHeight = (dH < 0);

	//create facets
	{
		for (unsigned j=0; j<angularSteps; ++j)
		{
			unsigned nextJ = ((j+1) % angularSteps);
			for (unsigned i=0; i+1<profVertCount; ++i)
			{
				unsigned vertA = j*profVertCount+i;
				unsigned vertB = nextJ*profVertCount+i;
				unsigned vertC = vertB+1;
				unsigned vertD = vertA+1;

				if (invertedHeight)
				{
					mesh->addTriangle(vertB,vertC,vertD);
					mesh->addTriangle(vertB,vertD,vertA);
				}
				else
				{
					mesh->addTriangle(vertB,vertD,vertC);
					mesh->addTriangle(vertB,vertA,vertD);
				}
			}
		}
	}

	//do we have a texture as well?
	if (!mapTexture.isNull())
	{
		//texture coordinates
		TextureCoordsContainer* texCoords = new TextureCoordsContainer();
		mesh->addChild(texCoords);
		if (!texCoords->reserve(meshVertCount+profVertCount)) //we add a column for correct wrapping!
		{
			//not enough memory to finish the job!
			return mesh;
		}

		//create default texture coordinates
		for (unsigned j=0; j<=angularSteps; ++j)
		{
			float T[2] = {static_cast<float>(j)/static_cast<float>(angularSteps), 0.0f};
			for (unsigned i=0; i<profVertCount; ++i)
			{
				T[1] = (profileVertices->getPoint(i)->y - h0) / dH;
				if (invertedHeight)
					T[1] = 1.0f - T[1];
				texCoords->addElement(T);
			}
		}

		if (!mesh->reservePerTriangleTexCoordIndexes())
		{
			//not enough memory to finish the job!
			return mesh;
		}
		
		//set texture indexes
		{
			for (unsigned j=0; j<angularSteps; ++j)
			{
				unsigned nextJ = ((j+1)/*% angularSteps*/);
				for (unsigned i=0; i+1<profVertCount; ++i)
				{
					unsigned vertA = j*profVertCount+i;
					unsigned vertB = nextJ*profVertCount+i;
					unsigned vertC = vertB+1;
					unsigned vertD = vertA+1;

					if (invertedHeight)
					{
						mesh->addTriangleTexCoordIndexes(vertB,vertC,vertD);
						mesh->addTriangleTexCoordIndexes(vertB,vertD,vertA);
					}
					else
					{
						mesh->addTriangleTexCoordIndexes(vertB,vertD,vertC);
						mesh->addTriangleTexCoordIndexes(vertB,vertA,vertD);
					}
				}
			}
		}
	
		//set material indexes
		if (!mesh->reservePerTriangleMtlIndexes())
		{
			//not enough memory to finish the job!
			mesh->removeChild(texCoords);
			mesh->removePerTriangleTexCoordIndexes();
			return mesh;
		}
		for (unsigned i=0; i<meshFaceCount; ++i)
		{
			mesh->addTriangleMtlIndex(0);
		}

		//set material
		{
			ccMaterial::Shared material(new ccMaterial("texture"));
			material->setTexture(mapTexture, QString(), false);

			ccMaterialSet* materialSet = new ccMaterialSet();
			materialSet->addMaterial(material);

			mesh->setMaterialSet(materialSet);
		}

		mesh->setTexCoordinatesTable(texCoords);
		mesh->showMaterials(true);
		mesh->setVisible(true);
		cloud->setVisible(false);
	}

	return mesh;
}
Ejemplo n.º 22
0
circle::circle()
:shape("standard circle", material()), center_(0,0,0), p1_(1,1,0), p2_(1,0,0), radius_(get_radius())
{
    //ctor
}
void InstancedHistogramScene::initialise()
{
#if !defined(Q_OS_MAC)
    // Resolve the OpenGL 3.3 functions that we need for instanced rendering
    m_funcs = m_context->versionFunctions<QOpenGLFunctions_3_3_Compatibility>();
    if ( !m_funcs )
        qFatal( "Could not obtain required OpenGL context version" );
    m_funcs->initializeOpenGLFunctions();
#else
    m_funcs = m_context->versionFunctions<QOpenGLFunctions_2_1>();
    if ( !m_funcs )
        qFatal( "Could not obtain required OpenGL context version" );
    m_funcs->initializeOpenGLFunctions();

    m_instanceFuncs = new QOpenGLExtension_ARB_instanced_arrays();
    m_instanceFuncs->initializeOpenGLFunctions();

    m_drawInstanced = new QOpenGLExtension_ARB_draw_instanced();
    m_drawInstanced->initializeOpenGLFunctions();
#endif

    // Create a Material we can use to operate on instanced geometry
    MaterialPtr material( new Material );
#if !defined(Q_OS_MAC)
    material->setShaders( ":/shaders/instancedhistogram.vert",
                          ":/shaders/instancedhistogram.frag" );
#else
    material->setShaders( ":/shaders/instancedhistogram_2_1.vert",
                          ":/shaders/instancedhistogram_2_1.frag" );
#endif

    // Create a cube
    m_cube = new Cube;
    m_cube->setMaterial( material );
    m_cube->create();

    // Create a VBO ready to hold our data
    prepareVertexBuffers();

    // Tell OpenGL how to pass the data VBOs to the shader program
    prepareVertexArrayObject();

    // Use a sphere for the background - we'll render the scene
    // inside the sphere
    MaterialPtr noiseMaterial( new Material );
#if !defined(Q_OS_MAC)
    noiseMaterial->setShaders( ":/shaders/noise.vert",
                               ":/shaders/noise.frag" );
#else
    noiseMaterial->setShaders( ":/shaders/noise_2_1.vert",
                               ":/shaders/noise_2_1.frag" );
#endif

    m_sphere = new Sphere;
    m_sphere->setMaterial( noiseMaterial );
    m_sphere->create();

    m_sphereModelMatrix.setToIdentity();
    m_sphereModelMatrix.scale( 30.0f );

    // Enable depth testing to prevent artifacts
    glEnable( GL_DEPTH_TEST );
}
Ejemplo n.º 24
0
 void keyboard(unsigned char key, int x, int y)
{
    //control de teclas que hacen referencia a Escalar y transladar el cubo en los ejes X,Y,Z.
    switch (key)
    {
		
    case 'c':
    
   //Propiedades del material cooper
        mat_amb0 = 0.19125;
        mat_amb1 = 0.0735;
        mat_amb2 = 0.0225;
        mat_diff0 = 0.70388;
        mat_diff1 = 0.27048;
        mat_diff2 = 0.0828;
        mat_spec0 = 0.25677;
        mat_spec1 = 0.137622;
        mat_spec2 = 0.086014;
        shin =0.1;
        material(mat_amb0,mat_amb1,mat_amb2,mat_diff0,mat_diff1,mat_spec0,mat_spec1,mat_spec2,shin);  
        break;
        
    case 'r':
    
   //Propiedades del material red plastic
        mat_amb0 = 0.0;
        mat_amb1 = 0.0;
        mat_amb2 = 0.0;
        mat_diff0 = 0.5;
        mat_diff1 = 0.0;
        mat_diff2 = 0.0;
        mat_spec0 = 0.7;
        mat_spec1 = 0.6;
        mat_spec2 = 0.6;
        shin =0.25;
        material(mat_amb0,mat_amb1,mat_amb2,mat_diff0,mat_diff1,mat_spec0,mat_spec1,mat_spec2,shin);  
        break;
   
   case 'g':
    
   //Propiedades del material gold
        mat_amb0 = 0.24725;
        mat_amb1 = 0.1995;
        mat_amb2 = 0.0745;
        mat_diff0 = 0.75164;
        mat_diff1 = 0.60648;
        mat_diff2 = 0.22648;
        mat_spec0 = 0.628281;
        mat_spec1 = 0.555802;
        mat_spec2 = 0.366065;
        shin =0.4;
        material(mat_amb0,mat_amb1,mat_amb2,mat_diff0,mat_diff1,mat_spec0,mat_spec1,mat_spec2,shin);  
        break;
   
    case 'b':
    
   //Propiedades del material brass
        mat_amb0 = 0.329412;
        mat_amb1 = 0.223529;
        mat_amb2 = 0.027451;
        mat_diff0 = 0.780392;
        mat_diff1 = 0.568627;
        mat_diff2 = 0.113725;
        mat_spec0 = 0.992157;
        mat_spec1 = 0.941176;
        mat_spec2 = 0.807843;
        shin =0.21794872;
        material(mat_amb0,mat_amb1,mat_amb2,mat_diff0,mat_diff1,mat_spec0,mat_spec1,mat_spec2,shin);  
        break;
        case 's':
    
   //Propiedades del material silver
        mat_amb0 = 0.19225;
        mat_amb1 = 0.19225;
        mat_amb2 = 0.19225;
        mat_diff0 = 0.50754;
        mat_diff1 = 0.50754;
        mat_diff2 = 0.50754;
        mat_spec0 = 0.508273;
        mat_spec1 = 0.508273;
        mat_spec2 = 0.508273;
        shin =0.4;
        material(mat_amb0,mat_amb1,mat_amb2,mat_diff0,mat_diff1,mat_spec0,mat_spec1,mat_spec2,shin);  
        break;
        
    case 'q':
        exit(0);			// exit
    }
  glutPostRedisplay();   
} 
Ejemplo n.º 25
0
void materialFrontBack() {
  material(Vector4(0.1,0.1,0.1,1),Vector3(0.8,0.1,0.0),Vector3(0.6,0.6,0.6),200);
  diffuseBackColor=Vector3(0,0.8,0);
}
    //! Sets the material used to render this object by name.
    //! @param name the name of the material
    inline void material(const std::string& name) {
		material(engine_->material(name));
	}
Ejemplo n.º 27
0
bool Quadric::intersect(const Ray& ray, Intersection& inter) const
{   
    float  acoef, bcoef, ccoef; // Intersection coefficents
    float  dx, dy, dz; // Direction - origin coordinates
    float  disc; // Distance to intersection
    float  root; // Root of distance to intersection
    float  t; // Distance along ray to intersection
    float  x0, y0, z0; // Origin coordinates

    dx = ray.d.x;
    dy = ray.d.y;
    dz = ray.d.z;

    x0 = ray.o.x;
    y0 = ray.o.y;
    z0 = ray.o.z;

    // Ax2 + By2 + Cz2 + Dxy+ Exz + Fyz + Gx + Hy + Iz + J = 0
    acoef = a * dx * dx +
            b * dy * dy +
            c * dz * dz +
            d * dx * dy +
            e * dx * dz +
            f * dy * dz;

    bcoef = 2 * a * x0 * dx +
            2 * b * y0 * dy +
            2 * c * z0 * dz +
            d * (x0 * dy + y0 * dx) +
            e * (x0 * dz + z0 * dx) +
            f * (y0 * dz + dy * z0) +
            g * dx +
            h * dy +
            i * dz;

    ccoef = a * x0 * x0 +
            b * y0 * y0 +
            c * z0 * z0 +
            d * x0 * y0 +
            e * x0 * z0 +
            f * y0 * z0 +
            g * x0 +
            h * y0 +
            i * z0 + j;

    if ( 1.0 + acoef == 1.0 ) {
        if ( 1.0 + bcoef == 1.0 )
            return false;
        t = ( -ccoef ) / ( bcoef );
    } else {
        disc = bcoef * bcoef - 4 * acoef * ccoef;
        if ( 1.0 + disc < 1.0 )
            return false;
        root = sqrt( disc );
        t = ( -bcoef - root ) / ( acoef + acoef );
        if ( t < 0.0 )
            t = ( -bcoef + root ) / ( acoef + acoef );
    }

    if (t < 0.001)
        return false;

    inter.p = {x0 + t * dx, y0 + t * dy, z0 + t * dz};
    inter.n = normal(inter.p);
    inter.m = material();

    return true;
}
Ejemplo n.º 28
0
void VDBLinearFEMSolverModule<LatticeType>::updateStencil() {

    if(!m_obj) {
        std::cout << "No object set... shouldn't be updating stencil" << std::endl;
        return;
    }

    const LatticeType& vL = m_obj->getDOFs();
    m_vertex_neighbors.resize(3*vL.activeCount());
    std::vector<int>::iterator begin=m_vertex_neighbors.begin();
    std::vector<int>::iterator end=m_vertex_neighbors.end();
    std::fill(begin,end,0);
    ActiveLatticeIterator a = m_obj->activeVertexIterator();

    int totalReserve = 0;
    for(ActiveLatticeIterator active = a; active; ++active) {
        for(int32_t m=-1; m < 2; ++m) {
            for(int32_t n=-1; n < 2; ++n) {
                for(int32_t l=-1; l < 2; ++l) {
                    //if((m & n & l) == 0) 
                    SIndex3 tmp = active.index() + SIndex3(m,n,l);
                    //if(!m_obj->validVertexIndex3(tmp)) continue;
                    if(m_obj->getVertex(tmp.i,tmp.j,tmp.k) != -1) {
                        m_vertex_neighbors[3*active.value()] += 1;
                        m_vertex_neighbors[3*active.value()+1] += 1;
                        m_vertex_neighbors[3*active.value()+2] += 1;
                        totalReserve+=3;
                    }

                }
            }
        }
    }
    int numDOFs = 3*vL.activeCount();
    int32_t NI=vL.NI();
    int32_t NJ=vL.NJ();
    int32_t NK=vL.NK();
    std::cout << "Allocating sparse matrix of size: " << numDOFs << std::endl;
    M = SparseMatrix(numDOFs,numDOFs);
    rhs = Vector::Zero(numDOFs);
    //Pre-reserve the places where we will have fillin
    M.reserve(m_vertex_neighbors);


    typedef Eigen::Triplet<Scalar> Triplet;
    typedef std::vector<Triplet> Triplets;
    Triplets triplets;
    triplets.reserve(totalReserve);
    std::vector<bool> used_constraints(numDOFs);
    //rms::ScalarGrid::ConstAccessor accessor = GetDistanceGrid()->getConstAccessor();
    rms::VectorGridPtr velocityFieldPtr = m_obj->getVectorField();
    rms::ScalarGridPtr rigidFieldPtr = m_obj->getRigidField();
    rms::ScalarGridPtr heatFieldPtr = m_obj->getHeatField();
    rms::RGBAGridPtr materialFieldPtr = m_obj->getMaterialField();
    rms::ScalarGrid::ConstAccessor heatAccessor = heatFieldPtr->getConstAccessor();
    rms::ScalarGrid::ConstAccessor rigidAccessor = rigidFieldPtr->getConstAccessor();
    rms::RGBAGrid::ConstAccessor materialAccessor = materialFieldPtr->getConstAccessor();
    rms::VectorGrid::ConstAccessor velocityAccessor = velocityFieldPtr->getConstAccessor();
    int count=0;

    std::cout << "About to look at heat field" << std::endl;
    Scalar scale = heatFieldPtr->transform().voxelVolume();
    std::set<int32_t> used_vertex;
    StiffnessEntryStorage store(scale,integrator);//TODO: need to fix this
    std::cout << "Mincoord: " << m_minCoord << std::endl;
    vdb::CoordBBox bbox = m_obj->getDistanceField()->evalActiveVoxelBoundingBox();
    std::cout << bbox.min() << " " << bbox.max() << std::endl;
    m_minCoord = bbox.min();
    for(rms::ScalarGrid::ValueOnCIter it =  m_obj->getDistanceField()->cbeginValueOn(); it; ++it) {
        if(it.getValue() >= 0) continue;
        /*
        if(count++ % 1000 == 0) {
            std::cout << count << "/" << numDOFs << std::endl;
        }
        */
        std::cout << "Working in voxel: " << it.getCoord() << std::endl;
        Index3 idx = VDBtoLatticeCoord(it.getCoord());
        //std::cout << "True index: " << idx << " " << it.getCoord() << std::endl;
        /*
           if(m_obj->getVertex(idx.i,idx.j,idx.k) == -1) {
           std::cout << "bottomleftinner lattice index doesn't exist, clearly lattice just isn't populated"<< std::endl;
           }
         */
        const vdb::Coord vdbcoord = m_minCoord + vdb::Coord(idx.i,idx.j,idx.k);

        vdb::Vec4f material = materialAccessor.getValue(vdbcoord);
        vdb::Vec3f velocity = velocityAccessor.getValue(vdbcoord);
        float lambda = material(0);
        float mu = material(1);
        float density = material(3) * 0.125;//Divide because each basis function only takes on 1/8th of a whole cube
        for(VDBVoxelNodeIterator<LatticeType> alpha(m_obj->getDOFs(),idx); alpha; ++alpha) {
            const Index3 & alpha_index = alpha.index();
            const vdb::Coord alpha_vdbcoord = m_minCoord + vdb::Coord(alpha_index.i,alpha_index.j,alpha_index.k);
            const int32_t alpha_value = alpha.value();
            const int32_t alphaind = mat_ind(alpha_value,0);
            //const LinearElasticVertexProperties & alpha_props = m_vertex_properties[alpha_value];
            //alpha sets the matrix, betas set the rhs values for alpha
            std::cout << alpha_vdbcoord << ": ";
            if(rigidAccessor.getValue(alpha_vdbcoord) < 0) {
                std::cout << "Rigid!" << std::endl;
                if(used_vertex.find(alpha_value) == used_vertex.end()) {
                    used_vertex.insert(alpha_value);
                    const int32_t ind = alphaind;
                    triplets.push_back(Triplet(ind,ind,1));
                    triplets.push_back(Triplet(ind+1,ind+1,1));
                    triplets.push_back(Triplet(ind+2,ind+2,1));
                    std::cout << rhs(alphaind+0) << " ";
                    std::cout << rhs(alphaind+1) << " ";
                    std::cout << rhs(alphaind+2) << std::endl;
                }
            } else {
                std::cout << "Elastic!" << std::endl;
                rhs(alphaind+0) += velocity(0)*density;
                rhs(alphaind+1) += velocity(1)*density;
                rhs(alphaind+2) += velocity(2)*density;
                //std::cout << velocity << std::endl;
                for(VDBVoxelNodeIterator<LatticeType> beta(m_obj->getDOFs(),idx); beta; ++beta) {
                    const Index3 & beta_index = beta.index();
                    const int32_t beta_value = beta.value();
                    /*
                       if(alpha_value < 0 || beta_value < 0) {
                       std::cout << "WTF Shouldn't be finding vertices out of nowhere..." << alpha_value << " " << beta_value << ": " << it.getCoord()<< ":A" << alpha_index << ":B" << beta_index << std::endl;
                       std::cout << idx << " " << it.getCoord() << std::endl;
                       }*/

                    //const LinearElasticVertexProperties & beta_props = m_vertex_properties[beta_value];
                    //const Vector3 beta_externalForce = beta_props.externalForce;
                    const vdb::Coord beta_vdbcoord = m_minCoord + vdb::Coord(beta_index.i,beta_index.j,beta_index.k);
                    if(rigidAccessor.getValue(beta_vdbcoord) > 0) {
                        for(int32_t alphadim = 0; alphadim < 3; ++alphadim) {
                            const int32_t alpha_i = mat_ind(alpha_value,alphadim);
                            for(int32_t betadim = 0; betadim < 3; ++betadim) {
                                const int32_t beta_i = mat_ind(beta_value,betadim);
                                const Scalar v = store.genericTerm(alpha.pos(), beta.pos(), alphadim, betadim,lambda,mu);

                                triplets.push_back(Triplet(alpha_i,beta_i,
                                            (
                                             v
                                            )
                                            ));

                            }
                        }
                    }
                    /*
                       const SIndex3 rel_alpha = alpha_index - idx;
                       const int32_t ind_alpha = rel_alpha.i * 4 + rel_alpha.j * 2 + rel_alpha.k;

                       const SIndex3 rel_beta = beta_index - idx;
                       const int32_t ind_beta = rel_beta.i * 4 + rel_beta.j * 2 + rel_beta.k;
                     */
                    //const Scalar diag = integrator.i(boost::bind(&StiffnessEntryFunctor::diagonalTermi
                    const Scalar diag = store.diagonalTerm(alpha.pos(), beta.pos(), mu);
                    for(int32_t dim = 0; dim < 3; ++dim) {
                        const int32_t ai = mat_ind(alpha_value,dim);
                        const int32_t bi = mat_ind(beta_value,dim);
                        triplets.push_back(Triplet(ai,bi,
                                    (
                                     diag
                                    )
                                    ));

                    }
                }
            }
        }
    }
    //std::cout << rhs.transpose() << std::endl;
    std::cout << "Number of matrix etdntries (with duplicates): " << triplets.size() << std::endl;

    M.setFromTriplets(triplets.begin(),triplets.end());
    M.prune(1,Eigen::NumTraits<Scalar>::dummy_precision());
    //std::cout << M << std::endl;
}
Ejemplo n.º 29
0
 void setTexture(const std::shared_ptr<render::Texture2D>& texture)
 { material()->textures()->at(0) = validate(texture); }
Ejemplo n.º 30
0
//==============================================================================
// MAIN
int main( int argc, char* argv[] )
{
    // spatial dimension
    const unsigned    dim = SPACEDIM; 

    typedef base::solver::Eigen3           Solver;
    
    // Check input arguments
    if ( argc != 2 ) {
        std::cerr << "Usage: " << argv[0] << " input.dat\n"
                  << "(Compiled for dim=" << dim << ")\n\n";
        return -1;
    }
    
    // read name of input file
    const std::string   inputFile = boost::lexical_cast<std::string>( argv[1] );
    const InputNucleus<dim> ui( inputFile );

    // Simulation attributes
    const bool simplex = false;
    const bool stokesStabil = false;
    typedef mat::hypel::NeoHookeanCompressible Material;
    typedef TypesAndAttributes<dim,simplex>    TA;

    // basic attributes of the computation
    base::auxi::BoundingBox<dim> bbox( ui.bbmin, ui.bbmax );
    
    TA::Mesh mesh;
    generateMesh( mesh, ui );

    // Creates a list of <Element,faceNo> pairs
    base::mesh::MeshBoundary meshBoundary;
    meshBoundary.create( mesh.elementsBegin(), mesh.elementsEnd() );

    TA::BoundaryMesh boundaryMesh;
    base::mesh::generateBoundaryMesh( meshBoundary.begin(),
                                      meshBoundary.end(),
                                      mesh, boundaryMesh );


    // mesh size (all equal, more or less)
    const double h = base::mesh::Size<TA::Mesh::Element>::apply( mesh.elementPtr(0) );

    //--------------------------------------------------------------------------
    typedef base::cut::LevelSet<dim> LevelSet;
    std::vector<LevelSet> levelSetNucleus, levelSetMembrane;
    base::cut::analyticLevelSet( mesh,
                                 base::cut::Sphere<dim>( ui.RN, ui.centerN ),
                                 true, levelSetNucleus );
    base::cut::analyticLevelSet( mesh,
                                 base::cut::Sphere<dim>( ui.RM, ui.centerM ),
                                 true, levelSetMembrane );

    //--------------------------------------------------------------------------
    // make cut cell structures
    std::vector<TA::Cell> cellsNucleus, cellsMembrane, cellsCS;
    base::cut::generateCutCells( mesh, levelSetNucleus,  cellsNucleus );
    base::cut::generateCutCells( mesh, levelSetMembrane, cellsMembrane );
    
    {
        cellsCS = cellsNucleus;
        std::for_each( cellsCS.begin(), cellsCS.end(),
                       boost::bind( &TA::Cell::reverse, _1 ) );

        base::cut::generateCutCells( mesh, levelSetMembrane, cellsCS,
                                     base::cut::INTERSECT );
    }

    // intersection with the box boundary
    std::vector<TA::SurfCell> surfaceCells;
    base::cut::generateCutCells( boundaryMesh, levelSetMembrane, surfaceCells );

    // Elastic material
    Material material( mat::Lame::lambda( ui.E, ui.nu),
                       mat::Lame::mu(     ui.E, ui.nu ) );

    // Solid and fluid handlers
    typedef Solid<TA::Mesh, Material>                        Solid;
    typedef Fluid<TA::Mesh, stokesStabil>                    Fluid;
    typedef SolidFluidInterface<TA::SurfaceMesh,Solid,Fluid> SFI;
    typedef FluidFluidInterface<TA::SurfaceMesh,Fluid>       FFI;
    
    Solid nucleus(      mesh, material );
    Fluid gel(          mesh, ui.viscosityGel, ui.alpha );
    Fluid cytoSkeleton( mesh, ui.viscosityCS,  ui.alpha );

    // find geometry association for the dofs
    std::vector<std::pair<std::size_t,TA::VecDim> > doFLocationD, doFLocationU;
    base::dof::associateLocation( nucleus.getDisplacement(), doFLocationD );
    base::dof::associateLocation( gel.getVelocity(),       doFLocationU );

    // Quadrature along a surface
    TA::CutQuadrature     cutQuadratureNucleus( cellsNucleus,  true  ); 
    TA::CutQuadrature     cutQuadratureGel(     cellsMembrane, false );
    TA::CutQuadrature     cutQuadratureCS(      cellsCS,       true  );
    TA::SurfaceQuadrature surfaceQuadrature;
    TA::SurfCutQuadrature surfaceCutQuadrature( surfaceCells, true );

    //--------------------------------------------------------------------------
    // Run a zero-th step in order to write the data before computation
    // (store the previously enclosed volume)
    double prevVolumeN, initialVolumeCS;
    {
        std::cout << 0 << "  " << 0. << "  0  " << std::flush;

        writeVTKFile( "nucleus", 0, mesh,
                      nucleus.getDisplacement(),
                      cytoSkeleton.getVelocity(), cytoSkeleton.getPressure(),
                      gel.getVelocity(),          gel.getPressure(),
                      levelSetNucleus, levelSetMembrane,  ui.dt );

        // for surface field
        TA::SurfaceMesh membrane, envelope;
        base::cut::generateSurfaceMesh<TA::Mesh,TA::Cell>( mesh, cellsMembrane, membrane );
        base::cut::generateSurfaceMesh<TA::Mesh,TA::Cell>( mesh, cellsNucleus,  envelope );

        writeSurfaceVTKFile( "membrane", 0, membrane );
        writeSurfaceVTKFile( "envelope", 0, envelope );
            
        surfaceFeatures( boundaryMesh, membrane, envelope,
                         surfaceQuadrature, surfaceCutQuadrature, std::cout );
        std::cout << std::endl;

        // store the contained volume
        prevVolumeN     = surf::enclosedVolume( envelope, surfaceQuadrature );
        initialVolumeCS =
            surf::enclosedVolume( membrane, surfaceQuadrature ) +
            surf::enclosedVolume( boundaryMesh, surfaceCutQuadrature );
    }

    //--------------------------------------------------------------------------
    // * Loop over time steps *
    //--------------------------------------------------------------------------
    const double supportThreshold = std::numeric_limits<double>::min();
    for ( unsigned step = 0; step < ui.numLoadSteps; step++ ) {
        
        // for surface field
        TA::SurfaceMesh membrane, envelope;
        base::cut::generateSurfaceMesh<TA::Mesh,TA::Cell>( mesh, cellsMembrane, membrane );
        base::cut::generateSurfaceMesh<TA::Mesh,TA::Cell>( mesh, cellsNucleus,  envelope );

        // Interface handler
        SFI envelopeHandler( envelope,
                             nucleus.getDisplacement(),
                             cytoSkeleton.getVelocity(), cytoSkeleton.getPressure(),
                             ui.viscosityCS );
        
        FFI membraneHandler( membrane,
                             cytoSkeleton.getVelocity(), cytoSkeleton.getPressure(),
                             gel.getVelocity(), gel.getPressure(),
                             cellsMembrane, 
                             ui.viscosityCS, ui.viscosityGel, ui.sigma );

        std::cout << step+1 << "  " << (step+1) * ui.dt << "  " << std::flush;

        //----------------------------------------------------------------------
        // 0) Solve Lagrangian problem
        
        // compute supports
        std::vector<double> supportsD, supportsUCS, supportsPCS, supportsUGel, supportsPGel;
        base::cut::supportComputation( mesh, nucleus.getDisplacement(),
                                       cutQuadratureNucleus, supportsD );
        base::cut::supportComputation( mesh, cytoSkeleton.getVelocity(),
                                       cutQuadratureCS, supportsUCS );
        base::cut::supportComputation( mesh, cytoSkeleton.getPressure(),
                                       cutQuadratureCS, supportsPCS );
        base::cut::supportComputation( mesh, gel.getVelocity(),
                                       cutQuadratureGel, supportsUGel );
        base::cut::supportComputation( mesh, gel.getPressure(),
                                       cutQuadratureGel, supportsPGel );

        // Hard-wired Dirichlet constraints (fluid BC)
        {
            // apply to outer material = gel
            base::dof::constrainBoundary<Fluid::FEBasisU>(
                meshBoundary.begin(),
                meshBoundary.end(),
                mesh, gel.getVelocity(),
                boost::bind( &dirichletBC<dim,Fluid::DoFU>,
                             _1, _2, ui.ubar, bbox, ui.bc ) );

            // in case of boundary intersections, apply to cytoskeleton
            base::dof::constrainBoundary<Fluid::FEBasisU>(
                meshBoundary.begin(),
                meshBoundary.end(),
                mesh, cytoSkeleton.getVelocity(),
                boost::bind( &dirichletBC<dim,Fluid::DoFU>,
                             _1, _2, ui.ubar, bbox, ui.bc ) );

            // Fix first pressure dof in case of closed cavity flow
            if ( ui.bc == CAVITY ) {
                Fluid::Pressure::DoFPtrIter pIter = gel.getPressure().doFsBegin();
                (*pIter) -> constrainValue( 0, 0.0 );
            }
        }
    
        // Basis stabilisation
        base::cut::stabiliseBasis( mesh, nucleus.getDisplacement(),  supportsD,    doFLocationD );
        base::cut::stabiliseBasis( mesh, cytoSkeleton.getVelocity(), supportsUCS,  doFLocationU );
        base::cut::stabiliseBasis( mesh, cytoSkeleton.getPressure(), supportsPCS,  doFLocationD );
        base::cut::stabiliseBasis( mesh, gel.getVelocity(),          supportsUGel, doFLocationU );
        base::cut::stabiliseBasis( mesh, gel.getPressure(),          supportsPGel, doFLocationD );
        
        // number DoFs 
        const std::size_t activeDoFsD = 
            base::dof::numberDoFsConsecutively( nucleus.getDisplacement().doFsBegin(),
                                                nucleus.getDisplacement().doFsEnd() );
        const std::size_t activeDoFsUCS = 
            base::dof::numberDoFsConsecutively( cytoSkeleton.getVelocity().doFsBegin(),
                                                cytoSkeleton.getVelocity().doFsEnd(),
                                                activeDoFsD );
        const std::size_t activeDoFsPCS = 
            base::dof::numberDoFsConsecutively( cytoSkeleton.getPressure().doFsBegin(),
                                                cytoSkeleton.getPressure().doFsEnd(),
                                                activeDoFsD + activeDoFsUCS );
        const std::size_t activeDoFsUGel = 
            base::dof::numberDoFsConsecutively( gel.getVelocity().doFsBegin(),
                                                gel.getVelocity().doFsEnd(),
                                                activeDoFsD + activeDoFsUCS + activeDoFsPCS );
        const std::size_t activeDoFsPGel = 
            base::dof::numberDoFsConsecutively( gel.getPressure().doFsBegin(),
                                                gel.getPressure().doFsEnd(),
                                                activeDoFsD + activeDoFsUCS + activeDoFsPCS +
                                                activeDoFsUGel );


        // start from 0 for the increments, set rest to zero too
        base::dof::clearDoFs( nucleus.getDisplacement() );
        base::dof::clearDoFs( cytoSkeleton.getPressure() );
        base::dof::clearDoFs( cytoSkeleton.getVelocity() );
        base::dof::clearDoFs( gel.getPressure() );
        base::dof::clearDoFs( gel.getVelocity() );

        //----------------------------------------------------------------------
        // Nonlinear iterations
        unsigned iter = 0;
        for ( ; iter < ui.maxIter; iter++ ) {

            // Create a solver object
            Solver solver( activeDoFsD + activeDoFsUCS + activeDoFsPCS +
                           activeDoFsUGel + activeDoFsPGel );

            // register to solver
            nucleus.registerInSolver(      solver );
            cytoSkeleton.registerInSolver( solver );
            gel.registerInSolver(          solver );
            membraneHandler.registerInSolver(     solver );
            envelopeHandler.registerInSolver(     solver );

            // Compute as(d,dd) and Da(d,dd)[Delta d]
            nucleus.assembleBulk( cutQuadratureNucleus, solver, iter );

            // Body force
            nucleus.bodyForce( cutQuadratureNucleus, solver,
                               boost::bind( unitForce<0,dim>, _1, ui.forceValue ) );

            // Computate af(u,p; du,dp)
            cytoSkeleton.assembleBulk( cutQuadratureCS,  solver );
            gel.assembleBulk(          cutQuadratureGel, solver );

            // Penalty terms for int_Gamma (dot(d) - u) (E delta d - mu delta u) ds
            envelopeHandler.assemblePenaltyTerms( surfaceQuadrature, solver, ui.penaltyFac, ui.dt );
            membraneHandler.assemblePenaltyTerms( surfaceQuadrature, solver, ui.penaltyFac );

            // Boundary energy terms (beta = 0)  [ -int_Gamma (...) ds ]
            envelopeHandler.assembleEnergyTerms( surfaceQuadrature, solver, ui.dt );
            membraneHandler.assembleEnergyTerms( surfaceQuadrature, solver );

            // surface tension
            membraneHandler.surfaceTension( surfaceQuadrature, solver );
            

            // Finalise assembly
            solver.finishAssembly();

            // norm of residual
            const double conv1 = solver.norm(0, activeDoFsD) / ui.E;

            if ( isnan( conv1 ) ) return 1;
            
            if ( ( iter > 0 )  and ( conv1 < ui.tolerance ) ) {
                std::cout << "schon" << std::endl;
                break;
            }

            // Solve
#ifdef LOAD_PARDISO
            solver.pardisoLUSolve();
#else

#ifdef LOAD_UMFPACK
            solver.umfPackLUSolve();
#else
            solver.superLUSolve();
            //solver.biCGStabSolve();
#endif
            
#endif
            // distribute results back to dofs
            base::dof::addToDoFsFromSolver( solver, nucleus.getDisplacement() ); //<>
            base::dof::setDoFsFromSolver(   solver, cytoSkeleton.getVelocity() );
            base::dof::setDoFsFromSolver(   solver, cytoSkeleton.getPressure() );
            base::dof::setDoFsFromSolver(   solver, gel.getVelocity() );
            base::dof::setDoFsFromSolver(   solver, gel.getPressure() );

            const double conv2 = solver.norm(0, activeDoFsD);

            if ( conv2 < ui.tolerance ) break;
            
        } // finish non-linear iteration
        std::cout << iter << "  " << std::flush;

        // write a vtk file
        writeVTKFile( "nucleus", step+1, mesh,
                      nucleus.getDisplacement(),
                      cytoSkeleton.getVelocity(), cytoSkeleton.getPressure(),
                      gel.getVelocity(),          gel.getPressure(),
                      levelSetNucleus, levelSetMembrane, ui.dt );
        writeSurfaceVTKFile( "membrane", step+1, membrane );
        writeSurfaceVTKFile( "envelope", step+1, envelope );

        //----------------------------------------------------------------------
        // 1) Pass Data to complementary domain of solid
        {
            const double extL = h; // extrapolation length

            // pass extrapolated solution to inactive DoFs
            extrapolateToFictitious( mesh, nucleus.getDisplacement(),
                                     extL, doFLocationD, levelSetNucleus, bbox );
        }

        //----------------------------------------------------------------------
        // 2) Geometry update
        // a) Nucleus
        {
            // get shape features
            const double volumeN = surf::enclosedVolume( envelope, surfaceQuadrature );
            const TA::VecDim momentN =
                surf::enclosedVolumeMoment( envelope, surfaceQuadrature );
            const TA::VecDim centroidN = momentN / volumeN;

            const double factorN = std::pow( prevVolumeN / volumeN,
                                            1./static_cast<double>( dim ) );
     
            // Move with velocity solution
            moveSurface( mesh, cytoSkeleton.getVelocity(),
                         envelope, ui.dt, factorN, centroidN );

            // compute new level set for envelope of nucleus
            base::cut::bruteForce( mesh, envelope, true, levelSetNucleus );

            // update the cut cell structure
            base::cut::generateCutCells( mesh, levelSetNucleus, cellsNucleus );


            // store the contained volume
            prevVolumeN = surf::enclosedVolume( envelope, surfaceQuadrature );
        }

        // b) CS
        {
            // get shape features
            const double volumeCS =
                surf::enclosedVolume( membrane,  surfaceQuadrature ) +
                surf::enclosedVolume( boundaryMesh, surfaceCutQuadrature );
            const TA::VecDim momentCS =
                surf::enclosedVolumeMoment( membrane, surfaceQuadrature ) +
                surf::enclosedVolumeMoment( boundaryMesh, surfaceCutQuadrature );
            const TA::VecDim centroidCS = momentCS / volumeCS;

            // Move with velocity solution
            moveSurface( mesh, gel.getVelocity(), membrane, ui.dt, 1.0, centroidCS );
            // rescale in order to preserve initial volume
            rescaleSurface( membrane, initialVolumeCS, volumeCS, centroidCS );

            // compute new level set for membrane
            base::cut::bruteForce( mesh, membrane, true, levelSetMembrane );

            // update the cut cell structure
            base::cut::generateCutCells( mesh, levelSetMembrane, cellsMembrane );
            base::cut::generateCutCells( boundaryMesh, levelSetMembrane, surfaceCells );
        }

        // new structure for cytoskeleton
        {
            cellsCS = cellsNucleus;
            std::for_each( cellsCS.begin(), cellsCS.end(),
                           boost::bind( &TA::Cell::reverse, _1 ) );
            
            base::cut::generateCutCells( mesh, levelSetMembrane, cellsCS,
                                         base::cut::INTERSECT );
        }


        //----------------------------------------------------------------------
        // 3) advect data
        {
            base::cut::supportComputation( mesh, nucleus.getDisplacement(),
                                           cutQuadratureNucleus, supportsD ); 
        
            // Find the location of the DoFs in the previous configuration
            std::vector<std::pair<std::size_t,TA::VecDim> > previousDoFLocation;
            findPreviousDoFLocations( mesh, nucleus.getDisplacement(), supportsD, 
                                      doFLocationD, previousDoFLocation, bbox, 
                                      supportThreshold, ui.findTolerance, 10 );
            
            // add previous solution to current solution: u_{n+1} = \Delta u + u_n
            {
                Solid::Displacement::DoFPtrIter dIter = nucleus.getDisplacement().doFsBegin();
                Solid::Displacement::DoFPtrIter dEnd  = nucleus.getDisplacement().doFsEnd();
                for ( ; dIter != dEnd; ++dIter ) {
                    for ( unsigned d = 0; d < dim; d++ ) {
                        const double prevU  = (*dIter) -> getHistoryValue<1>( d );
                        const double deltaU = (*dIter) -> getHistoryValue<0>( d );
                        const double currU = prevU + deltaU;
                        (*dIter) -> setValue( d, currU );
                    }
                }
            }
        
            // advect displacement field from previous to new location
            advectField( mesh, nucleus.getDisplacement(), previousDoFLocation, supportsD, 
                         supportThreshold );
        }

        //----------------------------------------------------------------------
        // push history
        base::dof::pushHistory( nucleus.getDisplacement() );

        // remove the linear constraints used in the stabilisation process
        base::dof::clearConstraints( nucleus.getDisplacement() );
        base::dof::clearConstraints( cytoSkeleton.getVelocity()     );
        base::dof::clearConstraints( cytoSkeleton.getPressure()     );
        base::dof::clearConstraints( gel.getVelocity()     );
        base::dof::clearConstraints( gel.getPressure()     );

        surfaceFeatures( boundaryMesh, membrane, envelope,
                         surfaceQuadrature, surfaceCutQuadrature, std::cout );
        std::cout << std::endl;

    } // end load-steps

    return 0;
}