void Generator::operator ()(Chunk &chunk) const noexcept { ExactLocation::Fine coords(chunk.Position() * ExactLocation::Extent()); coords += 0.5f; ValueField field { { solidity_noise, coords, config.solidity }, { humidity_noise, coords, config.humidity }, { temperature_noise, coords, config.temperature }, { richness_noise, coords, config.richness }, { random_noise, coords, config.randomness }, }; for (int z = 0; z < Chunk::side; ++z) { for (int y = 0; y < Chunk::side; ++y) { for (int x = 0; x < Chunk::side; ++x) { chunk.SetBlock(RoughLocation::Fine(x, y, z), Generate(field, RoughLocation::Fine(x, y, z))); } } } chunk.SetGenerated(); }
void CoordXmlTest::writeHumanReadableString() { namespace literal = XmlStreamLiteral; buffer.open(QBuffer::ReadWrite); QXmlStreamWriter xml(&buffer); xml.setAutoFormatting(false); xml.writeStartDocument(); QFETCH(int, num_coords); MapCoordVector coords(num_coords, proto_coord); QBENCHMARK { writeHumanReadableString_implementation(coords, xml); } xml.writeEndDocument(); buffer.close(); }
void map_t::way_cut_highlight(map_item_t *item, lpos_t pos) { if(item_is_selected_way(item)) { int seg = canvas->get_item_segment(item->item, pos); if(seg >= 0) { unsigned int width = (item->object.way->draw.flags & OSM_DRAW_FLAG_BG) ? 2 * item->object.way->draw.bg.width : 3 * item->object.way->draw.width; std::vector<lpos_t> coords(2); coords[0] = item->object.way->node_chain[seg]->lpos; coords[1] = item->object.way->node_chain[seg + 1]->lpos; cursor = canvas->polyline_new(CANVAS_GROUP_DRAW, coords, width, style->highlight.node_color); } } else if(item_is_selected_node(item)) { /* cutting a way at its first or last node doesn't make much sense ... */ if(!selected.object.way->ends_with_node(item->object.node)) hl_cursor_draw(item->object.node->lpos, 2 * style->node.radius); } }
int Hive::canMove(int position, Direction direction) { QPair<int, int> coords(move(toMap(position), direction)); if (coords.first < 0 || coords.first >= m_size || coords.second < 0 || coords.second >= m_size) { return position; } int newPosition(fromMap(coords)); QMutexLocker locker(&m_mutex); if (isCapacityExceed(newPosition)) { return position; } else { return newPosition; } }
nsIntPoint nsCoreUtils::GetScreenCoordsForWindow(nsINode *aNode) { nsIntPoint coords(0, 0); nsCOMPtr<nsIDocShellTreeItem> treeItem(GetDocShellFor(aNode)); if (!treeItem) return coords; nsCOMPtr<nsIDocShellTreeOwner> treeOwner; treeItem->GetTreeOwner(getter_AddRefs(treeOwner)); if (!treeOwner) return coords; nsCOMPtr<nsIBaseWindow> baseWindow = do_QueryInterface(treeOwner); if (baseWindow) baseWindow->GetPosition(&coords.x, &coords.y); // in device pixels return coords; }
// Check that the current state of the board is valid bool Board::BoardValid() { int solvedValue; for (int y=0; y<Common::NoNumbers; y++) { for(int x=0; x<Common::NoNumbers; x++) { Coords coords(x, y); solvedValue = _theSquares[x][y]->SolvedValue(); if(solvedValue && !IsSquareValid(coords, solvedValue)) { return false; } } } return true; }
void CoordXmlTest::writeFastImplementation() { buffer.open(QBuffer::ReadWrite); QXmlStreamWriter xml(&buffer); xml.setAutoFormatting(false); xml.writeStartDocument(); XMLFileFormat::active_version = 6; // Activate fast text format. XmlElementWriter element(xml, QLatin1String("root")); QFETCH(int, num_coords); MapCoordVector coords(num_coords, proto_coord); QBENCHMARK { element.write(coords); } xml.writeEndDocument(); buffer.close(); }
wxString wxSheetValueProviderSparseStringTest::GetValue( const wxSheetCoords& coords_ ) const { wxCHECK_MSG(ContainsCell(coords_), wxEmptyString, wxT("Invalid coords")); wxSheetCoords coords(HasOption(wxSHEET_ValueProviderColPref) ? coords_ : coords_.GetSwapped()); ((wxSheetValueProviderSparseStringTest*)this)->m_intArrayIntString.m_key = coords.m_row; const int rowPos = m_data.Index((wxSheetIntArrayIntString*)&m_intArrayIntString); // const int rowPos = m_data.Index(wxSheetIntArrayIntString(coords.m_row)); if (rowPos != wxNOT_FOUND) { ((wxSheetValueProviderSparseStringTest*)this)->m_intString.m_key = coords.m_col; const int colPos = m_data[rowPos].m_value->Index((wxSheetIntString*)&m_intString); //const int colPos = m_data[rowPos].m_value.Index(wxSheetIntString(coords.m_col)); if (colPos != wxNOT_FOUND) return m_data[rowPos].m_value->Item(colPos).m_value; } return wxEmptyString; }
void Mesquite::PlanarDomain::fit_vertices( Mesquite::Mesh* mesh, const Mesquite::Mesh::VertexHandle* verts, size_t num_verts, Mesquite::MsqError& err, double epsilon ) { std::vector<MsqVertex> coords( num_verts ); mesh->vertices_get_coordinates( verts, arrptr(coords), num_verts, err ); MSQ_ERRRTN(err); if (epsilon <= 0.0) epsilon = DomainUtil::default_tolerance( arrptr(coords), num_verts ); Vector3D pts[3]; if (!DomainUtil::non_colinear_vertices( arrptr(coords), num_verts, pts, epsilon )) { MSQ_SETERR(err)("All vertices are colinear", MsqError::INVALID_MESH); return; } this->set_plane( (pts[1] - pts[0]) * (pts[2] - pts[0]), pts[0] ); }
RegionTextureControl::RegionTextureControl(MyGUI::Widget* _parent) : TextureToolControl(_parent), mTextureVisible(false), mAreaSelectorControl(nullptr), mPositionSelectorControl(nullptr) { mTypeName = MyGUI::utility::toString((size_t)this); // immediately draw a frames for states std::vector<MyGUI::IntCoord> coords(10); drawUnselectedStates(coords); addSelectorControl(mAreaSelectorControl); addSelectorControl(mPositionSelectorControl); mPositionSelectorControl->setEnabled(false); mAreaSelectorControl->eventChangePosition += MyGUI::newDelegate(this, &RegionTextureControl::notifyChangePosition); CommandManager::getInstance().registerCommand("Command_MoveLeft", MyGUI::newDelegate(this, &RegionTextureControl::CommandMoveLeft)); CommandManager::getInstance().registerCommand("Command_MoveRight", MyGUI::newDelegate(this, &RegionTextureControl::CommandMoveRight)); CommandManager::getInstance().registerCommand("Command_MoveTop", MyGUI::newDelegate(this, &RegionTextureControl::CommandMoveTop)); CommandManager::getInstance().registerCommand("Command_MoveBottom", MyGUI::newDelegate(this, &RegionTextureControl::CommandMoveBottom)); CommandManager::getInstance().registerCommand("Command_SizeLeft", MyGUI::newDelegate(this, &RegionTextureControl::CommandSizeLeft)); CommandManager::getInstance().registerCommand("Command_SizeRight", MyGUI::newDelegate(this, &RegionTextureControl::CommandSizeRight)); CommandManager::getInstance().registerCommand("Command_SizeTop", MyGUI::newDelegate(this, &RegionTextureControl::CommandSizeTop)); CommandManager::getInstance().registerCommand("Command_SizeBottom", MyGUI::newDelegate(this, &RegionTextureControl::CommandSizeBottom)); CommandManager::getInstance().registerCommand("Command_GridMoveLeft", MyGUI::newDelegate(this, &RegionTextureControl::CommandGridMoveLeft)); CommandManager::getInstance().registerCommand("Command_GridMoveRight", MyGUI::newDelegate(this, &RegionTextureControl::CommandGridMoveRight)); CommandManager::getInstance().registerCommand("Command_GridMoveTop", MyGUI::newDelegate(this, &RegionTextureControl::CommandGridMoveTop)); CommandManager::getInstance().registerCommand("Command_GridMoveBottom", MyGUI::newDelegate(this, &RegionTextureControl::CommandGridMoveBottom)); CommandManager::getInstance().registerCommand("Command_GridSizeLeft", MyGUI::newDelegate(this, &RegionTextureControl::CommandGridSizeLeft)); CommandManager::getInstance().registerCommand("Command_GridSizeRight", MyGUI::newDelegate(this, &RegionTextureControl::CommandGridSizeRight)); CommandManager::getInstance().registerCommand("Command_GridSizeTop", MyGUI::newDelegate(this, &RegionTextureControl::CommandGridSizeTop)); CommandManager::getInstance().registerCommand("Command_GridSizeBottom", MyGUI::newDelegate(this, &RegionTextureControl::CommandGridSizeBottom)); initialiseAdvisor(); updateCaption(); }
void CustomMeshFactory::buildElements(STK_Interface &mesh) const { mesh.beginModification(); const int dim = mesh.getDimension(); // build the nodes std::vector<double> coords(dim,0.0); for (int i=0;i<NumNodesPerProc_;++i) { for (int k=0;k<dim;++k) coords[k] = Coords_[i*dim+k]; mesh.addNode(Nodes_[i], coords); } // build the elements std::vector<std::string> block_ids; mesh.getElementBlockNames(block_ids); for (int i=0;i<NumElementsPerProc_;++i) { // get block by its name std::stringstream block_id; block_id << "eblock-" << BlockIDs_[i]; stk_classic::mesh::Part *block = mesh.getElementBlockPart(block_id.str()); // construct element and its nodal connectivity stk_classic::mesh::EntityId elt = i + OffsetToGlobalElementIDs_; std::vector<stk_classic::mesh::EntityId> elt2nodes(8); for (int k=0;k<8;++k) elt2nodes[k] = Element2Nodes_[i*8+k]; RCP<ElementDescriptor> ed = rcp(new ElementDescriptor(elt,elt2nodes)); mesh.addElement(ed,block); } mesh.endModification(); }
void process () { // generate point set std::vector<typename K::Point_d> points; points.reserve( 100); { int d = 10; std::vector<double> coords( d+1); int i, j; double hom = 2.0; for ( i = 0; i < 100; ++i) { for (j=0; j<d; ++j) coords[ j] = CGAL::default_random( 0x100000); coords[d] = hom; points.push_back (typename K::Point_d(d, coords.begin(), coords.end())); } // call test function CGAL::test_Min_annulus_d(points.begin(), points.end(), Traits(), 0); } }
void Geocode::search(double longitude, double latitude) { if (!isActive()) { qmlInfo(this) << "geocoding is not active"; return; } if (!m_service->isInitialized()) { m_pending = QGeoCoordinate(latitude, longitude); return; } m_id = 0; QGeoCoordinate coords(latitude, longitude); GeoLocationService::GeoLocationError err = m_service->addressQuery(coords, 1, &m_id); if (err == GeoLocationService::QueryFailedError) { setActive(false); } if (err != GeoLocationService::NoError) { qmlInfo(this) << "error" << err << "from GeoLocationService"; } }
IDRangeList GCells::getParticleNeighbours(const magnet::math::MortonNumber<3>& particle_cell_coords) const { if (verbose) { derr << "Getting neighbours of cell " << particle_cell_coords.toString() << std::endl; } magnet::math::MortonNumber<3> zero_coords; for (size_t iDim(0); iDim < NDIM; ++iDim) zero_coords[iDim] = (particle_cell_coords[iDim].getRealValue() + cellCount[iDim] - overlink) % cellCount[iDim]; IDRangeList retval; //This initial reserve greatly speeds up the later inserts retval.getContainer().reserve(32); magnet::math::MortonNumber<3> coords(zero_coords); for (size_t x(0); x < 2 * overlink + 1; ++x) { coords[0] = (zero_coords[0].getRealValue() + x) % cellCount[0]; for (size_t y(0); y < 2 * overlink + 1; ++y) { coords[1] = (zero_coords[1].getRealValue() + y) % cellCount[1]; for (size_t z(0); z < 2 * overlink + 1; ++z) { coords[2] = (zero_coords[2].getRealValue() + z) % cellCount[2]; const std::vector<size_t>& nlist = list[coords.getMortonNum()]; retval.getContainer().insert(retval.getContainer().end(), nlist.begin(), nlist.end()); } } } return retval; }
nsIntPoint nsCoreUtils::GetScreenCoordsForWindow(nsINode *aNode) { nsIntPoint coords(0, 0); nsCOMPtr<nsIDocShellTreeItem> treeItem(GetDocShellTreeItemFor(aNode)); if (!treeItem) return coords; nsCOMPtr<nsIDocShellTreeItem> rootTreeItem; treeItem->GetRootTreeItem(getter_AddRefs(rootTreeItem)); nsCOMPtr<nsIDOMDocument> domDoc = do_GetInterface(rootTreeItem); if (!domDoc) return coords; nsCOMPtr<nsIDOMWindow> window; domDoc->GetDefaultView(getter_AddRefs(window)); if (!window) return coords; window->GetScreenX(&coords.x); window->GetScreenY(&coords.y); return coords; }
m::plane kdNode::findSplittingPlane(const kdTree *tree, const u::vector<int> &tris, m::axis axis) const { const size_t triangleCount = tris.size(); // every vertex component is stored depending on `axis' axis in the following // vector. The vector gets sorted and the median is chosen as the splitting // plane. u::vector<float> coords(triangleCount * 3); // 3 vertices for a triangle size_t k = 0; for (size_t i = 0; i < triangleCount; i++) { for (size_t j = 0; j < 3; j++) { const int index = tree->m_triangles[tris[i]].m_vertices[j]; const m::vec3 &vec = tree->m_vertices[index]; coords[k++] = vec[axis]; } } // sort coordinates for a L1 median estimation, this keeps us rather // robust against vertex outliers. u::sort(coords.begin(), coords.end(), [](float a, float b) { return a < b; }); const float split = coords[coords.size() / 2]; // median like const m::vec3 point(m::vec3::getAxis(axis) * split); const m::vec3 normal(m::vec3::getAxis(axis)); return m::plane(point, normal); }
/// Ist es an dieser Stelle für einen Spieler möglich einen Hafen zu bauen bool GameWorldBase::IsHarborPointFree(const unsigned harbor_id, const unsigned char player, const unsigned short sea_id) const { Point<MapCoord> coords(GetHarborPoint(harbor_id)); // Befindet sich der Hafenpunkt auch an dem erforderlichen Meer? bool at_sea = false; for(unsigned i = 0;i<6;++i) { if(harbor_pos[harbor_id].cps[i].sea_id == sea_id) { at_sea = true; break; } } if(!at_sea) return false; // Überprüfen, ob das Gebiet in einem bestimmten Radius entweder vom Spieler oder gar nicht besetzt ist for(MapCoord tx=GetXA(coords.x,coords.y,0), r=1;r<=4;tx=GetXA(tx,coords.y,0),++r) { MapCoord tx2 = tx, ty2 = coords.y; for(unsigned i = 2;i<8;++i) { for(MapCoord r2=0;r2<r;GetPointA(tx2,ty2,i%6),++r2) { unsigned char owner = GetNode(tx2,ty2).owner; if(owner != 0 && owner != player+1) return false; } } } return (CalcBQ(coords.x,coords.y,0,false,false,true) == BQ_HARBOR); }
double OBEnergyConformerScore::Score(OBMol &mol, unsigned int index, const RotorKeys &keys, const std::vector<double*> &conformers) { double *origCoords = mol.GetCoordinates(); // copy the original coordinates to coords // copy the conformer coordinates to OBMol object std::vector<double> coords(mol.NumAtoms() * 3); for (unsigned int i = 0; i < mol.NumAtoms() * 3; ++i) { coords[i] = origCoords[i]; origCoords[i] = conformers[index][i]; } OBForceField *ff = OBForceField::FindType("MMFF94"); if (!ff->Setup(mol)) return 10e10; // ff->SteepestDescent(500); double score = ff->Energy(); // copy original coordinates back for (unsigned int i = 0; i < mol.NumAtoms() * 3; ++i) origCoords[i] = coords[i]; return score; }
void TagVertexMesh::vertices_get_coordinates( const VertexHandle vert_array[], MsqVertex* coordinates, size_t num_vtx, MsqError &err ) { if (!num_vtx) return; if (!haveTagHandle) { get_mesh()->vertices_get_coordinates( vert_array, coordinates, num_vtx, err ); MSQ_ERRRTN(err); } else { std::vector<double> coords( num_vtx * 3 ); get_mesh()->tag_get_vertex_data( tagHandle, num_vtx, vert_array, arrptr(coords), err ); MSQ_ERRRTN(err); MsqVertex* coordinates_end = coordinates + num_vtx; std::vector<double>::const_iterator i = coords.begin(); while (coordinates != coordinates_end) { coordinates->set( &*i ); i += 3; ++coordinates; } } }
texture_atlas::coords texture_atlas::add(const unsigned int width, const unsigned int height, const void *data, const unsigned int type) { icoords space = get_space(width, height); vector<irec> newspace; for (size_t r = 0; r < open_space_[space.id].size(); r++) { vector<irec> subrec = open_space_[space.id][r].sub(space.area); newspace.insert(newspace.end(), subrec.begin(), subrec.end()); } open_space_[space.id] = newspace; GLenum test = glGetError(); glBindTexture(GL_TEXTURE_2D, ids_[space.id]); test = glGetError(); glTexSubImage2D(GL_TEXTURE_2D, 0, space.area.left(), space.area.top(), space.area.width(), space.area.height(), GL_RGBA, type, data); test = glGetError(); return coords(space.id, rec(space.area.left() / static_cast<float>(width_), space.area.top() / static_cast<float>(height_), space.area.width() / static_cast<float>(width_), space.area.height() / static_cast<float>(height_))); }
void wxSheetValueProviderString::SetValue( const wxSheetCoords& coords_, const wxString& value ) { wxCHECK_RET(ContainsCell(coords_), wxT("Invalid coords")); wxSheetCoords coords(HasOption(wxSHEET_ValueProviderColPref) ? coords_ : coords_.GetSwapped()); // add "rows" as necessary to store value int count = m_data.GetCount(); if (count <= coords.m_row) { wxArrayString sa; sa.Add( wxEmptyString, 1+coords.m_col ); m_data.Insert( sa, count, 1+coords.m_row-count ); } else // believe it or not - NOT having this else statement is 10% faster in gcc { // add "cols" as necessary to store value count = m_data[coords.m_row].GetCount(); if (count <= coords.m_col) { m_data.Item(coords.m_row).Insert( wxEmptyString, count, 1+coords.m_col-count ); } } m_data[coords.m_row][coords.m_col] = value; }
void MeshOpt::transformMeshtoPatch(MeshImpl * mesh, hier::Patch<NDIM>& patch, MsqError& err) { std::vector<Mesh::VertexHandle> vertices; mesh->get_all_vertices(vertices,err); size_t num_of_vertices = vertices.size(); // std::cout << num_of_vertices << std::endl; std::vector<MsqVertex> coords(num_of_vertices); mesh->vertices_get_coordinates(arrptr(vertices),arrptr(coords),num_of_vertices,err); tbox::Pointer< pdat::NodeData<NDIM,double> > coords_current = patch.getPatchData(d_coords_current_id); int count = 0; for(pdat::NodeIterator<NDIM> ic((*coords_current).getBox()); ic; ic++) { (*coords_current)(ic(),0) = coords[count][0]; (*coords_current)(ic(),1) = coords[count][1]; ++count; } return; }
void CoordXmlTest::readHumanReadableStream() { namespace literal = XmlStreamLiteral; QFETCH(int, num_coords); MapCoordVector coords(num_coords, proto_coord); buffer.buffer().truncate(0); QBuffer header; { QXmlStreamWriter xml(&header); header.open(QBuffer::ReadWrite); xml.setAutoFormatting(false); xml.writeStartDocument(); xml.writeStartElement("root"); xml.writeCharacters(""); // flush root start element buffer.open(QBuffer::ReadWrite); xml.setDevice(&buffer); xml.writeStartElement("coords"); // Using the more efficient string implementation. writeHumanReadableString_implementation(coords, xml); xml.writeEndElement(); xml.setDevice(NULL); buffer.close(); header.close(); } header.open(QBuffer::ReadOnly); buffer.open(QBuffer::ReadOnly); QXmlStreamReader xml; xml.addData(header.buffer()); xml.readNextStartElement(); QCOMPARE(xml.name().toString(), QString("root")); bool failed = false; QBENCHMARK { // benchmark iteration overhead coords.clear(); xml.addData(buffer.data()); xml.readNextStartElement(); if (xml.name() != "coords") { failed = true; break; } for( xml.readNext(); xml.tokenType() != QXmlStreamReader::EndElement; xml.readNext() ) { if (xml.error()) { qDebug() << xml.errorString(); failed = true; break; } const QXmlStreamReader::TokenType token = xml.tokenType(); if (token == QXmlStreamReader::EndDocument) { failed = true; break; } if (token == QXmlStreamReader::Characters && !xml.isWhitespace()) { QStringRef text = xml.text(); QString data = QString::fromRawData(text.constData(), text.length()); QTextStream stream(&data, QIODevice::ReadOnly); stream.setIntegerBase(10); while (!stream.atEnd()) { qint32 x, y; int flags = 0; char separator; stream >> x >> y >> separator; if (separator != ';') { stream >> flags >> separator; } coords.push_back(MapCoord::fromNative(x, y, flags)); } if (stream.status() == QTextStream::ReadCorruptData) { failed = true; break; } } // otherwise: ignore element }
bool handle(const LLSD& tokens, const LLSD& query_map, LLMediaCtrl* web) { // construct a "normal" SLURL, resolve the region to // a global position, and teleport to it if (tokens.size() < 1) return false; // <FS:AW optional opensim support> #ifdef HAS_OPENSIM_SUPPORT LLSLURL slurl(tokens, true); std::string grid = slurl.getGrid(); std::string gatekeeper = LLGridManager::getInstance()->getGatekeeper(grid); std::string region_name = slurl.getRegion(); std::string dest; std::string current = LLGridManager::getInstance()->getGrid(); if((grid != current ) && (!LLGridManager::getInstance()->isInOpenSim() || (!slurl.getHypergrid() && gatekeeper.empty() ) ) ) { dest = slurl.getSLURLString(); if (!dest.empty()) { LLSD args; args["SLURL"] = dest; args["GRID"] = grid; args["CURRENT_GRID"] = current; LLNotificationsUtil::add("CantTeleportToGrid", args); return true; } } else if(!gatekeeper.empty() && gatekeeper != LLGridManager::getInstance()->getGatekeeper()) { region_name = gatekeeper + ":" + region_name; } dest = "hop://" + current + "/" + region_name; for(int i=2; tokens.size() > i; i++) { dest.append("/" + tokens[i].asString()); } LLWorldMapMessage::getInstance()->sendNamedRegionRequest(region_name, LLURLDispatcherImpl::regionHandleCallback, LLSLURL(dest).getSLURLString(), true); // teleport #else // HAS_OPENSIM_SUPPORT LLVector3 coords(128, 128, 0); if (tokens.size() <= 4) { coords = LLVector3(tokens[1].asReal(), tokens[2].asReal(), tokens[3].asReal()); } // Region names may be %20 escaped. std::string region_name = LLURI::unescape(tokens[0]); LLWorldMapMessage::getInstance()->sendNamedRegionRequest(region_name, LLURLDispatcherImpl::regionHandleCallback, LLSLURL(region_name, coords).getSLURLString(), true); // teleport #endif // HAS_OPENSIM_SUPPORT // </FS:AW optional opensim support> return true; }
void DirectLightingIntegrator::integrate() { const size_t samp_dim = 8; RNG rng; ImageSampler image_sampler(spp, image->width, image->height); // Sample array Array<float> samps(RAYS_AT_A_TIME * samp_dim); // Sample pixel coordinate array Array<uint16_t> coords(RAYS_AT_A_TIME * 2); // Light path array Array<DLPath> paths(RAYS_AT_A_TIME); // Ray and Intersection arrays Array<Ray> rays(RAYS_AT_A_TIME); Array<Intersection> intersections(RAYS_AT_A_TIME); // ids corresponding to the rays Array<uint32_t> ids(RAYS_AT_A_TIME); bool last = false; while (true) { // Generate a bunch of samples std::cout << "\t--------\n\tGenerating samples" << std::endl; std::cout.flush(); for (int i = 0; i < RAYS_AT_A_TIME; i++) { if (!image_sampler.get_next_sample(samp_dim, &(samps[i*samp_dim]), &(coords[i*2]))) { samps.resize(i*samp_dim); paths.resize(i); last = true; break; } else { paths[i].done = false; } } uint32_t ssize = samps.size() / samp_dim; // Size the ray buffer appropriately rays.resize(ssize); // Generate a bunch of camera rays std::cout << "\tGenerating camera rays" << std::endl; std::cout.flush(); for (uint32_t i = 0; i < ssize; i++) { float rx = (samps[i*samp_dim] - 0.5) * (image->max_x - image->min_x); float ry = (0.5 - samps[i*samp_dim+1]) * (image->max_y - image->min_y); float dx = (image->max_x - image->min_x) / image->width; float dy = (image->max_y - image->min_y) / image->height; rays[i] = scene->camera->generate_ray(rx, ry, dx, dy, samps[i*samp_dim+4], samps[i*samp_dim+2], samps[i*samp_dim+3]); rays[i].finalize(); ids[i] = i; } // Trace the camera rays std::cout << "\tTracing camera rays" << std::endl; std::cout.flush(); tracer->trace(rays, &intersections); // Update paths std::cout << "\tUpdating paths" << std::endl; std::cout.flush(); uint32_t rsize = rays.size(); for (uint32_t i = 0; i < rsize; i++) { if (intersections[i].hit) { // Ray hit something! Store intersection data paths[ids[i]].inter = intersections[i]; } else { // Ray didn't hit anything, done and black background paths[ids[i]].done = true; paths[ids[i]].col = Color(0.0, 0.0, 0.0); } } // Generate a bunch of shadow rays std::cout << "\tGenerating shadow rays" << std::endl; std::cout.flush(); uint32_t sri = 0; // Shadow ray index for (uint32_t i = 0; i < ssize; i++) { if (!paths[i].done) { // Select a light and store the normalization factor for it's output Light *lighty = scene->finite_lights[(uint32_t)(samps[i*samp_dim+5] * scene->finite_lights.size()) % scene->finite_lights.size()]; // Sample the light source Vec3 ld; paths[i].lcol = lighty->sample(intersections[i].p, samps[i*samp_dim+6], samps[i*samp_dim+7], rays[i].time, &ld) * (float)(scene->finite_lights.size()); // Create a shadow ray for this path float d = ld.length(); ld.normalize(); rays[sri].o = paths[i].inter.p + paths[i].inter.offset; rays[sri].d = ld; rays[sri].time = samps[i*samp_dim+4]; rays[sri].is_shadow_ray = true; rays[sri].ow = paths[i].inter.owp(); rays[sri].dw = 0.0f; //rays[sri].has_differentials = false; rays[sri].max_t = d; rays[sri].finalize(); ids[sri] = i; // Increment shadow ray index sri++; } } rays.resize(sri); // Trace the shadow rays std::cout << "\tTracing shadow rays" << std::endl; std::cout.flush(); tracer->trace(rays, &intersections); // Calculate sample colors std::cout << "\tCalculating sample colors" << std::endl; std::cout.flush(); rsize = rays.size(); for (uint32_t i = 0; i < rsize; i++) { uint32_t id = ids[i]; if (intersections[i].hit) { // Sample was shadowed paths[id].done = true; paths[id].col = Color(0.0, 0.0, 0.0); } else { // Sample was lit paths[id].inter.n.normalize(); float lambert = dot(rays[i].d, paths[id].inter.n); if (lambert < 0.0) lambert = 0.0; paths[id].col = paths[id].lcol * lambert; } } // Print percentage complete static int32_t last_perc = -1; int32_t perc = image_sampler.percentage() * 100; if (perc > last_perc) { std::cout << perc << "%" << std::endl; last_perc = perc; } if (!Config::no_output) { // Accumulate the samples std::cout << "\tAccumulating samples" << std::endl; std::cout.flush(); for (size_t i = 0; i < ssize; i++) { image->add_sample(paths[i].col, coords[i*2], coords[i*2+1]); } if (callback) callback(); } if (last) break; } }
void ProcessEquiSpacedOutput::SetupEquiSpacedField(void) { if(m_f->m_verbose) { cout << "Interpolating fields to equispaced" << endl; } int coordim = m_f->m_exp[0]->GetCoordim(0); int shapedim = m_f->m_exp[0]->GetExp(0)->GetShapeDimension(); int npts = m_f->m_exp[0]->GetTotPoints(); Array<OneD, Array<OneD, NekDouble> > coords(3); int nel = m_f->m_exp[0]->GetExpSize(); // set up the number of points in each element int newpoints; int newtotpoints = 0; Array<OneD,int> conn; int prevNcoeffs = 0; int prevNpoints = 0; int cnt = 0; // identify face 1 connectivity for prisms map<int,StdRegions::Orientation > face0orient; set<int> prismorient; LocalRegions::ExpansionSharedPtr e; // prepare PtsField vector<std::string> fieldNames; vector<int> ppe; vector<Array<OneD, int> > ptsConn; int nfields; for(int i = 0; i < nel; ++i) { e = m_f->m_exp[0]->GetExp(i); if(e->DetShapeType() == LibUtilities::ePrism) { StdRegions::Orientation forient = e->GetForient(0); int fid = e->GetGeom()->GetFid(0); if(face0orient.count(fid)) { // face 1 meeting face 1 so reverse this id prismorient.insert(i); } else { // just store if Dir 1 is fwd or bwd if((forient == StdRegions::eDir1BwdDir1_Dir2FwdDir2) || (forient == StdRegions::eDir1BwdDir1_Dir2BwdDir2) || (forient == StdRegions::eDir1BwdDir2_Dir2FwdDir1) || (forient == StdRegions::eDir1BwdDir2_Dir2BwdDir1)) { face0orient[fid] = StdRegions::eBwd; } else { face0orient[fid] = StdRegions::eFwd; } } } } for(int i = 0; i < nel; ++i) { e = m_f->m_exp[0]->GetExp(i); if(e->DetShapeType() == LibUtilities::ePrism) { int fid = e->GetGeom()->GetFid(2); // check to see if face 2 meets face 1 if(face0orient.count(fid)) { // check to see how face 2 is orientated StdRegions::Orientation forient2 = e->GetForient(2); StdRegions::Orientation forient0 = face0orient[fid]; // If dir 1 or forient2 is bwd then check agains // face 1 value if((forient2 == StdRegions::eDir1BwdDir1_Dir2FwdDir2) || (forient2 == StdRegions::eDir1BwdDir1_Dir2BwdDir2) || (forient2 == StdRegions::eDir1BwdDir2_Dir2FwdDir1) || (forient2 == StdRegions::eDir1BwdDir2_Dir2BwdDir1)) { if(forient0 == StdRegions::eFwd) { prismorient.insert(i); } } else { if(forient0 == StdRegions::eBwd) { prismorient.insert(i); } } } } } for(int i = 0; i < nel; ++i) { e = m_f->m_exp[0]->GetExp(i); if(m_config["tetonly"].m_beenSet) { if(m_f->m_exp[0]->GetExp(i)->DetShapeType() != LibUtilities::eTetrahedron) { continue; } } ppe.push_back(newpoints); newtotpoints += newpoints; switch(e->DetShapeType()) { case LibUtilities::eSegment: { int npoints0 = e->GetBasis(0)->GetNumPoints(); newpoints = LibUtilities::StdSegData:: getNumberOfCoefficients(npoints0); } break; case LibUtilities::eTriangle: { int np0 = e->GetBasis(0)->GetNumPoints(); int np1 = e->GetBasis(1)->GetNumPoints(); int np = max(np0,np1); newpoints = LibUtilities::StdTriData:: getNumberOfCoefficients(np,np); } break; case LibUtilities::eQuadrilateral: { int np0 = e->GetBasis(0)->GetNumPoints(); int np1 = e->GetBasis(1)->GetNumPoints(); int np = max(np0,np1); newpoints = LibUtilities::StdQuadData:: getNumberOfCoefficients(np,np); } break; case LibUtilities::eTetrahedron: { int np0 = e->GetBasis(0)->GetNumPoints(); int np1 = e->GetBasis(1)->GetNumPoints(); int np2 = e->GetBasis(2)->GetNumPoints(); int np = max(np0,max(np1,np2)); newpoints = LibUtilities::StdTetData:: getNumberOfCoefficients(np,np,np); } break; case LibUtilities::ePrism: { int np0 = e->GetBasis(0)->GetNumPoints(); int np1 = e->GetBasis(1)->GetNumPoints(); int np2 = e->GetBasis(2)->GetNumPoints(); int np = max(np0,max(np1,np2)); newpoints = LibUtilities::StdPrismData:: getNumberOfCoefficients(np,np,np); } break; case LibUtilities::ePyramid: { int np0 = e->GetBasis(0)->GetNumPoints(); int np1 = e->GetBasis(1)->GetNumPoints(); int np2 = e->GetBasis(2)->GetNumPoints(); int np = max(np0,max(np1,np2)); newpoints = LibUtilities::StdPyrData:: getNumberOfCoefficients(np,np,np); } break; case LibUtilities::eHexahedron: { int np0 = e->GetBasis(0)->GetNumPoints(); int np1 = e->GetBasis(1)->GetNumPoints(); int np2 = e->GetBasis(2)->GetNumPoints(); int np = max(np0,max(np1,np2)); newpoints = LibUtilities::StdPyrData:: getNumberOfCoefficients(np,np,np); } break; default: { ASSERTL0(false,"Points not known"); } } if(e->DetShapeType() == LibUtilities::ePrism) { bool standard = true; if(prismorient.count(i)) { standard = false; // reverse direction } e->GetSimplexEquiSpacedConnectivity(conn,standard); } else { if((prevNcoeffs != e->GetNcoeffs()) || (prevNpoints != e->GetTotPoints())) { prevNcoeffs = e->GetNcoeffs(); prevNpoints = e->GetTotPoints(); e->GetSimplexEquiSpacedConnectivity(conn); } } Array<OneD, int> newconn(conn.num_elements()); for(int j = 0; j < conn.num_elements(); ++j) { newconn[j] = conn[j] + cnt; } ptsConn.push_back(newconn); cnt += newpoints; } if(m_f->m_fielddef.size()) { nfields = m_f->m_exp.size(); } else // just the mesh points { nfields = 0; } Array<OneD, Array<OneD, NekDouble> > pts(nfields + coordim); for(int i = 0; i < nfields + coordim; ++i) { pts[i] = Array<OneD, NekDouble>(newtotpoints); } // Interpolate coordinates for(int i = 0; i < coordim; ++i) { coords[i] = Array<OneD, NekDouble>(npts); } for(int i = coordim; i < 3; ++i) { coords[i] = NullNekDouble1DArray; } m_f->m_exp[0]->GetCoords(coords[0],coords[1],coords[2]); int nq1 = m_f->m_exp[0]->GetTotPoints(); Array<OneD, NekDouble> x1(nq1); Array<OneD, NekDouble> y1(nq1); Array<OneD, NekDouble> z1(nq1); m_f->m_exp[0]->GetCoords(x1, y1, z1); Array<OneD, NekDouble> tmp; for(int n = 0; n < coordim; ++n) { cnt = 0; int cnt1 = 0; for(int i = 0; i < nel; ++i) { m_f->m_exp[0]->GetExp(i)->PhysInterpToSimplexEquiSpaced( coords[n] + cnt, tmp = pts[n] + cnt1); cnt1 += ppe[i]; cnt += m_f->m_exp[0]->GetExp(i)->GetTotPoints(); } } if(m_f->m_fielddef.size()) { ASSERTL0(m_f->m_fielddef[0]->m_fields.size() == m_f->m_exp.size(), "More expansion defined than fields"); for(int n = 0; n < m_f->m_exp.size(); ++n) { cnt = 0; int cnt1 = 0; if(m_config["modalenergy"].m_beenSet) { Array<OneD, const NekDouble> phys = m_f->m_exp[n]->GetPhys(); for(int i = 0; i < nel; ++i) { GenOrthoModes(i,phys+cnt,tmp = pts[coordim + n] + cnt1); cnt1 += ppe[i]; cnt += m_f->m_exp[0]->GetExp(i)->GetTotPoints(); } } else { Array<OneD, const NekDouble> phys = m_f->m_exp[n]->GetPhys(); for(int i = 0; i < nel; ++i) { m_f->m_exp[0]->GetExp(i)->PhysInterpToSimplexEquiSpaced( phys + cnt, tmp = pts[coordim + n] + cnt1); cnt1 += ppe[i]; cnt += m_f->m_exp[0]->GetExp(i)->GetTotPoints(); } } // Set up Variable string. fieldNames.push_back(m_f->m_fielddef[0]->m_fields[n]); } } m_f->m_fieldPts = MemoryManager<LibUtilities::PtsField>::AllocateSharedPtr(coordim, fieldNames, pts); if (shapedim == 2) { m_f->m_fieldPts->SetPtsType(LibUtilities::ePtsTriBlock); } else if (shapedim == 3) { m_f->m_fieldPts->SetPtsType(LibUtilities::ePtsTetBlock); } m_f->m_fieldPts->SetConnectivity(ptsConn); }
void IntrepidKernel<Scalar>::transformPoint( double param_coords[3], const double physical_coords[3], const iMesh_Instance mesh, const iBase_EntityHandle physical_cell ) { int error = 0; iBase_EntityHandle *element_nodes = 0; int element_nodes_allocated = 0; int element_nodes_size = 0; iMesh_getEntAdj( mesh, physical_cell, iBase_VERTEX, &element_nodes, &element_nodes_allocated, &element_nodes_size, &error ); assert( iBase_SUCCESS == error ); TopologyTools::MBCN2Shards( element_nodes, element_nodes_size, this->b_topology ); int coords_allocated = 0; int coords_size = 0; double *coord_array = 0; iMesh_getVtxArrCoords( mesh, element_nodes, element_nodes_size, iBase_INTERLEAVED, &coord_array, &coords_allocated, &coords_size, &error ); assert( iBase_SUCCESS == error ); Teuchos::Tuple<int,3> cell_node_dimensions; cell_node_dimensions[0] = 1; cell_node_dimensions[1] = element_nodes_size; cell_node_dimensions[2] = 3; MDArray cell_nodes( Teuchos::Array<int>(cell_node_dimensions), coord_array ); MDArray reference_point( 1, 3 ); MDArray coords( 1, 3 ); coords(0,0) = physical_coords[0]; coords(0,1) = physical_coords[1]; coords(0,2) = physical_coords[2]; Intrepid::CellTools<double>::mapToReferenceFrame( reference_point, coords, cell_nodes, d_intrepid_basis->getBaseCellTopology(), 0 ); param_coords[0] = reference_point(0,0); param_coords[1] = reference_point(0,1); param_coords[2] = reference_point(0,2); free( element_nodes ); free( coord_array ); }
static void calculateAlphaPatchMatch(const cv::Mat_<cv::Vec3b> &image, const cv::Mat_<uchar> &trimap, const std::vector<cv::Point> &foregroundBoundary, const std::vector<cv::Point> &backgroundBoundary, std::vector<std::vector<Sample> > &samples) { int w = image.cols; int h = image.rows; samples.resize(h, std::vector<Sample>(w)); for (int y = 0; y < h; ++y) for (int x = 0; x < w; ++x) { if (trimap(y, x) == 128) { cv::Point p(x, y); samples[y][x].fi = rand() % foregroundBoundary.size(); samples[y][x].bj = rand() % backgroundBoundary.size(); samples[y][x].df = nearestDistance(foregroundBoundary, p); samples[y][x].db = nearestDistance(backgroundBoundary, p); samples[y][x].cost = FLT_MAX; } } std::vector<cv::Point> coords(w * h); for (int y = 0; y < h; ++y) for (int x = 0; x < w; ++x) coords[x + y * w] = cv::Point(x, y); for (int iter = 0; iter < 10; ++iter) { // propagation std::random_shuffle(coords.begin(), coords.end()); for (std::size_t i = 0; i < coords.size(); ++i) { const cv::Point &p = coords[i]; int x = p.x; int y = p.y; if (trimap(y, x) != 128) continue; const cv::Vec3b &I = image(y, x); Sample &s = samples[y][x]; for (int y2 = y - 1; y2 <= y + 1; ++y2) for (int x2 = x - 1; x2 <= x + 1; ++x2) { if (x2 < 0 || x2 >= w || y2 < 0 || y2 >= h) continue; if (trimap(y2, x2) != 128) continue; Sample &s2 = samples[y2][x2]; const cv::Point &fp = foregroundBoundary[s2.fi]; const cv::Point &bp = backgroundBoundary[s2.bj]; const cv::Vec3b F = image(fp.y, fp.x); const cv::Vec3b B = image(bp.y, bp.x); float alpha = calculateAlpha(F, B, I); float cost = colorCost(F, B, I, alpha) + distCost(p, fp, s.df) + distCost(p, bp, s.db); if (cost < s.cost) { s.fi = s2.fi; s.bj = s2.bj; s.cost = cost; s.alpha = alpha; } } } // random walk int w2 = (int)std::max(foregroundBoundary.size(), backgroundBoundary.size()); for (int y = 0; y < h; ++y) for (int x = 0; x < w; ++x) { if (trimap(y, x) != 128) continue; cv::Point p(x, y); const cv::Vec3b &I = image(y, x); Sample &s = samples[y][x]; for (int k = 0; ; k++) { float r = w2 * pow(0.5f, k); if (r < 1) break; int di = r * (rand() / (RAND_MAX + 1.f)); int dj = r * (rand() / (RAND_MAX + 1.f)); int fi = s.fi + di; int bj = s.bj + dj; if (fi < 0 || fi >= foregroundBoundary.size() || bj < 0 || bj >= backgroundBoundary.size()) continue; const cv::Point &fp = foregroundBoundary[fi]; const cv::Point &bp = backgroundBoundary[bj]; const cv::Vec3b F = image(fp.y, fp.x); const cv::Vec3b B = image(bp.y, bp.x); float alpha = calculateAlpha(F, B, I); float cost = colorCost(F, B, I, alpha) + distCost(p, fp, s.df) + distCost(p, bp, s.db); if (cost < s.cost) { s.fi = fi; s.bj = bj; s.cost = cost; s.alpha = alpha; } } } } }
/** * Render text using the currently loaded font and currently set font size. * Rendering starts at coordinates (x, y), z is always 0. * The pixel coordinates that the FreeType2 library uses are scaled by (sx, sy). */ void TextDrawer::renderText(const char *_pText, float _x, float _y) const { if (m_pAtlas == nullptr) return; OGLVideo & ogl = video(); const float sx = 2.0f / ogl.getWidth(); const float sy = 2.0f / ogl.getHeight(); const u8 *p; glUseProgram(m_program); /* Enable blending, necessary for our alpha texture */ glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glDisable(GL_CULL_FACE); glDisable(GL_DEPTH_TEST); glDepthMask(GL_FALSE); /* Set color */ glUniform4fv(m_uColor, 1, config.font.colorf); /* Use the texture containing the atlas */ glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, m_pAtlas->tex); glUniform1i(m_uTex, 0); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); #ifndef GLES2 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0); #endif /* Set up the VBO for our vertex data */ glBindBuffer(GL_ARRAY_BUFFER, m_vbo); glVertexAttribPointer(SC_POSITION, 4, GL_FLOAT, GL_FALSE, 0, 0); std::vector<point> coords(6 * strlen(_pText)); int c = 0; /* Loop through all characters */ for (p = (const u8 *)_pText; *p; ++p) { /* Calculate the vertex and texture coordinates */ float x2 = _x + m_pAtlas->c[*p].bl * sx; float y2 = -_y - m_pAtlas->c[*p].bt * sy; float w = m_pAtlas->c[*p].bw * sx; float h = m_pAtlas->c[*p].bh * sy; /* Advance the cursor to the start of the next character */ _x += m_pAtlas->c[*p].ax * sx; _y += m_pAtlas->c[*p].ay * sy; /* Skip glyphs that have no pixels */ if (!w || !h) continue; coords[c++] = point(x2, -y2, m_pAtlas->c[*p].tx, m_pAtlas->c[*p].ty); coords[c++] = point(x2 + w, -y2, m_pAtlas->c[*p].tx + m_pAtlas->c[*p].bw / m_pAtlas->w, m_pAtlas->c[*p].ty); coords[c++] = point(x2, -y2 - h, m_pAtlas->c[*p].tx, m_pAtlas->c[*p].ty + m_pAtlas->c[*p].bh / m_pAtlas->h); coords[c++] = point(x2 + w, -y2, m_pAtlas->c[*p].tx + m_pAtlas->c[*p].bw / m_pAtlas->w, m_pAtlas->c[*p].ty); coords[c++] = point(x2, -y2 - h, m_pAtlas->c[*p].tx, m_pAtlas->c[*p].ty + m_pAtlas->c[*p].bh / m_pAtlas->h); coords[c++] = point(x2 + w, -y2 - h, m_pAtlas->c[*p].tx + m_pAtlas->c[*p].bw / m_pAtlas->w, m_pAtlas->c[*p].ty + m_pAtlas->c[*p].bh / m_pAtlas->h); } /* Draw all the character on the screen in one go */ glBufferData(GL_ARRAY_BUFFER, coords.size()*sizeof(point), coords.data(), GL_DYNAMIC_DRAW); glDrawArrays(GL_TRIANGLES, 0, c); glBindBuffer(GL_ARRAY_BUFFER, 0); }
void CoordXmlTest::readXml() { QFETCH(int, num_coords); MapCoordVector coords(num_coords, proto_coord); buffer.buffer().truncate(0); QBuffer header; { QXmlStreamWriter xml(&header); header.open(QBuffer::ReadWrite); xml.setAutoFormatting(false); xml.writeStartDocument(); xml.writeStartElement("root"); xml.writeCharacters(" "); // flush root start element buffer.open(QBuffer::ReadWrite); xml.setDevice(&buffer); xml.writeStartElement("coords"); writeXml_implementation(coords, xml); xml.writeEndElement(/* coords */); xml.setDevice(NULL); buffer.close(); header.close(); } header.open(QBuffer::ReadOnly); buffer.open(QBuffer::ReadOnly); QXmlStreamReader xml; xml.addData(header.buffer()); xml.readNextStartElement(); QCOMPARE(xml.name().toString(), QString("root")); bool failed = false; QBENCHMARK { // benchmark iteration overhead coords.clear(); xml.addData(buffer.data()); xml.readNextStartElement(); if (xml.name() != "coords") { failed = true; break; } while(xml.readNextStartElement()) { if (xml.name() != XmlStreamLiteral::coord) { failed = true; break; } XmlElementReader element(xml); auto x = element.attribute<qint32>(literal::x); auto y = element.attribute<qint32>(literal::y); auto flags = element.attribute<int>(literal::flags); coords.push_back(MapCoord::fromNative(x, y, flags)); } } QVERIFY(!failed); QCOMPARE((int)coords.size(), num_coords); QVERIFY(compare_all(coords, proto_coord)); header.close(); buffer.close(); }