//! [4] void MainWindow::createActions() { //! [5] newAct = new QAction(tr("&New"), this); newAct->setShortcuts(QKeySequence::New); newAct->setStatusTip(tr("Create a new file")); connect(newAct, SIGNAL(triggered()), this, SLOT(newFile())); //! [4] openAct = new QAction(tr("&Open..."), this); openAct->setShortcuts(QKeySequence::Open); openAct->setStatusTip(tr("Open an existing file")); connect(openAct, SIGNAL(triggered()), this, SLOT(open())); //! [5] saveAct = new QAction(tr("&Save"), this); saveAct->setShortcuts(QKeySequence::Save); saveAct->setStatusTip(tr("Save the document to disk")); connect(saveAct, SIGNAL(triggered()), this, SLOT(save())); printAct = new QAction(tr("&Print..."), this); printAct->setShortcuts(QKeySequence::Print); printAct->setStatusTip(tr("Print the document")); connect(printAct, SIGNAL(triggered()), this, SLOT(print())); exitAct = new QAction(tr("E&xit"), this); exitAct->setShortcuts(QKeySequence::Quit); exitAct->setStatusTip(tr("Exit the application")); connect(exitAct, SIGNAL(triggered()), this, SLOT(close())); undoAct = new QAction(tr("&Undo"), this); undoAct->setShortcuts(QKeySequence::Undo); undoAct->setStatusTip(tr("Undo the last operation")); connect(undoAct, SIGNAL(triggered()), this, SLOT(undo())); redoAct = new QAction(tr("&Redo"), this); redoAct->setShortcuts(QKeySequence::Redo); redoAct->setStatusTip(tr("Redo the last operation")); connect(redoAct, SIGNAL(triggered()), this, SLOT(redo())); cutAct = new QAction(tr("Cu&t"), this); cutAct->setShortcuts(QKeySequence::Cut); cutAct->setStatusTip(tr("Cut the current selection's contents to the " "clipboard")); connect(cutAct, SIGNAL(triggered()), this, SLOT(cut())); copyAct = new QAction(tr("&Copy"), this); copyAct->setShortcuts(QKeySequence::Copy); copyAct->setStatusTip(tr("Copy the current selection's contents to the " "clipboard")); connect(copyAct, SIGNAL(triggered()), this, SLOT(copy())); pasteAct = new QAction(tr("&Paste"), this); pasteAct->setShortcuts(QKeySequence::Paste); pasteAct->setStatusTip(tr("Paste the clipboard's contents into the current " "selection")); connect(pasteAct, SIGNAL(triggered()), this, SLOT(paste())); boldAct = new QAction(tr("&Bold"), this); boldAct->setCheckable(true); boldAct->setShortcut(QKeySequence::Bold); boldAct->setStatusTip(tr("Make the text bold")); connect(boldAct, SIGNAL(triggered()), this, SLOT(bold())); QFont boldFont = boldAct->font(); boldFont.setBold(true); boldAct->setFont(boldFont); italicAct = new QAction(tr("&Italic"), this); italicAct->setCheckable(true); italicAct->setShortcut(QKeySequence::Italic); italicAct->setStatusTip(tr("Make the text italic")); connect(italicAct, SIGNAL(triggered()), this, SLOT(italic())); QFont italicFont = italicAct->font(); italicFont.setItalic(true); italicAct->setFont(italicFont); setLineSpacingAct = new QAction(tr("Set &Line Spacing..."), this); setLineSpacingAct->setStatusTip(tr("Change the gap between the lines of a " "paragraph")); connect(setLineSpacingAct, SIGNAL(triggered()), this, SLOT(setLineSpacing())); setParagraphSpacingAct = new QAction(tr("Set &Paragraph Spacing..."), this); setLineSpacingAct->setStatusTip(tr("Change the gap between paragraphs")); connect(setParagraphSpacingAct, SIGNAL(triggered()), this, SLOT(setParagraphSpacing())); aboutAct = new QAction(tr("&About"), this); aboutAct->setStatusTip(tr("Show the application's About box")); connect(aboutAct, SIGNAL(triggered()), this, SLOT(about())); aboutQtAct = new QAction(tr("About &Qt"), this); aboutQtAct->setStatusTip(tr("Show the Qt library's About box")); connect(aboutQtAct, SIGNAL(triggered()), qApp, SLOT(aboutQt())); connect(aboutQtAct, SIGNAL(triggered()), this, SLOT(aboutQt())); leftAlignAct = new QAction(tr("&Left Align"), this); leftAlignAct->setCheckable(true); leftAlignAct->setShortcut(tr("Ctrl+L")); leftAlignAct->setStatusTip(tr("Left align the selected text")); connect(leftAlignAct, SIGNAL(triggered()), this, SLOT(leftAlign())); rightAlignAct = new QAction(tr("&Right Align"), this); rightAlignAct->setCheckable(true); rightAlignAct->setShortcut(tr("Ctrl+R")); rightAlignAct->setStatusTip(tr("Right align the selected text")); connect(rightAlignAct, SIGNAL(triggered()), this, SLOT(rightAlign())); justifyAct = new QAction(tr("&Justify"), this); justifyAct->setCheckable(true); justifyAct->setShortcut(tr("Ctrl+J")); justifyAct->setStatusTip(tr("Justify the selected text")); connect(justifyAct, SIGNAL(triggered()), this, SLOT(justify())); centerAct = new QAction(tr("&Center"), this); centerAct->setCheckable(true); centerAct->setShortcut(tr("Ctrl+E")); centerAct->setStatusTip(tr("Center the selected text")); connect(centerAct, SIGNAL(triggered()), this, SLOT(center())); //! [6] //! [7] alignmentGroup = new QActionGroup(this); alignmentGroup->addAction(leftAlignAct); alignmentGroup->addAction(rightAlignAct); alignmentGroup->addAction(justifyAct); alignmentGroup->addAction(centerAct); leftAlignAct->setChecked(true); //! [6] }
void KviCtcpPageDialog::showEvent(QShowEvent *e) { QWidget::showEvent(e); center(); }
void MerchantRepair::open() { center(); // Reset scrollbars mList->setViewOffset(MyGUI::IntPoint(0, 0)); }
bool UpdateTextured(Textured & t, Range & r){ //now, set new current_range: V3f center((r.min+r.max)/2); center.x = floorf(center.x); center.y = floorf(center.y); center.z = floorf(center.z); V3f half_diagonal(SIZE/2, SIZE/2, SIZE/2); t.current_range = Range(center-half_diagonal, center+half_diagonal); //fill it with a dummy texture for now (maybe //better done with an external class Range fast_volume_range(V3f(0,0,0), V3f(255,255,255)); unsigned char res; V3f c(t.current_range.min); //start for(int x = 0; x < SIZE; x++) for(int y = 0; y < SIZE; y++) for(int z = 0; z < SIZE; z++){ V3f cur(c.x+x, c.y+y, c.z+z); if(t.texturing_fastvolume){ res = (unsigned char)t.texturing_fastvolume->\ SampleCentered((int)cur.x%255, (int)cur.y%255, (int)cur.z%255); //Color conversion. /* int r = res * 3; r=(r<0)?0:(r>255?255:r); int g = (res - 80) * 3; g=(g<0)?0:(g>255?255:g); int b = (res - 160) * 3; b=(b<0)?0:(b>255?255:b); */ float f_res = res; // f_res *= f_res; f_res /= 60.0; int r = f_res; int g = f_res; int b = f_res; ((BYTE)t.data)[Offset(x,y,z)] = r; ((BYTE)t.data)[Offset(x,y,z)+1] = g; ((BYTE)t.data)[Offset(x,y,z)+2] = b; ((BYTE)t.data)[Offset(x,y,z)+3] = 255; }else{ bool line_hit = !((int)cur.x % 10) || !((int)cur.y % 10) || !((int)cur.z % 10); ((BYTE)t.data)[Offset(x,y,z)] = line_hit?30:300; ((BYTE)t.data)[Offset(x,y,z)+1] =line_hit?70:0; ((BYTE)t.data)[Offset(x,y,z)+2] =line_hit?300:30; ((BYTE)t.data)[Offset(x,y,z)+3] = 200; }; }; //ready; now load the texture UploadTexture(t.data); return true; };
MailEditWindow::MailEditWindow() : // TRANSLATORS: mail edit window name Window(_("Edit mail"), Modal_false, nullptr, "mailedit.xml"), ActionListener(), // TRANSLATORS: mail edit window button mSendButton(new Button(this, _("Send"), "send", this)), // TRANSLATORS: mail edit window button mCloseButton(new Button(this, _("Close"), "close", this)), // TRANSLATORS: mail edit window button mAddButton(new Button(this, _("Add"), "add", this)), // TRANSLATORS: mail edit window label mToLabel(new Label(this, _("To:"))), // TRANSLATORS: mail edit window label mSubjectLabel(new Label(this, _("Subject:"))), // TRANSLATORS: mail edit window label mMoneyLabel(new Label(this, _("Money:"))), // TRANSLATORS: mail edit window label mItemLabel(new Label(this, _("Item:"))), // TRANSLATORS: mail edit window label mMessageLabel(new Label(this, _("Message:"))), mToField(new TextField(this)), mSubjectField(new TextField(this)), mMoneyField(new IntTextField(this, 0, 0, 10000000)), mMessageField(new TextField(this)), mInventory(new Inventory(InventoryType::Mail, 1)), mItemContainer(new ItemContainer(this, mInventory)), mItemScrollArea(new ScrollArea(this, mItemContainer, fromBool(getOptionBool("showitemsbackground"), Opaque), "mailedit_listbackground.xml")) { setWindowName("MailEdit"); setCloseButton(true); setResizable(true); setCloseButton(true); setSaveVisible(false); setStickyButtonLock(true); setVisible(Visible_true); setDefaultSize(380, 200, ImagePosition::CENTER); setMinWidth(200); setMinHeight(200); center(); ContainerPlacer placer; placer = getPlacer(0, 0); mToField->setWidth(100); mSubjectField->setWidth(100); mMessageField->setWidth(100); mItemScrollArea->setHeight(70); mItemScrollArea->setHorizontalScrollPolicy(ScrollArea::SHOW_NEVER); mItemScrollArea->setVerticalScrollPolicy(ScrollArea::SHOW_NEVER); placer(0, 0, mToLabel); placer(1, 0, mToField, 3); placer(0, 1, mSubjectLabel); placer(1, 1, mSubjectField, 3); placer(0, 2, mMoneyLabel); placer(1, 2, mMoneyField, 3); placer(0, 3, mItemLabel); placer(1, 3, mItemScrollArea, 2, 2); placer(3, 4, mAddButton, 1); placer(0, 5, mMessageLabel); placer(1, 5, mMessageField, 3); placer(0, 6, mSendButton); placer(3, 6, mCloseButton); loadWindowState(); enableVisibleSound(true); }
void pcl::rec_3d_framework::GlobalNNCVFHRecognizer<Distance, PointInT, FeatureT>::recognize () { models_.reset (new std::vector<ModelT>); transforms_.reset (new std::vector<Eigen::Matrix4d, Eigen::aligned_allocator<Eigen::Matrix4d> >); PointInTPtr processed (new pcl::PointCloud<PointInT>); PointInTPtr in (new pcl::PointCloud<PointInT>); std::vector<pcl::PointCloud<FeatureT>, Eigen::aligned_allocator<pcl::PointCloud<FeatureT> > > signatures; std::vector < Eigen::Vector3d > centroids; if (indices_.size ()) pcl::copyPointCloud (*input_, indices_, *in); else in = input_; { pcl::ScopeTime t ("Estimate feature"); micvfh_estimator_->estimate (in, processed, signatures, centroids); } std::vector<index_score> indices_scores; descriptor_distances_.clear (); if (signatures.size () > 0) { { pcl::ScopeTime t_matching ("Matching and roll..."); if (use_single_categories_ && (categories_to_be_searched_.size () > 0)) { //perform search of the different signatures in the categories_to_be_searched_ for (size_t c = 0; c < categories_to_be_searched_.size (); c++) { std::cout << "Using category:" << categories_to_be_searched_[c] << std::endl; for (size_t idx = 0; idx < signatures.size (); idx++) { /*double* hist = signatures[idx].points[0].histogram; std::vector<double> std_hist (hist, hist + getHistogramLength (dummy)); flann_model histogram ("", std_hist); flann::Matrix<int> indices; flann::Matrix<double> distances; std::map<std::string, int>::iterator it; it = category_to_vectors_indices_.find (categories_to_be_searched_[c]); assert (it != category_to_vectors_indices_.end ()); nearestKSearch (single_categories_index_[it->second], histogram, nmodels_, indices, distances);*/ double* hist = signatures[idx].points[0].histogram; int size_feat = sizeof(signatures[idx].points[0].histogram) / sizeof(double); std::vector<double> std_hist (hist, hist + size_feat); //ModelT empty; flann_model histogram; histogram.descr = std_hist; flann::Matrix<int> indices; flann::Matrix<double> distances; std::map<std::string, int>::iterator it; it = category_to_vectors_indices_.find (categories_to_be_searched_[c]); assert (it != category_to_vectors_indices_.end ()); nearestKSearch (single_categories_index_[it->second], histogram, NN_, indices, distances); //gather NN-search results double score = 0; for (size_t i = 0; i < NN_; ++i) { score = distances[0][i]; index_score is; is.idx_models_ = single_categories_pointers_to_models_[it->second]->at (indices[0][i]); is.idx_input_ = static_cast<int> (idx); is.score_ = score; indices_scores.push_back (is); } } //we cannot add more than nmodels per category, so sort here and remove offending ones... std::sort (indices_scores.begin (), indices_scores.end (), sortIndexScoresOp); indices_scores.resize ((c + 1) * NN_); } } else { for (size_t idx = 0; idx < signatures.size (); idx++) { double* hist = signatures[idx].points[0].histogram; int size_feat = sizeof(signatures[idx].points[0].histogram) / sizeof(double); std::vector<double> std_hist (hist, hist + size_feat); //ModelT empty; flann_model histogram; histogram.descr = std_hist; flann::Matrix<int> indices; flann::Matrix<double> distances; nearestKSearch (flann_index_, histogram, NN_, indices, distances); //gather NN-search results double score = 0; for (int i = 0; i < NN_; ++i) { score = distances[0][i]; index_score is; is.idx_models_ = indices[0][i]; is.idx_input_ = static_cast<int> (idx); is.score_ = score; indices_scores.push_back (is); //ModelT m = flann_models_[indices[0][i]].model; } } } std::sort (indices_scores.begin (), indices_scores.end (), sortIndexScoresOp); /* * There might be duplicated candidates, in those cases it makes sense to take * the closer one in descriptor space */ typename std::map<flann_model, bool> found; typename std::map<flann_model, bool>::iterator it_map; for (size_t i = 0; i < indices_scores.size (); i++) { flann_model m = flann_models_[indices_scores[i].idx_models_]; it_map = found.find (m); if (it_map == found.end ()) { indices_scores[found.size ()] = indices_scores[i]; found[m] = true; } } indices_scores.resize (found.size ()); int num_n = std::min (NN_, static_cast<int> (indices_scores.size ())); /* * Filter some hypothesis regarding to their distance to the first neighbour */ /*std::vector<index_score> indices_scores_filtered; indices_scores_filtered.resize (num_n); indices_scores_filtered[0] = indices_scores[0]; double best_score = indices_scores[0].score_; int kept = 1; for (int i = 1; i < num_n; ++i) { //std::cout << best_score << indices_scores[i].score_ << (best_score / indices_scores[i].score_) << std::endl; if ((best_score / indices_scores[i].score_) > 0.65) { indices_scores_filtered[i] = indices_scores[i]; kept++; } //best_score = indices_scores[i].score_; } indices_scores_filtered.resize (kept); //std::cout << indices_scores_filtered.size () << " § " << num_n << std::endl; indices_scores = indices_scores_filtered; num_n = indices_scores.size ();*/ std::cout << "Number of object hypotheses... " << num_n << std::endl; std::vector<bool> valid_trans; std::vector < Eigen::Matrix4d, Eigen::aligned_allocator<Eigen::Matrix4d> > transformations; micvfh_estimator_->getValidTransformsVec (valid_trans); micvfh_estimator_->getTransformsVec (transformations); for (int i = 0; i < num_n; ++i) { ModelT m = flann_models_[indices_scores[i].idx_models_].model; int view_id = flann_models_[indices_scores[i].idx_models_].view_id; int desc_id = flann_models_[indices_scores[i].idx_models_].descriptor_id; int idx_input = indices_scores[i].idx_input_; std::cout << m.class_ << "/" << m.id_ << " ==> " << indices_scores[i].score_ << std::endl; Eigen::Matrix4d roll_view_pose; bool roll_pose_found = getRollPose (m, view_id, desc_id, roll_view_pose); if (roll_pose_found && valid_trans[idx_input]) { Eigen::Matrix4d transposed = roll_view_pose.transpose (); //std::cout << transposed << std::endl; PointInTPtr view; getView (m, view_id, view); Eigen::Matrix4d model_view_pose; getPose (m, view_id, model_view_pose); Eigen::Matrix4d scale_mat; scale_mat.setIdentity (4, 4); if (compute_scale_) { //compute scale using the whole view PointInTPtr view_transformed (new pcl::PointCloud<PointInT>); Eigen::Matrix4d hom_from_OVC_to_CC; hom_from_OVC_to_CC = transformations[idx_input].inverse () * transposed; pcl::transformPointCloud (*view, *view_transformed, hom_from_OVC_to_CC); Eigen::Vector3d input_centroid = centroids[indices_scores[i].idx_input_]; Eigen::Vector3d view_centroid; getCentroid (m, view_id, desc_id, view_centroid); Eigen::Vector4d cmatch4f (view_centroid[0], view_centroid[1], view_centroid[2], 0); Eigen::Vector4d cinput4f (input_centroid[0], input_centroid[1], input_centroid[2], 0); Eigen::Vector4d max_pt_input; pcl::getMaxDistance (*processed, cinput4f, max_pt_input); max_pt_input[3] = 0; double max_dist_input = (cinput4f - max_pt_input).norm (); //compute max dist for transformed model_view pcl::getMaxDistance (*view, cmatch4f, max_pt_input); max_pt_input[3] = 0; double max_dist_view = (cmatch4f - max_pt_input).norm (); cmatch4f = hom_from_OVC_to_CC * cmatch4f; std::cout << max_dist_view << " " << max_dist_input << std::endl; double scale_factor_view = max_dist_input / max_dist_view; std::cout << "Scale factor:" << scale_factor_view << std::endl; Eigen::Matrix4d center, center_inv; center.setIdentity (4, 4); center (0, 3) = -cinput4f[0]; center (1, 3) = -cinput4f[1]; center (2, 3) = -cinput4f[2]; center_inv.setIdentity (4, 4); center_inv (0, 3) = cinput4f[0]; center_inv (1, 3) = cinput4f[1]; center_inv (2, 3) = cinput4f[2]; scale_mat (0, 0) = scale_factor_view; scale_mat (1, 1) = scale_factor_view; scale_mat (2, 2) = scale_factor_view; scale_mat = center_inv * scale_mat * center; } Eigen::Matrix4d hom_from_OC_to_CC; hom_from_OC_to_CC = scale_mat * transformations[idx_input].inverse () * transposed * model_view_pose; models_->push_back (m); transforms_->push_back (hom_from_OC_to_CC); descriptor_distances_.push_back (static_cast<double> (indices_scores[i].score_)); } else { PCL_WARN("The roll pose was not found, should use CRH here... \n"); } } } std::cout << "Number of object hypotheses:" << models_->size () << std::endl; /** * POSE REFINEMENT **/ if (ICP_iterations_ > 0) { pcl::ScopeTime t ("Pose refinement"); //Prepare scene and model clouds for the pose refinement step double VOXEL_SIZE_ICP_ = 0.005; PointInTPtr cloud_voxelized_icp (new pcl::PointCloud<PointInT> ()); { pcl::ScopeTime t ("Voxelize stuff..."); pcl::VoxelGrid<PointInT> voxel_grid_icp; voxel_grid_icp.setInputCloud (processed); voxel_grid_icp.setLeafSize (VOXEL_SIZE_ICP_, VOXEL_SIZE_ICP_, VOXEL_SIZE_ICP_); voxel_grid_icp.filter (*cloud_voxelized_icp); source_->voxelizeAllModels (VOXEL_SIZE_ICP_); } #pragma omp parallel for num_threads(omp_get_num_procs()) for (int i = 0; i < static_cast<int> (models_->size ()); i++) { ConstPointInTPtr model_cloud; PointInTPtr model_aligned (new pcl::PointCloud<PointInT>); if (compute_scale_) { model_cloud = models_->at (i).getAssembled (-1); PointInTPtr model_aligned_m (new pcl::PointCloud<PointInT>); pcl::transformPointCloud (*model_cloud, *model_aligned_m, transforms_->at (i)); pcl::VoxelGrid<PointInT> voxel_grid_icp; voxel_grid_icp.setInputCloud (model_aligned_m); voxel_grid_icp.setLeafSize (VOXEL_SIZE_ICP_, VOXEL_SIZE_ICP_, VOXEL_SIZE_ICP_); voxel_grid_icp.filter (*model_aligned); } else { model_cloud = models_->at (i).getAssembled (VOXEL_SIZE_ICP_); pcl::transformPointCloud (*model_cloud, *model_aligned, transforms_->at (i)); } pcl::IterativeClosestPoint<PointInT, PointInT> reg; reg.setInputCloud (model_aligned); //model reg.setInputTarget (cloud_voxelized_icp); //scene reg.setMaximumIterations (ICP_iterations_); reg.setMaxCorrespondenceDistance (VOXEL_SIZE_ICP_ * 3.); reg.setTransformationEpsilon (1e-6); typename pcl::PointCloud<PointInT>::Ptr output_ (new pcl::PointCloud<PointInT> ()); reg.align (*output_); Eigen::Matrix4d icp_trans = reg.getFinalTransformation (); transforms_->at (i) = icp_trans * transforms_->at (i); } } /** * HYPOTHESES VERIFICATION **/ if (hv_algorithm_) { pcl::ScopeTime t ("HYPOTHESES VERIFICATION"); std::vector<typename pcl::PointCloud<PointInT>::ConstPtr> aligned_models; aligned_models.resize (models_->size ()); for (size_t i = 0; i < models_->size (); i++) { ConstPointInTPtr model_cloud; PointInTPtr model_aligned (new pcl::PointCloud<PointInT>); if (compute_scale_) { model_cloud = models_->at (i).getAssembled (-1); PointInTPtr model_aligned_m (new pcl::PointCloud<PointInT>); pcl::transformPointCloud (*model_cloud, *model_aligned_m, transforms_->at (i)); pcl::VoxelGrid<PointInT> voxel_grid_icp; voxel_grid_icp.setInputCloud (model_aligned_m); voxel_grid_icp.setLeafSize (0.005, 0.005, 0.005); voxel_grid_icp.filter (*model_aligned); } else { model_cloud = models_->at (i).getAssembled (0.005); pcl::transformPointCloud (*model_cloud, *model_aligned, transforms_->at (i)); } //ConstPointInTPtr model_cloud = models_->at (i).getAssembled (0.005); //PointInTPtr model_aligned (new pcl::PointCloud<PointInT>); //pcl::transformPointCloud (*model_cloud, *model_aligned, transforms_->at (i)); aligned_models[i] = model_aligned; } std::vector<bool> mask_hv; hv_algorithm_->setSceneCloud (input_); hv_algorithm_->addModels (aligned_models, true); hv_algorithm_->verify (); hv_algorithm_->getMask (mask_hv); boost::shared_ptr < std::vector<ModelT> > models_temp; boost::shared_ptr < std::vector<Eigen::Matrix4d, Eigen::aligned_allocator<Eigen::Matrix4d> > > transforms_temp; models_temp.reset (new std::vector<ModelT>); transforms_temp.reset (new std::vector<Eigen::Matrix4d, Eigen::aligned_allocator<Eigen::Matrix4d> >); for (size_t i = 0; i < models_->size (); i++) { if (!mask_hv[i]) continue; models_temp->push_back (models_->at (i)); transforms_temp->push_back (transforms_->at (i)); } models_ = models_temp; transforms_ = transforms_temp; } } }
void SpellCreationDialog::open() { center(); }
void Vision_Objects::Main() { //Gui::getInstance(); //pluginTab = new Tab("Vision_Objects"); std::string action; cout<<"Intialization of ObjectRecognition"<<endl; cv::Mat kinect_rgb; cv::Mat kinect_gray; cv::Mat kinect_depth; cv::Mat contours_img; cv::Mat cutout; std::stringstream ss; //cout<<sharedMemory->getInstance().requestedObject->c_str()<<endl; //printf(sharedMemory->getInstance().requestedObject->c_str()); // sharedMemory->getInstance().setAction("reconocer_objeto"); int conta=0; OrbRecognizer OrbObject; OrbObject.setThreshold(0.8); OrbObject.setRecognitionTreshold(5); OrbObject.setMachine(3); // es SIFT. OrbObject.setDistance(1); bool newobject=true; for (;;) { action=sharedMemory->getInstance().getAction(); if (action=="recognizeObject") { cout<<"Starting: "<< action << " STATE in ObjectRecognition"<<endl; //TODO revisar posición de esta instrucción //Se indica a memoria compartida la orden que se esta atendiendo if(newobject) { ss.str(""); if (sharedMemory->getInstance().getTestRunning()=="CocktailParty") { sharedMemory->getInstance().setLastObjective(sharedMemory->getInstance().getUser(userOrder)); cout<< "***USER: "******" Name: "<< sharedMemory->getInstance().getUser(userOrder).getName()<<" Order: "<< sharedMemory->getInstance().getUser(userOrder).getOrder()<<endl; ss << "../data/Objects/" << sharedMemory->getInstance().getLastObjective().getOrder() << "/"; } else ss << "../data/Objects/" << sharedMemory->getInstance().getRequestedObject() << "/"; cout<< ss.str().c_str()<<endl; OrbObject.TrainingSet(ss.str().c_str()); newobject=false; } cv::RNG rng(12345); kinect_depth=sharedMemory->getInstance().kinectInfo->get_depth(); kinect_rgb = sharedMemory->getInstance().kinectInfo->get_RGB(); int threshold=50; cv::threshold(kinect_depth, kinect_depth, threshold, 255, cv::THRESH_TOZERO_INV ); cv::threshold(kinect_depth, kinect_depth, threshold-5, 255, cv::THRESH_TOZERO_INV); cv::Mat destination; cv::resize(kinect_depth, destination, kinect_rgb.size(), 0, 0, cv::INTER_CUBIC); // cv::blur( kinect_depth, kinect_depth, cv::Size(3,3) ); cv::namedWindow("threshold", CV_WINDOW_AUTOSIZE); cv::imshow("threshold", destination); vector<vector<cv::Point> > contours; vector<cv::Vec4i> hirarchy; cv::findContours(destination, contours, hirarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, cv::Point(0,0)); vector<vector<cv::Point> >contours_poly(contours.size()); vector<cv::Rect> boundRect (contours.size()); vector<cv::Point2f> center(contours.size()); vector<float>radius(contours.size()); for(int i=0; i< contours.size(); i++) { cv::approxPolyDP( cv::Mat(contours[i]), contours_poly[i], 3, true ); boundRect[i]=cv::boundingRect( cv::Mat(contours_poly[i]) ); cv::minEnclosingCircle( (cv::Mat)contours_poly[i], center[i], radius[i] ); } cvtColor( kinect_rgb, kinect_gray, CV_RGB2GRAY ); cv::GaussianBlur( kinect_gray, kinect_gray, cv::Size( 3, 3 ), 0, 0 ); contours_img= cv::Mat::zeros( destination.size(), CV_8UC3); for (int i=0; i < contours.size(); i++) { cv::Scalar color= cv::Scalar(rng.uniform(0,255), rng.uniform(0,255), rng.uniform(0,255) ); cv::drawContours( destination, contours_poly, i, color, 1, 8, vector<cv::Vec4i>(), 0, cv::Point() ); cv::rectangle(contours_img, boundRect[i].tl(), boundRect[i].br(), color, 2, 8, 0); cv::circle(contours_img, center[i], (int)radius[i], color, 2, 8, 0); if( boundRect[i].height>64 && boundRect[i].height<512 && boundRect[i].width>64 && boundRect[i].width<512 ) { cutout=kinect_gray(boundRect[i]); cv::imshow("cutout",cutout); std::cout << "ultima altura " << boundRect[i].height << "ultimo ancho " << boundRect[i].width << std::endl; cv::waitKey(100); std::cout << "despues de WAIT"<< std::endl; if(OrbObject.evalWindow(cutout)) { std::cout << "ENCONTRE" << std::endl; cv::rectangle(kinect_rgb, boundRect[i].tl(), boundRect[i].br(), color, 2, 8, 0); string phrase; if (sharedMemory->getInstance().getTestRunning()=="Emergency") phrase = "I found the "+ sharedMemory->getInstance().getRequestedObject(); else phrase = "I found the "+ sharedMemory->getInstance().getLastObjective().getOrder(); sharedMemory->getInstance().sintetizer.set_Phrase(phrase); //sharedMemory->getInstance().setAction(cambiar_estado("objeto_reconocido","si")); std::cout << "El objeto esta en los pixeles " << center[i].x << center[i].y << std::endl; sharedMemory->getInstance().setObjectPositionX(center[i].x/2); sharedMemory->getInstance().setObjectPositionY(center[i].y/2.1333333); newobject=true; // cv::destroyAllWindows(); //lastMoment i= contours.size(); userOrder++; // std::stringstream pp; // pp<< "../data/EmergencyReport/EmergencyObjectRequested.png"; // // conta++; cv::imwrite("../data/EmergencyReport/EmergencyObjectRequested.png", cutout); // std::stringstream cc; // cc<< "../data/SI/Kine" << conta << ".png"; // conta++; // cv::imwrite(cc.str().c_str(), kinect_rgb); sharedMemory->getInstance().setAction("computePoint"); } else { std::cout << "NO ENCONTRE" << std::endl; // std::stringstream pp; // pp<< "../data/Objects/negatives/" << conta << ".png"; // conta++; // cv::imwrite(pp.str().c_str(), cutout); } } } } } }
bool BoundingBox::Intersects(const Vector2& point, float radius) const { int xZone = point.X < ( Min.X ) ? 0 : ( point.X > ( Max.X ) ? 2 : 1 ); int yZone = point.Y < ( Min.Y ) ? 0 : ( point.Y > ( Max.Y ) ? 2 : 1 ); int zone = xZone + 3*yZone; Vector2 halfLen(HalfLength()); Vector2 center(halfLen+Min); bool bIntersects = false; switch ( zone ) { // top and bottom side zones // check vertical distance between centers case 1: case 7: { float distY = fabs( point.Y - center.Y ); if ( distY <= ( radius + halfLen.Y ) ) { bIntersects = true; } } break; // left and right side zones. check distance between centers // check horizontal distance between centers case 3: case 5: { float distX = fabs( point.X - center.X ); if ( distX <= ( radius + halfLen.X ) ) { bIntersects = true; } } break; // inside zone. collision for sure case 4: bIntersects = true; break; // corner zone. // get the corner and check if inside the circle default: { float cornerX = ( zone == 0 || zone == 6 ) ? Min.X : Max.X; float cornerY = ( zone == 0 || zone == 2 ) ? Min.Y : Max.Y; float distX = cornerX - point.X; float distY = cornerY - point.Y; float squaredist = distX*distX + distY*distY; if (squaredist <= radius* radius ) { // corner is inside circle bIntersects = true; } } break; } return bIntersects; }
void InternalSpriteRenderer::drawRequest( const Matrix& transform, const Vector2& size, const Vector2& anchorRatio, const Rect& srcRect, const Color& color, SpriteBaseDirection baseDir, BillboardType billboardType, SpriteFlipFlags flipFlags) { SpriteData sprite; Vector2 center(size.x * anchorRatio.x, size.y * anchorRatio.y); Vector3 normal = Vector3::UnitZ; // 3D の場合の頂点座標 if (baseDir != SpriteBaseDirection::Basic2D) { //Vector3 origin(-center); float l, t, r, b; #if 1 // 原点左下、povot.y+ が↑ r = size.x; b = 0; l = 0; t = size.y; l -= center.x; r -= center.x; t -= center.y; b -= center.y; #else // 原点中央 povot.y+ が↓ Vector2 harf_size(size * 0.5f); r = harf_size.x; b = -harf_size.y; l = -r; t = -b; l -= center.x; r -= center.x; t -= center.y; b -= center.y; #endif #define LN_WRITE_V3( x_, y_, z_ ) x_, y_, z_ switch (baseDir) { case SpriteBaseDirection::XPlus: sprite.vertices[0].position.set(LN_WRITE_V3(0, t, l)); // 左上 sprite.vertices[1].position.set(LN_WRITE_V3(0, t, r)); // 右上 sprite.vertices[2].position.set(LN_WRITE_V3(0, b, l)); // 左下 sprite.vertices[3].position.set(LN_WRITE_V3(0, b, r)); // 右下 normal = Vector3(1, 0, 0); break; case SpriteBaseDirection::YPlus: sprite.vertices[0].position.set(LN_WRITE_V3(l, 0, t)); sprite.vertices[1].position.set(LN_WRITE_V3(r, 0, t)); sprite.vertices[2].position.set(LN_WRITE_V3(l, 0, b)); sprite.vertices[3].position.set(LN_WRITE_V3(r, 0, b)); normal = Vector3(0, 1, 0); break; case SpriteBaseDirection::ZPlus: sprite.vertices[0].position.set(LN_WRITE_V3(r, t, 0)); sprite.vertices[1].position.set(LN_WRITE_V3(l, t, 0)); sprite.vertices[2].position.set(LN_WRITE_V3(r, b, 0)); sprite.vertices[3].position.set(LN_WRITE_V3(l, b, 0)); normal = Vector3(0, 0, 1); break; case SpriteBaseDirection::XMinus: sprite.vertices[0].position.set(LN_WRITE_V3(0, t, r)); sprite.vertices[1].position.set(LN_WRITE_V3(0, t, l)); sprite.vertices[2].position.set(LN_WRITE_V3(0, b, r)); sprite.vertices[3].position.set(LN_WRITE_V3(0, b, l)); normal = Vector3(-1, 0, 0); break; case SpriteBaseDirection::YMinus: sprite.vertices[0].position.set(LN_WRITE_V3(r, 0, t)); sprite.vertices[1].position.set(LN_WRITE_V3(l, 0, t)); sprite.vertices[2].position.set(LN_WRITE_V3(r, 0, b)); sprite.vertices[3].position.set(LN_WRITE_V3(l, 0, b)); normal = Vector3(0, -1, 0); break; case SpriteBaseDirection::ZMinus: sprite.vertices[0].position.set(LN_WRITE_V3(l, t, 0)); sprite.vertices[1].position.set(LN_WRITE_V3(r, t, 0)); sprite.vertices[2].position.set(LN_WRITE_V3(l, b, 0)); sprite.vertices[3].position.set(LN_WRITE_V3(r, b, 0)); normal = Vector3(0, 0, -1); break; } #undef LN_WRITE_V3 } // 2D の場合の頂点座標 else { Vector2 origin(-center); sprite.vertices[0].position.set(origin.x, origin.y, 0); sprite.vertices[1].position.set(origin.x + size.x, origin.y, 0); sprite.vertices[2].position.set(origin.x, origin.y + size.y, 0); sprite.vertices[3].position.set(origin.x + size.x, origin.y + size.y, 0); normal = Vector3(0, 0, -1); } for (int i = 0; i < 4; i++) sprite.vertices[i].normal = normal; const Vector3& worldPoint = transform.position(); Matrix actualTransform; { // ビルボード if (billboardType == BillboardType::ToCameraPoint) { Vector3 f = Vector3::normalize(m_viewPosition - worldPoint); Vector3 r = Vector3::normalize(Vector3::cross(Vector3::UnitY, f)); Vector3 u = Vector3::cross(f, r); actualTransform = Matrix( r.x, r.y, r.z, 0.0f, u.x, u.y, u.z, 0.0f, f.x, f.y, f.z, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f); } else if (billboardType == BillboardType::ToScreen) { // ↑がカメラ位置を基準にするのに対し、こちらはビュー平面に垂直に交差する点を基準とする。 // ビュー平面との距離 float d = Vector3::dot(worldPoint - m_viewPosition, m_viewDirection); // left-hand coord Vector3 f = Vector3::normalize(m_viewDirection * d); Vector3 r = Vector3::normalize(Vector3::cross(Vector3::UnitY, f)); Vector3 u = Vector3::cross(f, r); actualTransform = Matrix( r.x, r.y, r.z, 0.0f, u.x, u.y, u.z, 0.0f, f.x, f.y, f.z, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f); } // ビルボード・Y 軸のみに適用 else if (billboardType == BillboardType::RotY) { LN_NOTIMPLEMENTED(); //if (m_viewDirection.x > 0.0f) //{ // rotMat.rotateY(-atanf(m_viewDirection.z / m_viewDirection.x) + Math::PI / 2); //} //else if (m_viewDirection.x == 0.0f) //{ // //D3DXMatrixIdentity(&matWorld); // 0除算を防ぐため //} //else //{ // rotMat.rotateY(-atanf(m_viewDirection.z / m_viewDirection.x) - Math::PI / 2); //} } // ビルボードではない else { actualTransform = transform.getRotationMatrix(); } actualTransform.translate(worldPoint); } // 座標変換 sprite.vertices[0].position.transformCoord(actualTransform); sprite.vertices[1].position.transformCoord(actualTransform); sprite.vertices[2].position.transformCoord(actualTransform); sprite.vertices[3].position.transformCoord(actualTransform); // 色 sprite.vertices[0].color = color; sprite.vertices[1].color = color; sprite.vertices[2].color = color; sprite.vertices[3].color = color; // テクスチャ { float l = srcRect.x; float t = srcRect.y; float r = (srcRect.x + srcRect.width); float b = (srcRect.y + srcRect.height); if (testFlag(flipFlags, SpriteFlipFlags::FlipX)) { std::swap(l, r); } if (testFlag(flipFlags, SpriteFlipFlags::FlipY)) { std::swap(t, b); } sprite.vertices[0].uv.x = l; sprite.vertices[0].uv.y = t; sprite.vertices[1].uv.x = r; sprite.vertices[1].uv.y = t; sprite.vertices[2].uv.x = l; sprite.vertices[2].uv.y = b; sprite.vertices[3].uv.x = r; sprite.vertices[3].uv.y = b; } // カメラからの距離をソート用Z値にする場合 if (m_state.sortingBasis == SortingDistanceBasis::ViewPont) { sprite.depth = (m_viewPosition - worldPoint).lengthSquared(); } else { sprite.depth = worldPoint.z; } m_spriteDataList.add(sprite); }
std::shared_ptr<Detector2DResult> Detector2D::detect(Detector2DProperties& props, cv::Mat& image, cv::Mat& color_image, cv::Mat& debug_image, cv::Rect& roi, bool visualize, bool use_debug_image, bool pause_video = false) { std::shared_ptr<Detector2DResult> result = std::make_shared<Detector2DResult>(); result->current_roi = roi; result->image_width = image.size().width; result->image_height = image.size().height; const int image_width = image.size().width; const int image_height = image.size().height; const cv::Mat pupil_image = cv::Mat(image, roi).clone(); // image with roi, copy the image, since we alter it const int w = pupil_image.size().width / 2; const float coarse_pupil_width = w / 2.0f; const int padding = int(coarse_pupil_width / 4.0f); const int offset = props.intensity_range; const int spectral_offset = 5; cv::Mat histogram; int histSize; histSize = 256; //from 0 to 255 /// Set the ranges float range[] = { 0, 256 } ; //the upper boundary is exclusive const float* histRange = { range }; cv::calcHist(&pupil_image, 1 , 0, cv::Mat(), histogram , 1 , &histSize, &histRange, true, false); int lowest_spike_index = 255; int highest_spike_index = 0; float max_intensity = 0; singleeyefitter::detector::calculate_spike_indices_and_max_intenesity(histogram, 40, lowest_spike_index, highest_spike_index, max_intensity); if (visualize) { const int scale_x = 100; const int scale_y = 1 ; // display the histogram and the spikes for (int i = 0; i < histogram.rows; i++) { const float norm_i = histogram.ptr<float>(i)[0] / max_intensity ; // normalized intensity cv::line(color_image, {image_width, i * scale_y}, { image_width - int(norm_i * scale_x), i * scale_y}, mBlue_color); } cv::line(color_image, {image_width, lowest_spike_index * scale_y}, { int(image_width - 0.5f * scale_x), lowest_spike_index * scale_y }, mRed_color); cv::line(color_image, {image_width, (lowest_spike_index + offset)* scale_y}, { int(image_width - 0.5f * scale_x), (lowest_spike_index + offset)* scale_y }, mYellow_color); cv::line(color_image, {image_width, (highest_spike_index)* scale_y}, { int(image_width - 0.5f * scale_x), highest_spike_index * scale_y }, mRed_color); cv::line(color_image, {image_width, (highest_spike_index - spectral_offset)* scale_y}, { int(image_width - 0.5f * scale_x), (highest_spike_index - spectral_offset)* scale_y }, mWhite_color); } //create dark and spectral glint masks cv::Mat binary_img,spec_mask,kernel; cv::inRange(pupil_image, cv::Scalar(0) , cv::Scalar(lowest_spike_index + props.intensity_range), binary_img); // binary threshold kernel = cv::getStructuringElement(cv::MORPH_ELLIPSE, {7, 7}); cv::dilate(binary_img, binary_img, kernel, { -1, -1}, 2); cv::inRange(pupil_image, cv::Scalar(0) , cv::Scalar(highest_spike_index - spectral_offset), spec_mask); // binary threshold cv::erode(spec_mask, spec_mask, kernel); kernel = cv::getStructuringElement(cv::MORPH_ELLIPSE, {9, 9}); //open operation to remove eye lashes cv::morphologyEx(pupil_image, pupil_image, cv::MORPH_OPEN, kernel); if (props.blur_size > 1) cv::medianBlur(pupil_image, pupil_image, props.blur_size); cv::Mat edges; cv::Canny(pupil_image, edges, props.canny_treshold, props.canny_treshold * props.canny_ration, props.canny_aperture); //remove edges in areas not dark enough and where the glint is (spectral refelction from IR leds) cv::min(edges, spec_mask, edges); cv::min(edges, binary_img, edges); if (visualize) { // get sub matrix cv::Mat overlay = cv::Mat(color_image, roi); cv::Mat g_channel(overlay.rows, overlay.cols, CV_8UC1); cv::Mat b_channel(overlay.rows, overlay.cols, CV_8UC1); cv::Mat r_channel(overlay.rows, overlay.cols, CV_8UC1); cv::Mat out[] = {b_channel, g_channel, r_channel}; cv::split(overlay, out); cv::max(g_channel, edges, g_channel); cv::max(b_channel, binary_img, b_channel); cv::min(b_channel, spec_mask, b_channel); cv::merge(out, 3, overlay); //draw a frame around the automatic pupil ROI in overlay. auto rect = cv::Rect(0, 0, overlay.size().width, overlay.size().height); cvx::draw_dotted_rect(overlay, rect, mWhite_color); //draw a frame around the area we require the pupil center to be. rect = cv::Rect(padding, padding, roi.width - padding, roi.height - padding); cvx::draw_dotted_rect(overlay, rect, mWhite_color); //draw size ellipses cv::Point center(100, image_height - 100); cv::circle(color_image, center, props.pupil_size_min / 2.0, mRed_color); // real pupil size of this frame is calculated further down, so this size is from the last frame cv::circle(color_image, center, mPupil_Size / 2.0, mGreen_color); cv::circle(color_image, center, props.pupil_size_max / 2.0, mRed_color); auto text_string = std::to_string(mPupil_Size); cv::Size text_size = cv::getTextSize(text_string, cv::FONT_HERSHEY_SIMPLEX, 0.4 , 1, 0); cv::Point text_pos = { center.x - text_size.width / 2 , center.y + text_size.height / 2}; cv::putText(color_image, text_string, text_pos, cv::FONT_HERSHEY_SIMPLEX, 0.4, mRoyalBlue_color); } //GuoHallThinner thinner; //thinner.thin(edges, true); //get raw edge pixel for later std::vector<cv::Point> raw_edges; // find zero crashes if it doesn't find one. replace with cv implementation if opencv version is 3.0 or above singleeyefitter::cvx::findNonZero(edges, raw_edges); /////////////////////////////// /// Strong Prior Part Begin /// /////////////////////////////// //if we had a good ellipse before ,let see if it is still a good first guess: if( mUse_strong_prior ){ mUse_strong_prior = false; //recalculate center in coords system of new ROI views! roi changes every framesub Ellipse ellipse = mPrior_ellipse; ellipse.center[0] -= roi.x ; ellipse.center[1] -= roi.y ; if( !raw_edges.empty() ){ std::vector<cv::Point> support_pixels; double ellipse_circumference = ellipse.circumference(); support_pixels = ellipse_true_support(props,ellipse, ellipse_circumference, raw_edges); double support_ratio = support_pixels.size() / ellipse_circumference; if(support_ratio >= props.strong_perimeter_ratio_range_min){ cv::RotatedRect refit_ellipse = cv::fitEllipse(support_pixels); if(use_debug_image){ cv::ellipse(debug_image, toRotatedRect(ellipse), mRoyalBlue_color, 4); cv::ellipse(debug_image, refit_ellipse, mRed_color, 1); } ellipse = toEllipse<double>(refit_ellipse); ellipse_circumference = ellipse.circumference(); support_pixels = ellipse_true_support(props,ellipse, ellipse_circumference, raw_edges); support_ratio = support_pixels.size() / ellipse_circumference; ellipse.center[0] += roi.x; ellipse.center[1] += roi.y; mPrior_ellipse = ellipse; mUse_strong_prior = true; double goodness = std::min(1.0, support_ratio); mPupil_Size = ellipse.major_radius * 2.0; result->confidence = goodness; result->ellipse = ellipse; //result->final_contours = std::move(best_contours); // no contours when strong prior //result->contours = std::move(split_contours); result->raw_edges = std::move(raw_edges); // do we need it when strong prior ? result->final_edges = std::move(support_pixels); // need for optimisation return result; } } } /////////////////////////////// /// Strong Prior Part End /// /////////////////////////////// //from edges to contours Contours_2D contours ; cv::findContours(edges, contours, CV_RETR_LIST, CV_CHAIN_APPROX_NONE); //first we want to filter out the bad stuff, to short ones const auto contour_size_min_pred = [&props](const Contour_2D & contour) { return contour.size() > props.contour_size_min; }; contours = singleeyefitter::fun::filter(contour_size_min_pred , contours); //now we learn things about each contour through looking at the curvature. //For this we need to simplyfy the contour so that pt to pt angles become more meaningfull Contours_2D approx_contours; std::for_each(contours.begin(), contours.end(), [&](const Contour_2D & contour) { std::vector<cv::Point> approx_c; cv::approxPolyDP(contour, approx_c, 1.5, false); approx_contours.push_back(std::move(approx_c)); }); // split contours looking at curvature and angle double split_angle = 80; int split_contour_size_min = 3; //removing stubs makes combinatorial search feasable //split_contours = singleeyefitter::detector::split_rough_contours(approx_contours, split_angle ); //removing stubs makes combinatorial search feasable // MOVED TO split_contours_optimized //split_contours = singleeyefitter::fun::filter( [](std::vector<cv::Point>& v){ return v.size() <= 3;} , split_contours); Contours_2D split_contours = singleeyefitter::detector::split_rough_contours_optimized(approx_contours, split_angle , split_contour_size_min); if (split_contours.empty()) { result->confidence = 0.0; // Does it make seens to return anything ? //result->ellipse = toEllipse<double>(refit_ellipse); //result->final_contours = std::move(best_contours); //result->contours = std::move(split_contours); //result->raw_edges = std::move(raw_edges); return result; } if (use_debug_image) { // debug segments int colorIndex = 0; for (const auto& segment : split_contours) { const cv::Scalar_<int> colors[] = {mRed_color, mBlue_color, mRoyalBlue_color, mYellow_color, mWhite_color, mGreen_color}; cv::polylines(debug_image, segment, false, colors[colorIndex], 1, 4); colorIndex++; colorIndex %= 6; } } std::sort(split_contours.begin(), split_contours.end(), [](const Contour_2D & a,const Contour_2D & b) { return a.size() > b.size(); }); const cv::Rect ellipse_center_varianz = cv::Rect(padding, padding, pupil_image.size().width - 2.0 * padding, pupil_image.size().height - 2.0 * padding); const EllipseEvaluation2D is_Ellipse(ellipse_center_varianz, props.ellipse_roundness_ratio, props.pupil_size_min, props.pupil_size_max); //finding potential candidates for ellipse seeds that describe the pupil. auto seed_contours = detector::divide_strong_and_weak_contours( split_contours, is_Ellipse, props.initial_ellipse_fit_treshhold, props.strong_perimeter_ratio_range_min, props.strong_perimeter_ratio_range_max, props.strong_area_ratio_range_min, props.strong_area_ratio_range_max ); std::vector<int> seed_indices = seed_contours.first; // strong contours if (seed_indices.empty() && !seed_contours.second.empty()) { seed_indices = seed_contours.second; // weak contours } // still empty ? --> exits if (seed_indices.empty()) { result->confidence = 0.0; // Does it make seens to return anything ? //result->ellipse = toEllipse<double>(refit_ellipse); //result->final_contours = std::move(best_contours); //result->contours = std::move(split_contours); result->raw_edges = std::move(raw_edges); return result; } auto pruning_quick_combine = [&](const std::vector<std::vector<cv::Point>>& contours, std::set<int>& seed_indices, int max_evals = 1e20, int max_depth = 5) { // describes different combinations of contours typedef std::set<int> Path; // combinations we wanna test std::vector<Path> unknown(seed_indices.size()); // init with paths of size 1 == seed indices int n = 0; std::generate(unknown.begin(), unknown.end(), [&]() { return Path{n++}; }); // fill with increasing values, starting from 0 std::vector<int> mapping; // contains all indices, starting with seed_indices mapping.reserve(contours.size()); mapping.insert(mapping.begin(), seed_indices.begin(), seed_indices.end()); // add indices which are not used to the end of mapping for (int i = 0; i < contours.size(); i++) { if (seed_indices.find(i) == seed_indices.end()) { mapping.push_back(i); } } // contains all the indices for the contours, which altogther fit best std::vector<Path> results; // contains bad paths, we won't test again // even a superset is not tested again, because if a subset is bad, we can't make it better if more contours are added std::vector<Path> prune; int eval_count = 0; while (!unknown.empty() && eval_count <= max_evals) { eval_count++; //take a path and combine it with others to see if the fit gets better Path current_path = unknown.back(); unknown.pop_back(); if (current_path.size() <= max_depth) { bool includes_bad_paths = fun::isSubset(current_path, prune); if (!includes_bad_paths) { int size = 0; for (int j : current_path) { size += contours.at(mapping.at(j)).size(); }; std::vector<cv::Point> test_contour; test_contour.reserve(size); std::set<int> test_contour_indices; //concatenate contours to one contour for (int k : current_path) { const std::vector<cv::Point>& c = contours.at(mapping.at(k)); test_contour.insert(test_contour.end(), c.begin(), c.end()); test_contour_indices.insert(mapping.at(k)); } //we have not tested this and a subset of this was sucessfull before double fit_variance = detector::contour_ellipse_deviation_variance(test_contour); if (fit_variance < props.initial_ellipse_fit_treshhold) { //yes this was good, keep as solution results.push_back(test_contour_indices); //lets explore more by creating paths to each remaining node for (int l = (*current_path.rbegin()) + 1 ; l < mapping.size(); l++) { unknown.push_back(current_path); unknown.back().insert(l); // add a new path } } else { prune.push_back(current_path); } } } } return results; }; std::set<int> seed_indices_set = std::set<int>(seed_indices.begin(), seed_indices.end()); std::vector<std::set<int>> solutions = pruning_quick_combine(split_contours, seed_indices_set, 1000, 5); //find largest sets which contains all previous ones auto filter_subset = [](std::vector<std::set<int>>& sets) { std::vector<std::set<int>> filtered_set; int i = 0; for (auto& current_set : sets) { //check if this current_set is a subset of set bool isSubset = false; for (int j = 0; j < sets.size(); j++) { if (j == i) continue;// don't compare to itself auto& set = sets.at(j); // for std::include both containers need to be ordered. std::set guarantees this isSubset |= std::includes(set.begin(), set.end(), current_set.begin(), current_set.end()); } if (!isSubset) { filtered_set.push_back(current_set); } i++; } return filtered_set; }; solutions = filter_subset(solutions); int index_best_Solution = -1; int enum_index = 0; for (auto& s : solutions) { std::vector<cv::Point> test_contour; //concatenate contours to one contour for (int i : s) { std::vector<cv::Point>& c = split_contours.at(i); test_contour.insert(test_contour.end(), c.begin(), c.end()); } auto cv_ellipse = cv::fitEllipse(test_contour); if (use_debug_image) { cv::ellipse(debug_image, cv_ellipse , mRed_color); } Ellipse ellipse = toEllipse<double>(cv_ellipse); double ellipse_circumference = ellipse.circumference(); std::vector<cv::Point> support_pixels = ellipse_true_support(props, ellipse, ellipse_circumference, raw_edges); double support_ratio = support_pixels.size() / ellipse_circumference; //TODO: refine the selection of final candidate if (support_ratio >= props.final_perimeter_ratio_range_min && is_Ellipse(cv_ellipse)) { index_best_Solution = enum_index; if (support_ratio >= props.strong_perimeter_ratio_range_min) { ellipse.center[0] += roi.x; ellipse.center[1] += roi.y; mPrior_ellipse = ellipse; mUse_strong_prior = true; if (use_debug_image) { cv::ellipse(debug_image, cv_ellipse , mGreen_color); } } } enum_index++; } // select ellipse if (index_best_Solution == -1) { // no good final ellipse found result->confidence = 0.0; // Does it make seens to return anything ? //result->ellipse = toEllipse<double>(refit_ellipse); //result->final_contours = std::move(best_contours); //result->contours = std::move(split_contours); result->raw_edges = std::move(raw_edges); return result; } auto& best_solution = solutions.at(index_best_Solution); std::vector<std::vector<cv::Point>> best_contours; std::vector<cv::Point>best_contour; //concatenate contours to one contour for (int i : best_solution) { std::vector<cv::Point>& c = split_contours.at(i); best_contours.push_back(c); best_contour.insert(best_contour.end(), c.begin(), c.end()); } auto cv_ellipse = cv::fitEllipse(best_contour); // final calculation of goodness of fit auto ellipse = toEllipse<double>(cv_ellipse); double ellipse_circumference = ellipse.circumference(); std::vector<cv::Point> support_pixels = ellipse_true_support(props, ellipse, ellipse_circumference, raw_edges); double support_ratio = support_pixels.size() / ellipse_circumference; double goodness = std::min(double(0.99), support_ratio); //final fitting and return of result auto final_fitting = [&](std::vector<std::vector<cv::Point>>& contours, cv::Mat & edges) -> std::vector<cv::Point> { //use the real edge pixels to fit, not the aproximated contours cv::Mat support_mask(edges.rows, edges.cols, edges.type(), {0, 0, 0}); cv::polylines(support_mask, contours, false, {255, 255, 255}, 2); //draw into the suport mask with thickness 2 cv::Mat new_edges; std::vector<cv::Point> new_contours; cv::min(edges, support_mask, new_edges); // can't do this here, because final result gets much distorted. // see if it even can crash !!! //new_edges.at<int>(0,0) = 1; // find zero crashes if it doesn't find one. remove if opencv version is 3.0 or above cv::findNonZero(new_edges, new_contours); if (visualize) { cv::Mat overlay = color_image.colRange(roi.x, roi.x + roi.width).rowRange(roi.y, roi.y + roi.height); cv::Mat g_channel(overlay.rows, overlay.cols, CV_8UC1); cv::Mat b_channel(overlay.rows, overlay.cols, CV_8UC1); cv::Mat r_channel(overlay.rows, overlay.cols, CV_8UC1); cv::Mat out[] = {b_channel, g_channel, r_channel}; cv::split(overlay, out); cv::threshold(new_edges, new_edges, 0, 255, cv::THRESH_BINARY); cv::max(r_channel, new_edges, r_channel); cv::merge(out, 3, overlay); } return new_contours; }; std::vector<cv::Point> final_edges = final_fitting(best_contours, edges); auto cv_new_Ellipse = cv::fitEllipse(final_edges); double size_difference = std::abs(1.0 - cv_ellipse.size.height / cv_new_Ellipse.size.height); auto& cv_final_Ellipse = cv_ellipse; if (is_Ellipse(cv_new_Ellipse) && size_difference < 0.3) { if (use_debug_image) { cv::ellipse(debug_image, cv_new_Ellipse, mGreen_color); } cv_final_Ellipse = cv_new_Ellipse; } //cv::imshow("debug_image", debug_image); mPupil_Size = cv_final_Ellipse.size.height; result->confidence = goodness; result->ellipse = toEllipse<double>(cv_final_Ellipse); result->ellipse.center[0] += roi.x; result->ellipse.center[1] += roi.y; //result->final_contours = std::move(best_contours); // TODO optimize // just do this if we really need it // std::for_each(contours.begin(), contours.end(), [&](const Contour_2D & contour) { // std::vector<cv::Point> approx_c; // cv::approxPolyDP(contour, approx_c, 1.0, false); // approx_contours.push_back(std::move(approx_c)); // }); // split_contours = singleeyefitter::detector::split_rough_contours_optimized(approx_contours, 150.0 , split_contour_size_min); // result->contours = std::move(split_contours); result->final_edges = std::move(final_edges);// need for optimisation result->raw_edges = std::move(raw_edges); return result; }
void Repair::open() { center(); }
void drawCircle(cv::Vec3f circles, cv::Scalar color) { cv::Point center(cvRound(circles[0]), cvRound(circles[1])); int radius = cvRound(circles[2]); cv::circle(depthSegmentation.frameBGR, center, radius, color, 3, 8, 0); }
bool OBDepict::DrawMolecule(OBMol *mol) { if (!d->painter) return false; d->mol = mol; OBAtom *atom; OBBondIterator j; OBAtomIterator i; // scale bond lengths double bondLengthSum = 0.0; for (OBBond *bond = mol->BeginBond(j); bond; bond = mol->NextBond(j)) bondLengthSum += bond->GetLength(); const double averageBondLength = bondLengthSum / mol->NumBonds(); const double f = mol->NumBonds() ? d->bondLength / averageBondLength : 1.0; for (atom = mol->BeginAtom(i); atom; atom = mol->NextAtom(i)) atom->SetVector(atom->GetX() * f, atom->GetY() * f, 0.0); // find min/max values double min_x, max_x; double min_y, max_y; atom = mol->BeginAtom(i); min_x = max_x = atom->GetX(); min_y = max_y = atom->GetY(); for (atom = mol->NextAtom(i); atom; atom = mol->NextAtom(i)) { min_x = std::min(min_x, atom->GetX()); max_x = std::max(max_x, atom->GetX()); min_y = std::min(min_y, atom->GetY()); max_y = std::max(max_y, atom->GetY()); } const double margin = 40.0; // translate all atoms so the bottom-left atom is at margin,margin for (atom = mol->BeginAtom(i); atom; atom = mol->NextAtom(i)) atom->SetVector(atom->GetX() - min_x + margin, atom->GetY() - min_y + margin, 0.0); double width = max_x - min_x + 2*margin; double height = max_y - min_y + 2*margin; //d->painter->SetPenWidth(d->penWidth); //d->painter->SetPenColor(d->pen)); //d->painter->SetFillColor(OBColor("black")); d->painter->NewCanvas(width, height); // draw bonds for (OBBond *bond = mol->BeginBond(j); bond; bond = mol->NextBond(j)) { OBAtom *begin = bond->GetBeginAtom(); OBAtom *end = bond->GetEndAtom(); if (bond->IsWedge()) { d->DrawWedge(begin, end); } else if (bond->IsHash()) { d->DrawHash(begin, end); } else if (!bond->IsInRing()) { d->DrawSimpleBond(begin, end, bond->GetBO()); } } // draw ring bonds std::vector<OBRing*> rings(mol->GetSSSR()); OBBitVec drawnBonds; for (std::vector<OBRing*>::iterator k = rings.begin(); k != rings.end(); ++k) { OBRing *ring = *k; std::vector<int> indexes = ring->_path; vector3 center(VZero); for (std::vector<int>::iterator l = indexes.begin(); l != indexes.end(); ++l) { center += mol->GetAtom(*l)->GetVector(); } center /= indexes.size(); for (unsigned int l = 0; l < indexes.size(); ++l) { OBAtom *begin = mol->GetAtom(indexes[l]); OBAtom *end; if (l+1 < indexes.size()) end = mol->GetAtom(indexes[l+1]); else end = mol->GetAtom(indexes[0]); OBBond *ringBond = mol->GetBond(begin, end); if (drawnBonds.BitIsSet(ringBond->GetId())) continue; d->DrawRingBond(begin, end, center, ringBond->GetBO()); drawnBonds.SetBitOn(ringBond->GetId()); } } // draw atom labels for (atom = mol->BeginAtom(i); atom; atom = mol->NextAtom(i)) { double x = atom->GetX(); double y = atom->GetY(); int alignment = GetLabelAlignment(atom); bool rightAligned = false; switch (alignment) { case TopRight: case CenterRight: case BottomRight: rightAligned = true; default: break; } d->painter->SetPenColor(OBColor(etab.GetRGB(atom->GetAtomicNum()))); //charge and radical NEEDS REVISION int charge = atom->GetFormalCharge(); int spin = atom->GetSpinMultiplicity(); if(charge || spin) { OBFontMetrics metrics = d->painter->GetFontMetrics("N"); double yoffset = d->HasLabel(atom) ? 0.4 * metrics.height : 0.0; switch (GetLabelAlignment(atom)) { case TopCenter: case TopRight: case TopLeft: case CenterLeft: case CenterRight: yoffset = - 1.2 * metrics.height; } stringstream ss; if(charge) { if(abs(charge)!=1) ss << abs(charge); ss << (charge>0 ? "+" : "-") ; } if(spin) { ss << (spin==2 ? "." : ".."); yoffset += 0.5 * metrics.height; } if(spin || charge<0) d->painter->SetFontSize(2 * metrics.fontSize); d->painter->DrawText(x-0.4*metrics.width, y-yoffset, ss.str()); d->painter->SetFontSize(metrics.fontSize);//restore } if (atom->IsCarbon()) { if (atom->GetValence() > 1) continue; if ((atom->GetValence() == 1) && !d->drawTerminalC) continue; } stringstream ss; AliasData* ad = NULL; if(d->aliasMode && atom->HasData(AliasDataType)) ad = static_cast<AliasData*>(atom->GetData(AliasDataType)); //For unexpanded aliases use appropriate form of alias instead of element symbol, Hs, etc if(ad && !ad->IsExpanded()) { ss <<ad->GetAlias(rightAligned); OBColor aliasColor = !ad->GetColor().empty() ? ad->GetColor() : d->bondColor; d->painter->SetPenColor(aliasColor); } else { unsigned int hCount = atom->ImplicitHydrogenCount(); // rightAligned: // false CH3 // true H3C if (hCount && rightAligned) ss << "H"; if ((hCount > 1) && rightAligned) ss << hCount; ss << etab.GetSymbol(atom->GetAtomicNum()); if (hCount && !rightAligned) ss << "H"; if ((hCount > 1) && !rightAligned) ss << hCount; } d->DrawAtomLabel(ss.str(), alignment, vector3(x, y, 0.0)); } return true; }
int makeGeometry(Box& a_domain, RealVect& a_dx) { int eekflag = 0; //parse input file ParmParse pp; int verbosity = 0; RealVect origin = RealVect::Zero; Vector<int> n_cell(SpaceDim); pp.getarr("n_cell",n_cell,0,SpaceDim); CH_assert(n_cell.size() == SpaceDim); IntVect lo = IntVect::Zero; IntVect hi; for (int ivec = 0; ivec < SpaceDim; ivec++) { if (n_cell[ivec] <= 0) { pout() << " bogus number of cells input = " << n_cell[ivec]; return(-1); } hi[ivec] = n_cell[ivec] - 1; } a_domain.setSmall(lo); a_domain.setBig(hi); Vector<Real> prob_lo(SpaceDim, 1.0); Real prob_hi; pp.getarr("prob_lo",prob_lo,0,SpaceDim); pp.get("prob_hi",prob_hi); for (int idir = 0; idir < SpaceDim; idir++) { a_dx[idir] = (prob_hi-prob_lo[idir])/n_cell[idir]; origin[idir] = prob_lo[idir]; } int whichgeom; pp.get("which_geom",whichgeom); CH_XD::EBIndexSpace* ebisPtr = Chombo_EBIS::instance(); if (whichgeom == 0) { //allregular pout() << "all regular geometry" << endl; AllRegularService regserv; ebisPtr->define(a_domain, origin, a_dx[0], regserv); } else if (whichgeom == 1) { pout() << "ramp geometry" << endl; int upDir; int indepVar; Real startPt; Real slope; pp.get("up_dir",upDir); pp.get("indep_var",indepVar); pp.get("start_pt", startPt); pp.get("ramp_slope", slope); RealVect normal = RealVect::Zero; normal[upDir] = 1.0; normal[indepVar] = -slope; RealVect point = RealVect::Zero; point[upDir] = -slope*startPt; bool normalInside = true; PlaneIF ramp(normal,point,normalInside); GeometryShop workshop(ramp,verbosity,a_dx); //this generates the new EBIS ebisPtr->define(a_domain, origin, a_dx[0], workshop); } else if (whichgeom == 5) { pout() << "sphere geometry" << endl; vector<Real> sphere_center(SpaceDim); pp.getarr("sphere_center",sphere_center, 0, SpaceDim); RealVect sphereCenter; for (int idir = 0; idir < SpaceDim; idir++) { sphereCenter[idir] = sphere_center[idir]; } Real sphereRadius; pp.get("sphere_radius", sphereRadius); bool insideRegular = false; SphereIF implicit(sphereRadius,sphereCenter,insideRegular); GeometryShop workshop(implicit,verbosity,a_dx); //this generates the new EBIS ebisPtr->define(a_domain, origin, a_dx[0], workshop); } else if (whichgeom == 6) { pout() << "multisphere geometry" << endl; int numSpheres; pp.get("num_spheres", numSpheres); Vector<Real> radius(numSpheres); Vector<RealVect> center(numSpheres); for (int isphere = 0; isphere < numSpheres; isphere++) { char radiusString[80]; char centerString[80]; sprintf(radiusString, "sphere_radius_%d", isphere); sprintf(centerString, "sphere_center_%d", isphere); vector<Real> sphere_center(SpaceDim); Real sphereRadius; pp.get(radiusString, sphereRadius); pp.getarr(centerString,sphere_center, 0, SpaceDim); RealVect sphereCenter; for (int idir = 0; idir < SpaceDim; idir++) { sphereCenter[idir] = sphere_center[idir]; } center[isphere] = sphereCenter; radius[isphere] = sphereRadius; } bool inside = false; MultiSphereIF spheres(radius, center, inside); GeometryShop workshop(spheres,verbosity,a_dx); //this generates the new EBIS ebisPtr->define(a_domain, origin, a_dx[0], workshop); } else { //bogus which_geom pout() << " bogus which_geom input = " << whichgeom; eekflag = 33; } return eekflag; }
glm::vec3 AABox::calcCenter() const { glm::vec3 center(_corner); center += (_scale * 0.5f); return center; }
ReviewDialog::ReviewDialog() : WindowModal("openmw_chargen_review.layout") { // Centre dialog center(); // Setup static stats MyGUI::Button* button; getWidget(mNameWidget, "NameText"); getWidget(button, "NameButton"); adjustButtonSize(button); button->eventMouseButtonClick += MyGUI::newDelegate(this, &ReviewDialog::onNameClicked); getWidget(mRaceWidget, "RaceText"); getWidget(button, "RaceButton"); adjustButtonSize(button); button->eventMouseButtonClick += MyGUI::newDelegate(this, &ReviewDialog::onRaceClicked); getWidget(mClassWidget, "ClassText"); getWidget(button, "ClassButton"); adjustButtonSize(button); button->eventMouseButtonClick += MyGUI::newDelegate(this, &ReviewDialog::onClassClicked); getWidget(mBirthSignWidget, "SignText"); getWidget(button, "SignButton"); adjustButtonSize(button); button->eventMouseButtonClick += MyGUI::newDelegate(this, &ReviewDialog::onBirthSignClicked); // Setup dynamic stats getWidget(mHealth, "Health"); mHealth->setTitle(MWBase::Environment::get().getWindowManager()->getGameSettingString("sHealth", "")); mHealth->setValue(45, 45); getWidget(mMagicka, "Magicka"); mMagicka->setTitle(MWBase::Environment::get().getWindowManager()->getGameSettingString("sMagic", "")); mMagicka->setValue(50, 50); getWidget(mFatigue, "Fatigue"); mFatigue->setTitle(MWBase::Environment::get().getWindowManager()->getGameSettingString("sFatigue", "")); mFatigue->setValue(160, 160); // Setup attributes Widgets::MWAttributePtr attribute; for (int idx = 0; idx < ESM::Attribute::Length; ++idx) { getWidget(attribute, std::string("Attribute") + MyGUI::utility::toString(idx)); mAttributeWidgets.insert(std::make_pair(static_cast<int>(ESM::Attribute::sAttributeIds[idx]), attribute)); attribute->setAttributeId(ESM::Attribute::sAttributeIds[idx]); attribute->setAttributeValue(Widgets::MWAttribute::AttributeValue()); } // Setup skills getWidget(mSkillView, "SkillView"); mSkillView->eventMouseWheel += MyGUI::newDelegate(this, &ReviewDialog::onMouseWheel); for (int i = 0; i < ESM::Skill::Length; ++i) { mSkillValues.insert(std::make_pair(i, MWMechanics::SkillValue())); mSkillWidgetMap.insert(std::make_pair(i, static_cast<MyGUI::TextBox*> (0))); } MyGUI::Button* backButton; getWidget(backButton, "BackButton"); backButton->eventMouseButtonClick += MyGUI::newDelegate(this, &ReviewDialog::onBackClicked); MyGUI::Button* okButton; getWidget(okButton, "OKButton"); okButton->eventMouseButtonClick += MyGUI::newDelegate(this, &ReviewDialog::onOkClicked); }
Vector2D DrawableObject::Center() { Vector2D center(x + (width/2),y + (height/2)); return center; }
void SpeedTest() { #ifdef _DEBUG int N = 20; #else int N = 1000; #endif int qi_iterations = 7; int xcor_iterations = 7; CPUTracker* tracker = new CPUTracker(150,150, 128); int radialSteps = 64, zplanes = 120; float zmin = 2, zmax = 8; float zradius = tracker->xcorw/2; float* zlut = new float[radialSteps*zplanes]; for (int x=0;x<zplanes;x++) { vector2f center (tracker->GetWidth()/2, tracker->GetHeight()/2); float s = zmin + (zmax-zmin) * x/(float)(zplanes-1); GenerateTestImage(ImageData(tracker->srcImage, tracker->GetWidth(), tracker->GetHeight()), center.x, center.y, s, 0.0f); tracker->mean = 0.0f; tracker->ComputeRadialProfile(&zlut[x*radialSteps], radialSteps, 64, 1, zradius, center, false); } tracker->SetRadialZLUT(zlut, zplanes, radialSteps, 1,1, zradius, true, true); delete[] zlut; // Speed test vector2f comdist, xcordist, qidist; float zdist=0.0f; double zerrsum=0.0f; double tcom = 0.0, tgen=0.0, tz = 0.0, tqi=0.0, txcor=0.0; for (int k=0;k<N;k++) { double t0 = GetPreciseTime(); float xp = tracker->GetWidth()/2+(rand_uniform<float>() - 0.5) * 5; float yp = tracker->GetHeight()/2+(rand_uniform<float>() - 0.5) * 5; float z = zmin + 0.1f + (zmax-zmin-0.2f) * rand_uniform<float>(); GenerateTestImage(ImageData(tracker->srcImage, tracker->GetWidth(), tracker->GetHeight()), xp, yp, z, 0); double t1 = GetPreciseTime(); vector2f com = tracker->ComputeMeanAndCOM(); vector2f initial(com.x, com.y); double t2 = GetPreciseTime(); bool boundaryHit = false; vector2f xcor = tracker->ComputeXCorInterpolated(initial, xcor_iterations, 16, boundaryHit); if (boundaryHit) dbgprintf("xcor boundaryhit!!\n"); comdist.x += fabsf(com.x - xp); comdist.y += fabsf(com.y - yp); xcordist.x +=fabsf(xcor.x - xp); xcordist.y +=fabsf(xcor.y - yp); double t3 = GetPreciseTime(); boundaryHit = false; vector2f qi = tracker->ComputeQI(initial, qi_iterations, 64, 16,ANGSTEPF, 5,50, boundaryHit); qidist.x += fabsf(qi.x - xp); qidist.y += fabsf(qi.y - yp); double t4 = GetPreciseTime(); if (boundaryHit) dbgprintf("qi boundaryhit!!\n"); boundaryHit = false; float est_z = zmin + (zmax-zmin)*tracker->ComputeZ(qi, 64, 0, &boundaryHit, 0) / (zplanes-1); zdist += fabsf(est_z-z); zerrsum += est_z-z; if (boundaryHit) dbgprintf("computeZ boundaryhit!!\n"); double t5 = GetPreciseTime(); // dbgout(SPrintf("xpos:%f, COM err: %f, XCor err: %f\n", xp, com.x-xp, xcor.x-xp)); if (k>0) { // skip first initialization round tgen+=t1-t0; tcom+=t2-t1; txcor+=t3-t2; tqi+=t4-t3; tz+=t5-t4; } } int Nns = N-1; dbgprintf("Image gen. (img/s): %f\nCenter-of-Mass speed (img/s): %f\n", Nns/tgen, Nns/tcom); dbgprintf("XCor estimation (img*it/s): %f\n", (Nns*xcor_iterations)/txcor); dbgprintf("COM+XCor(%d) (img/s): %f\n", xcor_iterations, Nns/(tcom+txcor)); dbgprintf("Z estimation (img/s): %f\n", Nns/tz); dbgprintf("QI speed: %f (img*it/s)\n", (Nns*qi_iterations)/tqi); dbgprintf("Average dist: COM x: %f, y: %f\n", comdist.x/N, comdist.y/N); dbgprintf("Average dist: Cross-correlation x: %f, y: %f\n", xcordist.x/N, xcordist.y/N); dbgprintf("Average dist: QI x: %f, y: %f\n", qidist.x/N, qidist.y/N); dbgprintf("Average dist: Z: %f. Mean error:%f\n", zdist/N, zerrsum/N); delete tracker; }
PfxBool pfxIntersectRayCapsule(const PfxRayInput &ray,PfxRayOutput &out,const PfxCapsule &capsule,const PfxTransform3 &transform) { // レイをCapsuleのローカル座標へ変換 PfxTransform3 transformCapsule = orthoInverse(transform); PfxVector3 startPosL = transformCapsule.getUpper3x3() * ray.m_startPosition + transformCapsule.getTranslation(); PfxVector3 rayDirL = transformCapsule.getUpper3x3() * ray.m_direction; PfxFloat radSqr = capsule.m_radius * capsule.m_radius; // 始点がカプセルの内側にあるか判定 { PfxFloat h = fabsf(startPosL[0]); if(h > capsule.m_halfLen) h = capsule.m_halfLen; PfxVector3 Px(out.m_variable,0,0); PfxFloat sqrLen = lengthSqr(startPosL-Px); if(sqrLen <= radSqr) return false; } // カプセルの胴体との交差判定 do { PfxVector3 P(startPosL); PfxVector3 D(rayDirL); P[0] = 0.0f; D[0] = 0.0f; PfxFloat a = dot(D,D); PfxFloat b = dot(P,D); PfxFloat c = dot(P,P) - radSqr; PfxFloat d = b * b - a * c; if(d < 0.0f || fabs(a) < 0.00001f) return false; PfxFloat tt = ( -b - sqrtf(d) ) / a; if(tt < 0.0f) break; else if(tt > 1.0f) return false; if(tt < out.m_variable) { PfxVector3 cp = startPosL + tt * rayDirL; if(fabsf(cp[0]) <= capsule.m_halfLen) { out.m_contactFlag = true; out.m_variable = tt; out.m_contactPoint = PfxVector3(transform * PfxPoint3(cp)); out.m_contactNormal = transform.getUpper3x3() * normalize(cp); out.m_subData.m_type = PfxSubData::NONE; return true; } } } while(0); // カプセルの両端にある球体との交差判定 PfxFloat a = dot(rayDirL,rayDirL); if(fabs(a) < 0.00001f) return false; do { PfxVector3 center(capsule.m_halfLen,0.0f,0.0f); PfxVector3 v = startPosL - center; PfxFloat b = dot(v,rayDirL); PfxFloat c = dot(v,v) - radSqr; PfxFloat d = b * b - a * c; if(d < 0.0f) break; PfxFloat tt = ( -b - sqrtf(d) ) / a; if(tt < 0.0f || tt > 1.0f) break; if(tt < out.m_variable) { PfxVector3 cp = startPosL + tt * rayDirL; out.m_contactFlag = true; out.m_variable = tt; out.m_contactPoint = ray.m_startPosition + tt * ray.m_direction; out.m_contactNormal = transform.getUpper3x3() * normalize(cp-center); out.m_subData.m_type = PfxSubData::NONE; return true; } } while(0); { PfxVector3 center(-capsule.m_halfLen,0.0f,0.0f); PfxVector3 v = startPosL - center; PfxFloat b = dot(v,rayDirL); PfxFloat c = dot(v,v) - radSqr; PfxFloat d = b * b - a * c; if(d < 0.0f) return false; PfxFloat tt = ( -b - sqrtf(d) ) / a; if(tt < 0.0f || tt > 1.0f) return false; if(tt < out.m_variable) { PfxVector3 cp = startPosL + out.m_variable * rayDirL; out.m_contactFlag = true; out.m_variable = tt; out.m_contactPoint = ray.m_startPosition + tt * ray.m_direction; out.m_contactNormal = transform.getUpper3x3() * normalize(cp-center); out.m_subData.m_type = PfxSubData::NONE; return true; } } return false; }
void EditEffectDialog::open() { WindowModal::open(); center(); }
void MerchantRepair::open() { center(); }
void Gizmo3D::Position() { Vector3 center(0, 0, 0); bool containsScene = false; for (unsigned i = 0; i < editNodes_->Size(); ++i) { // Scene's transform should not be edited, so hide gizmo if it is included if (editNodes_->At(i) == scene_) { containsScene = true; break; } center += editNodes_->At(i)->GetWorldPosition(); } if (editNodes_->Empty() || containsScene) { Hide(); return; } center /= editNodes_->Size(); gizmoNode_->SetPosition(center); if (axisMode_ == AXIS_WORLD || editNodes_->Size() > 1) gizmoNode_->SetRotation(Quaternion()); else gizmoNode_->SetRotation(editNodes_->At(0)->GetWorldRotation()); ResourceCache* cache = GetSubsystem<ResourceCache>(); if (editMode_ != lastEditMode_) { switch (editMode_) { case EDIT_MOVE: gizmo_->SetModel(cache->GetResource<Model>("AtomicEditor/Models/Axes.mdl")); break; case EDIT_ROTATE: gizmo_->SetModel(cache->GetResource<Model>("AtomicEditor/Models/RotateAxes.mdl")); break; case EDIT_SCALE: gizmo_->SetModel(cache->GetResource<Model>("AtomicEditor/Models/ScaleAxes.mdl")); break; default: break; } lastEditMode_ = editMode_; } bool orbiting = false; if ((editMode_ != EDIT_SELECT && !orbiting) && !gizmo_->IsEnabled()) Show(); else if ((editMode_ == EDIT_SELECT || orbiting) && gizmo_->IsEnabled()) Hide(); if (gizmo_->IsEnabled()) { float scale = 0.1f / camera_->GetZoom(); if (camera_->IsOrthographic()) scale *= camera_->GetOrthoSize(); else scale *= (camera_->GetView() * gizmoNode_->GetPosition()).z_; gizmoNode_->SetScale(Vector3(scale, scale, scale)); } }
// Default constructor LLFloaterAbout::LLFloaterAbout() : LLFloater(std::string("floater_about"), std::string("FloaterAboutRect"), LLStringUtil::null) { LLUICtrlFactory::getInstance()->buildFloater(this, "floater_about.xml"); // Support for changing product name. std::string title("About "); title += LLAppViewer::instance()->getSecondLifeTitle(); setTitle(title); LLViewerTextEditor *support_widget = getChild<LLViewerTextEditor>("support_editor", true); LLViewerTextEditor *credits_widget = getChild<LLViewerTextEditor>("credits_editor", true); if (!support_widget || !credits_widget) { return; } // For some reason, adding style doesn't work unless this is true. support_widget->setParseHTML(TRUE); // Text styles for release notes hyperlinks LLStyleSP viewer_link_style(new LLStyle); viewer_link_style->setVisible(true); viewer_link_style->setFontName(LLStringUtil::null); viewer_link_style->setLinkHREF(get_viewer_release_notes_url()); viewer_link_style->setColor(gSavedSettings.getColor4("HTMLLinkColor")); // Version string std::string version = std::string(LLAppViewer::instance()->getSecondLifeTitle() + llformat(" %d.%d.%d (%d) %s %s (%s)\n", LL_VERSION_MAJOR, LL_VERSION_MINOR, LL_VERSION_PATCH, LL_VIEWER_BUILD, __DATE__, __TIME__, LL_CHANNEL)); support_widget->appendColoredText(version, FALSE, FALSE, gColors.getColor("TextFgReadOnlyColor")); support_widget->appendStyledText(LLTrans::getString("ReleaseNotes"), false, false, viewer_link_style); std::string support; support.append("\n\n"); #if LL_MSVC support.append(llformat("Built with MSVC version %d\n\n", _MSC_VER)); #endif #if LL_GNUC support.append(llformat("Built with GCC version %d\n\n", GCC_VERSION)); #endif // Position LLViewerRegion* region = gAgent.getRegion(); if (region) { LLStyleSP server_link_style(new LLStyle); server_link_style->setVisible(true); server_link_style->setFontName(LLStringUtil::null); server_link_style->setLinkHREF(region->getCapability("ServerReleaseNotes")); server_link_style->setColor(gSavedSettings.getColor4("HTMLLinkColor")); const LLVector3d &pos = gAgent.getPositionGlobal(); LLUIString pos_text = getString("you_are_at"); pos_text.setArg("[POSITION]", llformat("%.1f, %.1f, %.1f ", pos.mdV[VX], pos.mdV[VY], pos.mdV[VZ])); support.append(pos_text); std::string region_text = llformat("in %s located at ", gAgent.getRegion()->getName().c_str()); support.append(region_text); std::string buffer; buffer = gAgent.getRegion()->getHost().getHostName(); support.append(buffer); support.append(" ("); buffer = gAgent.getRegion()->getHost().getString(); support.append(buffer); support.append(")\n"); support.append(gLastVersionChannel); support.append("\n"); support_widget->appendColoredText(support, FALSE, FALSE, gColors.getColor("TextFgReadOnlyColor")); support_widget->appendStyledText(LLTrans::getString("ReleaseNotes"), false, false, server_link_style); support = "\n\n"; } // *NOTE: Do not translate text like GPU, Graphics Card, etc - // Most PC users that know what these mean will be used to the english versions, // and this info sometimes gets sent to support // CPU support.append("CPU: "); support.append( gSysCPU.getCPUString() ); support.append("\n"); U32 memory = gSysMemory.getPhysicalMemoryKB() / 1024; // Moved hack adjustment to Windows memory size into llsys.cpp std::string mem_text = llformat("Memory: %u MB\n", memory ); support.append(mem_text); support.append("OS Version: "); support.append( LLAppViewer::instance()->getOSInfo().getOSString() ); support.append("\n"); support.append("Graphics Card Vendor: "); support.append( (const char*) glGetString(GL_VENDOR) ); support.append("\n"); support.append("Graphics Card: "); support.append( (const char*) glGetString(GL_RENDERER) ); support.append("\n"); #if LL_WINDOWS getWindow()->incBusyCount(); getWindow()->setCursor(UI_CURSOR_ARROW); support.append("Windows Graphics Driver Version: "); LLSD driver_info = gDXHardware.getDisplayInfo(); if (driver_info.has("DriverVersion")) { support.append(driver_info["DriverVersion"]); } support.append("\n"); getWindow()->decBusyCount(); getWindow()->setCursor(UI_CURSOR_ARROW); #endif support.append("OpenGL Version: "); support.append( (const char*) glGetString(GL_VERSION) ); support.append("\n"); support.append("\n"); support.append("libcurl Version: "); support.append( LLCurl::getVersionString() ); support.append("\n"); support.append("J2C Decoder Version: "); support.append( LLImageJ2C::getEngineInfo() ); support.append("\n"); support.append("Audio Driver Version: "); bool want_fullname = true; support.append( gAudiop ? gAudiop->getDriverName(want_fullname) : "(none)" ); support.append("\n"); // TODO: Implement media plugin version query support.append("Qt Webkit Version: 4.5.2 "); support.append("\n"); if (gPacketsIn > 0) { std::string packet_loss = llformat("Packets Lost: %.0f/%.0f (%.1f%%)", LLViewerStats::getInstance()->mPacketsLostStat.getCurrent(), F32(gPacketsIn), 100.f*LLViewerStats::getInstance()->mPacketsLostStat.getCurrent() / F32(gPacketsIn) ); support.append(packet_loss); support.append("\n"); } support_widget->appendColoredText(support, FALSE, FALSE, gColors.getColor("TextFgReadOnlyColor")); // Fix views support_widget->setCursorPos(0); support_widget->setEnabled(FALSE); support_widget->setTakesFocus(TRUE); support_widget->setHandleEditKeysDirectly(TRUE); credits_widget->setCursorPos(0); credits_widget->setEnabled(FALSE); credits_widget->setTakesFocus(TRUE); credits_widget->setHandleEditKeysDirectly(TRUE); center(); sInstance = this; }
GUI_Dialog::GUI_Dialog(GUI_WinBase *pw,const char *t,int x,int y,int w,int h,SDL_Color c,int b,void (*cm)(GUI_WinBase *)): GUI_MainWin( pw, t, x, y, w, h, c, b, cm ) { center(); GUI_modalWindow = this; }
RegisterDialog::RegisterDialog(LoginData &data) : // TRANSLATORS: register dialog name Window(_("Register"), Modal_false, nullptr, "register.xml"), ActionListener(), KeyListener(), mLoginData(&data), mUserField(new TextField(this, mLoginData->username)), mPasswordField(new PasswordField(this, mLoginData->password)), mConfirmField(new PasswordField(this)), mEmailField(nullptr), // TRANSLATORS: register dialog. button. mRegisterButton(new Button(this, _("Register"), "register", this)), // TRANSLATORS: register dialog. button. mCancelButton(new Button(this, _("Cancel"), "cancel", this)), mMaleButton(nullptr), mFemaleButton(nullptr), mOtherButton(nullptr), mWrongDataNoticeListener(new WrongDataNoticeListener) { setCloseButton(true); const int optionalActions = loginHandler-> supportedOptionalActions(); // TRANSLATORS: register dialog. label. Label *const userLabel = new Label(this, _("Name:")); // TRANSLATORS: register dialog. label. Label *const passwordLabel = new Label(this, _("Password:"******"Confirm:")); ContainerPlacer placer; placer = getPlacer(0, 0); placer(0, 0, userLabel); placer(0, 1, passwordLabel); placer(0, 2, confirmLabel); placer(1, 0, mUserField, 3).setPadding(2); placer(1, 1, mPasswordField, 3).setPadding(2); placer(1, 2, mConfirmField, 3).setPadding(2); int row = 3; if (optionalActions & Net::RegistrationOptions::SetGenderOnRegister) { // TRANSLATORS: register dialog. button. mMaleButton = new RadioButton(this, _("Male"), "sex", true); // TRANSLATORS: register dialog. button. mFemaleButton = new RadioButton(this, _("Female"), "sex", false); if (serverFeatures->haveOtherGender()) { // TRANSLATORS: register dialog. button. mOtherButton = new RadioButton(this, _("Other"), "sex", false); placer(0, row, mMaleButton); placer(1, row, mFemaleButton); placer(2, row, mOtherButton); } else { placer(1, row, mMaleButton); placer(2, row, mFemaleButton); } row++; } if (optionalActions & Net::RegistrationOptions::SetEmailOnRegister) { // TRANSLATORS: register dialog. label. Label *const emailLabel = new Label(this, _("Email:")); mEmailField = new TextField(this); placer(0, row, emailLabel); placer(1, row, mEmailField, 3).setPadding(2); // row++; } placer = getPlacer(0, 2); placer(1, 0, mRegisterButton); placer(2, 0, mCancelButton); reflowLayout(250, 0); mUserField->addKeyListener(this); mPasswordField->addKeyListener(this); mConfirmField->addKeyListener(this); mUserField->setActionEventId("register"); mPasswordField->setActionEventId("register"); mConfirmField->setActionEventId("register"); mUserField->addActionListener(this); mPasswordField->addActionListener(this); mConfirmField->addActionListener(this); center(); }
void CKWResearchWorkDoc::OnHelpTest() { // TODO: Add your command handler code here vector<Point_3> SamplePoints; GeometryAlgorithm::SampleCircle(Point_3(0,0,0),0.3,20,SamplePoints); FILE* pfile=fopen("circle0.contour","w"); for (unsigned int i=0;i<SamplePoints.size();i++) { fprintf(pfile,"%.3f %.3f %.3f\n",SamplePoints.at(i).x(),SamplePoints.at(i).y(),SamplePoints.at(i).z()); } fclose(pfile); Polygon_2 PolyTest; PolyTest.push_back(Point_2(0,0)); PolyTest.push_back(Point_2(1,1)); PolyTest.push_back(Point_2(2,0)); PolyTest.push_back(Point_2(2,2)); PolyTest.push_back(Point_2(0,2)); Point_2 ResultPoint; bool bResult=GeometryAlgorithm::GetArbiPointInPolygon(PolyTest,ResultPoint); DBWindowWrite("result point: %f %f\n",ResultPoint.x(),ResultPoint.y()); SparseMatrix LHMatrix(2); LHMatrix.m = 3; LHMatrix[0][0] = 2; LHMatrix[0][1] = -1; LHMatrix[0][2] = 1; LHMatrix[1][1] = 1; LHMatrix[1][2] = 1; SparseMatrix LHMatrixAT(LHMatrix.NCols()); CMath MathCompute; MathCompute.TAUCSFactorize(LHMatrix,LHMatrixAT); vector<vector<double>> RightMatB,ResultMat; vector<double> BRow; BRow.push_back(5);BRow.push_back(3); RightMatB.push_back(BRow); BRow.clear(); BRow.push_back(10);BRow.push_back(1); RightMatB.push_back(BRow); BRow.clear(); MathCompute.TAUCSComputeLSE(LHMatrixAT,RightMatB,ResultMat); return; int iVer=this->Mesh.size_of_vertices(); int iEdge=this->Mesh.size_of_halfedges(); int iFacet=this->Mesh.size_of_facets(); Polygon_2 BoundingPolygon0; Polygon_2 BoundingPolygon1; bool bSimple0=BoundingPolygon0.is_simple(); bool bSimple1=BoundingPolygon1.is_simple(); bool bConvex0=BoundingPolygon0.is_convex(); bool bConvex1=BoundingPolygon1.is_convex(); bool bOrien0=BoundingPolygon0.is_clockwise_oriented(); bool bOrien1=BoundingPolygon1.is_clockwise_oriented(); BoundingPolygon0.reverse_orientation(); BoundingPolygon1.reverse_orientation(); //float? bool bIntersect=CGAL::do_intersect(BoundingPolygon0,BoundingPolygon1); bool bCW=BoundingPolygon0.is_clockwise_oriented(); bool bConvex=BoundingPolygon0.is_convex(); Plane_3 plane(1,1,1,0); vector<vector<Point_3>> IntersectCurves; int iNum=GeometryAlgorithm::GetMeshPlaneIntersection(this->Mesh,plane,IntersectCurves); CMath CMathTest; CMathTest.testTAUCS(); // Vector_3 vec0(Point_3(0,0,1),Point_3(0,0,0)); Vector_3 vec0(Point_3(0,0,0),Point_3(0,0,1)); // Vector_3 vec0(0,0,1); // Vector_3 vec1(0,-1,-1); Vector_3 vec1(Point_3(0,0,0),Point_3(0,-1,-1)); double dAngle=GeometryAlgorithm::GetAngleBetweenTwoVectors3d(vec0,vec1); vector<double> number; number.push_back(2); number.push_back(4); number.push_back(4); number.push_back(4); number.push_back(5); number.push_back(5); number.push_back(7); number.push_back(9); double dderi=GeometryAlgorithm::GetDerivation(number); Point_3 center(0,0,0); Sphere_3 sphere(center,1); Line_3 line(Point_3(0,2,1),Point_3(0,2,-1)); vector<Point_3> points; GeometryAlgorithm::GetLineSphereIntersection(line,sphere,points); vector<Point_3> Group0,Group1; vector<Int_Int_Pair> GroupResult; Group0.push_back(Point_3(3,3,2)); Group0.push_back(Point_3(5,3,2)); Group0.push_back(Point_3(2,3,2)); Group0.push_back(Point_3(6,3,2)); Group0.push_back(Point_3(4,3,2)); Group0.push_back(Point_3(1,3,2)); Group1.push_back(Point_3(3,4,2)); Group1.push_back(Point_3(1,4,2)); Group1.push_back(Point_3(6,4,2)); Group1.push_back(Point_3(2,4,2)); Group1.push_back(Point_3(5,4,2)); Group1.push_back(Point_3(4,4,2)); vector<Point_3> vecMidPoint; GeometryAlgorithm::GroupNearestPoints(Group0,Group1,GroupResult,vecMidPoint);// vector<Point_3> OriginalCurve; OriginalCurve.push_back(Point_3(-1,0,2)); OriginalCurve.push_back(Point_3(1,0,2)); OriginalCurve.push_back(Point_3(1,0,0)); OriginalCurve.push_back(Point_3(-1,0,0)); vector<Point_3> NewCurve=OriginalCurve; vector<int> HandleInd; HandleInd.push_back(0); HandleInd.push_back(1); vector<Point_3> NewPos; NewPos.push_back(Point_3(-1,0,3)); NewPos.push_back(Point_3(1,0,3)); // CCurveDeform::ClosedCurveNaiveLaplacianDeform(NewCurve,HandleInd,NewPos,1); vector<vector<float>> MatrixA,MatrixB,Result; vector<float> CurrentRow; CurrentRow.push_back(2);CurrentRow.push_back(0);CurrentRow.push_back(1); MatrixA.push_back(CurrentRow); CurrentRow.clear(); CurrentRow.push_back(3);CurrentRow.push_back(1);CurrentRow.push_back(2); MatrixA.push_back(CurrentRow); CurrentRow.clear(); CurrentRow.push_back(0);CurrentRow.push_back(1);CurrentRow.push_back(0); MatrixA.push_back(CurrentRow); CurrentRow.clear(); CurrentRow.push_back(1);CurrentRow.push_back(3);CurrentRow.push_back(0); MatrixB.push_back(CurrentRow); CurrentRow.clear(); CurrentRow.push_back(2);CurrentRow.push_back(0);CurrentRow.push_back(2); MatrixB.push_back(CurrentRow); CurrentRow.clear(); CurrentRow.push_back(1);CurrentRow.push_back(0);CurrentRow.push_back(1); MatrixB.push_back(CurrentRow); CurrentRow.clear(); int iANonZeroSize=0; for (unsigned int i=0;i<MatrixA.size();i++) { for (unsigned int j=0;j<MatrixA.front().size();j++) { if (MatrixA.at(i).at(j)!=0) { iANonZeroSize++; } } } KW_SparseMatrix A(MatrixA.size(),MatrixA.front().size(),iANonZeroSize); for (unsigned int i=0;i<MatrixA.size();i++) { for (unsigned int j=0;j<MatrixA.front().size();j++) { if (MatrixA.at(i).at(j)!=0) { A.fput(i,j,MatrixA.at(i).at(j)); } } } int iBNonZeroSize=0; for (unsigned int i=0;i<MatrixB.size();i++) { for (unsigned int j=0;j<MatrixB.front().size();j++) { if (MatrixB.at(i).at(j)!=0) { iBNonZeroSize++; } } } KW_SparseMatrix B(MatrixB.size(),MatrixB.front().size(),iBNonZeroSize); for (unsigned int i=0;i<MatrixB.size();i++) { for (unsigned int j=0;j<MatrixB.front().size();j++) { if (MatrixB.at(i).at(j)!=0) { B.fput(i,j,MatrixB.at(i).at(j)); } } } KW_SparseMatrix C(A.m,B.n,0); KW_SparseMatrix::KW_multiply(A,B,C); int iIndex=0; Result.clear(); for (int i=0;i<C.m;i++) { vector<float> CurrentRow; for (int j=0;j<C.n;j++) { iIndex=0; while (iIndex<C.vol) { if (C.indx[iIndex]==i&&C.jndx[iIndex]==j) { break; } iIndex++; } if (iIndex!=C.vol) { CurrentRow.push_back(C.array[iIndex]); } else { CurrentRow.push_back(0); } } Result.push_back(CurrentRow); } }
void type(Flayer *l, int res) /* what a bloody mess this is */ { Text *t = (Text *)l->user1; Rune buf[100]; Rune *p = buf; int c, backspacing; int32_t a, a0; int scrollkey; scrollkey = 0; if(res == RKeyboard) scrollkey = nontypingkey(qpeekc()); /* ICK */ if(hostlock || t->lock){ kbdblock(); return; } a = l->p0; if(a!=l->p1 && !scrollkey){ flushtyping(1); cut(t, t->front, 1, 1); return; /* it may now be locked */ } backspacing = 0; while((c = kbdchar())>0){ if(res == RKeyboard){ if(nontypingkey(c) || c==ESC) break; /* backspace, ctrl-u, ctrl-w, del */ if(c=='\b' || c==0x15 || c==0x17 || c==0x7F){ backspacing = 1; break; } } *p++ = c; if(autoindent) if(c == '\n'){ /* autoindent */ int cursor, ch; cursor = ctlu(&t->rasp, 0, a+(p-buf)-1); while(p < buf+nelem(buf)){ ch = raspc(&t->rasp, cursor++); if(ch == ' ' || ch == '\t') *p++ = ch; else break; } } if(c == '\n' || p >= buf+sizeof(buf)/sizeof(buf[0])) break; } if(p > buf){ if(typestart < 0) typestart = a; if(typeesc < 0) typeesc = a; hgrow(t->tag, a, p-buf, 0); t->lock++; /* pretend we Trequest'ed for hdatarune*/ hdatarune(t->tag, a, buf, p-buf); a += p-buf; l->p0 = a; l->p1 = a; typeend = a; if(c=='\n' || typeend-typestart>100) flushtyping(0); onethird(l, a); } if(c==SCROLLKEY || c==PAGEDOWN){ flushtyping(0); center(l, l->origin+l->f.nchars+1); /* backspacing immediately after outcmd(): sorry */ }else if(c==BACKSCROLLKEY || c==PAGEUP){ flushtyping(0); a0 = l->origin-l->f.nchars; if(a0 < 0) a0 = 0; center(l, a0); }else if(c == RIGHTARROW){ flushtyping(0); a0 = l->p0; if(a0 < t->rasp.nrunes) a0++; flsetselect(l, a0, a0); center(l, a0); }else if(c == LEFTARROW){ flushtyping(0); a0 = l->p0; if(a0 > 0) a0--; flsetselect(l, a0, a0); center(l, a0); }else if(c == HOMEKEY){ flushtyping(0); center(l, 0); }else if(c == ENDKEY){ flushtyping(0); center(l, t->rasp.nrunes); }else if(c == LINESTART || c == LINEEND){ flushtyping(1); if(c == LINESTART) while(a > 0 && raspc(&t->rasp, a-1)!='\n') a--; else while(a < t->rasp.nrunes && raspc(&t->rasp, a)!='\n') a++; l->p0 = l->p1 = a; for(l=t->l; l<&t->l[NL]; l++) if(l->textfn) flsetselect(l, l->p0, l->p1); }else if(backspacing && !hostlock){ /* backspacing immediately after outcmd(): sorry */ if(l->f.p0>0 && a>0){ switch(c){ case '\b': case 0x7F: /* del */ l->p0 = a-1; break; case 0x15: /* ctrl-u */ l->p0 = ctlu(&t->rasp, l->origin, a); break; case 0x17: /* ctrl-w */ l->p0 = ctlw(&t->rasp, l->origin, a); break; } l->p1 = a; if(l->p1 != l->p0){ /* cut locally if possible */ if(typestart<=l->p0 && l->p1<=typeend){ t->lock++; /* to call hcut */ hcut(t->tag, l->p0, l->p1-l->p0); /* hcheck is local because we know rasp is contiguous */ hcheck(t->tag); }else{ flushtyping(0); cut(t, t->front, 0, 1); } } if(typeesc >= l->p0) typeesc = l->p0; if(typestart >= 0){ if(typestart >= l->p0) typestart = l->p0; typeend = l->p0; if(typestart == typeend){ typestart = -1; typeend = -1; modified = 0; } } } }else{ if(c==ESC && typeesc>=0){ l->p0 = typeesc; l->p1 = a; flushtyping(1); } for(l=t->l; l<&t->l[NL]; l++) if(l->textfn) flsetselect(l, l->p0, l->p1); } }
double rdistance(xcb_rectangle_t r1, xcb_rectangle_t r2) { return distance(center(r1), center(r2)); }
osg::Node* createTestTexture2D(osg::Node* node, const std::string& filename) { osg::BoundingBox bb; osg::ref_ptr<osg::ComputeBoundsVisitor> boundsVistor = new osg::ComputeBoundsVisitor(); boundsVistor->reset(); node->accept(*boundsVistor.get()); bb = boundsVistor->getBoundingBox(); osg::Group* group = new osg::Group; // left hand side of bounding box. osg::Vec3 top_left(bb.xMin(), bb.yMin(), bb.zMax()); osg::Vec3 bottom_left(bb.xMin(), bb.yMin(), bb.zMin()); osg::Vec3 bottom_right(bb.xMin(), bb.yMax(), bb.zMin()); osg::Vec3 top_right(bb.xMin(), bb.yMax(), bb.zMax()); osg::Vec3 center(bb.xMin(), (bb.yMin() + bb.yMax())*0.5f, (bb.zMin() + bb.zMax())*0.5f); float height = bb.zMax() - bb.zMin(); // create the geometry for the wall. osg::Geometry* geom = new osg::Geometry; osg::Vec3Array* vertices = new osg::Vec3Array(4); (*vertices)[0] = top_left; (*vertices)[1] = bottom_left; (*vertices)[2] = bottom_right; (*vertices)[3] = top_right; geom->setVertexArray(vertices); osg::Vec2Array* texcoords = new osg::Vec2Array(4); (*texcoords)[0].set(0.0f, 1.0f); (*texcoords)[1].set(0.0f, 0.0f); (*texcoords)[2].set(1.0f, 0.0f); (*texcoords)[3].set(1.0f, 1.0f); geom->setTexCoordArray(0, texcoords); osg::Vec3Array* normals = new osg::Vec3Array(1); (*normals)[0].set(1.0f, 0.0f, 0.0f); geom->setNormalArray(normals, osg::Array::BIND_OVERALL); osg::Vec4Array* colors = new osg::Vec4Array(1); (*colors)[0].set(1.0f, 1.0f, 1.0f, 1.0f); geom->setColorArray(colors, osg::Array::BIND_OVERALL); geom->addPrimitiveSet(new osg::DrawArrays(GL_QUADS, 0, 4)); osg::Geode* geom_geode = new osg::Geode; geom_geode->addDrawable(geom); group->addChild(geom_geode); // set up the texture state. osg::Texture2D* texture = new osg::Texture2D; texture->setDataVariance(osg::Object::DYNAMIC); // protect from being optimized away as static state. osg::notify(osg::FATAL) << filename << std::endl; osg::Image* image = g_SystemContext._resourceLoader->getImageByFileName(filename); if (image == NULL) { osg::notify(osg::FATAL) << filename << "--load faile!!!" << std::endl; } else texture->setImage(0, image); osg::StateSet* stateset = geom->getOrCreateStateSet(); stateset->setTextureAttributeAndModes(0, texture, osg::StateAttribute::ON); osg::notify(osg::FATAL) << "33333" << std::endl; // create the text label. osgText::Text* text = new osgText::Text; text->setDataVariance(osg::Object::DYNAMIC); text->setFont("fonts/arial.ttf"); text->setPosition(center); text->setCharacterSize(height*0.03f); text->setAlignment(osgText::Text::CENTER_CENTER); text->setAxisAlignment(osgText::Text::YZ_PLANE); osg::Geode* text_geode = new osg::Geode; text_geode->addDrawable(text); osg::StateSet* text_stateset = text_geode->getOrCreateStateSet(); text_stateset->setAttributeAndModes(new osg::PolygonOffset(-1.0f, -1.0f), osg::StateAttribute::ON); group->addChild(text_geode); // set the update callback to cycle through the various min and mag filter modes. //group->setUpdateCallback(new FilterCallback(texture,text)); return group; }