// Generic load function for both ASCII and binary. Calls // pure-virtual function implemented in subclasses to read // the data from the file. ErrorCode ReadSTL::load_file(const char* filename, const EntityHandle* /* file_set */, const FileOptions& opts, const ReaderIface::SubsetList* subset_list, const Tag* file_id_tag) { if (subset_list) { MB_SET_ERR(MB_UNSUPPORTED_OPERATION, "Reading subset of files not supported for STL"); } ErrorCode result; std::vector<ReadSTL::Triangle> triangles; bool is_ascii = false, is_binary = false; if (MB_SUCCESS == opts.get_null_option("ASCII")) is_ascii = true; if (MB_SUCCESS == opts.get_null_option("BINARY")) is_binary = true; if (is_ascii && is_binary) { MB_SET_ERR(MB_FAILURE, "Conflicting options: BINARY ASCII"); } bool big_endian = false, little_endian = false; if (MB_SUCCESS == opts.get_null_option("BIG_ENDIAN")) big_endian = true; if (MB_SUCCESS == opts.get_null_option("LITTLE_ENDIAN")) little_endian = true; if (big_endian && little_endian) { MB_SET_ERR(MB_FAILURE, "Conflicting options: BIG_ENDIAN LITTLE_ENDIAN"); } ByteOrder byte_order = big_endian ? STL_BIG_ENDIAN : little_endian ? STL_LITTLE_ENDIAN : STL_UNKNOWN_BYTE_ORDER; if (is_ascii) result = ascii_read_triangles(filename, triangles); else if (is_binary) result = binary_read_triangles(filename, byte_order, triangles); else { // Try ASCII first result = ascii_read_triangles(filename, triangles); if (MB_SUCCESS != result) // ASCII failed, try binary result = binary_read_triangles(filename, byte_order, triangles); } if (MB_SUCCESS != result) return result; // Create a std::map from position->handle, and such // that all positions are specified, and handles are zero. std::map<Point, EntityHandle> vertex_map; for (std::vector<Triangle>::iterator i = triangles.begin(); i != triangles.end(); ++i) { vertex_map[i->points[0]] = 0; vertex_map[i->points[1]] = 0; vertex_map[i->points[2]] = 0; } // Create vertices std::vector<double*> coord_arrays; EntityHandle vtx_handle = 0; result = readMeshIface->get_node_coords(3, vertex_map.size(), MB_START_ID, vtx_handle, coord_arrays); if (MB_SUCCESS != result) return result; // Copy vertex coordinates into entity sequence coordinate arrays // and copy handle into vertex_map. double *x = coord_arrays[0], *y = coord_arrays[1], *z = coord_arrays[2]; for (std::map<Point, EntityHandle>::iterator i = vertex_map.begin(); i != vertex_map.end(); ++i) { i->second = vtx_handle; ++vtx_handle; *x = i->first.coords[0]; ++x; *y = i->first.coords[1]; ++y; *z = i->first.coords[2]; ++z; } // Allocate triangles EntityHandle elm_handle = 0; EntityHandle* connectivity; result = readMeshIface->get_element_connect(triangles.size(), 3, MBTRI, MB_START_ID, elm_handle, connectivity); if (MB_SUCCESS != result) return result; // Use vertex_map to recover triangle connectivity from // vertex coordinates. EntityHandle *conn_sav = connectivity; for (std::vector<Triangle>::iterator i = triangles.begin(); i != triangles.end(); ++i) { *connectivity = vertex_map[i->points[0]]; ++connectivity; *connectivity = vertex_map[i->points[1]]; ++connectivity; *connectivity = vertex_map[i->points[2]]; ++connectivity; } // Notify MOAB of the new elements result = readMeshIface->update_adjacencies(elm_handle, triangles.size(), 3, conn_sav); if (MB_SUCCESS != result) return result; if (file_id_tag) { Range vertices(vtx_handle, vtx_handle + vertex_map.size() - 1); Range elements(elm_handle, elm_handle + triangles.size() - 1); readMeshIface->assign_ids(*file_id_tag, vertices); readMeshIface->assign_ids(*file_id_tag, elements); } return MB_SUCCESS; }
ImageBlending::ImageBlending(std::vector<cv::Mat>&& images, std::vector<float>&& focal, std::vector<cv::Matx<float,3,3>>&& transforms) : m_Images(std::forward<std::vector<cv::Mat>>(images)), m_FocalLengths(std::forward<std::vector<float>>(focal)), m_Transforms(std::forward<std::vector<cv::Matx<float,3,3>>>(transforms)) { std::vector<cv::Matx<float,3,3>> invTransforms; invTransforms.reserve(m_Transforms.size()); for (cv::Matx<float,3,3>& mat : m_Transforms) { invTransforms.emplace_back(); cv::invert(mat, invTransforms.back(), cv::DECOMP_SVD); } m_Bounds.reserve(m_Images.size()); for (auto img = m_Images.begin(); img != m_Images.end(); ++img) { int index = img - m_Images.begin(); cv::Matx<float,3,3>& mat = invTransforms[index]; cv::Rect origRect(cv::Point(0,0), img->size()); cv::Mat vertices(4, 1, CV_32FC2), verticesProj; vertices.at<cv::Point2f>(0, 0) = cv::Point2f(0, 0); vertices.at<cv::Point2f>(1, 0) = cv::Point2f(0, img->rows); vertices.at<cv::Point2f>(2, 0) = cv::Point2f(img->cols, img->rows); vertices.at<cv::Point2f>(3, 0) = cv::Point2f(img->cols, 0); cv::perspectiveTransform(vertices, verticesProj, mat); cv::Point topLeft, bottomRight; topLeft = bottomRight = verticesProj.at<cv::Point2f>(0,0); for (int i = 0; i < 4; ++i) { cv::Point2f pt = verticesProj.at<cv::Point2f>(i,0); topLeft.x = std::min(topLeft.x, (int)std::floor(pt.x)); topLeft.y = std::min(topLeft.y, (int)std::floor(pt.y)); bottomRight.x = std::max(bottomRight.x, (int)std::ceil(pt.x)); bottomRight.y = std::max(bottomRight.y, (int)std::ceil(pt.y)); } TransformedRect rect; rect.bound = cv::Rect(topLeft, bottomRight); for (int i = 0; i < 4; ++i) rect.vertex[i] = verticesProj.at<cv::Point2f>(i,0); m_Bounds.push_back(rect); } cv::Rect canvasBound = m_Bounds[0].bound; for (auto& rt : m_Bounds) { canvasBound = canvasBound | rt.bound; } printf("canvas: %d %d %d %d\n", canvasBound.x, canvasBound.y, canvasBound.width, canvasBound.height); for (auto rt = m_Bounds.begin(); rt != m_Bounds.end(); ++rt) { rt->bound.x -= canvasBound.x; rt->bound.y -= canvasBound.y; for (int i = 0; i < 4; ++i) rt->vertex[i] = rt->vertex[i] - cv::Point2f(canvasBound.tl()); cv::Matx<float,3,3>& transform = m_Transforms[rt-m_Bounds.begin()]; cv::Matx<float,3,3> trans; cv::setIdentity(trans); trans(0,2) += canvasBound.x; trans(1,2) += canvasBound.y; transform = transform * trans; //cv::Matx<float,3,3>& h = trans; //for (int i = 0; i < 3; ++i) { // printf(" [ "); // for (int j = 0; j < 3; ++j) // printf("%f ", h(i,j)); // printf("]\n"); //} } canvasBound.x = 0; canvasBound.y = 0; framebuffer.create(canvasBound.size(), CV_8UC3); stencilbuffer.create(canvasBound.size(), CV_8UC1); }
int main(int argc, char *argv[]) { #ifdef HAVE_MPI Teuchos::GlobalMPISession mpiSession(&argc, &argv,0); choice::MpiArgs args( argc, argv ); #else choice::Args args( argc, argv ); #endif int rank = Teuchos::GlobalMPISession::getRank(); int numProcs = Teuchos::GlobalMPISession::getNProc(); int nCells = args.Input<int>("--nCells", "num cells",2); int numRefs = args.Input<int>("--numRefs","num adaptive refinements",0); int numPreRefs = args.Input<int>("--numPreRefs","num preemptive adaptive refinements",0); double eps = args.Input<double>("--epsilon","diffusion parameter",1e-2); int order = args.Input<int>("--order","order of approximation",2); FunctionPtr zero = Function::constant(0.0); FunctionPtr one = Function::constant(1.0); FunctionPtr n = Teuchos::rcp( new UnitNormalFunction ); vector<double> e1,e2; e1.push_back(1.0); e1.push_back(0.0); e2.push_back(0.0); e2.push_back(1.0); //////////////////// DECLARE VARIABLES /////////////////////// // define test variables VarFactory varFactory; VarPtr tau = varFactory.testVar("\\tau", HDIV); VarPtr v = varFactory.testVar("v", HGRAD); // define trial variables VarPtr uhat = varFactory.traceVar("\\widehat{u}"); VarPtr beta_n_u_minus_sigma_n = varFactory.fluxVar("\\widehat{\\beta \\cdot n u - \\sigma_{n}}"); VarPtr u = varFactory.fieldVar("u"); VarPtr sigma1 = varFactory.fieldVar("\\sigma_1"); VarPtr sigma2 = varFactory.fieldVar("\\sigma_2"); vector<double> beta; beta.push_back(1.0); beta.push_back(0.0); //////////////////// DEFINE BILINEAR FORM /////////////////////// BFPtr confusionBF = Teuchos::rcp( new BF(varFactory) ); // tau terms: confusionBF->addTerm(sigma1 / eps, tau->x()); confusionBF->addTerm(sigma2 / eps, tau->y()); confusionBF->addTerm(u, tau->div()); confusionBF->addTerm(uhat, -tau->dot_normal()); // v terms: confusionBF->addTerm( sigma1, v->dx() ); confusionBF->addTerm( sigma2, v->dy() ); confusionBF->addTerm( -u, beta * v->grad() ); confusionBF->addTerm( beta_n_u_minus_sigma_n, v); // first order term with magnitude alpha double alpha = 10.0; confusionBF->addTerm(alpha * u, v); //////////////////// DEFINE INNER PRODUCT(S) /////////////////////// // robust test norm IPPtr robIP = Teuchos::rcp(new IP); FunctionPtr C_h = Teuchos::rcp( new EpsilonScaling(eps) ); FunctionPtr invH = Teuchos::rcp(new InvHScaling); FunctionPtr invSqrtH = Teuchos::rcp(new InvSqrtHScaling); FunctionPtr sqrtH = Teuchos::rcp(new SqrtHScaling); robIP->addTerm(v*alpha); robIP->addTerm(invSqrtH*v); // robIP->addTerm(v); robIP->addTerm(sqrt(eps) * v->grad() ); robIP->addTerm(beta * v->grad() ); robIP->addTerm(tau->div() ); robIP->addTerm(C_h/sqrt(eps) * tau ); LinearTermPtr vVecLT = Teuchos::rcp(new LinearTerm); LinearTermPtr tauVecLT = Teuchos::rcp(new LinearTerm); vVecLT->addTerm(sqrt(eps)*v->grad()); tauVecLT->addTerm(C_h/sqrt(eps)*tau); //////////////////// SPECIFY RHS /////////////////////// Teuchos::RCP<RHSEasy> rhs = Teuchos::rcp( new RHSEasy ); FunctionPtr f = zero; // f = one; rhs->addTerm( f * v ); // obviously, with f = 0 adding this term is not necessary! //////////////////// CREATE BCs /////////////////////// Teuchos::RCP<BCEasy> bc = Teuchos::rcp( new BCEasy ); // SpatialFilterPtr inflowBoundary = Teuchos::rcp( new InflowSquareBoundary ); // SpatialFilterPtr outflowBoundary = Teuchos::rcp( new OutflowSquareBoundary); // bc->addDirichlet(beta_n_u_minus_sigma_n, inflowBoundary, zero); // bc->addDirichlet(uhat, outflowBoundary, zero); SpatialFilterPtr wallInflow = Teuchos::rcp( new WallInflow); SpatialFilterPtr wallBoundary = Teuchos::rcp( new WallSquareBoundary); SpatialFilterPtr nonWall = Teuchos::rcp( new NonWallSquareBoundary); SpatialFilterPtr halfWallOutflow = Teuchos::rcp( new HalfWallOutflow); bc->addDirichlet(uhat, wallBoundary, one); bc->addDirichlet(beta_n_u_minus_sigma_n, wallInflow, zero); bc->addDirichlet(beta_n_u_minus_sigma_n, nonWall, zero); //////////////////// BUILD MESH /////////////////////// // define nodes for mesh int H1Order = order+1; int pToAdd = 2; // create a pointer to a new mesh: // Teuchos::RCP<Mesh> mesh = MeshUtilities::buildUnitQuadMesh(nCells,confusionBF, H1Order, H1Order+pToAdd); Teuchos::RCP<Mesh> mesh = MeshUtilities::buildRampMesh(confusionBF, H1Order, H1Order+pToAdd); mesh->setPartitionPolicy(Teuchos::rcp(new ZoltanMeshPartitionPolicy("HSFC"))); //////////////////// SOLVE & REFINE /////////////////////// Teuchos::RCP<Solution> solution; solution = Teuchos::rcp( new Solution(mesh, bc, rhs, robIP) ); // solution->solve(false); solution->condensedSolve(); LinearTermPtr residual = rhs->linearTermCopy(); residual->addTerm(-confusionBF->testFunctional(solution)); RieszRepPtr rieszResidual = Teuchos::rcp(new RieszRep(mesh, robIP, residual)); rieszResidual->computeRieszRep(); FunctionPtr e_v = Teuchos::rcp(new RepFunction(v,rieszResidual)); FunctionPtr e_tau = Teuchos::rcp(new RepFunction(tau,rieszResidual)); map<int,FunctionPtr> errRepMap; errRepMap[v->ID()] = e_v; errRepMap[tau->ID()] = e_tau; FunctionPtr errTau = tauVecLT->evaluate(errRepMap,false); FunctionPtr errV = vVecLT->evaluate(errRepMap,false); FunctionPtr xErr = (errTau->x())*(errTau->x()) + (errV->dx())*(errV->dx()); FunctionPtr yErr = (errTau->y())*(errTau->y()) + (errV->dy())*(errV->dy()); double energyThreshold = 0.2; // for mesh refinements RefinementStrategy refinementStrategy( solution, energyThreshold ); //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // PRE REFINEMENTS //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// if (rank==0) { cout << "Number of pre-refinements = " << numPreRefs << endl; } for (int i =0; i<=numPreRefs; i++) { vector<ElementPtr> elems = mesh->activeElements(); vector<ElementPtr>::iterator elemIt; vector<int> wallCells; for (elemIt=elems.begin(); elemIt != elems.end(); elemIt++) { int cellID = (*elemIt)->cellID(); int numSides = mesh->getElement(cellID)->numSides(); FieldContainer<double> vertices(numSides,2); //for quads mesh->verticesForCell(vertices, cellID); bool cellIDset = false; for (int j = 0; j<numSides; j++) { if ((abs(vertices(j,0)-.5)<1e-7) && (abs(vertices(j,1))<1e-7) && !cellIDset) // if at singularity, i.e. if a vertex is (.5,0) { wallCells.push_back(cellID); cellIDset = true; } } } if (i<numPreRefs) { refinementStrategy.refineCells(wallCells); } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// for (int refIndex=0; refIndex<numRefs; refIndex++) { if (rank==0) { cout << "on ref index " << refIndex << endl; } rieszResidual->computeRieszRep(); // in preparation to get anisotropy vector<int> cellIDs; refinementStrategy.getCellsAboveErrorThreshhold(cellIDs); map<int,double> xErrMap = xErr->cellIntegrals(cellIDs,mesh,15,true); map<int,double> yErrMap = yErr->cellIntegrals(cellIDs,mesh,15,true); // refinementStrategy.refine(rank==0,xErrMap,yErrMap); //anisotropic refinements refinementStrategy.refine(rank==0); // no anisotropy solution->condensedSolve(); } //////////////////// print to file /////////////////////// FunctionPtr orderFxn = Teuchos::rcp(new MeshPolyOrderFunction(mesh)); VTKExporter exporter(solution, mesh, varFactory); std::ostringstream oss; oss << nCells; if (rank==0) { exporter.exportSolution(string("robustIP")+oss.str()); exporter.exportFunction(orderFxn, "meshOrder"); cout << endl; } return 0; }
float rsurf_data::ComputeFaceArea(const std::size_t& rsIndex,const std::size_t& faceIndex) { CheckFaceParameter(rsIndex,faceIndex); Intb* vertices(this->localData->tabRs[rsIndex].dataFaces[faceIndex].dataFace.sommetsIndex); return GetAireTriangle(this->localData->tabNodes[vertices[0]].node,this->localData->tabNodes[vertices[1]].node,this->localData->tabNodes[vertices[2]].node); }
inline typename graph_traits<Graph>::vertex_descriptor get_root_vertex( const Graph& g) { return *(vertices(g).first); };
void hypergraph::print_characteristics() { info(" |cGraph| %i %i %i : ", number_of_vertices_, number_of_hyperedges_, number_of_pins_); double weighted_ave = 0; double percentile_75; double percentile_50; double percentile_25; double percentile_95; ds::dynamic_array<int> hEdgeLens(number_of_hyperedges_); ds::dynamic_array<int> hEdges(number_of_hyperedges_); ds::dynamic_array<int> vertices(number_of_vertices_); int j = 0; for (int i = 0; i < number_of_hyperedges_; ++i) { hEdges[i] = i; hEdgeLens[i] = hyperedge_offsets_[i + 1] - hyperedge_offsets_[i]; weighted_ave += (hEdgeLens[i] * hyperedge_weights_[i]); j += hyperedge_weights_[i]; } percentile_75 = (static_cast<double>(j) * 75) / 100; percentile_50 = (static_cast<double>(j) * 50) / 100; percentile_95 = (static_cast<double>(j) * 95) / 100; percentile_25 = (static_cast<double>(j) * 25) / 100; info("%i ", weighted_ave / j); hEdges.sort_using_another_array(hEdgeLens); j = 0; int ij = 0; for (int i = 0; i < number_of_hyperedges_;) { j += hyperedge_weights_[hEdges[i++]]; if (ij == 0 && j > percentile_25) { info("%i ", hEdgeLens[hEdges[i]]); ++ij; } if (ij == 1 && j > percentile_50) { info("%i ", hEdgeLens[hEdges[i]]); ++ij; } if (ij == 2 && j > percentile_75) { info("%i ", hEdgeLens[hEdges[i]]); ++ij; } if (ij == 3 && j > percentile_95) { info("%i ", hEdgeLens[hEdges[i]]); ++ij; } if (i == number_of_hyperedges_ - 1) { info("%i ", hEdgeLens[hEdges[i]]); } } j = 0; for (int i = 0; i < number_of_vertices_; ++i) { vertices[i] = i; j += vertex_weights_[i]; } percentile_75 = (static_cast<double>(j) * 75) / 100; percentile_50 = (static_cast<double>(j) * 50) / 100; percentile_95 = (static_cast<double>(j) * 95) / 100; percentile_25 = (static_cast<double>(j) * 25) / 100; vertices.sort_using_another_array(vertex_weights_); j = 0; ij = 0; for (int i = 0; i < number_of_vertices_;) { j += vertex_weights_[vertices[i++]]; if (ij == 0 && j > percentile_25) { info("%i ", vertex_weights_[vertices[i]]); ++ij; } if (ij == 1 && j > percentile_50) { info("%i ", vertex_weights_[vertices[i]]); ++ij; } if (ij == 2 && j > percentile_75) { info("%i ", vertex_weights_[vertices[i]]); ++ij; } if (ij == 3 && j > percentile_95) { info("%i ", vertex_weights_[vertices[i]]); ++ij; } if (i == number_of_vertices_ - 1) { info("%i \n", vertex_weights_[vertices[i]]); } } }
void FSISPOptimizerOLD::calculateFunctionBenefitsWithSCFGProperties(ControlFlowGraph scfg) { // get node property structures property_map<ControlFlowGraph, nodetype_t>::type scfg_nodeTypeNProp = get(nodetype_t(), scfg); property_map<ControlFlowGraph, startaddr_t>::type scfg_startAddrNProp = get(startaddr_t(), scfg); // property_map<ControlFlowGraph, startaddrstring_t>::type scfg_startAddrStringNProp = get(startaddrstring_t(), scfg); // unused // property_map<ControlFlowGraph, bbsize_t>::type scfg_bbSizeNProp = get(bbsize_t(), scfg); // unused // property_map<ControlFlowGraph, calllabel_t>::type scfg_calllabel_t = get(calllabel_t(), scfg); // unused // get edge property structures property_map<ControlFlowGraph, cost_t>::type scfg_costEProp = get(cost_t(), scfg); property_map<ControlFlowGraph, cost_onchip_t>::type scfg_costOnChipEProp = get(cost_onchip_t(), scfg); property_map<ControlFlowGraph, cost_offchip_t>::type scfg_costOffChipEProp = get(cost_offchip_t(), scfg); property_map<ControlFlowGraph, mem_penalty_t>::type scfg_memPenaltyEProp = get(mem_penalty_t(), scfg); property_map<ControlFlowGraph, activation_t>::type scfg_actEProp = get(activation_t(), scfg); cfgVertexIter vp; cfgOutEdgeIter epo; cfgInEdgeIter epi; CFGVertex v; CFGEdge e; LOG_DEBUG(logger, function_data.size() << " functions found."); // cycle through all vertices of the supergraph and set the max flow (activation count) and the costs for each basic block for each function (stored in function_data) for(vp = vertices(scfg); vp.first != vp.second; ++vp.first) { v = *vp.first; if(get(scfg_nodeTypeNProp, v) == BasicBlock) { uint32_t bb_addr = get(scfg_startAddrNProp, v); uint32_t affiliated_function=0; bool block_found = false; // assign the wcet costs for that block to the function it belongs to for(uint32_t i = 0; i < function_data.size(); i++) { if((bb_addr >= function_data[i].address) && (function_data[i].end_address > bb_addr)) { block_found = true; LOG_DEBUG(logger, "Assigning block cost of bb: 0x" << hex << bb_addr << " for function " << function_data[i].name); affiliated_function = i; break; } } assert(block_found); for(epo = out_edges(v, scfg); epo.first != epo.second; ++epo.first) { e = *epo.first; uint32_t cur_cost = get(scfg_costEProp, e); uint32_t off_cost = get(scfg_costOffChipEProp, e); uint32_t on_cost = get(scfg_costOnChipEProp, e); uint32_t mem_penalty = get(scfg_memPenaltyEProp, e); uint32_t activation_count = get(scfg_actEProp,e); switch((analysis_metric_t) conf->getUint(CONF_USE_METRIC)) { case WCET_RATIO_FILES: case WCET: { function_data[affiliated_function].cur_cost += activation_count * cur_cost; function_data[affiliated_function].offchip_cost += activation_count * off_cost; function_data[affiliated_function].onchip_cost += activation_count * on_cost; assert(mem_penalty == (off_cost - on_cost)); function_data[affiliated_function].benefit += activation_count * (off_cost - on_cost); break; } case MDIC: { function_data[affiliated_function].cur_cost += activation_count * cur_cost; function_data[affiliated_function].offchip_cost += activation_count * off_cost; function_data[affiliated_function].onchip_cost += activation_count * on_cost; function_data[affiliated_function].benefit += function_data[affiliated_function].cur_cost; break; } case MPL: { function_data[affiliated_function].cur_cost += cur_cost; function_data[affiliated_function].offchip_cost += off_cost; function_data[affiliated_function].onchip_cost += on_cost; function_data[affiliated_function].benefit += function_data[affiliated_function].cur_cost; // this method is _not_ to be used, so fall down to assert(false) // break; } default: { assert(false); } } } } } LOG_DEBUG(logger, function_data.size() << " functions found."); for(uint32_t i = 0; i < function_data.size(); i++) { LOG_DEBUG(logger, "Function id: " << function_data[i].id << " name: " << function_data[i].name << " addr: 0x" << hex << function_data[i].address << " end addr: 0x" << function_data[i].end_address << " size: " << dec << function_data[i].size << " on/offchip cost: " << function_data[i].onchip_cost << "/" << function_data[i].offchip_cost << " benefit: " << function_data[i].benefit); } }
int volumetric_knt_cuda(int argc, char **argv) { Timer timer; int vol_size = vx_count * vx_size; float half_vol_size = vol_size * 0.5f; Eigen::Vector3i voxel_size(vx_size, vx_size, vx_size); Eigen::Vector3i volume_size(vol_size, vol_size, vol_size); Eigen::Vector3i voxel_count(vx_count, vx_count, vx_count); int total_voxels = voxel_count.x() * voxel_count.y() * voxel_count.z(); std::cout << std::fixed << "Voxel Count : " << voxel_count.transpose() << std::endl << "Voxel Size : " << voxel_size.transpose() << std::endl << "Volume Size : " << volume_size.transpose() << std::endl << "Total Voxels : " << total_voxels << std::endl << std::endl; timer.start(); KinectFrame knt(filepath); timer.print_interval("Importing knt frame : "); Eigen::Affine3f grid_affine = Eigen::Affine3f::Identity(); grid_affine.translate(Eigen::Vector3f(0, 0, half_vol_size)); grid_affine.scale(Eigen::Vector3f(1, 1, 1)); // z is negative inside of screen Eigen::Matrix4f grid_matrix = grid_affine.matrix(); float knt_near_plane = 0.1f; float knt_far_plane = 10240.0f; Eigen::Matrix4f projection = perspective_matrix<float>(KINECT_V2_FOVY, KINECT_V2_DEPTH_ASPECT_RATIO, knt_near_plane, knt_far_plane); Eigen::Matrix4f projection_inverse = projection.inverse(); Eigen::Matrix4f view_matrix = Eigen::Matrix4f::Identity(); std::vector<float4> vertices(knt.depth.size(), make_float4(0, 0, 0, 1)); std::vector<float4> normals(knt.depth.size(), make_float4(0, 0, 1, 1)); std::vector<Eigen::Vector2f> grid_voxels_params(total_voxels); // // setup image parameters // unsigned short image_width = KINECT_V2_DEPTH_WIDTH; unsigned short image_height = image_width / aspect_ratio; QImage img(image_width, image_height, QImage::Format::Format_RGBA8888); img.fill(Qt::GlobalColor::gray); uchar4* image_data = (uchar4*)img.bits(); //float4* debug_buffer = new float4[image_width * image_height]; //memset(debug_buffer, 0, image_width * image_height * sizeof(float4)); knt_cuda_setup( vx_count, vx_size, grid_matrix.data(), projection.data(), projection_inverse.data(), *grid_voxels_params.data()->data(), KINECT_V2_DEPTH_WIDTH, KINECT_V2_DEPTH_HEIGHT, KINECT_V2_DEPTH_MIN, KINECT_V2_DEPTH_MAX, vertices.data()[0], normals.data()[0], image_width, image_height ); timer.start(); knt_cuda_allocate(); knt_cuda_init_grid(); timer.print_interval("Allocating gpu : "); timer.start(); knt_cuda_copy_host_to_device(); knt_cuda_copy_depth_buffer_to_device(knt.depth.data()); timer.print_interval("Copy host to device : "); timer.start(); knt_cuda_normal_estimation(); timer.print_interval("Normal estimation : "); timer.start(); knt_cuda_update_grid(view_matrix.data()); timer.print_interval("Update grid : "); timer.start(); knt_cuda_grid_params_copy_device_to_host(); knt_cuda_copy_device_to_host(); timer.print_interval("Copy device to host : "); // // setup camera parameters // timer.start(); Eigen::Affine3f camera_to_world = Eigen::Affine3f::Identity(); float cam_z = -half_vol_size; camera_to_world.scale(Eigen::Vector3f(1, 1, -1)); camera_to_world.translate(Eigen::Vector3f(half_vol_size, half_vol_size, cam_z)); Eigen::Matrix4f camera_to_world_matrix = camera_to_world.matrix(); knt_cuda_raycast(KINECT_V2_FOVY, KINECT_V2_DEPTH_ASPECT_RATIO, camera_to_world_matrix.data()); timer.print_interval("Raycast : "); timer.start(); knt_cuda_copy_image_device_to_host(*(uchar4*)img.bits()); timer.print_interval("Copy Img to host : "); timer.start(); knt_cuda_free(); timer.print_interval("Cleanup gpu : "); #if 0 //memset(image_data, 0, image_width * image_height * sizeof(uchar4)); //memset(debug_buffer, 0, image_width * image_height * sizeof(float4)); Eigen::Vector3f camera_pos = camera_to_world_matrix.col(3).head<3>(); float fov_scale = (float)tan(DegToRad(KINECT_V2_FOVY * 0.5f)); float aspect_ratio = KINECT_V2_DEPTH_ASPECT_RATIO; // // for each pixel, trace a ray // timer.start(); for (int y = 0; y < image_height; ++y) { for (int x = 0; x < image_width; ++x) { // Convert from image space (in pixels) to screen space // Screen Space along X axis = [-aspect ratio, aspect ratio] // Screen Space along Y axis = [-1, 1] float x_norm = (2.f * float(x) + 0.5f) / (float)image_width; float y_norm = (2.f * float(y) + 0.5f) / (float)image_height; Eigen::Vector3f screen_coord( (x_norm - 1.f) * aspect_ratio * fov_scale, (1.f - y_norm) * fov_scale, 1.0f); Eigen::Vector3f direction; multDirMatrix(screen_coord, camera_to_world_matrix, direction); direction.normalize(); long voxels_zero_crossing[2] = { -1, -1 }; int hit_count = raycast_tsdf_volume<float>( camera_pos, direction, voxel_count.cast<int>(), voxel_size.cast<int>(), grid_voxels_params, voxels_zero_crossing); if (hit_count > 0) { if (hit_count == 2) { float4 n = normals[y * image_width + x]; //image_data[y * image_width + x].x = 0; //image_data[y * image_width + x].y = 128; //image_data[y * image_width + x].z = 128; //image_data[y * image_width + x].w = 255; image_data[y * image_width + x].x = uchar((n.x * 0.5f + 0.5f) * 255); image_data[y * image_width + x].y = uchar((n.y * 0.5f + 0.5f) * 255); image_data[y * image_width + x].z = uchar((n.z * 0.5f + 0.5f) * 255); image_data[y * image_width + x].w = 255; } else { image_data[y * image_width + x].x = 128; image_data[y * image_width + x].y = 128; image_data[y * image_width + x].z = 0; image_data[y * image_width + x].w = 255; } } else { image_data[y * image_width + x].x = 128; image_data[y * image_width + x].y = 0; image_data[y * image_width + x].z = 0; image_data[y * image_width + x].w = 255; } } } timer.print_interval("Raycasting to image : "); //export_debug_buffer("../../data/cpu_image_data_screen_coord_f4.txt", debug_buffer, image_width, image_height); //export_image_buffer("../../data/cpu_image_data_screen_coord_uc.txt", image_data, image_width, image_height); #else //export_debug_buffer("../../data/gpu_image_data_screen_coord_f4.txt", debug_buffer, image_width, image_height); //export_image_buffer("../../data/gpu_image_data_screen_coord_uc.txt", image_data, image_width, image_height); #endif QImage image(&image_data[0].x, image_width, image_height, QImage::Format_RGBA8888); //image.fill(Qt::GlobalColor::black); QApplication app(argc, argv); QImageWidget widget; widget.resize(KINECT_V2_DEPTH_WIDTH, KINECT_V2_DEPTH_HEIGHT); widget.setImage(image); widget.show(); return app.exec(); }
returnValue MultiObjectiveAlgorithm::solveSingleObjective( const int &number_ ){ int run1 ; returnValue returnvalue; ASSERT( ocp != 0 ); ASSERT( number_ < m ); if( N == 0 ) get( PARETO_FRONT_DISCRETIZATION, N ); int N_pow_m_minus_1 = 1; int i; for(i=0; i<m-1; i++) N_pow_m_minus_1 *= N; Expression **arg = 0; arg = new Expression*[m]; for( run1 = 0; run1 < m; run1++ ) ocp->getObjective( run1, &arg[run1] ); Grid tmp_grid; ocp->getGrid( tmp_grid ); Objective tmp(tmp_grid); tmp.addMayerTerm(*arg[number_]); ocp->setObjective( tmp ); setStatus( BS_NOT_INITIALIZED ); acadoPrintf("\n\n Optimization of individual objective %d out of %d \n\n",number_ +1, m ); totalCPUtime = -acadoGetTime(); returnvalue = OptimizationAlgorithm::solve(); totalCPUtime += acadoGetTime(); int index; Matrix Weights = getWeights(); for( run1 = 0; run1 < (int) Weights.getNumCols(); run1++ ){ if( fabs( Weights( number_, run1 ) - 1.0 ) < 1000.0*EPS ) index = run1; } if( xResults == 0 ) xResults = new VariablesGrid[Weights.getNumCols()]; if( xaResults == 0 ) xaResults = new VariablesGrid[Weights.getNumCols()]; if( pResults == 0 ) pResults = new VariablesGrid[Weights.getNumCols()]; if( uResults == 0 ) uResults = new VariablesGrid[Weights.getNumCols()]; if( wResults == 0 ) wResults = new VariablesGrid[Weights.getNumCols()]; getDifferentialStates( xResults[index] ); getAlgebraicStates ( xaResults[index] ); getParameters ( pResults[index] ); getControls ( uResults[index] ); getDisturbances ( wResults[index] ); if( returnvalue != SUCCESSFUL_RETURN ) return ACADOERROR(returnvalue); if( nlpSolver != 0 ) totalNumberOfSQPiterations = nlpSolver->getNumberOfSteps(); int hotstart; get( PARETO_FRONT_HOTSTART, hotstart ); int *indices = new int[m]; for( run1 = 0; run1 < m; run1++ ) indices[run1] = number_; VariablesGrid xd_tmp, xa_tmp, p_tmp, u_tmp, w_tmp; if( hotstart == BT_TRUE ){ getDifferentialStates( *userInit.x ); getAlgebraicStates ( *userInit.xa ); getParameters ( *userInit.p ); getControls ( *userInit.u ); getDisturbances ( *userInit.w ); xd_tmp = *userInit.x; xa_tmp = *userInit.xa; p_tmp = *userInit.p; u_tmp = *userInit.u; w_tmp = *userInit.w; } else{ getDifferentialStates( xd_tmp ); getAlgebraicStates ( xa_tmp ); getParameters ( p_tmp ); getControls ( u_tmp ); getDisturbances ( w_tmp ); } VariablesGrid *_xd = 0; VariablesGrid *_xa = 0; VariablesGrid *_p = 0; VariablesGrid *_u = 0; VariablesGrid *_w = 0; if( xd_tmp.isEmpty() == BT_FALSE ) _xd = new VariablesGrid(xd_tmp); if( xa_tmp.isEmpty() == BT_FALSE ) _xa = new VariablesGrid(xa_tmp); if( p_tmp.isEmpty() == BT_FALSE ) _p = new VariablesGrid(p_tmp ); if( u_tmp.isEmpty() == BT_FALSE ) _u = new VariablesGrid(u_tmp ); if( w_tmp.isEmpty() == BT_FALSE ) _w = new VariablesGrid(w_tmp ); if( vertices.getDim() == 0 ){ vertices.init(m,m); vertices.setAll(-INFTY); } Objective **obj = new Objective*[m]; for( run1 = 0; run1 < m; run1++ ){ obj[run1] = new Objective( tmp_grid ); obj[run1]->addMayerTerm(*arg[run1]); OCPiterate xx( _xd, _xa, _p, _u, _w ); obj[run1]->evaluate( xx ); obj[run1]->getObjectiveValue( vertices(number_,run1) ); } if( _xd != 0 ) delete _xd; if( _xa != 0 ) delete _xa; if( _p != 0 ) delete _p ; if( _u != 0 ) delete _u ; if( _w != 0 ) delete _w ; delete[] indices; for( run1 = 0; run1 < m; run1++ ) delete arg[run1]; delete[] arg; for( run1 = 0; run1 < m; run1++ ) delete obj[run1]; delete[] obj; return SUCCESSFUL_RETURN; }
typename property_traits<CoreMap>::value_type core_numbers_impl(Graph& g, CoreMap c, PositionMap pos, Visitor vis) { typedef typename graph_traits<Graph>::vertices_size_type size_type; typedef typename graph_traits<Graph>::degree_size_type degree_type; typedef typename graph_traits<Graph>::vertex_descriptor vertex; typename graph_traits<Graph>::vertex_iterator vi,vi_end; // store the vertex core numbers typename property_traits<CoreMap>::value_type v_cn = 0; // compute the maximum degree (degrees are in the coremap) typename graph_traits<Graph>::degree_size_type max_deg = 0; for (boost::tie(vi,vi_end) = vertices(g); vi!=vi_end; ++vi) { max_deg = (std::max<typename graph_traits<Graph>::degree_size_type>)(max_deg, get(c,*vi)); } // store the vertices in bins by their degree // allocate two extra locations to ease boundary cases std::vector<size_type> bin(max_deg+2); for (boost::tie(vi,vi_end) = vertices(g); vi!=vi_end; ++vi) { ++bin[get(c,*vi)]; } // this loop sets bin[d] to the starting position of vertices // with degree d in the vert array for the bucket sort size_type cur_pos = 0; for (degree_type cur_deg = 0; cur_deg < max_deg+2; ++cur_deg) { degree_type tmp = bin[cur_deg]; bin[cur_deg] = cur_pos; cur_pos += tmp; } // perform the bucket sort with pos and vert so that // pos[0] is the vertex of smallest degree std::vector<vertex> vert(num_vertices(g)); for (boost::tie(vi,vi_end) = vertices(g); vi!=vi_end; ++vi) { vertex v=*vi; size_type p=bin[get(c,v)]; put(pos,v,p); vert[p]=v; ++bin[get(c,v)]; } // we ``abused'' bin while placing the vertices, now, // we need to restore it std::copy(boost::make_reverse_iterator(bin.end()-2), boost::make_reverse_iterator(bin.begin()), boost::make_reverse_iterator(bin.end()-1)); // now simulate removing the vertices for (size_type i=0; i < num_vertices(g); ++i) { vertex v = vert[i]; vis.examine_vertex(v,g); v_cn = get(c,v); typename graph_traits<Graph>::out_edge_iterator oi,oi_end; for (boost::tie(oi,oi_end) = out_edges(v,g); oi!=oi_end; ++oi) { vis.examine_edge(*oi,g); vertex u = target(*oi,g); // if c[u] > c[v], then u is still in the graph, if (get(c,u) > v_cn) { degree_type deg_u = get(c,u); degree_type pos_u = get(pos,u); // w is the first vertex with the same degree as u // (this is the resort operation!) degree_type pos_w = bin[deg_u]; vertex w = vert[pos_w]; if (u!=v) { // swap u and w put(pos,u,pos_w); put(pos,w,pos_u); vert[pos_w] = u; vert[pos_u] = w; } // now, the vertices array is sorted assuming // we perform the following step // start the set of vertices with degree of u // one into the future (this now points at vertex // w which we swapped with u). ++bin[deg_u]; // we are removing v from the graph, so u's degree // decreases put(c,u,get(c,u)-1); } } vis.finish_vertex(v,g); } return v_cn; }
bool MyWorld::init() { if (!oPlatformWorld::init()) { return false; } this->setTouchEnabled(true); // Create Back Menu CCPoint visibleOrigin = CCEGLView::sharedOpenGLView()->getVisibleOrigin(); CCSize visibleSize = CCEGLView::sharedOpenGLView()->getVisibleSize(); CCMenuItemFont *itemBack = CCMenuItemFont::create("Back", this, menu_selector(MyWorld::toExtensionsMainLayer)); itemBack->setPosition(ccp(visibleOrigin.x+visibleSize.width - 50, visibleOrigin.y+25)); CCMenu *menuBack = CCMenu::create(itemBack, NULL); menuBack->setPosition(CCPointZero); this->getUILayer()->addChild(menuBack); // Set Contact Info /* By default all groups won`t collide each other. You could set the contact info before game start or change it later. Group number can only be 0 to 15. */ GROUP_TERRAIN = 0; GROUP_ONE = 1; GROUP_TWO = 2; GROUP_TEST_SENSOR = 15; this->setShouldContact(GROUP_TERRAIN, GROUP_TERRAIN, true); this->setShouldContact(GROUP_TWO, GROUP_TERRAIN, true); this->setShouldContact(GROUP_TEST_SENSOR, GROUP_ONE, true);// Body from GROUP_ONE will be detected by test sensor. // Create Borders oBodyDef* bodyDef = oBodyDef::create(); bodyDef->type = b2_staticBody; vector<b2Vec2> vertices(5); vertices[0].Set(0, 0); vertices[1].Set(visibleSize.width, 0); vertices[2].Set(visibleSize.width, visibleSize.height); vertices[3].Set(0, visibleSize.height); vertices[4].Set(0, 0); bodyDef->attachChain(vertices, 0.4f, 0.4f); oBody* body = bodyDef->toBody(this, GROUP_TERRAIN, 0, 0, 0); CCSprite* sprite = CCSprite::create("Images/Icon.png"); sprite->setPosition(ccp(100,40)); body->addChild(sprite); this->addChild(body); // Create Body sprite = CCSprite::create("Images/Icon.png"); CCSize size = sprite->getContentSize(); bodyDef = oBodyDef::create(); bodyDef->type = b2_dynamicBody; bodyDef->attachPolygon(size.width, size.height, 1.0f, 0.4f, 0.4f);//Body define use bodyDef->attach body = bodyDef->toBody(this, GROUP_ONE, visibleSize.width*0.5f-20.0f, visibleSize.height*0.5f+20.0f, 50.0f); //body->attach(CCBodyDef::polygon(size.width, size.height, 1.0f, 0.4f, 0.4f)); //Body instance use body->attach body->addChild(sprite); this->addChild(body); body = bodyDef->toBody(this, GROUP_TERRAIN, visibleSize.width*0.5f+50.0f, visibleSize.height*0.5f+20.0f); sprite = CCSprite::create("Images/Icon.png"); sprite->runAction( CCRepeatForever::create( CCSequence::create( CCRotateTo::create(3.0f, 45), CCRotateTo::create(3.0f, 0), nullptr))); body->addChild(sprite); this->addChild(body); // Create Test Sensor int SENSOR_TAG = 1; bodyDef = oBodyDef::create(); bodyDef->type = b2_staticBody; //bodyDef->attachPolygonSensor(SENSOR_TAG, visibleSize.width, 40.0f); body = bodyDef->toBody(this, GROUP_TEST_SENSOR, visibleSize.width*0.5f, 20.0f); //CCSensor* sensor = body->getSensorByTag(SENSOR_TAG); oSensor* sensor = body->attachSensor(SENSOR_TAG, oBodyDef::polygon(visibleSize.width, 40.0f)); oSharedEffectCache.load("main.effect"); sensor->bodyEnter += [&](oSensor* sensor, oBody* body) { // When body enters sensor area, remove the body //body->getParent()->removeChild(body); this->query(CCRect(0.0f,0.0f,100.0f,100.0f), [&](oBody* body) { if (body->getGroup() != GROUP_TERRAIN) { body->getParent()->removeChild(body); return true; } return false; }); // Create a jumping grossini using its def _character = _characterDef->toBody(this, GROUP_TWO, 100.0f, 200.0f); CCSprite* sprite = CCSprite::create("Images/grossini.png"); _character->addChild(sprite); this->getCamera()->setFollowRatio(ccp(0.1f,0.1f)); this->getCamera()->follow(_character); this->addChild(_character); oEffect::create(1)->attachTo(_character)->autoRemove()->start(); }; //sensor->bodyEnter += std::make_pair(this, &MyWorld::onBodyEnter); this->addChild(body); /* Create a Platform Character`s Define (The method to make a platform character will be included in Box2D Nodes extension in the future) */ TAG_GROUND_SENSOR = 2; float BOTTOM_OFFSET = 4.0f; float GROUND_SENSOR_HEIGHT = 4.0f; size.setSize(65,116);//The physical size of our character _characterDef = oBodyDef::create(); _characterDef->type = b2_dynamicBody; //_characterDef->fixedRotation = true; float hw = size.width * 0.5f; float hh = size.height * 0.5f; b2Vec2 verts[] = { b2Vec2(-hw, hh), b2Vec2(-hw + BOTTOM_OFFSET, -hh), b2Vec2(hw - BOTTOM_OFFSET, -hh), b2Vec2(hw, hh) }; _characterDef->attachPolygon(verts, 4, 1.0f, 0.4f, 0.4f); _characterDef->attachPolygonSensor( TAG_GROUND_SENSOR, size.width - BOTTOM_OFFSET * 2, GROUND_SENSOR_HEIGHT, b2Vec2(0, -hh - GROUND_SENSOR_HEIGHT * 0.5f)); sprite = CCSprite::create("Images/Icon.png"); //sprite->setOpacity(0); sprite->runAction( oSequence::create( CCSpawn::create( oKeyPos::create(2.0f, 300.0f, 300.0f, oEase::OutBack), oKeyScale::create(2.0f, 3.0f, 3.0f, oEase::InOutElastic), nullptr), CCSpawn::create( oKeyPos::create(2.0f, 100.0f, 100.0f, oEase::OutBack), oKeyScale::create(2.0f, 1.0f, 1.0f, oEase::InOutElastic), nullptr), nullptr)); this->addChild(sprite); this->getCamera()->setBoudary(CCRectMake(-1000, -1000, 2000, 2000)); sprite = CCSprite::create("Images/Icon.png"); sprite->setScale(100.0f); this->addChild(sprite, -100); this->setLayerRatio(-100, ccp(-1.5f, -1.5f)); /* CCSpriteBatchNode* batchNode = CCSpriteBatchNode::createWithTexture(CCTextureCache::sharedTextureCache()->addImage("Images/grossini.png")); sprite = CCSprite::create("Images/grossini.png"); CCSprite* childSp = CCSprite::create("Images/grossini.png"); childSp->setRotation(45.0f); childSp->setPosition(ccp(20,30)); sprite->addChild(childSp); batchNode->addChild(sprite); this->addChild(batchNode);*/ oModelDef* modelDef = oSharedModelCache.load("nvjing.model"); _model = modelDef->toModel(); _model->setPosition(ccp(200,200)); _model->setRecovery(0.2f); _model->setFaceRight(false); _model->setLook("happy"); _model->setLoop(true); _model->play("walk"); this->addChild(_model); return true; }
int main() { Transport::GraphFactory gf("/vagrant/ubimob/graph.txt-dump", false); gf.setAll2(); const Transport::Graph * gr = gf.get(); string path="/vagrant/ubimob/analysis/output/projection/matching.csv"; Users users=carpooling::SampleGraph::load(path); std::cout << "------------------ After ------------"<<std::endl; std::cout << "length drivers: " << users.drivers.size() <<std::endl; std::cout << "length pedestrians: " << users.passengers.size() <<std::endl; carpooling::vertex_descriptor s_heuristik,t_heuristik; carpooling::Graph g_heuristik; carpooling::vertex_descriptor s_ideal,t_ideal; carpooling::Graph g_ideal; //------------heuristic method std::cout<<"----------------- Geo distance heuristic ------------------"<<std::endl; carpooling::SampleGraph::heuristik_Graph(users,g_heuristik, s_heuristik, t_heuristik); boost::edmonds_karp_max_flow(g_heuristik, s_heuristik, t_heuristik); boost::cycle_canceling(g_heuristik); int cost_heuristik = boost::find_flow_cost(g_heuristik); std::cout<<"cost: "<< cost_heuristik <<std::endl; boost::graph_traits<carpooling::Graph>::vertex_iterator vi_heuristik, vend_heuristik; carpooling::Capacity capacity_heuristik = get(boost::edge_capacity, g_heuristik); carpooling::Weight weight_heuristik = get(boost::edge_weight, g_heuristik); carpooling::ResidualCapacity residual_capacity_heuristik = get(boost::edge_residual_capacity, g_heuristik); boost::graph_traits < carpooling::Graph >::vertex_iterator u_iter_heuristik, u_end_heuristik; boost::graph_traits < carpooling::Graph >::out_edge_iterator ei_heuristik, e_end_heuristik; int compt_heuristik=0; for (boost::tie(u_iter_heuristik, u_end_heuristik) = vertices(g_heuristik); u_iter_heuristik != u_end_heuristik; ++u_iter_heuristik){ for (boost::tie(ei_heuristik, e_end_heuristik) = out_edges(*u_iter_heuristik, g_heuristik); ei_heuristik != e_end_heuristik; ++ei_heuristik){ if ( (capacity_heuristik[*ei_heuristik]-residual_capacity_heuristik[*ei_heuristik] ) > 0 && weight_heuristik[*ei_heuristik] > 0 ){ User _driver=carpooling::SampleGraph::findByPk_driver(*u_iter_heuristik-1,users); Privacy::Driver *d1=new Privacy::Driver(_driver.origin, _driver.destination); User _pedestrian= carpooling::SampleGraph::findByPk_passenger(target(*ei_heuristik, g_heuristik)-users.drivers.size()-1,users); Privacy::Pedestrian *p1=new Privacy::Pedestrian(_pedestrian.origin, _pedestrian.destination); int cost1; Privacy::cc_output cc; Privacy::Toolbox *tb=new Privacy::Toolbox(); cc=tb->cc_carpooling_test(*d1,*p1,gr); cost1=cc.cc_costs.total_cost; std::cout << "node " << *u_iter_heuristik << " with node " << target(*ei_heuristik, g_heuristik) << " with cost: " << cost1 << std::endl; compt_heuristik ++; delete d1; delete p1; delete tb; } } } std::cout<<"----------------- Number of matching ------------------ : " << compt_heuristik <<std::endl; //-----------------ideal algorithm------------------ std::cout<<"----------------- ideal algorithm ------------------"<<std::endl; carpooling::SampleGraph::ideal_Graph(users,g_ideal, s_ideal, t_ideal,gr); boost::edmonds_karp_max_flow(g_ideal, s_ideal, t_ideal); boost::cycle_canceling(g_ideal); int cost_ideal = boost::find_flow_cost(g_ideal); std::cout<<"cost: "<< cost_ideal <<std::endl; boost::graph_traits<carpooling::Graph>::vertex_iterator vi_ideal, vend_ideal; carpooling::Capacity capacity_ideal = get(boost::edge_capacity, g_ideal); carpooling::Weight weight_ideal = get(boost::edge_weight, g_ideal); carpooling::ResidualCapacity residual_capacity_ideal = get(boost::edge_residual_capacity, g_ideal); boost::graph_traits < carpooling::Graph >::vertex_iterator u_iter_ideal, u_end_ideal; boost::graph_traits < carpooling::Graph >::out_edge_iterator ei_ideal, e_end_ideal; int compt_ideal=0; for (boost::tie(u_iter_ideal, u_end_ideal) = vertices(g_ideal); u_iter_ideal != u_end_ideal; ++u_iter_ideal){ for (boost::tie(ei_ideal, e_end_ideal) = out_edges(*u_iter_ideal, g_ideal); ei_ideal != e_end_ideal; ++ei_ideal){ if ( (capacity_ideal[*ei_ideal]-residual_capacity_ideal[*ei_ideal] ) > 0 && weight_ideal[*ei_ideal] > 0 ){ User _driver1=carpooling::SampleGraph::findByPk_driver(*u_iter_ideal-1,users); Privacy::Driver *d2=new Privacy::Driver(_driver1.origin, _driver1.destination); User _pedestrian1= carpooling::SampleGraph::findByPk_passenger(target(*ei_ideal, g_ideal)-users.drivers.size()-1,users); Privacy::Pedestrian *p2=new Privacy::Pedestrian(_pedestrian1.origin, _pedestrian1.destination); int cost2; Privacy::cc_output cc2; Privacy::Toolbox *tbb=new Privacy::Toolbox(); cc2=tbb->cc_carpooling_test(*d2,*p2,gr); cost2=cc2.cc_costs.total_cost; std::cout << "node " << *u_iter_ideal << " with node " << target(*ei_ideal, g_ideal) << " with cost: " << cost2 << std::endl; compt_ideal ++; delete d2; delete p2; delete tbb; } } } std::cout<<"----------------- Number of matching ------------------ : " << compt_ideal <<std::endl; return 0; }
//--------------------------------------------------------------------- // TODO factor code out of here and into its own class for loading and // saving PLY files (additional code in stereo/multiviewstereo.cpp) // void MainWindow::on_actionView_PLY_File_triggered() { QString initialDir = userSettings.contains("InitialPLYDir") ? userSettings.value("InitialPLYDir").toString() : QDir::homePath(); // TODO sheets would be nice for Mac users :) QString fname = QFileDialog::getOpenFileName(this, tr("Open File"), initialDir, "PLY Files (*.ply)"); if(!fname.isNull()) { QFile file(fname); if(file.open(QFile::ReadOnly)) { userSettings.setValue("InitialPLYDir", QDir(fname).absolutePath()); QTextStream textStream(&file); // For now we'll ignore the header and assume a certain format QString line; bool hasNormal = false; bool hasColor = false; bool isBinary = false; unsigned int numVertices = 0; unsigned int numFaces = 0; static QRegExp typeTest("n[xyz]"); static QRegExp normalTest("n[xyz]"); static QRegExp colorTest("diffuse_(red|blue|green)"); static QRegExp elementTest("element (vertex|face) (\\d+)"); while((line = textStream.readLine().trimmed()) != "end_header") { if(line.startsWith("property")) { if( line.contains(normalTest) ) hasNormal = true; if( line.contains(colorTest) ) hasColor = true; } else if(elementTest.indexIn(line) != -1) { if(elementTest.cap(1) == "face") numFaces = elementTest.cap(2).toUInt(); else if(elementTest.cap(1) == "vertex") numVertices = elementTest.cap(2).toUInt(); } else if(line.startsWith("format")) { isBinary = line.contains("binary"); } } QDataStream dataStream; if(isBinary) { qint64 pos = textStream.pos(); file.close(); file.open(QFile::ReadOnly); dataStream.setDevice(&file); dataStream.skipRawData(pos); } // // Read in the verticies // GLfloat d[9] = {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}; std::vector<GLfloat> vertices(numVertices * 9); std::vector<GLfloat>::iterator vertexIter = vertices.begin(); if(isBinary) { uint len = 12 + (hasNormal ? 12 : 0) + (hasColor ? 3 : 0); // TODO more efficient to read in larger chunk of data for(unsigned int vertex = 0; vertex < numVertices && !textStream.atEnd(); ++vertex) { dataStream.readRawData(reinterpret_cast<char *>(d), len); if(!hasNormal) d[3] = d[4] = d[5] = 0; if(!hasColor) d[6] = d[7] = d[8] = 1; if(dataStream.status() != QDataStream::ReadPastEnd) vertexIter = std::copy(d, d + 9, vertexIter); } } else { for(unsigned int vertex = 0; vertex < numVertices && !textStream.atEnd(); ++vertex) { textStream >> d[0] >> d[1] >> d[2]; if(hasNormal) textStream >> d[3] >> d[4] >> d[5]; else d[3] = d[4] = d[5] = 0.0f; if(hasColor) { textStream >> d[6] >> d[7] >> d[8]; d[6] /= 255.0; d[7] /= 255.0; d[8] /= 255.0; } else { d[6] = d[7] = d[8] = 0.5f; //d[6] = qrand() / (1.0*RAND_MAX); //d[7] = qrand() / (1.0*RAND_MAX); //d[8] = qrand() / (1.0*RAND_MAX); } if(textStream.status() != QTextStream::ReadPastEnd) vertexIter = std::copy(d, d + 9, vertexIter); textStream.readLine(); }
void Player::buildBuffers() { GeometryGenerator::MeshData thePlayer; GeometryGenerator geoGen; geoGen.CreateBox(1.0f, 1.0f, 1.0f, thePlayer); // Cache the vertex offsets to each object in the concatenated vertex buffer. mPlayerVertexOffset = 0; // Cache the index count of each object. mPlayerIndexCount = thePlayer.Indices.size(); // Cache the starting index for each object in the concatenated index buffer. mPlayerIndexOffset = 0; UINT totalVertexCount = thePlayer.Vertices.size(); UINT totalIndexCount = mPlayerIndexCount; // // Extract the vertex elements we are interested in and pack the // vertices of all the meshes into one vertex buffer. // std::vector<Vertex::Basic32> vertices(totalVertexCount); UINT k = 0; for (size_t i = 0; i < thePlayer.Vertices.size(); ++i, ++k) { vertices[k].Pos = thePlayer.Vertices[i].Position; vertices[k].Normal = thePlayer.Vertices[i].Normal; vertices[k].Tex = thePlayer.Vertices[i].TexC; } D3D11_BUFFER_DESC vbd; vbd.Usage = D3D11_USAGE_IMMUTABLE; vbd.ByteWidth = sizeof(Vertex::Basic32) * totalVertexCount; vbd.BindFlags = D3D11_BIND_VERTEX_BUFFER; vbd.CPUAccessFlags = 0; vbd.MiscFlags = 0; D3D11_SUBRESOURCE_DATA vinitData; vinitData.pSysMem = &vertices[0]; HR(pdevice->CreateBuffer(&vbd, &vinitData, &mPlayerVB)); // // Pack the indices of all the meshes into one index buffer. // std::vector<UINT> indices; indices.insert(indices.end(), thePlayer.Indices.begin(), thePlayer.Indices.end()); D3D11_BUFFER_DESC ibd; ibd.Usage = D3D11_USAGE_IMMUTABLE; ibd.ByteWidth = sizeof(UINT) * totalIndexCount; ibd.BindFlags = D3D11_BIND_INDEX_BUFFER; ibd.CPUAccessFlags = 0; ibd.MiscFlags = 0; D3D11_SUBRESOURCE_DATA iinitData; iinitData.pSysMem = &indices[0]; HR(pdevice->CreateBuffer(&ibd, &iinitData, &mPlayerIB)); }
bool CameraRenderable::buildFrustumMesh() { bool result = false; if(m_FrustumMesh) { delete m_FrustumMesh; m_FrustumMesh = nullptr; } Camera* parent = dynamic_cast<Camera*>(m_Parent); if(parent) { Graphics::VertexBuffer* vb = OcularGraphics->createVertexBuffer(); Graphics::IndexBuffer* ib = OcularGraphics->createIndexBuffer(); //------------------------------------------------------------ // Get the corners that comprise the frustum Math::Frustum frustum = parent->getFrustum(); frustum.rebuild(); auto nearCorners = frustum.getNearClipCorners(); auto farCorners = frustum.getFarClipCorners(); //------------------------------------------------------------ // Build the vertex buffer std::vector<Graphics::Vertex> vertices(8); vertices[0].position = nearCorners[0]; // Near bottom left vertices[1].position = nearCorners[1]; // Near bottom right vertices[2].position = nearCorners[2]; // Near top right vertices[3].position = nearCorners[3]; // Near top left vertices[4].position = farCorners[0]; // Far bottom left vertices[5].position = farCorners[1]; // Far bottom right vertices[6].position = farCorners[2]; // Far top right vertices[7].position = farCorners[3]; // Far top left vb->addVertices(vertices); if(!vb->build()) { result = false; } //-------------------------------------------------------- // Build the index buffer std::vector<uint32_t> indices(24); indices[0] = 0; indices[1] = 1; // Line from near bottom left to near bottom right indices[2] = 1; indices[3] = 2; // Line from near bottom right to near top right indices[4] = 2; indices[5] = 3; // Line from near top right to near top left indices[6] = 3; indices[7] = 0; // Line from near top left to near bottom left indices[8] = 4; indices[9] = 5; // Line from far bottom left to far bottom right indices[10] = 5; indices[11] = 6; // Line from far bottom right to far top right indices[12] = 6; indices[13] = 7; // Line from far top right to far top left indices[14] = 7; indices[15] = 4; // Line from far top left to far bottom left indices[16] = 0; indices[17] = 4; // Line from near bottom left to far bottom left indices[18] = 1; indices[19] = 5; // Line from near bottom right to far bottom right indices[20] = 2; indices[21] = 6; // Line from near top right to far top right indices[22] = 3; indices[23] = 7; // Line from near top left to far top left ib->addIndices(indices); if(!ib->build()) { result = false; } //-------------------------------------------------------- // Build the mesh m_FrustumMesh = new Graphics::Mesh(); m_FrustumMesh->addSubMesh(); m_FrustumMesh->setVertexBuffer(vb); m_FrustumMesh->setIndexBuffer(ib); } return result; }
returnValue MultiObjectiveAlgorithm::solve( ){ int run1,run2; returnValue returnvalue; ASSERT( ocp != 0 ); ASSERT( m >= 2 ); if( N == 0 ) get( PARETO_FRONT_DISCRETIZATION, N ); int paretoGeneration; get( PARETO_FRONT_GENERATION, paretoGeneration ); int hotstart; get( PARETO_FRONT_HOTSTART, hotstart ); Expression **arg = 0; arg = new Expression*[m]; for( run1 = 0; run1 < m; run1++ ) ocp->getObjective( run1, &arg[run1] ); Constraint tmp_con; double *idx = new double[m]; WeightGeneration generator; Matrix Weights; Vector formers; Vector lb(m); Vector ub(m); lb.setZero(); ub.setAll(1.0); generator.getWeights( m, N, lb, ub, Weights, formers ); result.init( Weights.getNumCols(), m ); count = 0; if( xResults == 0 ) xResults = new VariablesGrid[Weights.getNumCols()]; if( xaResults == 0 ) xaResults = new VariablesGrid[Weights.getNumCols()]; if( pResults == 0 ) pResults = new VariablesGrid[Weights.getNumCols()]; if( uResults == 0 ) uResults = new VariablesGrid[Weights.getNumCols()]; if( wResults == 0 ) wResults = new VariablesGrid[Weights.getNumCols()]; totalNumberOfSQPiterations = 0; totalCPUtime = -acadoGetTime(); run1 = 0; while( run1 < (int) Weights.getNumCols() ){ // PRINT THE ITERATION NUMBER: // --------------------------- acadoPrintf("\n\n Multi-objective point: %d out of %d \n\n",run1+1, (int) Weights.getNumCols() ); ocp->getConstraint( tmp_con ); for( run2 = 0; run2 < (int) Weights.getNumRows(); run2++ ) idx[run2] = Weights( run2, run1 ); // THIS PART OF THE CODE WILL NOT RUN YET FOR GENERAL WEIGHTS int vertex = -1; for( run2 = 0; run2 < m; run2++ ){ if( fabs( idx[run2]-1.0 ) < 100.0*EPS ) vertex = run2; } // ---------------------------------------------------------- if( vertex == -1 || paretoGeneration == PFG_WEIGHTED_SUM ){ formulateOCP( idx, ocp, arg ); setStatus( BS_NOT_INITIALIZED ); returnvalue = OptimizationAlgorithm::solve(); if( nlpSolver != 0 ) totalNumberOfSQPiterations += nlpSolver->getNumberOfSteps(); ocp->setConstraint( tmp_con ); set( PRINT_COPYRIGHT, BT_FALSE ); if( returnvalue != SUCCESSFUL_RETURN ){ ACADOERROR(returnvalue); } else{ getDifferentialStates( xResults[run1] ); getAlgebraicStates ( xaResults[run1] ); getParameters ( pResults[run1] ); getControls ( uResults[run1] ); getDisturbances ( wResults[run1] ); if( hotstart == BT_TRUE ){ getDifferentialStates( *userInit.x ); getAlgebraicStates ( *userInit.xa ); getParameters ( *userInit.p ); getControls ( *userInit.u ); getDisturbances ( *userInit.w ); evaluateObjectives( *userInit.x, *userInit.xa, *userInit.p, *userInit.u, *userInit.w, arg ); } else{ VariablesGrid xd_tmp, xa_tmp, p_tmp, u_tmp, w_tmp; getDifferentialStates( xd_tmp ); getAlgebraicStates ( xa_tmp ); getParameters ( p_tmp ); getControls ( u_tmp ); getDisturbances ( w_tmp ); evaluateObjectives( xd_tmp, xa_tmp, p_tmp, u_tmp, w_tmp, arg ); } } } else{ acadoPrintf(" Result from single objective optimization is adopted. \n\n" ); for( run2 = 0; run2 < m; run2++ ){ result(count,run2) = vertices(vertex,run2); } count++; } run1++; } totalCPUtime += acadoGetTime(); for( run1 = 0; run1 < m; run1++ ) delete arg[run1]; delete[] arg; delete[] idx; return SUCCESSFUL_RETURN; }
void SkyBox::load( const he::String& asset ) { HE_ASSERT(m_Drawable == nullptr, "Skybox is loaded twice!"); m_Drawable = HENew(Drawable)(); m_Drawable->setLocalScale(vec3(1000000000)); // bounds must be huge ////////////////////////////////////////////////////////////////////////// /// Load Model ////////////////////////////////////////////////////////////////////////// ModelMesh* const cube( ResourceFactory<gfx::ModelMesh>::getInstance()->get(ResourceFactory<gfx::ModelMesh>::getInstance()->create())); cube->setName(he::String("skybox-") + asset); he::PrimitiveList<vec3> vertices(8); vertices.add(vec3(-1, 1, -1)); vertices.add(vec3( 1, 1, -1)); vertices.add(vec3(-1, -1, -1)); vertices.add(vec3( 1, -1, -1)); vertices.add(vec3(-1, 1, 1)); vertices.add(vec3( 1, 1, 1)); vertices.add(vec3(-1, -1, 1)); vertices.add(vec3( 1, -1, 1)); he::PrimitiveList<uint16> indices(36); indices.add(0); indices.add(1); indices.add(2); //front indices.add(1); indices.add(3); indices.add(2); indices.add(5); indices.add(4); indices.add(7); //back indices.add(4); indices.add(6); indices.add(7); indices.add(4); indices.add(0); indices.add(6); //left indices.add(0); indices.add(2); indices.add(6); indices.add(1); indices.add(5); indices.add(3); //right indices.add(5); indices.add(7); indices.add(3); indices.add(4); indices.add(5); indices.add(0); //top indices.add(5); indices.add(1); indices.add(0); indices.add(3); indices.add(7); indices.add(2); //bottom indices.add(7); indices.add(6); indices.add(2); VertexLayout layout; layout.addElement(VertexElement(eShaderAttribute_Position, eShaderAttributeType_Float, eShaderAttributeTypeComponents_3, 0)); cube->init(layout, MeshDrawMode_Triangles); cube->setVertices(&vertices[0], static_cast<uint32>(vertices.size()), MeshUsage_Static, false); cube->setIndices(&indices[0], static_cast<uint32>(indices.size()), IndexStride_UShort, MeshUsage_Static); cube->setLoaded(eLoadResult_Success); m_Drawable->setModelMesh(cube); cube->release(); Material* const material(CONTENT->loadMaterial("engine/sky.material")); m_Drawable->setMaterial(material); material->release(); const int8 cubeMap(m_Drawable->getMaterial()->findParameter(HEFS::strcubeMap)); if (cubeMap >= 0) { const TextureCube* cube(CONTENT->asyncLoadTextureCube(asset)); m_Drawable->getMaterial()->getParameter(cubeMap).setTextureCube(cube); cube->release(); } }
void GridMesh::GenerateGrid() { uint numVerticies = rows * columns; vector<PositionTexCoordVertex> vertices(numVerticies); vector<vec3> points; auto width = columns * scale; auto height = rows * scale; auto halfWidth = width * 0.5f; auto halfHeight = height * 0.5f; vec3 originPosition(-halfWidth, 0, -halfHeight); for (uint row = 0; row < rows; row++) { for (uint column = 0; column < columns; column++) { auto index = row * columns + column; auto columnPosition = (float)column * scale; auto rowPosition = row * scale; vec3 position(columnPosition, 0, rowPosition); points.push_back(position); vertices[index].position = glm::vec4((originPosition + position), 1); glm::vec2 texCoord(row / (float)(rows), column / (float)columns); vertices[index].textureCoordinate = texCoord; } } //AddNoise(vertices); boundingSphere.Fit(points); auto numIndices = (rows - 1) * (columns - 1) * 6; vector<uint> indices(numIndices); uint index = 0; for (uint row = 0; row < rows - 1; row++) { for (uint column = 0; column < columns - 1; column++) { auto currentIndex = row * columns + column; auto nextRow = (row + 1) * columns + column; auto nextColumn = currentIndex + 1; auto nextRowNextColumn = nextRow + 1; assert(index + 6 <= numIndices); // First triangle indices[index++] = currentIndex; indices[index++] = nextRow; indices[index++] = nextRowNextColumn; // Second triangle indices[index++] = currentIndex; indices[index++] = nextRowNextColumn; indices[index++] = nextColumn; } } DynamicEnum texturePaths; texturePaths.Add(texturePath); BindVertexAndIndexData(&renderData, vertices, indices); BuildMaterialFromLoaderNode(&material, texturePaths); }
int main(int, char *[]) { typedef boost::property<boost::edge_weight_t, float> EdgeWeightProperty; typedef boost::adjacency_list < boost::listS, boost::vecS, boost::directedS, boost::no_property, EdgeWeightProperty > Graph; typedef boost::graph_traits < Graph >::vertex_descriptor vertex_descriptor; typedef boost::graph_traits < Graph >::edge_descriptor edge_descriptor; typedef std::pair<int, int> Edge; // Create a graph Graph g; boost::graph_traits<Graph>::vertex_descriptor v0 = add_vertex(g); boost::graph_traits<Graph>::vertex_descriptor v1 = add_vertex(g); boost::graph_traits<Graph>::vertex_descriptor v2 = add_vertex(g); // Add weighted edges EdgeWeightProperty weight0(5); add_edge(v0, v1, weight0, g); EdgeWeightProperty weight1 = 3; add_edge(v1, v2, weight1, g); EdgeWeightProperty weight2 = 2; add_edge(v2, v0, weight2, g); // At this point the graph is /* v0 . 5 / \ 2 /___\ v1 3 v2 */ // Create things for Dijkstra std::vector<vertex_descriptor> parents(num_vertices(g)); // To store parents std::vector<int> distances(num_vertices(g)); // To store distances // Compute shortest paths from v0 to all vertices, and store the output in parents and distances boost::dijkstra_shortest_paths(g, v0, boost::predecessor_map(&parents[0]).distance_map(&distances[0])); // Output results std::cout << "distances and parents:" << std::endl; boost::graph_traits < Graph >::vertex_iterator vertexIterator, vend; for (boost::tie(vertexIterator, vend) = vertices(g); vertexIterator != vend; ++vertexIterator) { std::cout << "distance(" << *vertexIterator << ") = " << distances[*vertexIterator] << ", "; std::cout << "parent(" << *vertexIterator << ") = " << parents[*vertexIterator] << std::endl; } std::cout << std::endl; /* The output is: distance(0) = 0, parent(0) = 0 distance(1) = 5, parent(1) = 0 distance(2) = 8, parent(2) = 1 which means: the distance from v0 to v0 is 0 the distance from v0 to v1 is 5 the distance from v0 to v2 is 8 */ return EXIT_SUCCESS; }
/// Returns the number of vertices in the delaunay triangulation. int DelaunayTriangulation::vertexCount() const { return vertices().size(); }
MeshGeometry ObjLoader::LoadMesh(const std::string& path) const { // Try opening the file for starters. std::ifstream input(path.c_str()); std::string buffer; unsigned int numberOfTextureCoordinates = 0; unsigned int numberOfNormals = 0; unsigned int numberOfTriangles = 0; unsigned int numberOfVertices = 0; // Create the geometry cache object MeshGeometry output; output.vertices = NULL; output.indices = NULL; if(!input.is_open()) { // Load failed (file not found) std::cerr << "Could not open OBJ file \"" + path + "\"!" << std::endl; } else { // First we'll scan to figure out how many vertices, // texture coordinates, normals and triangles there are // in the file. while(!input.eof()) { // Read each line std::getline(input, buffer); if(buffer.substr(0, 2) == "vn") { // Vertex normal numberOfNormals++; } else if(buffer.substr(0, 2) == "vt") { // Vertex texture coordinate numberOfTextureCoordinates++; } else if(buffer.substr(0, 1) == "v") { // Vertex numberOfVertices++; } else if(buffer.substr(0, 1) == "f") { // Face // Not necessarily a triangle, so now we gotta count it. std::vector<std::string> faceParts = SplitString(buffer, ' '); numberOfTriangles++; if(faceParts.size() > 4) { // We have to make another triangle for this face. It's a quad. numberOfTriangles++; } } } // Instantiate the arrays std::vector<ObjVertex> vertices(numberOfVertices); std::vector<ObjNormal> normals(std::max(1u, numberOfNormals)); // if no normals, just predefine some std::vector<ObjTextureCoordinate> textureCoordinates(std::max(1u, numberOfTextureCoordinates)); std::vector<ObjTriangle> triangles(numberOfTriangles); // Reset the read pointer, otherwise it will just keep shouting eof. input.clear(); input.seekg(0, std::ios::beg); if(!input.is_open()) { std::cerr << "Could not reopen OBJ file for second stage load" << std::endl; } else { // Keep reading through line by line and break down the format now int normal = 0; int textureCoordinate = 0; int vertex = 0; int triangle = 0; while(!input.eof()) { // Fetch the line std::getline(input, buffer); // Create a stringstream for fast searching std::istringstream line(buffer); if(buffer.substr(0, 2) == "vn") { std::string temp, f1, f2, f3; // Parse out some floats and the parameters // Format vn nx ny nz line >> temp >> f1 >> f2 >> f3; float x = (float)atof(f1.c_str()); float y = (float)atof(f2.c_str()); float z = (float)atof(f3.c_str()); normals[normal].x = x; normals[normal].y = y; normals[normal].z = z; normal++; } else if(buffer.substr(0, 2) == "vt") { // format: vt u v std::string temp, f1, f2; line >> temp >> f1 >> f2; float u = (float)atof(f1.c_str()); float v = (float)atof(f2.c_str()); textureCoordinates[textureCoordinate].u = u; textureCoordinates[textureCoordinate].v = v; textureCoordinate++; } else if(buffer.substr(0, 1) == "v") {
void AmbientOcclusionApp::BuildSkullGeometryBuffers() { std::ifstream fin("Models/skull.txt"); if(!fin) { MessageBox(0, L"Models/skull.txt not found.", 0, 0); return; } UINT vcount = 0; UINT tcount = 0; std::string ignore; fin >> ignore >> vcount; fin >> ignore >> tcount; fin >> ignore >> ignore >> ignore >> ignore; std::vector<Vertex::AmbientOcclusion> vertices(vcount); for(UINT i = 0; i < vcount; ++i) { fin >> vertices[i].Pos.x >> vertices[i].Pos.y >> vertices[i].Pos.z; fin >> vertices[i].Normal.x >> vertices[i].Normal.y >> vertices[i].Normal.z; } fin >> ignore; fin >> ignore; fin >> ignore; mSkullIndexCount = 3*tcount; std::vector<UINT> indices(mSkullIndexCount); for(UINT i = 0; i < tcount; ++i) { fin >> indices[i*3+0] >> indices[i*3+1] >> indices[i*3+2]; } fin.close(); BuildVertexAmbientOcclusion(vertices, indices); D3D11_BUFFER_DESC vbd; vbd.Usage = D3D11_USAGE_IMMUTABLE; vbd.ByteWidth = sizeof(Vertex::AmbientOcclusion) * vcount; vbd.BindFlags = D3D11_BIND_VERTEX_BUFFER; vbd.CPUAccessFlags = 0; vbd.MiscFlags = 0; D3D11_SUBRESOURCE_DATA vinitData; vinitData.pSysMem = &vertices[0]; HR(md3dDevice->CreateBuffer(&vbd, &vinitData, &mSkullVB)); // // Pack the indices of all the meshes into one index buffer. // D3D11_BUFFER_DESC ibd; ibd.Usage = D3D11_USAGE_IMMUTABLE; ibd.ByteWidth = sizeof(UINT) * mSkullIndexCount; ibd.BindFlags = D3D11_BIND_INDEX_BUFFER; ibd.CPUAccessFlags = 0; ibd.MiscFlags = 0; D3D11_SUBRESOURCE_DATA iinitData; iinitData.pSysMem = &indices[0]; HR(md3dDevice->CreateBuffer(&ibd, &iinitData, &mSkullIB)); }
bool ccQuadric::buildUp() { if (m_drawPrecision < MIN_DRAWING_PRECISION) return false; unsigned vertCount = m_drawPrecision*m_drawPrecision; unsigned triCount = (m_drawPrecision-1)*(m_drawPrecision-1)*2; if (!init(vertCount,true,triCount,0)) { ccLog::Error("[ccQuadric::buildUp] Not enough memory"); return false; } ccPointCloud* verts = vertices(); assert(verts); assert(verts->hasNormals()); CCVector2 areaSize = m_maxCorner - m_minCorner; PointCoordinateType stepX = areaSize.x/static_cast<PointCoordinateType>(m_drawPrecision-1); PointCoordinateType stepY = areaSize.y/static_cast<PointCoordinateType>(m_drawPrecision-1); m_minZ = m_minZ = 0; for (unsigned x=0; x<m_drawPrecision; ++x) { CCVector3 P(m_minCorner.x + stepX * x, 0, 0); for (unsigned y=0; y<m_drawPrecision; ++y) { P.y = m_minCorner.y + stepY * y; P.z = m_eq[0] + m_eq[1]*P.x + m_eq[2]*P.y + m_eq[3]*P.x*P.x + m_eq[4]*P.x*P.y + m_eq[5]*P.y*P.y; //compute the min and max heights of the quadric! if (x != 0 || y != 0) { if (m_minZ > P.z) m_minZ = P.z; else if (m_maxZ < P.z) m_maxZ = P.z; } else { m_minZ = m_maxZ = P.z; } verts->addPoint(P); //normal --> TODO: is there a simple way to deduce it from the equation? //CCVector3 N; //N.x = m_eq[1] + 2*m_eq[3]*P.x + m_eq[4]*P.y; //N.y = m_eq[2] + 2*m_eq[5]*P.y + m_eq[4]*P.x; //N.z = -PC_ONE; //N.normalize(); //verts->addNorm(N); if (x != 0 && y != 0) { unsigned iA = (x-1) * m_drawPrecision + y-1; unsigned iB = iA + 1; unsigned iC = iA + m_drawPrecision; unsigned iD = iB + m_drawPrecision; addTriangle(iA,iC,iB); addTriangle(iB,iC,iD); } } } computeNormals(true); return true; }
vertex_range_t getVertices() const { return vertices( _graph ); }
bool ccTorus::buildUp() { if (m_drawPrecision < MIN_DRAWING_PRECISION) return false; //invalid parameters? if ((m_rectSection && m_rectSectionHeight < ZERO_TOLERANCE) || m_insideRadius >= m_outsideRadius || m_angle_rad < ZERO_TOLERANCE) return false; //topology bool closed = (m_angle_rad >= 2.0*M_PI); const unsigned steps = m_drawPrecision; unsigned sweepSteps = 4 * (closed ? steps : static_cast<unsigned>(ceil((m_angle_rad * steps)/(2.0*M_PI)))); unsigned sectSteps = (m_rectSection ? 4 : steps); //vertices unsigned vertCount = (sweepSteps + (closed ? 0 : 1)) * sectSteps; //DGM: +1 row for non closed loops //faces unsigned facesCount = sweepSteps * sectSteps *2; //faces normals unsigned faceNormCount = (sweepSteps + (closed ? 0 : 1)) * sectSteps; //DGM: +1 row for non closed loops if (!closed) facesCount += (m_rectSection ? 2 : sectSteps)*2; if (!init(vertCount + (closed || m_rectSection ? 0 : 2), false, facesCount, faceNormCount + (closed ? 0 : 2))) { ccLog::Error("[ccTorus::buildUp] Not enough memory"); return false; } //2D section std::vector<CCVector3> sectPoints; try { sectPoints.resize(sectSteps); } catch (const std::bad_alloc&) { init(0,false,0,0); ccLog::Error("[ccTorus::buildUp] Not enough memory"); return false; } double sweepStep_rad = m_angle_rad / sweepSteps; double sectStep_rad = (2.0*M_PI) / sectSteps; PointCoordinateType sectionRadius = (m_outsideRadius-m_insideRadius)/2; if (m_rectSection) { //rectangular section sectPoints[0].x = (m_outsideRadius-m_insideRadius)/2; sectPoints[0].z = m_rectSectionHeight/2; sectPoints[1].x = -sectPoints[0].x; sectPoints[1].z = sectPoints[0].z; sectPoints[2].x = sectPoints[1].x; sectPoints[2].z = -sectPoints[1].z; sectPoints[3].x = -sectPoints[2].x; sectPoints[3].z = sectPoints[2].z; } else { //circular section for (unsigned i=0; i<sectSteps; ++i) { double sect_angle_rad = i * sectStep_rad; sectPoints[i].x = static_cast<PointCoordinateType>(cos(sect_angle_rad) * sectionRadius); sectPoints[i].z = static_cast<PointCoordinateType>(sin(sect_angle_rad) * sectionRadius); } } ccPointCloud* verts = vertices(); assert(verts); assert(m_triNormals); //main sweep PointCoordinateType sweepRadius = (m_insideRadius + m_outsideRadius)/2; for (unsigned t=0; t<(closed ? sweepSteps : sweepSteps+1); ++t) { //unit director vector CCVector3 sweepU(static_cast<PointCoordinateType>(cos(t*sweepStep_rad)), static_cast<PointCoordinateType>(sin(t*sweepStep_rad)), 0); //section points for (unsigned i=0; i<sectSteps; ++i) { CCVector3 P(sweepU.x * (sweepRadius + sectPoints[i].x), sweepU.y * (sweepRadius + sectPoints[i].x), sectPoints[i].z); verts->addPoint(P); } //normals if (m_rectSection) { m_triNormals->addElement(ccNormalVectors::GetNormIndex(CCVector3(0.0,0.0,1.0).u)); m_triNormals->addElement(ccNormalVectors::GetNormIndex((-sweepU).u)); m_triNormals->addElement(ccNormalVectors::GetNormIndex(CCVector3(0.0,0.0,-1.0).u)); m_triNormals->addElement(ccNormalVectors::GetNormIndex(sweepU.u)); } else //circular section { for (unsigned i=0; i<sectSteps; ++i) { double sectAngle_rad = i * sectStep_rad; CCVector3 sectU = CCVector3::fromArray(CCVector3(cos(sectAngle_rad), 0.0, sin(sectAngle_rad)).u); CCVector3 N(sweepU.x * sectU.x, sweepU.y * sectU.x, sectU.z); m_triNormals->addElement(ccNormalVectors::GetNormIndex(N.u)); } } } if (!closed && !m_rectSection) { CCVector3 P(sweepRadius,0,0); verts->addPoint(P); CCVector3 P2( static_cast<PointCoordinateType>(cos(m_angle_rad))*sweepRadius, static_cast<PointCoordinateType>(sin(m_angle_rad))*sweepRadius, 0); verts->addPoint(P2); } if (!closed) { //first section (left side) m_triNormals->addElement(ccNormalVectors::GetNormIndex(CCVector3(0,-1,0).u)); //last section (right side) m_triNormals->addElement(ccNormalVectors::GetNormIndex(CCVector3( static_cast<PointCoordinateType>(-sin(m_angle_rad)), static_cast<PointCoordinateType>(cos(m_angle_rad)), 0).u)); } sectPoints.clear(); //mesh faces { assert(m_triVertIndexes); for (unsigned t=0;t<sweepSteps;++t) { unsigned sweepStart = t*sectSteps; for (unsigned i=0;i<sectSteps;++i) { unsigned iNext = (i+1)%sectSteps; addTriangle(sweepStart+i,(sweepStart+i+sectSteps)%vertCount,(sweepStart+iNext+sectSteps)%vertCount); if (m_rectSection) addTriangleNormalIndexes(sweepStart+i,(sweepStart+i+sectSteps)%faceNormCount,(sweepStart+i+sectSteps)%faceNormCount); else addTriangleNormalIndexes(sweepStart+i,(sweepStart+i+sectSteps)%faceNormCount,(sweepStart+iNext+sectSteps)%faceNormCount); addTriangle(sweepStart+i,(sweepStart+iNext+sectSteps)%vertCount,sweepStart+iNext); if (m_rectSection) addTriangleNormalIndexes(sweepStart+i,(sweepStart+i+sectSteps)%faceNormCount,sweepStart+i); else addTriangleNormalIndexes(sweepStart+i,(sweepStart+iNext+sectSteps)%faceNormCount,sweepStart+iNext); } } if (!closed) { unsigned lastSectionShift = sweepSteps*sectSteps; if (m_rectSection) { //rectangular left section addTriangle(0,1,2); addTriangleNormalIndexes(faceNormCount,faceNormCount,faceNormCount); addTriangle(0,2,3); addTriangleNormalIndexes(faceNormCount,faceNormCount,faceNormCount); //rectangular right section addTriangle(lastSectionShift,lastSectionShift+2,lastSectionShift+1); addTriangleNormalIndexes(faceNormCount+1,faceNormCount+1,faceNormCount+1); addTriangle(lastSectionShift,lastSectionShift+3,lastSectionShift+2); addTriangleNormalIndexes(faceNormCount+1,faceNormCount+1,faceNormCount+1); } else { unsigned lastSectionCenterShift = vertCount; //circular 'left' section for (unsigned i=0;i<sectSteps;++i) { unsigned iNext = (i+1)%sectSteps; addTriangle(lastSectionCenterShift,i,iNext); addTriangleNormalIndexes(faceNormCount,faceNormCount,faceNormCount); } //circular 'right' section for (unsigned i=0;i<sectSteps;++i) { unsigned iNext = (i+1)%sectSteps; addTriangle(lastSectionCenterShift+1,lastSectionShift+iNext,lastSectionShift+i); addTriangleNormalIndexes(faceNormCount+1,faceNormCount+1,faceNormCount+1); } } } } notifyGeometryUpdate(); showTriNorms(true); return true; }
void DepthExporter::exportPlyMesh(string filename, int width, int height, const bool* mask, const float* depth, const unsigned char* color) { ofstream ply; ply.open(ofToDataPath(filename).c_str(), ios::out | ios::binary); if (ply.is_open()) { int n = width * height; unsigned int* names = new unsigned int[n]; // label all the vertices int total = 0; for (int i = 0; i < n; i++) if (!mask[i]) names[i] = total++; // create all the vertices stringstream vertices(ios::in | ios::out | ios::binary); exportPlyVertices(vertices, width, height, mask, depth, color); // create all the faces int totalFaces = 0; int nw, ne, sw, se; stringstream faces(ios::in | ios::out | ios::binary); for (int y = 0; y < height - 1; y++) { for (int x = 0; x < width - 1; x++) { nw = y * width + x; ne = nw + 1; sw = nw + width; se = ne + width; if (!mask[nw] && !mask[se]) { if (!mask[ne]) { exportPlyFace(faces, names[se], names[ne], names[nw]); totalFaces++; } if (!mask[sw]) { exportPlyFace(faces, names[sw], names[se], names[nw]); totalFaces++; } } else if (!mask[ne] && !mask[sw]) { if (!mask[nw]) { exportPlyFace(faces, names[sw], names[ne], names[nw]); totalFaces++; } if (!mask[se]) { exportPlyFace(faces, names[sw], names[se], names[ne]); totalFaces++; } } } } // write the header ply << "ply" << endl; ply << "format binary_little_endian 1.0" << endl; ply << "element vertex " << total << endl; ply << "property float x" << endl; ply << "property float y" << endl; ply << "property float z" << endl; if (color != NULL) { ply << "property uchar red" << endl; ply << "property uchar green" << endl; ply << "property uchar blue" << endl; } ply << "element face " << totalFaces << endl; ply << "property list uchar uint vertex_indices" << endl; ply << "end_header" << endl; ply << vertices.rdbuf(); ply << faces.rdbuf(); delete [] names; } }
/*! * \brief Get the damper mesh. */ Teuchos::RCP<DataTransferKit::MeshManager<DamperAdapter::MeshType> > DamperAdapter::getMesh( const RCP_Damper& damper ) { // Get the process rank. int my_rank = damper->get_comm()->getRank(); // Set the vertex dimension - this is a 1D problem. int vertex_dimension = 1; // Compute globally unique vertex ids. Teuchos::RCP< std::vector<double> > grid = damper->get_grid(); Teuchos::ArrayRCP<int> vertices( grid->size() ); for ( int i = 0; i < (int) vertices.size(); ++i ) { vertices[i] = i + my_rank*vertices.size(); } // Get the grid vertex coordinates. Teuchos::ArrayRCP<double> coordinates( &(*grid)[0], 0, grid->size(), false ); // Set the grid topology - this is 1D so we are using line segments. DataTransferKit::DTK_ElementTopology element_topology = DataTransferKit::DTK_LINE_SEGMENT; // Each line segment will be constructed by 2 vertices. int vertices_per_element = 2; // Compute globally unique element ids. Teuchos::ArrayRCP<int> elements( grid->size() - 1 ); for ( int i = 0; i < (int) elements.size(); ++i ) { elements[i] = i + my_rank*elements.size(); } // Generate element connectivity. The global vertex ids are used to // describe the construction of each line segment. Teuchos::ArrayRCP<int> connectivity( vertices_per_element*elements.size() ); for ( int i = 0; i < (int) elements.size(); ++i ) { connectivity[i] = vertices[i]; connectivity[ elements.size() + i ] = vertices[i+1]; } // Define the permutation list. Here our line segments are ordered the // same as DTK canonical ordering so the list is an monotonically // increasing set of integers. Teuchos::ArrayRCP<int> permutation_list( vertices_per_element ); for ( int i = 0; i < vertices_per_element; ++i ) { permutation_list[i] = i; } // Build a DTK Mesh container with the data. The MeshType typedef is set // in the header file. Teuchos::RCP<MeshType> mesh_container = Teuchos::rcp( new MeshType( vertex_dimension, vertices, coordinates, element_topology, vertices_per_element, elements, connectivity, permutation_list ) ); // We only have 1 element topology in this grid so we make just one mesh // block. Teuchos::ArrayRCP<Teuchos::RCP<MeshType> > mesh_blocks( 1 ); mesh_blocks[0] = mesh_container; // Return a mesh manager. return Teuchos::rcp( new DataTransferKit::MeshManager<MeshType>( mesh_blocks, damper->get_comm(), 1 ) ); }
inline std::pair< typename DIRECTED_GRAPH::vertex_iterator, typename DIRECTED_GRAPH::vertex_iterator > vertices(DIRECTED_GRAPH const& g) { return vertices(g.impl()); }
sge::postprocessing::fullscreen_quad::fullscreen_quad( sge::renderer::device::core &_renderer, sge::renderer::vertex::declaration &_vertex_declaration) : renderer_( _renderer), vertex_declaration_( _vertex_declaration), vertex_buffer_( renderer_.create_vertex_buffer( sge::renderer::vertex::buffer_parameters( vertex_declaration_, sge::renderer::vf::dynamic::make_part_index < sge::postprocessing::vf::format, sge::postprocessing::vf::format_part >(), sge::renderer::vertex::count( 4u), sge::renderer::resource_flags_field::null()))) { sge::renderer::vertex::scoped_lock vblock( *vertex_buffer_, sge::renderer::lock_mode::writeonly); sge::renderer::vf::view<sge::postprocessing::vf::format_part> vertices( vblock.value()); sge::renderer::vf::view<sge::postprocessing::vf::format_part>::iterator vb_it( vertices.begin()); // Left top vb_it->set<sge::postprocessing::vf::position>( sge::postprocessing::vf::position::packed_type( -1.0f, 1.0f)); (vb_it++)->set<sge::postprocessing::vf::texcoord>( sge::postprocessing::vf::texcoord::packed_type( 0.0f, 0.0f)); // Left bottom vb_it->set<sge::postprocessing::vf::position>( sge::postprocessing::vf::position::packed_type( -1.0f, -1.0f)); (vb_it++)->set<sge::postprocessing::vf::texcoord>( sge::postprocessing::vf::texcoord::packed_type( 0.0f, 1.0f)); // Right top vb_it->set<sge::postprocessing::vf::position>( sge::postprocessing::vf::position::packed_type( 1.0f, 1.0f)); (vb_it++)->set<sge::postprocessing::vf::texcoord>( sge::postprocessing::vf::texcoord::packed_type( 1.0f, 0.0f)); // Right bottom vb_it->set<sge::postprocessing::vf::position>( sge::postprocessing::vf::position::packed_type( 1.0f, -1.0f)); (vb_it++)->set<sge::postprocessing::vf::texcoord>( sge::postprocessing::vf::texcoord::packed_type( 1.0f, 1.0f)); }
Archipelago::Archipelago(const std::string& islandFile, const std::string& linkFile) { // read from file if present std::string currentFileRead = islandFile; try { // consume island data file std::ifstream is(islandFile); if (is.good()) { // digest file std::istream_iterator<std::string> start(is), end; std::vector<std::string> islandDataStrings = std::vector<std::string>(start, end); // extact data to property set std::vector<IslandProperties> islandNodes(islandDataStrings.size()); std::transform (islandDataStrings.begin(), islandDataStrings.end(), islandNodes.begin(), ExtractIslandData); // insert data into graph for ( auto island : islandNodes ) { vertex_t u = boost::add_vertex(m_islandGraph); m_islandGraph[u].name = island.name; m_islandGraph[u].terrain = island.terrain; } } currentFileRead = linkFile; is = std::ifstream(linkFile); if (is.good()) { // digest file std::istream_iterator<std::string> start(is), end; std::vector<std::string> linkDataStrings = std::vector<std::string>(start, end); // extact data to property set std::vector<LinkData> linkData(linkDataStrings.size()); std::transform (linkDataStrings.begin(), linkDataStrings.end(), linkData.begin(), ExtractLinkData); // insert data into graph for ( auto link : linkData ) { unsigned int searchResultA; unsigned int searchResultB; if (FindIslandByName(link.nodeNameA, searchResultA) && FindIslandByName(link.nodeNameB, searchResultB)) { link.resolvedNodeA = searchResultA; link.resolvedNodeB = searchResultB; } else { throw std::runtime_error("Error: could not find one of " + link.nodeNameA + " or " + link.nodeNameB + "in island nodes\n"); } // Create an edge conecting those two vertices edge_t e; bool b; Graph::vertex_descriptor u = *vertices(m_islandGraph).first + link.resolvedNodeA; Graph::vertex_descriptor v = *vertices(m_islandGraph).first + link.resolvedNodeB; boost::tie(e,b) = boost::add_edge(u,v,m_islandGraph); // Set the properties of a vertex and the edge m_islandGraph[e].linkType = link.properties.linkType; } } } catch (std::runtime_error& error) { throw std::runtime_error(error.what() + std::string("Error in file: ") + currentFileRead + "\n"); } }