/*! Nothing else than: canvas()->palette().brush( QPalette::Normal, QPalette::Window); \return Background brush of the plotting area. \sa setCanvasBackground() */ QBrush QwtPlot::canvasBackground() const { return canvas()->palette().brush( QPalette::Normal, QPalette::Window ); }
ribi::QtToolTestApproximatorXyzMainDialog::QtToolTestApproximatorXyzMainDialog(QWidget *parent) noexcept : QtHideAndShowDialog(parent), ui(new Ui::QtToolTestApproximatorXyzMainDialog), m_approximator(), m_data(CreateData()) { #ifndef NDEBUG Test(); #endif ui->setupUi(this); //Set up the plots and curves GetPlot(0)->setTitle("Approximator, for z = 0.0"); GetPlot(1)->setTitle("Approximator, for z = 0.5"); GetPlot(2)->setTitle("Approximator, for z = 1.0"); for (auto i=0; i!=m_n_curves; ++i) { const auto plot = GetPlot(i); plot->setAxisTitle(QwtPlot::xBottom,"X"); plot->setAxisTitle(QwtPlot::yLeft,"Y"); #ifdef _WIN32 plot->setCanvasBackground(QBrush(QColor(255,255,255))); #else plot->setCanvasBackground(QColor(255,255,255)); #endif const auto curve_values = GetCurveValues(i); assert(curve_values); curve_values->setTitle("Points"); curve_values->attach(plot.get()); curve_values->setStyle(QwtPlotCurve::Dots); curve_values->setPen(QPen(QColor(255,0,0),5)); const auto curve_approximation = GetCurveApproximation(i); assert(curve_approximation); curve_approximation->setTitle("Approximation"); curve_approximation->attach(plot.get()); curve_approximation->setStyle(QwtPlotCurve::Dots); curve_approximation->setPen(QPen(QColor(0,0,255),3)); //Add grid { QwtPlotGrid * const grid = new QwtPlotGrid; grid->setPen(QPen(QColor(128,128,128))); grid->attach(plot.get()); } //Add zoomer { new QwtPlotZoomer(plot->canvas()); } //Add legend { QwtLegend * const legend = new QwtLegend; legend->setFrameStyle(QFrame::Box|QFrame::Sunken); plot->insertLegend(legend, QwtPlot::RightLegend); } plot->setAxisScale( QwtPlot::xBottom, static_cast<double>(ui->box_int_x->minimum()), static_cast<double>(ui->box_int_x->maximum()) ); plot->setAxisScale( QwtPlot::yLeft, static_cast<double>(ui->box_double_y->minimum()), static_cast<double>(ui->box_double_y->maximum()) ); //Add to dialog assert(ui->verticalLayout->layout()); ui->verticalLayout->layout()->addWidget(plot.get()); } //Add some nice testing values ui->box_int_x->setValue(ui->box_int_x->minimum() / 2); ui->box_double_y->setValue(ui->box_double_y->maximum() / 2.0); on_button_clicked(); ui->box_int_x->setValue(ui->box_int_x->minimum() / 4); ui->box_double_y->setValue(ui->box_double_y->minimum() / 2.0); on_button_clicked(); ui->box_int_x->setValue(ui->box_int_x->maximum() / 4); ui->box_double_y->setValue(ui->box_double_y->maximum() / 2.0); on_button_clicked(); ui->box_int_x->setValue(ui->box_int_x->maximum() / 2); ui->box_double_y->setValue(ui->box_double_y->minimum() / 2.0); on_button_clicked(); ui->box_int_x->setValue(0); ui->box_double_y->setValue(0.0); }
int App::start(const std::vector<std::string> &args) { clan::DisplayWindowDescription description; description.set_title("Thread Example"); description.set_size(clan::Size(1024, 768), true); clan::DisplayWindow window(description); clan::InputDevice keyboard = window.get_ic().get_keyboard(); clan::Canvas canvas(window); clan::SlotContainer cc; cc.connect(window.get_ic().get_keyboard().sig_key_up(), clan::bind_member(this, &App::on_input_up)); cc.connect(window.sig_window_close(), clan::bind_member(this, &App::window_close)); // Load the font clan::Font font(canvas, "tahoma", 32); // Create the initial textures texture_buffers[0] = clan::Texture2D(canvas, texture_size, texture_size); texture_buffers[1] = clan::Texture2D(canvas, texture_size, texture_size); // Create the initial pixelbuffers pixel_buffers[0] = clan::PixelBuffer(texture_size, texture_size, clan::tf_rgba8); pixel_buffers[1] = clan::PixelBuffer(texture_size, texture_size, clan::tf_rgba8); // Initially clear the textures, so they are filled with a "Calculating..." message clan::FrameBuffer framebuffer(canvas); framebuffer.attach_color(0, texture_buffers[0]); clan::Canvas canvas_fb( canvas, framebuffer ); canvas_fb.clear(); font.draw_text(canvas_fb, 32, 96, "Calculating..."); canvas_fb.flush(); framebuffer.attach_color(0, texture_buffers[1]); canvas_fb = clan::Canvas( canvas, framebuffer ); canvas_fb.clear(); font.draw_text(canvas_fb, 32, 96, "Calculating..."); canvas_fb.flush(); // Setup the initial texture double buffering variables texture_buffers_offset = 0; pixel_buffers_offset = 0; worker_thread_complete = false; texture_write = &texture_buffers[0]; texture_completed = &texture_buffers[1]; pixelbuffer_write = &pixel_buffers[0]; pixelbuffer_completed = &pixel_buffers[1]; dest_pixels = NULL; quit = false; crashed_flag = false; clan::MutexSection worker_thread_mutex_section(&worker_thread_mutex, false); // We require a try block, so the worker thread exits correctly clan::Thread thread; try { thread.start(this, &App::worker_thread); // Main loop FramerateCounter framerate_counter; FramerateCounter worker_thread_framerate_counter; clan::ubyte64 last_time = clan::System::get_time(); clan::ubyte64 last_mandelbrot_time = clan::System::get_time(); float angle = 0.0f; bool worker_thread_started = false; bool texture_write_active = false; while (!quit) { framerate_counter.frame_shown(); // Calculate timings clan::ubyte64 current_time = clan::System::get_time(); float time_delta_ms = (float) (current_time - last_time); last_time = current_time; angle += time_delta_ms / 50.0f; while(angle > 360.0f) angle-=360.0f; canvas.clear(); // If the pixel buffer was uploaded on the last frame, double buffer it if (texture_write_active) { texture_write_active = false; if (texture_buffers_offset == 0) { texture_buffers_offset = 1; texture_write = &texture_buffers[1]; texture_completed = &texture_buffers[0]; } else { texture_buffers_offset = 0; texture_write = &texture_buffers[0]; texture_completed = &texture_buffers[1]; } } // Wait for pixel buffer completion if ((worker_thread_started == true) && (worker_thread_complete==true)) { worker_thread_mutex_section.lock(); worker_thread_started = false; worker_thread_complete = false; pixelbuffer_write->unlock(); worker_thread_mutex_section.unlock(); texture_write->set_subimage(canvas, 0, 0, *pixelbuffer_write, pixelbuffer_write->get_size()); texture_write_active = true; // Note the worker thread will start on the other pixelbuffer straight away, in the next "if" statement } // Start a new transfer when required if ((worker_thread_started == false) && (worker_thread_complete==false)) { worker_thread_framerate_counter.frame_shown(); worker_thread_mutex_section.lock(); // Swap the pixelbuffer's if (pixel_buffers_offset == 0) { pixel_buffers_offset = 1; pixelbuffer_write = &pixel_buffers[1]; pixelbuffer_completed = &pixel_buffers[0]; } else { pixel_buffers_offset = 0; pixelbuffer_write = &pixel_buffers[0]; pixelbuffer_completed = &pixel_buffers[1]; } pixelbuffer_write->lock(canvas, clan::access_write_only); dest_pixels = (unsigned char *) pixelbuffer_write->get_data(); worker_thread_started = true; worker_thread_complete = false; // Adjust the mandelbrot scale float mandelbrot_time_delta_ms = (float) (current_time - last_mandelbrot_time); last_mandelbrot_time = current_time; scale -= scale * mandelbrot_time_delta_ms / 1000.0f; if (scale <= 0.001f) scale = 4.0f; worker_thread_mutex_section.unlock(); worker_thread_activate_event.set(); } // Draw rotating mandelbrot canvas.set_transform(clan::Mat4f::translate(canvas.get_width()/2, canvas.get_height()/2, 0.0f) * clan::Mat4f::rotate(clan::Angle(angle, clan::angle_degrees), 0.0f, 0.0f, 1.0f)); clan::Image image(*texture_completed, clan::Size(texture_size, texture_size)); image.draw( canvas, -texture_size/2, -texture_size/2 ); canvas.set_transform(clan::Mat4f::identity()); // Draw FPS std::string fps; fps = std::string(clan::string_format("Main Loop %1 fps", framerate_counter.get_framerate())); font.draw_text(canvas, 16, canvas.get_height()-16-2, fps, clan::Colorf(1.0f, 1.0f, 0.0f, 1.0f)); fps = std::string(clan::string_format("Worker Thread %1 fps", worker_thread_framerate_counter.get_framerate())); font.draw_text(canvas, 16, canvas.get_height()-64-2, fps, clan::Colorf(1.0f, 1.0f, 0.0f, 1.0f)); // Draw worker thread crashed message if (crashed_flag) font.draw_text(canvas, 16, 32, "WORKER THREAD CRASHED"); window.flip(0); clan::KeepAlive::process(); } canvas.clear(); font.draw_text(canvas, 32, 32, "Waiting for worker thread to exit"); window.flip(0); worker_thread_stop_event.set(); thread.join(); } catch(clan::Exception &exception) { worker_thread_stop_event.set(); thread.join(); throw exception; } return 0; }
ProgressWindow::ProgressWindow(ContainerWindow &parent) :background_color(COLOR_WHITE), background_brush(background_color), position(0) { PixelRect rc = parent.GetClientRect(); WindowStyle style; style.Hide(); Create(parent, rc, style); const unsigned width = rc.right - rc.left, height = rc.bottom - rc.top; // Load progress bar background bitmap_progress_border.Load(IDB_PROGRESSBORDER); // Determine text height #ifndef USE_GDI font.Load(FontDescription(Layout::FontScale(10))); text_height = font.GetHeight(); #else VirtualCanvas canvas({1, 1}); text_height = canvas.GetFontHeight(); #endif // Make progress bar height proportional to window height const unsigned progress_height = height / 20; const unsigned progress_horizontal_border = progress_height / 2; progress_border_height = progress_height * 2; // Initialize message text field PixelRect message_rc = rc; message_rc.bottom -= progress_border_height + height / 48; message_rc.top = message_rc.bottom - text_height; TextWindowStyle message_style; message_style.center(); message.Create(*this, nullptr, message_rc, message_style); #ifndef USE_GDI message.SetFont(font); #endif // Initialize progress bar PixelRect pb_rc; pb_rc.left = progress_horizontal_border; pb_rc.right = pb_rc.left + width - progress_height; pb_rc.top = height - progress_border_height + progress_horizontal_border; pb_rc.bottom = pb_rc.top + progress_height; ProgressBarStyle pb_style; progress_bar.Create(*this, pb_rc, pb_style); #ifdef USE_GDI message.InstallWndProc(); // needed for OnChildColor() #endif // Set progress bar step size and range SetRange(0, 1000); SetStep(50); // Show dialog ShowOnTop(); }
void ColDiagramView::dropEvent(QDropEvent * e) { BrowserNode * bn; QPoint p = viewportToContents(e->pos()); if ((bn = UmlDrag::decode(e, UmlClassInstance)) != 0) { history_save(); CodClassInstCanvas * i = new CodClassInstCanvas((BrowserClassInstance *) bn, the_canvas(), p.x(), p.y(), 0); history_protected = TRUE; i->show(); i->upper(); canvas()->update(); history_protected = FALSE; window()->package_modified(); } else if ((bn = UmlDrag::decode(e, UmlClass)) != 0) { history_save(); CodClassInstCanvas * cli = new CodClassInstCanvas(bn, the_canvas(), p.x(), p.y(), 0); history_protected = TRUE; cli->show(); cli->upper(); canvas()->update(); history_protected = FALSE; window()->package_modified(); } else if ((bn = UmlDrag::decode(e, UmlPackage)) != 0) { history_save(); PackageCanvas * pk = new PackageCanvas(bn, the_canvas(), p.x(), p.y(), 0); history_protected = TRUE; pk->show(); pk->upper(); canvas()->update(); window()->package_modified(); } else if (((bn = UmlDrag::decode(e, UmlClassDiagram)) != 0) || ((bn = UmlDrag::decode(e, UmlUseCaseDiagram)) != 0) || ((bn = UmlDrag::decode(e, UmlSeqDiagram)) != 0) || ((bn = UmlDrag::decode(e, UmlColDiagram)) != 0) || ((bn = UmlDrag::decode(e, UmlObjectDiagram)) != 0) || ((bn = UmlDrag::decode(e, UmlComponentDiagram)) != 0) || ((bn = UmlDrag::decode(e, UmlDeploymentDiagram)) != 0) || ((bn = UmlDrag::decode(e, UmlStateDiagram, TRUE)) != 0) || ((bn = UmlDrag::decode(e, UmlActivityDiagram, TRUE)) != 0)) { history_save(); IconCanvas * ic = new IconCanvas(bn, the_canvas(), p.x(), p.y(), 0); history_protected = TRUE; ic->show(); ic->upper(); canvas()->update(); history_protected = FALSE; window()->package_modified(); } }
void SdSelfMsgCanvas::menu(const QPoint&) { Q3PopupMenu m(0); m.insertItem(new MenuTitle(TR("Message"), m.font()), -1); m.insertSeparator(); m.insertItem(TR("Upper"), 0); m.insertItem(TR("Lower"), 1); m.insertItem(TR("Go up"), 13); m.insertItem(TR("Go down"), 14); m.insertSeparator(); m.insertItem(TR("Edit"), 2); m.insertItem(TR("Edit drawing settings"), 3); m.insertSeparator(); if (msg != 0) m.insertItem(TR("Select operation in browser"), 8); m.insertItem(TR("Select linked items"), 4); if (label || stereotype) { m.insertSeparator(); m.insertItem(TR("Select stereotype and label"), 5); m.insertItem(TR("Default stereotype and label position"), 6); } if (((BrowserSeqDiagram *) the_canvas()->browser_diagram()) ->is_overlapping_bars()) { m.insertSeparator(); m.insertItem(TR("Go to new overlapping bar"), 9); if (dest->isOverlappingDuration()) m.insertItem(TR("Go to parent bar"), 10); } m.insertSeparator(); m.insertItem(TR("Remove from diagram"), 7); switch (m.exec(QCursor::pos())) { case 0: upper(); // force son reaffichage hide(); show(); break; case 1: lower(); // force son reaffichage hide(); show(); break; case 13: z_up(); // force son reaffichage hide(); show(); break; case 14: z_down(); // force son reaffichage hide(); show(); break; case 2: open(); break; case 3: edit_drawing_settings(); return; case 4: select_associated(); break; case 5: the_canvas()->unselect_all(); if (label) the_canvas()->select(label); if (stereotype) the_canvas()->select(stereotype); break; case 6: if (label) default_label_position(); if (stereotype) default_stereotype_position(); break; case 7: delete_it(); return; case 8: msg->get_browser_node()->select_in_browser(); return; case 9: ((SdDurationCanvas *) dest)->go_up(this, TRUE); break; case 10: ((SdDurationCanvas *) dest)->go_down(this); default: return; } package_modified(); canvas()->update(); }
void ScrollZoomer::updateScrollBars() { if (!canvas()) return; const int xAxis = QwtPlotZoomer::xAxis(); const int yAxis = QwtPlotZoomer::yAxis(); int xScrollBarAxis = xAxis; if (hScrollBarPosition() == OppositeToScale) xScrollBarAxis = oppositeAxis(xScrollBarAxis); int yScrollBarAxis = yAxis; if (vScrollBarPosition() == OppositeToScale) yScrollBarAxis = oppositeAxis(yScrollBarAxis); QwtPlotLayout *layout = plot()->plotLayout(); bool showHScrollBar = needScrollBar(Qt::Horizontal); if (showHScrollBar) { ScrollBar *sb = scrollBar(Qt::Horizontal); sb->setPalette(plot()->palette()); const QwtScaleDiv *sd = &plot()->axisScaleDiv(xAxis); sb->setInverted(sd->lowerBound() > sd->upperBound()); sb->setBase(zoomBase().left(), zoomBase().right()); sb->moveSlider(zoomRect().left(), zoomRect().right()); if (!sb->isVisibleTo(canvas())) { sb->show(); layout->setCanvasMargin(layout->canvasMargin(xScrollBarAxis) + sb->extent(), xScrollBarAxis); } } else { if (horizontalScrollBar()) { horizontalScrollBar()->hide(); layout->setCanvasMargin(layout->canvasMargin(xScrollBarAxis) - horizontalScrollBar()->extent(), xScrollBarAxis); } } bool showVScrollBar = needScrollBar(Qt::Vertical); if (showVScrollBar) { ScrollBar *sb = scrollBar(Qt::Vertical); sb->setPalette(plot()->palette()); const QwtScaleDiv *sd = &plot()->axisScaleDiv(yAxis); sb->setInverted(sd->lowerBound() < sd->upperBound()); sb->setBase(zoomBase().top(), zoomBase().bottom()); sb->moveSlider(zoomRect().top(), zoomRect().bottom()); if (!sb->isVisibleTo(canvas())) { sb->show(); layout->setCanvasMargin(layout->canvasMargin(yScrollBarAxis) + sb->extent(), yScrollBarAxis); } } else { if (verticalScrollBar()) { verticalScrollBar()->hide(); layout->setCanvasMargin(layout->canvasMargin(yScrollBarAxis) - verticalScrollBar()->extent(), yScrollBarAxis); } } if (showHScrollBar && showVScrollBar) { if (d_cornerWidget == NULL) { d_cornerWidget = new QWidget(canvas()); #if QT_VERSION >= 0x040100 d_cornerWidget->setAutoFillBackground(true); #endif d_cornerWidget->setPalette(plot()->palette()); } d_cornerWidget->show(); } else { if (d_cornerWidget) d_cornerWidget->hide(); } layoutScrollBars(((QwtPlotCanvas *) canvas())->contentsRect()); plot()->updateLayout(); }
void flux_compare(Int_t mode,TString file,bool antinu=false) { Init(); //conversion to physical units Double_t mb_r=610.0; //from an email from Sam, 2008-03-06 Double_t flux_factor=1.0/(TMath::Pi()*pow(mb_r,2)); ////from NUANCE card file //Double_t mb_density=0.855; //Double_t mb_mass=mb_density*4.0*TMath::Pi()*pow(mb_r,3)/3.0; Double_t mb_factor=flux_factor; TString linlog="log"; //mine TFile f(file); gROOT->cd(); TTree *tree=(TTree*)f.Get("tree"); TGraph *gr=(TGraph*)f.Get("ccqe_rate")->Clone(); Int_t process=4; Double_t rate,dummy; gr->GetPoint(process,dummy,rate); delete gr; const Int_t NLines=83; Double_t linex[NLines]; if (linlog=="log") { Int_t iLine; //iLine= 0; linex[iLine]=0.1371614; //iLine= 1; linex[iLine]=0.1480541; //iLine= 2; linex[iLine]=0.1725035; //iLine= 3; linex[iLine]=0.2009903; //iLine= 4; linex[iLine]=0.2341815; //iLine= 5; linex[iLine]=0.2728536; //iLine= 6; linex[iLine]=0.3179121; //iLine= 7; linex[iLine]=0.3704115; //iLine= 8; linex[iLine]=0.4315804; //iLine= 9; linex[iLine]=0.5028507; //iLine=10; linex[iLine]=0.5858902; //iLine=11; linex[iLine]=0.6826431; //iLine=12; linex[iLine]=0.7953730; //iLine=13; linex[iLine]=0.9267194; //iLine=14; linex[iLine]=1.0797561; //iLine=15; linex[iLine]=1.2580642; //iLine=16; linex[iLine]=1.4658186; //iLine=17; linex[iLine]=1.7078801; //iLine=18; linex[iLine]=1.9899162; //iLine=19; linex[iLine]=2.3185259; //iLine=20; linex[iLine]=2.7014029; //iLine=21; linex[iLine]=3.1475057; //iLine=22; linex[iLine]=3.6672788; //iLine=23; linex[iLine]=4.2728839; //iLine=24; linex[iLine]=4.9784997; //iLine=25; linex[iLine]=5.8006397; //iLine=26; linex[iLine]=6.7585426; //iLine=27; linex[iLine]=7.8746354; //iLine=28; linex[iLine]=8.5000022; iLine= 0; linex[iLine]= 0.1371614; iLine= 1; linex[iLine]= 0.1407002; iLine= 2; linex[iLine]= 0.1480541; iLine= 3; linex[iLine]= 0.1557924; iLine= 4; linex[iLine]= 0.1639352; iLine= 5; linex[iLine]= 0.1725035; iLine= 6; linex[iLine]= 0.1815197; iLine= 7; linex[iLine]= 0.1910070; iLine= 8; linex[iLine]= 0.2009903; iLine= 9; linex[iLine]= 0.2114955; iLine=10; linex[iLine]= 0.2225496; iLine=11; linex[iLine]= 0.2341815; iLine=12; linex[iLine]= 0.2464213; iLine=13; linex[iLine]= 0.2593009; iLine=14; linex[iLine]= 0.2728536; iLine=15; linex[iLine]= 0.2871149; iLine=16; linex[iLine]= 0.3021213; iLine=17; linex[iLine]= 0.3179121; iLine=18; linex[iLine]= 0.3345283; iLine=19; linex[iLine]= 0.3520129; iLine=20; linex[iLine]= 0.3704115; iLine=21; linex[iLine]= 0.3897716; iLine=22; linex[iLine]= 0.4101436; iLine=23; linex[iLine]= 0.4315804; iLine=24; linex[iLine]= 0.4541376; iLine=25; linex[iLine]= 0.4778740; iLine=26; linex[iLine]= 0.5028507; iLine=27; linex[iLine]= 0.5291330; iLine=28; linex[iLine]= 0.5567889; iLine=29; linex[iLine]= 0.5858902; iLine=30; linex[iLine]= 0.6165126; iLine=31; linex[iLine]= 0.6487359; iLine=32; linex[iLine]= 0.6826431; iLine=33; linex[iLine]= 0.7183224; iLine=34; linex[iLine]= 0.7558665; iLine=35; linex[iLine]= 0.7953730; iLine=36; linex[iLine]= 0.8369448; iLine=37; linex[iLine]= 0.8806889; iLine=38; linex[iLine]= 0.9267194; iLine=39; linex[iLine]= 0.9751557; iLine=40; linex[iLine]= 1.0261236; iLine=41; linex[iLine]= 1.0797561; iLine=42; linex[iLine]= 1.1361911; iLine=43; linex[iLine]= 1.1955758; iLine=44; linex[iLine]= 1.2580642; iLine=45; linex[iLine]= 1.3238188; iLine=46; linex[iLine]= 1.3930101; iLine=47; linex[iLine]= 1.4658186; iLine=48; linex[iLine]= 1.5424317; iLine=49; linex[iLine]= 1.6230491; iLine=50; linex[iLine]= 1.7078801; iLine=51; linex[iLine]= 1.7971450; iLine=52; linex[iLine]= 1.8910764; iLine=53; linex[iLine]= 1.9899162; iLine=54; linex[iLine]= 2.0939221; iLine=55; linex[iLine]= 2.2033639; iLine=56; linex[iLine]= 2.3185259; iLine=57; linex[iLine]= 2.4397070; iLine=58; linex[iLine]= 2.5672232; iLine=59; linex[iLine]= 2.7014029; iLine=60; linex[iLine]= 2.8425956; iLine=61; linex[iLine]= 2.9911680; iLine=62; linex[iLine]= 3.1475057; iLine=63; linex[iLine]= 3.3120164; iLine=64; linex[iLine]= 3.4851237; iLine=65; linex[iLine]= 3.6672788; iLine=66; linex[iLine]= 3.8589544; iLine=67; linex[iLine]= 4.0606482; iLine=68; linex[iLine]= 4.2728839; iLine=69; linex[iLine]= 4.4962148; iLine=70; linex[iLine]= 4.7312159; iLine=71; linex[iLine]= 4.9784997; iLine=72; linex[iLine]= 5.2387082; iLine=73; linex[iLine]= 5.5125169; iLine=74; linex[iLine]= 5.8006397; iLine=75; linex[iLine]= 6.1038185; iLine=76; linex[iLine]= 6.4228434; iLine=77; linex[iLine]= 6.7585426; iLine=78; linex[iLine]= 7.1117876; iLine=79; linex[iLine]= 7.4834995; iLine=80; linex[iLine]= 7.8746354; iLine=81; linex[iLine]= 8.2862146; iLine=82; linex[iLine]= 8.5000022; } if (linlog=="lin") { //Int_t iLine; //iLine= 0; linex[iLine]=0.1371614; //iLine= 1; linex[iLine]=0.2920288; //iLine= 2; linex[iLine]=0.6017636; //iLine= 3; linex[iLine]=0.9114983; //iLine= 4; linex[iLine]=1.2212331; //iLine= 5; linex[iLine]=1.5309679; //iLine= 6; linex[iLine]=1.8407026; //iLine= 7; linex[iLine]=2.1504375; //iLine= 8; linex[iLine]=2.4601721; //iLine= 9; linex[iLine]=2.7699069; //iLine=10; linex[iLine]=3.0796416; //iLine=11; linex[iLine]=3.3893764; //iLine=12; linex[iLine]=3.6991110; //iLine=13; linex[iLine]=4.0088459; //iLine=14; linex[iLine]=4.3185805; //iLine=15; linex[iLine]=4.6283154; //iLine=16; linex[iLine]=4.9380502; //iLine=17; linex[iLine]=5.2477851; //iLine=18; linex[iLine]=5.5575195; //iLine=19; linex[iLine]=5.8672543; //iLine=20; linex[iLine]=6.1769892; //iLine=21; linex[iLine]=6.4867241; //iLine=22; linex[iLine]=6.7964589; //iLine=23; linex[iLine]=7.1061933; //iLine=24; linex[iLine]=7.4159282; //iLine=25; linex[iLine]=7.7256630; //iLine=26; linex[iLine]=8.0353979; //iLine=27; linex[iLine]=8.3451328; //iLine=28; linex[iLine]= 8.5; } TString *tree_var=0; TString *nuance_var=0; TCut *nuance_cut=0; TString *label=0; Int_t N_bins=0; Double_t lower=0.0; Double_t upper=0.0; Double_t x_leg=0.0; switch (mode) { case 1: tree_var=new TString("kprime[0]"); nuance_var=new TString("p_lepton[0][3]/1.0e3"); nuance_cut=new TCut("cc && bound && channel==1"); label=new TString(";E_{#mu} (GeV);(<events>/POT/target) / GeV"); x_leg=0.15; N_bins=250; lower=0.12; upper=2.0; break; case 2: tree_var=new TString("-q[0]**2+q[1]**2+q[2]**2+q[3]**2"); nuance_var=new TString("-qsq/1.0e6"); nuance_cut=new TCut("cc && bound && channel==1"); label=new TString(";Q^{2} (GeV^{2});(<events>/POT/target) / GeV^{2}"); x_leg=0.55; N_bins=250; lower=0.0; upper=2.0; break; case 3: tree_var=new TString("mag_p"); nuance_var=new TString("p_targ[4]/1.0e3"); nuance_cut=new TCut("cc && bound && channel==1"); label=new TString(";p_{i} (GeV/c);(<events>/POT/target) / (GeV/c)"); x_leg=0.15; N_bins=150; lower=0.0; upper=0.25; break; case 4: tree_var=new TString("sqrt(pprime[1]**2+pprime[2]**2+pprime[3]**2)"); nuance_var=new TString("p_hadron[][4]/1.0e3"); nuance_cut=new TCut("cc && bound && channel==1 && n_hadrons==1 && n_leptons==1"); label=new TString(";p_{f} (GeV/c);(<events>/POT/target) / (GeV/c)"); x_leg=0.15; N_bins=150; lower=0.0; upper=0.8; break; case 5: tree_var=new TString("sqrt(pprime[1]**2+pprime[2]**2+pprime[3]**2)"); nuance_var=new TString("sqrt((p_neutrino[0]-p_lepton[0][0]+p_targ[0])**2+(p_neutrino[1]-p_lepton[0][1]+p_targ[1])**2+(p_neutrino[2]-p_lepton[0][2]+p_targ[2])**2)/1.0e3"); nuance_cut=new TCut("cc && bound && channel==1 && n_leptons==1"); label=new TString(";p_{f} (GeV/c);(<events>/POT/target) / (GeV/c)"); x_leg=0.15; N_bins=150; lower=0.2; upper=1.3; break; case 6: tree_var=new TString("k[0]"); nuance_var=new TString("p_neutrino[3]/1.0e3"); nuance_cut=new TCut("cc && bound && channel==1 && n_leptons==1"); label=new TString(";E_{#nu} (GeV);(<events>/POT/target) / GeV"); x_leg=0.15; N_bins=150; lower=0.0; upper=2.0; break; case 7: tree_var=new TString("k[0]"); nuance_var=new TString("p_neutrino[3]/1.0e3"); nuance_cut=new TCut("cc && bound && channel==1 && n_leptons==1"); label=new TString(";E_{#nu} (GeV);(<events>/POT/target) / GeV"); x_leg=0.15; N_bins=150; lower=0.0; upper=5.0; break; } TCanvas canvas("canvas","",700,1000); canvas.Divide(1,2); canvas.cd(1); TH1D nh("nh",*label,N_bins,lower,upper); nh.Sumw2(); nh.SetStats(kFALSE); Int_t NFiles=40; for (Int_t iFile=0;iFile<NFiles;iFile++) { TString file; if (!antinu) file="../../nuance_from_fnal/oxygen_dipole_mbflux_e"+linlog+Form("_81/nuance%d.root",iFile+1); if ( antinu) file=Form("../../nuance_from_fnal/oxygen_dipole_mbflux_antinu_elog_81/nuance%d.root",iFile+1); TFile f(file); gROOT->cd(); TTree *ntree=(TTree*)f.Get("h3"); ntree->Draw(*nuance_var+">>+nh",*nuance_cut,"goff"); f.Close(); } if (linlog=="log") { if (!antinu) nh.Scale(2.29697e-07*8*1.0e-36/nh.Integral("width")); if ( antinu) nh.Scale(7.47831e-08*8*1.0e-36/nh.Integral("width")); } else nh.Scale(1.0/nh.Integral("width")); nh.Scale(mb_factor); nh.Draw("e"); nh.Print(); TH1D *contribs=new TH1D("contribs",*label,N_bins,lower,upper); Int_t NHistos=1; Int_t base_index=0; TH1D *h[NHistos]; for (Int_t iHisto=0;iHisto<NHistos;iHisto++) { h[iHisto]=new TH1D(Form("h%d",iHisto),*label,N_bins,lower,upper); h[iHisto]->Sumw2(); } Int_t color=2; Double_t factor=1.0; for (Int_t iHisto=0;iHisto<NHistos;iHisto++) { tree->Draw(*tree_var+Form(">>h%d",iHisto),Form("(MA_weights[%d]) * (process==%d)",iHisto,process),"goff"); if (iHisto==0) factor=rate/h[0]->Integral("width"); h[iHisto]->Scale(factor*mb_factor); h[iHisto]->SetStats(kFALSE); h[iHisto]->GetXaxis()->CenterTitle(); h[iHisto]->GetYaxis()->CenterTitle(); h[iHisto]->GetYaxis()->SetTitleOffset(1.2); h[iHisto]->SetLineColor(color); h[iHisto]->SetMarkerColor(color); if (++color==5) color++; h[iHisto]->Draw("esame"); h[iHisto]->Print(); } if (mode==6 || mode==7) { Double_t y1=nh.GetYaxis()->GetXmin(); Double_t y2=nh.GetYaxis()->GetXmax(); Double_t xmin=nh.GetXaxis()->GetXmin(); Double_t xmax=nh.GetXaxis()->GetXmax(); for (Int_t iLine=0;iLine<NLines;iLine++) { TLine line; line.SetLineColor(kGreen); Double_t x=linex[iLine]; if (x<xmin || x>xmax) continue; line.DrawLine(x,y1,x,y2); } } TString legendtitle; if (!antinu) legendtitle="#nu_{#mu} + ^{16}O #rightarrow #mu + p + X (E_{#nu} from MB flux)"; if ( antinu) legendtitle="#bar{#nu}_{#mu} + ^{16}O #rightarrow #mu + n + X (E_{#nu} from MB flux)"; TLegend legend(x_leg,0.7,x_leg+0.45,0.9,legendtitle); legend.SetBorderSize(0); legend.SetFillStyle(0); //legend.SetHeader("S-M, dipole, FP=0"); legend.AddEntry(h[base_index],"my generated events (NUANCE mode)"); legend.AddEntry(&nh,"NUANCE"); legend.Draw("same"); chi2_compare(h[base_index],&nh,1,N_bins,contribs); //TLatex text(0.20,0.92,comp_str); //text.SetNDC(); //text.DrawClone(); canvas.cd(2); contribs->Draw(); canvas.cd(0); canvas.DrawClone(); f.Close(); delete tree_var; delete nuance_var; delete nuance_cut; delete label; delete contribs; for (Int_t iHisto=0;iHisto<NHistos;iHisto++) { delete h[iHisto]; } }
void MA_compare1(Int_t mode,Int_t energy_point) { Init(); TFile g(Form("../../events_6_nofp_%3d.root",energy_point)); gROOT->cd(); TTree *gtree=(TTree*)g.Get("tree"); gtree->SetName("gtree"); TGraph *ggr=(TGraph*)g.Get("ccqe_rate")->Clone(); Int_t gprocess=1; Double_t gxs,gdummy; ggr->GetPoint(gprocess,gdummy,gxs); delete ggr; //mine TFile f(Form("../../events_5_nofp_%3d.root",energy_point)); gROOT->cd(); TTree *tree=(TTree*)f.Get("tree"); TGraph *gr=(TGraph*)f.Get("ccqe_rate")->Clone(); Int_t process=4; Double_t xs,dummy; gr->GetPoint(process,dummy,xs); delete gr; //NUANCE /*argh--chains are unusable in this ROOT version*/ Int_t N_files=0; if (energy_point==300) N_files=40; if (energy_point==800) N_files=20; TFile *nu_files[N_files]; TTree *nu_trees[N_files]; for (Int_t iFile=0;iFile<N_files;iFile++) { TString file; if (energy_point==300) file=Form("../../nuance_from_fnal/oxnofp3/nuance%d.root",iFile+1); if (energy_point==800) file=Form("../../nuance_from_fnal/oxyg_no_fp2/nuance%d.root",iFile+1); nu_files[iFile]=new TFile(file); //nu_files[iFile]=new TFile(Form("$CONDOR_TMP/nuance/oxyg_no_fp2_300/nuance%d.root",iFile+1)); //nu_files[iFile]=new TFile(Form("$CONDOR_TMP/nuance/oxyg_no_fp2/nuance%d.root",iFile+1)); //nu_files[iFile]=new TFile(Form("$CONDOR_TMP/nuance/oxyg_no_fp_nor_eb/nuance%d.root",iFile+1)); gROOT->cd(); nu_trees[iFile]=(TTree*)(nu_files[iFile]->Get("h3")); } TString *tree_var=0; TString *nuance_var=0; TCut *nuance_cut=0; TString *label=0; Int_t N_bins=0; Double_t lower=0.0; Double_t upper=0.0; Double_t x_leg=0.0; switch (mode) { case 1: tree_var=new TString("kprime[0]"); nuance_var=new TString("p_lepton[0][3]/1.0e3"); nuance_cut=new TCut("cc && bound && channel==1"); label=new TString(";E_{#mu} (GeV);d#sigma/dE_{#mu} (cm^{2}/GeV)"); x_leg=0.15; N_bins=70; lower=0.12; upper=energy_point/1.0e3; break; case 2: tree_var=new TString("-q[0]**2+q[1]**2+q[2]**2+q[3]**2"); nuance_var=new TString("-qsq/1.0e6"); nuance_cut=new TCut("cc && bound && channel==1"); label=new TString(";Q^{2} (GeV^{2});d#sigma/dQ^{2} (cm^{2}/GeV^{2})"); x_leg=0.55; N_bins=70; lower=0.0; if (energy_point==300) upper=0.8; if (energy_point==800) upper=1.4; break; case 3: tree_var=new TString("mag_p"); nuance_var=new TString("p_targ[4]/1.0e3"); nuance_cut=new TCut("cc && bound && channel==1"); label=new TString(";p_{i} (GeV/c);d#sigma/dp_{i} (cm^{2}/(GeV/c))"); x_leg=0.15; N_bins=150; lower=0.0; upper=0.25; break; case 4: tree_var=new TString("sqrt(pprime[1]**2+pprime[2]**2+pprime[3]**2)"); nuance_var=new TString("p_hadron[][4]/1.0e3"); nuance_cut=new TCut("cc && bound && channel==1 && n_hadrons==1 && n_leptons==1"); label=new TString(";p_{f} (GeV/c);d#sigma/dp_{f} (cm^{2}/(GeV/c))"); x_leg=0.15; N_bins=150; lower=0.0; upper=0.8; break; case 5: tree_var=new TString("sqrt(pprime[1]**2+pprime[2]**2+pprime[3]**2)"); nuance_var=new TString("sqrt((p_neutrino[0]-p_lepton[0][0]+p_targ[0])**2+(p_neutrino[1]-p_lepton[0][1]+p_targ[1])**2+(p_neutrino[2]-p_lepton[0][2]+p_targ[2])**2)/1.0e3"); nuance_cut=new TCut("cc && bound && channel==1 && n_leptons==1"); label=new TString(";p_{f} (GeV/c);d#sigma/dp_{f} (cm^{2}/(GeV/c))"); x_leg=0.15; N_bins=150; lower=0.2; upper=0.6; //lower=0.2; //upper=1.3; break; } TCanvas canvas("canvas","",700,1000); canvas.Divide(1,2); canvas.cd(1); TH1D g0("g0",*label,N_bins,lower,upper); g0.Sumw2(); gtree->Draw(*tree_var+">>g0","","goff"); g0.Scale(gxs/g0.Integral("width")); g0.SetStats(kFALSE); g0.Draw("e"); TH1D nh("nh",*label,N_bins,lower,upper); nh.Sumw2(); nh.SetStats(kFALSE); for (Int_t iFile=0;iFile<N_files;iFile++) { nu_trees[iFile]->Draw(*nuance_var+">>+nh",*nuance_cut,"goff"); } if (energy_point==300) nh.Scale(0.0033647*8*1.0e-36/nh.Integral("width")); if (energy_point==800) nh.Scale(0.0093045*8*1.0e-36/nh.Integral("width")); nh.SetLineColor(kRed); nh.SetMarkerColor(kRed); nh.Draw("esame"); Int_t NHistos=5; TH1D *h[NHistos]; TH1D *r[NHistos]; for (Int_t iHisto=0;iHisto<NHistos;iHisto++) { h[iHisto]=new TH1D(Form("h%d",iHisto),*label,N_bins,lower,upper); h[iHisto]->Sumw2(); } Int_t color=3; for (Int_t iHisto=0;iHisto<NHistos;iHisto++) { tree->Draw(*tree_var+Form(">>h%d",iHisto),Form("(MA_weights[%d]) * (process==%d)",iHisto,process),"goff"); h[iHisto]->SetStats(kFALSE); h[iHisto]->GetXaxis()->CenterTitle(); h[iHisto]->GetYaxis()->CenterTitle(); h[iHisto]->GetYaxis()->SetTitleOffset(1.2); h[iHisto]->SetLineColor(color); h[iHisto]->SetMarkerColor(color); color++; h[iHisto]->Print(); } TLegend legend(x_leg,0.6,x_leg+0.35,0.9); legend.SetBorderSize(0); legend.SetFillStyle(0); legend.SetHeader("S-M, dipole, FP=0"); legend.AddEntry(&g0,"my events (A-S mode,MA=1.03)"); legend.AddEntry(&nh,"NUANCE (MA=1.03)"); Double_t MA_values[NHistos]; for (Int_t iMA=0;iMA<NHistos;iMA++) { Double_t base=1.03; MA_values[iMA]=base+(iMA-2)*0.03; } Double_t factor=xs/h[1]->Integral("width"); for (Int_t iHisto=0;iHisto<NHistos;iHisto++) { h[iHisto]->Scale(factor); h[iHisto]->Draw("esame"); r[iHisto]=(TH1D*)h[iHisto]->Clone(Form("r%d",iHisto)); legend.AddEntry(h[iHisto],Form("my events (NUANCE mode,MA=%#4.3g)",MA_values[iHisto])); } legend.Draw("same"); canvas.cd(2); TH2D null("null",";;ratio to black",1,0.0,1.4,1,0.8,1.2); null.SetStats(kFALSE); null.Draw(); for (Int_t iHisto=0;iHisto<NHistos;iHisto++) { //r[iHisto]->Scale(1.0/r[iHisto]->Integral()); r[iHisto]->Divide(&g0); r[iHisto]->Draw("same"); } canvas.cd(0); canvas.DrawClone(); f.Close(); delete tree_var; delete nuance_var; delete nuance_cut; delete label; for (Int_t iHisto=0;iHisto<NHistos;iHisto++) { delete h[iHisto]; delete r[iHisto]; } for (Int_t iFile=0;iFile<N_files;iFile++) { delete nu_files[iFile]; } }
void polish_compare(Int_t proc,Int_t mode,TString file) { Init(); //mine TFile f(file); gROOT->cd(); TTree *tree=(TTree*)f.Get("tree"); TGraph *gr=(TGraph*)f.Get("ccqe_rate")->Clone(); Int_t gr_size=gr->GetN(); Double_t *graph_proc = new Double_t[gr_size]; Double_t *graph_xs = new Double_t[gr_size]; for (Int_t iProc=0;iProc<gr_size;iProc++) { gr->GetPoint(iProc,graph_proc[iProc],graph_xs[iProc]); } delete gr; //polish TFile f_polish("../ref/polish/O16/graph.root"); gROOT->cd(); TGraph *gr_pol=0; TString *var=0; TString *title=0; TString *model=0; TString legend_string=""; switch(proc) { case 1: model=new TString("sm"); legend_string="Ankowski-Sobczyk Fermi Gas Model"; break; case 2: model=new TString("as_mf"); legend_string="Ankowski-Sobczyk SF (mean field part)"; break; case 3: model=new TString("as_corr"); legend_string="Ankowski-Sobczyk SF (correlated part)"; break; case 23: model=new TString("as"); legend_string="Ankowski-Sobczyk Spectral Function Model"; break; } Int_t N_bins=0; Double_t lower=0.0; Double_t upper=0.0; Double_t x_leg=0.1; if (mode==50) { gr_pol=(TGraph*)f_polish.Get("polish_Q2_"+*model)->Clone(); N_bins=100; lower=0.0; upper=1.4; var=new TString("q[1]**2+q[2]**2+q[3]**2-q[0]**2"); title=new TString(";Q^{2} (GeV^{2});d#sigma/dQ^{2} (cm^{2}/GeV^{2})"); } if (mode==60) { gr_pol=(TGraph*)f_polish.Get("polish_e_"+*model)->Clone(); N_bins=100; lower=0.1; upper=0.8; x_leg=0.1; var=new TString("kprime[0]"); title=new TString(";E_{#mu} (GeV);d#sigma/dE_{#mu} (cm^{2}/GeV)"); } if (mode==70) { gr_pol=(TGraph*)f_polish.Get("polish_nopb_e_"+*model)->Clone(); N_bins=100; lower=0.1; upper=0.8; var=new TString("kprime[0]"); title=new TString(";E_{#mu} (GeV);d#sigma/dE_{#mu} (cm^{2}/GeV)"); } f_polish.Close(); TH1D h1("h1",*title,N_bins,lower,upper); h1.Sumw2(); TH1D h2("h2",*title,N_bins,lower,upper); h2.Sumw2(); TH1D *contribs=(TH1D*)h1.Clone("contribs"); TString cut=Form("process==%d",proc); Double_t xs=graph_xs[proc]; if (proc==23) { cut="process==2 || process==3"; xs=graph_xs[2]+graph_xs[3]; } tree->Draw(*var+">>h1",cut,"goff"); h1.Scale(xs/h1.Integral("width")); printf("proc=%d; norm=%8.6g\n",proc,xs); TCanvas canvas("canvas","",700,1000); canvas.Divide(1,2); canvas.cd(1); h1.SetStats(kFALSE); h1.GetXaxis()->CenterTitle(); h1.GetYaxis()->CenterTitle(); h1.GetYaxis()->SetTitleOffset(1.2); h1.SetLineColor(kRed); h1.SetMarkerColor(kRed); h1.Draw("e"); //Double_t previous_x=0.0; //for (Int_t iPoint=0;iPoint<gr_pol->GetN();iPoint++) { // Double_t this_x,this_y; // gr_pol->GetPoint(iPoint,this_x,this_y); // cout << iPoint << "," << this_x-previous_x << endl; // previous_x=this_x; //} gr_pol->Draw("psame"); histo_graph(&h2,gr_pol,4000000); h2.Draw("same"); TLegend legend(x_leg,0.60,x_leg+0.65,0.9,"#nu_{#mu} + ^{16}O #rightarrow #mu + p + X (E_{#nu}=0.8 GeV)"); legend.SetBorderSize(0); legend.SetFillStyle(0); legend.AddEntry(&h1,"my generated events ("+legend_string+")","l"); legend.AddEntry(&h2,"Ankowski-Sobczyk paper ("+legend_string+")","l"); legend.Draw("same"); chi2_compare(&h1,&h2,1,N_bins,contribs); canvas.cd(2); contribs->GetXaxis()->CenterTitle(); contribs->GetYaxis()->CenterTitle(); contribs->Draw(); canvas.cd(0); canvas.DrawClone(); if (gr_pol) delete gr_pol; if (model) delete model; if (title) delete title; if (var) delete var; if (contribs) delete contribs; delete graph_proc; delete graph_xs; }
void NUANCE_compare(Int_t mode,Int_t energy_point,TString file,bool antinu=false) { Init(); //mine TFile f(file); gROOT->cd(); TTree *tree=(TTree*)f.Get("tree"); TGraph *gr=(TGraph*)f.Get("ccqe_rate")->Clone(); Int_t process=4; Double_t xs,dummy; gr->GetPoint(process,dummy,xs); delete gr; //NUANCE /*argh--chains are unusable in this ROOT version*/ Int_t N_files=0; if (energy_point== 300) N_files=40; if (energy_point== 800) N_files=20; if (energy_point==1200) N_files=40; TString *tree_var=0; TString *nuance_var=0; TCut *nuance_cut=0; TString *label=0; Int_t N_bins=0; Double_t lower=0.0; Double_t upper=0.0; Double_t x_leg=0.0; switch (mode) { case 1: tree_var=new TString("kprime[0]"); nuance_var=new TString("p_lepton[0][3]/1.0e3"); nuance_cut=new TCut("cc && bound && channel==1"); label=new TString(";E_{#mu} (GeV);d#sigma/dE_{#mu} (cm^{2}/GeV)"); x_leg=0.15; N_bins=250; lower=0.12; upper=energy_point/1.0e3; break; case 2: tree_var=new TString("-q[0]**2+q[1]**2+q[2]**2+q[3]**2"); nuance_var=new TString("-qsq/1.0e6"); nuance_cut=new TCut("cc && bound && channel==1"); label=new TString(";Q^{2} (GeV^{2});d#sigma/dQ^{2} (cm^{2}/GeV^{2})"); x_leg=0.55; N_bins=250; lower=0.0; if (energy_point==300) upper=0.8; if (energy_point==800) upper=1.4; break; case 3: tree_var=new TString("mag_p"); nuance_var=new TString("p_targ[4]/1.0e3"); nuance_cut=new TCut("cc && bound && channel==1"); label=new TString(";p_{i} (GeV/c);d#sigma/dp_{i} (cm^{2}/(GeV/c))"); x_leg=0.15; N_bins=150; lower=0.0; upper=0.25; break; case 4: tree_var=new TString("sqrt(pprime[1]**2+pprime[2]**2+pprime[3]**2)"); nuance_var=new TString("p_hadron[][4]/1.0e3"); nuance_cut=new TCut("cc && bound && channel==1 && n_hadrons==1 && n_leptons==1"); label=new TString(";p_{f} (GeV/c);d#sigma/dp_{f} (cm^{2}/(GeV/c))"); x_leg=0.15; N_bins=150; lower=0.0; upper=0.8; break; case 5: tree_var=new TString("sqrt(pprime[1]**2+pprime[2]**2+pprime[3]**2)"); nuance_var=new TString("sqrt((p_neutrino[0]-p_lepton[0][0]+p_targ[0])**2+(p_neutrino[1]-p_lepton[0][1]+p_targ[1])**2+(p_neutrino[2]-p_lepton[0][2]+p_targ[2])**2)/1.0e3"); nuance_cut=new TCut("cc && bound && channel==1 && n_leptons==1"); label=new TString(";p_{f} (GeV/c);d#sigma/dp_{f} (cm^{2}/(GeV/c))"); x_leg=0.15; N_bins=150; lower=0.2; upper=0.6; //lower=0.2; //upper=1.3; break; } TCanvas canvas("canvas","",700,1000); canvas.Divide(1,2); canvas.cd(1); TH1D nh("nh",*label,N_bins,lower,upper); nh.Sumw2(); nh.SetStats(kFALSE); for (Int_t iFile=0;iFile<N_files;iFile++) { TString file; if (energy_point== 300 ) file=Form("../../nuance_from_fnal/oxnofp3/nuance%d.root",iFile+1); if (energy_point== 800 && !antinu) file=Form("../../nuance_from_fnal/oxyg_no_fp2/nuance%d.root",iFile+1); if (energy_point== 800 && antinu) file=Form("../../nuance_from_fnal/antinumu_oxygen_dipole_800/nuance%d.root",iFile+1); if (energy_point==1200 ) file=Form("../../nuance_from_fnal/numu_oxygen_dipole_1200/nuance%d.root",iFile+1); TFile nfile(file); gROOT->cd(); TTree *ntree=(TTree*)nfile.Get("h3"); ntree->Draw(*nuance_var+">>+nh",*nuance_cut,"goff"); nfile.Close(); } if (energy_point== 300 ) nh.Scale(0.0033647*8*1.0e-36/nh.Integral("width")); if (energy_point== 800 && !antinu) nh.Scale(0.0093045*8*1.0e-36/nh.Integral("width")); if (energy_point== 800 && antinu) nh.Scale(0.0027100*8*1.0e-36/nh.Integral("width")); if (energy_point==1200 ) nh.Scale(0.0100135*8*1.0e-36/nh.Integral("width")); nh.Draw("e"); TH1D *contribs=new TH1D("contribs",*label,N_bins,lower,upper); Int_t NHistos=1; Int_t base_index=0; TH1D *h[NHistos]; for (Int_t iHisto=0;iHisto<NHistos;iHisto++) { h[iHisto]=new TH1D(Form("h%d",iHisto),*label,N_bins,lower,upper); h[iHisto]->Sumw2(); } Int_t color=2; Double_t factor=1.0; for (Int_t iHisto=0;iHisto<NHistos;iHisto++) { tree->Draw(*tree_var+Form(">>h%d",iHisto),Form("(MA_weights[%d]) * (process==%d)",iHisto,process),"goff"); if (iHisto==0) factor=xs/h[0]->Integral("width"); h[iHisto]->Scale(factor); h[iHisto]->SetStats(kFALSE); h[iHisto]->GetXaxis()->CenterTitle(); h[iHisto]->GetYaxis()->CenterTitle(); h[iHisto]->GetYaxis()->SetTitleOffset(1.2); h[iHisto]->SetLineColor(color); h[iHisto]->SetMarkerColor(color); if (++color==5) color++; h[iHisto]->Draw("esame"); h[iHisto]->Print(); } TString legendtitle; if (!antinu) legendtitle=Form("#nu_{#mu} + ^{16}O #rightarrow #mu + p + X (E_{#nu}=%d MeV)",energy_point); if ( antinu) legendtitle=Form("#bar{#nu}_{#mu} + ^{16}O #rightarrow #mu + n + X (E_{#nu}=%d MeV)",energy_point); TLegend legend(x_leg,0.7,x_leg+0.45,0.9,legendtitle); legend.SetBorderSize(0); legend.SetFillStyle(0); //legend.SetHeader("S-M, dipole, FP=0"); legend.AddEntry(h[base_index],"my generated events (NUANCE mode)"); legend.AddEntry(&nh,"NUANCE"); legend.Draw("same"); chi2_compare(h[base_index],&nh,1,N_bins,contribs); //TLatex text(0.20,0.92,comp_str); //text.SetNDC(); //text.DrawClone(); canvas.cd(2); contribs->Draw(); canvas.cd(0); canvas.DrawClone(); f.Close(); delete tree_var; delete nuance_var; delete nuance_cut; delete label; delete contribs; for (Int_t iHisto=0;iHisto<NHistos;iHisto++) { delete h[iHisto]; } }
void compare6() { Init(); TFile f1("../../events_3.root"); TTree *tree1=(TTree*)f1.Get("tree"); TGraph *gr1=(TGraph*)f1.Get("ccqe_rate")->Clone(); Int_t process1=4; Double_t xs1,dummy; gr1->GetPoint(process1,dummy,xs1); delete gr1; TFile f2("../../events_4.root"); TTree *tree2=(TTree*)f2.Get("tree"); TGraph *gr2=(TGraph*)f2.Get("ccqe_rate")->Clone(); Int_t process2=1; Double_t xs2; gr2->GetPoint(process2,dummy,xs2); delete gr2; Double_t x_leg=0.15; Int_t N_bins=100; Double_t lower=0.0; Double_t upper=1.2; TH1D h1("h1","",N_bins,lower,upper); TH1D h2("h2","",N_bins,lower,upper); h1.Sumw2(); h2.Sumw2(); TH1D *contribs=(TH1D*)h1.Clone("contribs"); tree1->Draw("-q[0]**2+q[1]**2+q[2]**2+q[3]**2>>h1",Form("process==%d",process1),"goff"); tree2->Draw("-q[0]**2+q[1]**2+q[2]**2+q[3]**2>>h2",Form("process==%d",process2),"goff"); h1.Scale(xs1/h1.Integral("width")); h2.Scale(xs2/h2.Integral("width")); TCanvas canvas("canvas","",700,1000); canvas.Divide(1,2); canvas.cd(1); h1.SetStats(kFALSE); h1.GetXaxis()->CenterTitle(); h1.GetYaxis()->CenterTitle(); h1.GetYaxis()->SetTitleOffset(1.2); h1.SetLineColor(kRed); h1.SetMarkerColor(kRed); h1.Draw("e"); h2.SetLineColor(kBlue); h2.SetMarkerColor(kBlue); h2.Draw("esame"); TLegend legend(x_leg,0.8,x_leg+0.35,0.9); legend.SetBorderSize(0); legend.SetFillStyle(0); legend.SetHeader("S-M, dipole, FP=0"); legend.AddEntry(&h1,"my events (no OS,Ep-Eb)"); legend.AddEntry(&h2,"NUANCE"); legend.Draw("same"); chi2_compare(&h1,&h2,1,N_bins,contribs); //TLatex text(0.20,0.92,comp_str); //text.SetNDC(); //text.DrawClone(); canvas.cd(2); contribs->Draw(); canvas.cd(0); canvas.DrawClone(); delete contribs; }
void MA_compare_800() { Init(); //polish TFile f_polish("../ref/polish/O16/graph.root"); gROOT->cd(); TGraph *gr_pol_benhar=(TGraph*)f_polish.Get("benhar_q2")->Clone(); TGraph *gr_pol_fg=(TGraph*)f_polish.Get("FG_q2")->Clone(); f_polish.Close(); //mine Int_t mode=2; //TFile f("../../events_5_nofp_800.root"); TFile f("../../events.root"); gROOT->cd(); TTree *tree=(TTree*)f.Get("tree"); TGraph *gr=(TGraph*)f.Get("ccqe_rate")->Clone(); Int_t process=4; Double_t xs,dummy; gr->GetPoint(process,dummy,xs); delete gr; TString *tree_var=0; TString *label=0; Int_t N_bins=0; Double_t lower=0.0; Double_t upper=0.0; Double_t x_leg=0.0; switch (mode) { case 1: tree_var=new TString("kprime[0]"); label=new TString(";E_{#mu} (GeV);d#sigma/dE_{#mu} (cm^{2}/GeV)"); x_leg=0.15; N_bins=70; lower=0.12; upper=0.8; break; case 2: tree_var=new TString("-q[0]**2+q[1]**2+q[2]**2+q[3]**2"); label=new TString(";Q^{2} (GeV^{2});d#sigma/dQ^{2} (cm^{2}/GeV^{2})"); x_leg=0.55; N_bins=70; lower=0.0; upper=1.4; break; case 3: tree_var=new TString("mag_p"); label=new TString(";p_{i} (GeV/c);d#sigma/dp_{i} (cm^{2}/(GeV/c))"); x_leg=0.15; N_bins=150; lower=0.0; upper=0.25; break; case 4: tree_var=new TString("sqrt(pprime[1]**2+pprime[2]**2+pprime[3]**2)"); label=new TString(";p_{f} (GeV/c);d#sigma/dp_{f} (cm^{2}/(GeV/c))"); x_leg=0.15; N_bins=150; lower=0.0; upper=0.8; break; case 5: tree_var=new TString("sqrt(pprime[1]**2+pprime[2]**2+pprime[3]**2)"); label=new TString(";p_{f} (GeV/c);d#sigma/dp_{f} (cm^{2}/(GeV/c))"); x_leg=0.15; N_bins=150; lower=0.2; upper=0.6; //lower=0.2; //upper=1.3; break; } TCanvas canvas("canvas","",700,1000); canvas.Divide(1,2); canvas.cd(1); TH1D g_benhar("g_benhar",*label,N_bins,lower,upper); TH1D g_fg ("g_fg", *label,N_bins,lower,upper); g_benhar.Sumw2(); g_fg.Sumw2(); histo_graph(&g_benhar,gr_pol_benhar,4000000); histo_graph(&g_fg,gr_pol_fg,4000000); if (gr_pol_benhar) delete gr_pol_benhar; if (gr_pol_fg) delete gr_pol_fg; g_fg.SetStats(kFALSE); g_benhar.SetStats(kFALSE); g_fg.SetLineColor(kRed); g_fg.SetMarkerColor(kRed); g_fg.Draw("e"); g_benhar.Draw("esame"); Int_t NHistos=5; TH1D *h[NHistos]; TH1D *r[NHistos]; for (Int_t iHisto=0;iHisto<NHistos;iHisto++) { h[iHisto]=new TH1D(Form("h%d",iHisto),*label,N_bins,lower,upper); h[iHisto]->Sumw2(); } Int_t color=3; for (Int_t iHisto=0;iHisto<NHistos;iHisto++) { tree->Draw(*tree_var+Form(">>h%d",iHisto),Form("(MA_weights[%d]) * (process==%d)",iHisto,process),"goff"); h[iHisto]->SetStats(kFALSE); h[iHisto]->GetXaxis()->CenterTitle(); h[iHisto]->GetYaxis()->CenterTitle(); h[iHisto]->GetYaxis()->SetTitleOffset(1.2); h[iHisto]->SetLineColor(color); h[iHisto]->SetMarkerColor(color); color++; h[iHisto]->Print(); } TLegend legend(x_leg,0.6,x_leg+0.35,0.9); legend.SetBorderSize(0); legend.SetFillStyle(0); legend.SetHeader("dipole form factors, O^{16}, 800 MeV #nu_{#mu}"); legend.AddEntry(&g_benhar,"A-S (Benhar, MA=1.03)"); legend.AddEntry(&g_fg ,"A-S (FG, MA=1.03)"); Double_t MA_values[NHistos]; for (Int_t iMA=0;iMA<NHistos;iMA++) { Double_t base=1.03; MA_values[iMA]=base+(iMA-2)*0.03; } Double_t factor=xs/h[0]->Integral("width"); for (Int_t iHisto=0;iHisto<NHistos;iHisto++) { h[iHisto]->Scale(factor); h[iHisto]->Draw("esame"); r[iHisto]=(TH1D*)h[iHisto]->Clone(Form("r%d",iHisto)); legend.AddEntry(h[iHisto],Form("my events (NUANCE mode,MA=%#4.3g)",MA_values[iHisto])); } TH1D *r_fg=(TH1D*)g_fg.Clone("r_fg"); legend.Draw("same"); canvas.cd(2); TH2D null("null",";;ratio to A-S Benhar",1,lower,upper,1,0.8,2.0); null.SetStats(kFALSE); null.Draw(); r_fg->Divide(&g_benhar); r_fg->Draw("same"); for (Int_t iHisto=0;iHisto<NHistos;iHisto++) { //r[iHisto]->Scale(1.0/r[iHisto]->Integral()); r[iHisto]->Divide(&g_benhar); r[iHisto]->Draw("same"); } canvas.cd(0); canvas.DrawClone(); f.Close(); delete tree_var; delete label; for (Int_t iHisto=0;iHisto<NHistos;iHisto++) { delete h[iHisto]; delete r[iHisto]; } }
PfPvPlot::PfPvPlot(MainWindow *mainWindow) : rideItem (NULL), mainWindow(mainWindow), cp_ (0), cad_ (85), cl_ (0.175), shade_zones(true) { setInstanceName("PfPv Plot"); setCanvasBackground(Qt::white); canvas()->setFrameStyle(QFrame::NoFrame); setAxisTitle(yLeft, tr("Average Effective Pedal Force (N)")); setAxisScale(yLeft, 0, 600); setAxisTitle(xBottom, tr("Circumferential Pedal Velocity (m/s)")); setAxisScale(xBottom, 0, 3); setAxisMaxMinor(yLeft, 0); setAxisMaxMinor(xBottom, 0); QwtScaleDraw *sd = new QwtScaleDraw; sd->setTickLength(QwtScaleDiv::MajorTick, 3); setAxisScaleDraw(xBottom, sd); sd = new QwtScaleDraw; sd->setTickLength(QwtScaleDiv::MajorTick, 3); setAxisScaleDraw(yLeft, sd); mX = new QwtPlotMarker(); mX->setLineStyle(QwtPlotMarker::VLine); mX->attach(this); mY = new QwtPlotMarker(); mY->setLineStyle(QwtPlotMarker::HLine); mY->attach(this); cpCurve = new QwtPlotCurve(); cpCurve->setRenderHint(QwtPlotItem::RenderAntialiased); cpCurve->attach(this); curve = new QwtPlotCurve(); curve->attach(this); cl_ = appsettings->value(this, GC_CRANKLENGTH).toDouble() / 1000.0; // markup timeInQuadrant tiqMarker[0] = new QwtPlotMarker(); tiqMarker[0]->attach(this); tiqMarker[0]->setXValue(2.9); tiqMarker[0]->setYValue(580); tiqMarker[1] = new QwtPlotMarker(); tiqMarker[1]->attach(this); tiqMarker[1]->setXValue(0.1); tiqMarker[1]->setYValue(580); tiqMarker[2] = new QwtPlotMarker(); tiqMarker[2]->attach(this); tiqMarker[2]->setXValue(0.1); tiqMarker[2]->setYValue(10); tiqMarker[3] = new QwtPlotMarker(); tiqMarker[3]->attach(this); tiqMarker[3]->setXValue(2.9); tiqMarker[3]->setYValue(10); merge_intervals = false; frame_intervals = true; // only default on first time through, after this the user may have adjusted if (appsettings->value(this, GC_SHADEZONES, true).toBool()==false) shade_zones = false; else shade_zones = true; configChanged(); recalc(); }
int main(int argc, char** argv) { SkCommandLineFlags::SetUsage( "Usage: visualize_color_gamut --input <path to input image> " "--output <path to output image> " "--sRGB <draw canonical sRGB gamut> " "--adobeRGB <draw canonical Adobe RGB gamut> " "--uncorrected <path to reencoded, uncorrected " " input image>\n" "Description: Writes a visualization of the color gamut to the output image ." "Also, if a path is provided, writes uncorrected bytes to an unmarked " "png, for comparison with the input image.\n"); SkCommandLineFlags::Parse(argc, argv); const char* input = FLAGS_input[0]; const char* output = FLAGS_output[0]; if (!input || !output) { SkCommandLineFlags::PrintUsage(); return -1; } SkAutoTUnref<SkData> data(SkData::NewFromFileName(input)); if (!data) { SkDebugf("Cannot find input image.\n"); return -1; } SkAutoTDelete<SkCodec> codec(SkCodec::NewFromData(data)); if (!codec) { SkDebugf("Invalid input image.\n"); return -1; } // Load a graph of the CIE XYZ color gamut. SkBitmap gamut; if (!GetResourceAsBitmap("gamut.png", &gamut)) { SkDebugf("Program failure.\n"); return -1; } SkCanvas canvas(gamut); // Draw the sRGB gamut if requested. if (FLAGS_sRGB) { sk_sp<SkColorSpace> sRGBSpace = SkColorSpace::NewNamed(SkColorSpace::kSRGB_Named); draw_gamut(&canvas, sRGBSpace->xyz(), "sRGB", 0xFFFF9394, false); } // Draw the Adobe RGB gamut if requested. if (FLAGS_adobeRGB) { sk_sp<SkColorSpace> adobeRGBSpace = SkColorSpace::NewNamed(SkColorSpace::kAdobeRGB_Named); draw_gamut(&canvas, adobeRGBSpace->xyz(), "Adobe RGB", 0xFF31a9e1, false); } // Draw gamut for the input image. sk_sp<SkColorSpace> colorSpace = sk_ref_sp(codec->getInfo().colorSpace()); if (!colorSpace) { SkDebugf("Image had no embedded color space information. Defaulting to sRGB.\n"); colorSpace = SkColorSpace::NewNamed(SkColorSpace::kSRGB_Named); } draw_gamut(&canvas, colorSpace->xyz(), input, 0xFF000000, true); // Finally, encode the result to the output file. SkAutoTUnref<SkData> out(SkImageEncoder::EncodeData(gamut, SkImageEncoder::kPNG_Type, 100)); if (!out) { SkDebugf("Failed to encode gamut output.\n"); return -1; } SkFILEWStream stream(output); bool result = stream.write(out->data(), out->size()); if (!result) { SkDebugf("Failed to write gamut output.\n"); return -1; } // Also, if requested, decode and reencode the uncorrected input image. if (!FLAGS_uncorrected.isEmpty()) { SkBitmap bitmap; int width = codec->getInfo().width(); int height = codec->getInfo().height(); SkAlphaType alphaType = codec->getInfo().alphaType(); bitmap.allocN32Pixels(width, height, kOpaque_SkAlphaType == alphaType); SkImageInfo decodeInfo = SkImageInfo::MakeN32(width, height, alphaType); if (SkCodec::kSuccess != codec->getPixels(decodeInfo, bitmap.getPixels(), bitmap.rowBytes())) { SkDebugf("Could not decode input image.\n"); return -1; } out.reset(SkImageEncoder::EncodeData(bitmap, SkImageEncoder::kPNG_Type, 100)); if (!out) { SkDebugf("Failed to encode uncorrected image.\n"); return -1; } SkFILEWStream bitmapStream(FLAGS_uncorrected[0]); result = bitmapStream.write(out->data(), out->size()); if (!result) { SkDebugf("Failed to write uncorrected image output.\n"); return -1; } } return 0; }
int App::start(const std::vector<std::string> &args) { clan::DisplayWindowDescription description; description.set_title("Shockwave Shader"); description.set_size(clan::Size(1024, 768), true); clan::DisplayWindow window(description); clan::InputDevice keyboard = window.get_ic().get_keyboard(); clan::Canvas canvas(window); clan::SlotContainer cc; cc.connect(window.get_ic().get_keyboard().sig_key_up(), clan::bind_member(this, &App::on_input_up)); cc.connect(window.sig_window_close(), clan::bind_member(this, &App::window_close)); // Create offscreen texture clan::Texture2D texture_offscreen(canvas, canvas.get_width(), canvas.get_height()); texture_offscreen.set_min_filter(clan::filter_nearest); texture_offscreen.set_mag_filter(clan::filter_nearest); // Create offscreen framebuffer clan::FrameBuffer framebuffer_offscreen(canvas); framebuffer_offscreen.attach_color(0, texture_offscreen); clan::Canvas canvas_offscreen(canvas, framebuffer_offscreen); clan::Image background(canvas, "../PostProcessing/Resources/background.png"); clan::Image ball(canvas, "../PostProcessing/Resources/ball.png"); ball.set_alignment(clan::origin_center); // Load and link shaders clan::ProgramObject shader = clan::ProgramObject::load(canvas, "Resources/vertex_shader.glsl", "Resources/fragment_shader.glsl"); shader.bind_attribute_location(0, "Position"); shader.bind_attribute_location(1, "TexCoord0"); shader.bind_frag_data_location(0, "cl_FragColor"); if (!shader.link()) throw clan::Exception("Unable to link shader program: Error:" + shader.get_info_log()); shader.set_uniform1i("Texture0", 0); quit = false; float amount = 0.0f; timer = 0.0f; float scale = 1.0f; clan::Font font(canvas, "tahoma", 32); // Shader idea and code from http://www.geeks3d.com/20091116/shader-library-2d-shockwave-post-processing-filter-glsl/ // Shader enhanced for clanlib gpu_positions = clan::VertexArrayVector<clan::Vec2f>(canvas, 6); gpu_tex1_coords = clan::VertexArrayVector<clan::Vec2f>(canvas, 6); gpu_uniforms = clan::UniformVector<ProgramUniforms>(canvas, 1); gpu_primitives_array = clan::PrimitivesArray(canvas); gpu_primitives_array.set_attributes(0, gpu_positions); gpu_primitives_array.set_attributes(1, gpu_tex1_coords); uniforms.shockParams = clan::Vec3f(10.0f, 0.8f, 0.1f); clan::ubyte64 startTime = clan::System::get_time(); shockwave_start_time = 0.0f; shockwave_rate = 1.0f; uniforms.glow = 0.1f; while (!quit) { timer = (clan::System::get_time() - startTime) / 1000.0f; uniforms.time = (timer - shockwave_start_time) / shockwave_rate; // Render standard image to offscreen buffer background.draw(canvas_offscreen, 0, 0); float xpos = canvas.get_width() / 2 + 200 * sinf(timer / 2.0f); float ypos = canvas.get_height() / 2 + 200 * cosf(timer / 2.0f); ball.draw(canvas_offscreen, xpos, ypos); canvas_offscreen.flush(); uniforms.center.x = xpos / ((float) canvas.get_width()); uniforms.center.y = ypos / ((float) canvas.get_height()); render_shockwave(canvas, texture_offscreen, shader); const int gap = 32; font.draw_text(canvas, 10, 64 + gap*0, "Press 'M' to emit a shockwave"); font.draw_text(canvas, 10, 64 + gap*1, "base: " + clan::StringHelp::float_to_text(uniforms.shockParams.x) + " (Press Q,W)"); font.draw_text(canvas, 10, 64 + gap*2, "exponent: " + clan::StringHelp::float_to_text(uniforms.shockParams.y) + " (Press A,S)"); font.draw_text(canvas, 10, 64 + gap*3, "distance: " + clan::StringHelp::float_to_text(uniforms.shockParams.z) + " (Press Z,X)"); font.draw_text(canvas, 10, 64 + gap*4, "rate: " + clan::StringHelp::float_to_text(shockwave_rate) + " (Press E,R)"); font.draw_text(canvas, 10, 64 + gap*5, "glow: " + clan::StringHelp::float_to_text(uniforms.glow) + " (Press D,F)"); window.flip(); clan::System::sleep(10); clan::KeepAlive::process(); } return 0; }
// The start of the Application int App::start(const std::vector<std::string> &args) { clan::DisplayWindowDescription win_desc; win_desc.set_allow_resize(true); win_desc.set_title("Perlin Noise Example"); win_desc.set_size(clan::Size( 800, 520 ), false); clan::DisplayWindow window(win_desc); clan::SlotContainer cc; cc.connect(window.sig_window_close(), clan::bind_member(this, &App::on_window_close)); cc.connect(window.get_ic().get_keyboard().sig_key_up(), clan::bind_member(this, &App::on_input_up)); std::string theme; if (clan::FileHelp::file_exists("../../../Resources/GUIThemeAero/theme.css")) theme = "../../../Resources/GUIThemeAero"; else if (clan::FileHelp::file_exists("../../../Resources/GUIThemeBasic/theme.css")) theme = "../../../Resources/GUIThemeBasic"; else throw clan::Exception("No themes found"); clan::Canvas canvas(window); clan::GUIWindowManagerTexture wm(window); clan::GUIManager gui(wm, theme); // Deleted automatically by the GUI Options *options = new Options(gui, canvas.get_size()); clan::Image image_grid(canvas, "../../Display_Render/Blend/Resources/grid.png"); image_grid.set_color(clan::Colorf(0.4f, 0.4f, 1.0f, 1.0f)); clan::PerlinNoise noise; clan::Image noise_image; clan::TextureFormat last_sized_format = clan::tf_rgb8; float last_amplitude = 0.0f; int last_width = 0; int last_height = 0; int last_octaves = 0 ; float last_start_x = 0.0f; float last_length_x = 0.0f; float last_start_y = 0.0f; float last_length_y = 0.0f; float last_position_z = 0.0f; float last_position_w = 0.0f; PerlinDimension last_dimension = perlin_2d; bool last_is_normals_set = false; while (!quit) { wm.process(); wm.draw_windows(canvas); bool changed_flag = false; if (last_dimension != options->dimension) { changed_flag = true; last_dimension = options->dimension; } if (last_is_normals_set != options->is_normals_set) { changed_flag = true; last_is_normals_set = options->is_normals_set; } if (last_sized_format != options->sized_format) { changed_flag = true; last_sized_format = options->sized_format; noise.set_format(last_sized_format); } if (last_amplitude != options->amplitude) { changed_flag = true; last_amplitude = options->amplitude; noise.set_amplitude(last_amplitude); } if (last_width != options->width) { changed_flag = true; last_width = options->width; noise.set_size(last_width, last_height); } if (last_height != options->height) { changed_flag = true; last_height = options->height; noise.set_size(last_width, last_height); } if (last_octaves != options->octaves) { changed_flag = true; last_octaves = options->octaves; noise.set_octaves(last_octaves); } if (last_start_x != options->start_x) { changed_flag = true; last_start_x = options->start_x; } if (last_length_x != options->length_x) { changed_flag = true; last_length_x = options->length_x; } if (last_start_y != options->start_y) { changed_flag = true; last_start_y = options->start_y; } if (last_length_y != options->length_y) { changed_flag = true; last_length_y = options->length_y; } if (last_position_z != options->position_z) { changed_flag = true; last_position_z = options->position_z; } if (last_position_w != options->position_w) { changed_flag = true; last_position_w = options->position_w; } if (changed_flag) { clan::PixelBuffer pbuff; switch (last_dimension) { case perlin_1d: pbuff = noise.create_noise1d(last_start_x, last_start_x + last_length_x); break; case perlin_2d: pbuff = noise.create_noise2d(last_start_x, last_start_x + last_length_x, last_start_y, last_start_y + last_length_y); break; case perlin_3d: pbuff = noise.create_noise3d(last_start_x, last_start_x + last_length_x, last_start_y, last_start_y + last_length_y, last_position_z); break; case perlin_4d: default: pbuff = noise.create_noise4d(last_start_x, last_start_x + last_length_x, last_start_y, last_start_y + last_length_y, last_position_z, last_position_w); break; } if (last_is_normals_set) pbuff = convert_to_normalmap(pbuff); pbuff = pbuff.to_format(clan::tf_rgba8); // Required for clanD3D noise_image = clan::Image(canvas, pbuff, pbuff.get_size()); } image_grid.draw(canvas, 32, 32); noise_image.draw(canvas, 33, 33); window.flip(1); clan::KeepAlive::process(); } return 0; }
virtual void exec(ForthEngine* fe) { SkScalar radius = fe->fpop(); SkScalar y = fe->fpop(); SkScalar x = fe->fpop(); canvas()->drawCircle(x, y, radius, *paint()); }
Psdplot::Psdplot(QWidget *parent) :QwtPlot(parent) ,xMin_(0) ,xMax_(0) ,haveLine1_(false) ,haveLine2_(false) ,havevLine1_(false) { counter_ = 0; numPoints_ = 1; indexPoints_ = new double[numPoints_]; dataPoints_ = new double[numPoints_]; setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); QPalette palette; palette.setColor(canvas()->backgroundRole(), QColor("white")); canvas()->setPalette(palette); curve_ = new QwtPlotCurve("Curve"); curve_->setPen(QPen(Qt::blue, 1, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin)); curve_->setStyle(QwtPlotCurve::Lines); curve_->setRawSamples(indexPoints_, dataPoints_, numPoints_); curve_->setYAxis(QwtPlot::yLeft); curve_->attach(this); memset(dataPoints_, 0x0, numPoints_*sizeof(double)); for(int i=0;i<numPoints_;i++) indexPoints_[i] = i; line1_ = new QwtPlotCurve("Line1"); line1_->setPen(QPen(Qt::red, 5, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin)); line1_->setStyle(QwtPlotCurve::Lines); line1_->attach(this); line2_ = new QwtPlotCurve("Line2"); line2_->setPen(QPen(Qt::blue, 5, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin)); line2_->setStyle(QwtPlotCurve::Lines); line2_->attach(this); vline1_ = new QwtPlotCurve("vLine1"); vline1_->setPen(QPen(Qt::black, 3, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin)); vline1_->setStyle(QwtPlotCurve::Lines); vline1_->attach(this); enableAxis(QwtPlot::yRight); QwtScaleWidget *leftAxis = axisWidget(QwtPlot::yLeft); connect(leftAxis, SIGNAL(scaleDivChanged()), this, SLOT(linkScales())); setAxisScaleEngine(QwtPlot::xBottom, new QwtLinearScaleEngine); setAxisScaleEngine(QwtPlot::yLeft, new QwtLinearScaleEngine); setAxisScaleEngine(QwtPlot::yRight, new QwtLinearScaleEngine); axisScaleEngine(QwtPlot::xBottom)->setAttribute(QwtScaleEngine::Floating,true); axisScaleEngine(QwtPlot::yLeft)->setAttribute(QwtScaleEngine::Floating,true); axisScaleEngine(QwtPlot::yRight)->setAttribute(QwtScaleEngine::Floating,true); zoomer_ = new MyZoomer(canvas()); zoomer_->setMousePattern(QwtEventPattern::MouseSelect1, Qt::LeftButton); zoomer_->setMousePattern(QwtEventPattern::MouseSelect2, Qt::LeftButton, Qt::ControlModifier); panner_ = new QwtPlotPanner(canvas()); panner_->setMouseButton(Qt::RightButton); magnifier_ = new QwtPlotMagnifier(canvas()); magnifier_->setMouseButton(Qt::NoButton); }
virtual void exec(ForthEngine* fe) { SkScalar dy = fe->fpop(); SkScalar dx = fe->fpop(); canvas()->translate(dx, dy); }
bool SkImageFilter::applyCropRect(const Context& ctx, Proxy* proxy, const SkBitmap& src, SkIPoint* srcOffset, SkIRect* bounds, SkBitmap* dst) const { SkIRect srcBounds; src.getBounds(&srcBounds); srcBounds.offset(*srcOffset); #ifdef SK_SUPPORT_SRC_BOUNDS_BLOAT_FOR_IMAGEFILTERS if (!fCropRect.applyTo(srcBounds, ctx, bounds)) { #else SkIRect dstBounds; this->onFilterNodeBounds(srcBounds, ctx.ctm(), &dstBounds, kForward_MapDirection); if (!fCropRect.applyTo(dstBounds, ctx, bounds)) { #endif return false; } if (srcBounds.contains(*bounds)) { *dst = src; return true; } else { SkAutoTUnref<SkBaseDevice> device(proxy->createDevice(bounds->width(), bounds->height())); if (!device) { return false; } SkCanvas canvas(device); canvas.clear(0x00000000); canvas.drawBitmap(src, srcOffset->x() - bounds->x(), srcOffset->y() - bounds->y()); *srcOffset = SkIPoint::Make(bounds->x(), bounds->y()); *dst = device->accessBitmap(false); return true; } } bool SkImageFilter::onFilterBounds(const SkIRect& src, const SkMatrix& ctm, SkIRect* dst) const { if (fInputCount < 1) { *dst = src; return true; } SkIRect bounds, totalBounds; this->onFilterNodeBounds(src, ctm, &bounds, kReverse_MapDirection); for (int i = 0; i < fInputCount; ++i) { SkImageFilter* filter = this->getInput(i); SkIRect rect = bounds; if (filter && !filter->filterBounds(bounds, ctm, &rect)) { return false; } if (0 == i) { totalBounds = rect; } else { totalBounds.join(rect); } } // don't modify dst until now, so we don't accidentally change it in the // loop, but then return false on the next filter. *dst = totalBounds; return true; } void SkImageFilter::onFilterNodeBounds(const SkIRect& src, const SkMatrix&, SkIRect* dst, MapDirection) const { *dst = src; } SkImageFilter::Context SkImageFilter::mapContext(const Context& ctx) const { #ifdef SK_SUPPORT_SRC_BOUNDS_BLOAT_FOR_IMAGEFILTERS return ctx; #else SkIRect clipBounds; this->onFilterNodeBounds(ctx.clipBounds(), ctx.ctm(), &clipBounds, MapDirection::kReverse_MapDirection); return Context(ctx.ctm(), clipBounds, ctx.cache(), ctx.sizeConstraint()); #endif } bool SkImageFilter::asFragmentProcessor(GrFragmentProcessor**, GrTexture*, const SkMatrix&, const SkIRect&) const { return false; } SkImageFilter* SkImageFilter::CreateMatrixFilter(const SkMatrix& matrix, SkFilterQuality filterQuality, SkImageFilter* input) { return SkMatrixImageFilter::Create(matrix, filterQuality, input); } SkImageFilter* SkImageFilter::newWithLocalMatrix(const SkMatrix& matrix) const { // SkLocalMatrixImageFilter takes SkImage* in its factory, but logically that parameter // is *always* treated as a const ptr. Hence the const-cast here. // return SkLocalMatrixImageFilter::Create(matrix, const_cast<SkImageFilter*>(this)); } #if SK_SUPPORT_GPU void SkImageFilter::WrapTexture(GrTexture* texture, int width, int height, SkBitmap* result) { SkImageInfo info = SkImageInfo::MakeN32Premul(width, height); result->setInfo(info); result->setPixelRef(new SkGrPixelRef(info, texture))->unref(); }
virtual void exec(ForthEngine* fe) { canvas()->drawColor(fe->pop()); }
void ColDiagramView::contentsMousePressEvent(QMouseEvent * e) { if (!window()->frozen()) { if (e->button() == ::Qt::RightButton) DiagramView::contentsMousePressEvent(e); else { UmlCode c = window()->buttonOn(); switch (c) { case UmlClass: { history_protected = FALSE; unselect_all(); window()->selectOn(); history_save(); BrowserNode * parent = ((BrowserNode *) window()->browser_diagram()->parent()); BrowserClass * b = BrowserClass::get_class(parent); if (b != 0) { CodClassInstCanvas * cl = new CodClassInstCanvas(b, the_canvas(), e->x(), e->y(), 0); cl->show(); cl->upper(); window()->package_modified(); } } canvas()->update(); break; case UmlClassInstance: { history_protected = TRUE; unselect_all(); window()->selectOn(); history_save(); BrowserNode * parent = ((BrowserNode *) window()->browser_diagram()->parent()); BrowserClassInstance * b = BrowserClassInstance::get_classinstance(parent); if (b != 0) { CodClassInstCanvas * cl = new CodClassInstCanvas(b, the_canvas(), e->x(), e->y(), 0); cl->show(); cl->upper(); window()->package_modified(); } } canvas()->update(); history_protected = FALSE; break; case UmlSelfLink: { history_protected = TRUE; window()->selectOn(); history_save(); Q3CanvasItem * ci = the_canvas()->collision(e->pos()); if (ci != 0) { DiagramItem * i = QCanvasItemToDiagramItem(ci); if (i != 0) { QString err = i->may_start(c); if (!err.isEmpty()) msg_critical("Douml", err); else { i->connexion(c, i, e->pos(), e->pos()); window()->package_modified(); } } } } canvas()->update(); history_protected = FALSE; break; default: DiagramView::contentsMousePressEvent(e); break; } } } else DiagramView::contentsMousePressEvent(e); }
void Canvas::DrawHLine(int x1, int x2, int y, Color color) { SDLRasterCanvas canvas(buffer); canvas.DrawHLine(x1, x2, y, canvas.Import(color)); }
void ColDiagramView::save(QTextStream & st, QString & warning, bool copy) const { DiagramItemList items(canvas()->allItems()); if (!copy) // sort is useless for a copy items.sort(); st << "format " << api_format() << "\n"; // save first the packages fragment, classes instances, notes, icons and text foreach (DiagramItem *di, items) { switch (di->type()) { case UmlPackage: case UmlFragment: case UmlClass: case UmlClassInstance: case UmlNote: case UmlText: case UmlImage: case UmlIcon: if (!copy || di->copyable()) di->save(st, FALSE, warning); // no break default: break; } } // then save links selflink and dirs (without messages) foreach (DiagramItem *di, items) { switch (di->type()) { case UmlLink: // saves associated dirs case UmlSelfLink: if (!copy || di->copyable()) di->save(st, FALSE, warning); default: // to avoid warning break; } } // then save messages ColMsg::save(st, msgs, copy, warning, window()->browser_diagram()->full_name()); // then save anchors foreach (DiagramItem *di, items) if ((!copy || di->copyable()) && (di->type() == UmlAnchor)) di->save(st, FALSE, warning); if (!copy && (preferred_zoom != 0)) { nl_indent(st); st << "preferred_whz " << preferred_size.width() << " " << preferred_size.height() << " " << preferred_zoom; } nl_indent(st); st << "end\n"; }
void CrossCheckPlotter::plot( const PlotType PLOT_TYPE, const std::string FILE_NAME ) { // Get our config_pair and some of the values from it config_map::iterator i_config_pair = conf_map_.find(PLOT_TYPE); if (i_config_pair == conf_map_.end()) { std::cout << "Missing PLOT_TYPE in conf_map_!" << std::endl; return; } PlotConfig plot_config = i_config_pair->second; const std::string HISTO_NAME = plot_config.histo_name; // Open the histograms const bool DO_RESCALING = true; HistoStore histo_store = open_histos(HISTO_NAME, DO_RESCALING); TH1D* data_histo = histo_store.data_histo; TH1D* mc_histo = histo_store.mc_histo; std::vector<std::pair<std::string, TH1D*>> bg_histos = histo_store.bg_histos; // Check that open_histos exited successfully, otherwise end if (data_histo == NULL || mc_histo == NULL) { return; } // Rebin if the binning is greater than 0 in size. If it is size one assume // we want a simple rebinning (where N bins are combined to 1), otherwise // the vector is the edges of the bins. if (plot_config.binning.size() == 1) { mc_histo->Rebin(static_cast<int>(plot_config.binning[0])); data_histo->Rebin(static_cast<int>(plot_config.binning[0])); for (auto& i_pair : bg_histos) { i_pair.second->Rebin(static_cast<int>(plot_config.binning[0])); } } else if (plot_config.binning.size() > 1) { std::vector<double> new_binning = get_rebinning( plot_config.binning, data_histo ); mc_histo = dynamic_cast<TH1D*>( mc_histo->Rebin( new_binning.size() - 1, "mc_rebinned_histo", &new_binning[0] // double* ) ); data_histo = dynamic_cast<TH1D*>( data_histo->Rebin( new_binning.size() - 1, "data_rebinned_histo", &new_binning[0] // double* ) ); for (auto& i_pair : bg_histos) { std::string new_name = i_pair.first + "_rebinned_histo"; i_pair.second = dynamic_cast<TH1D*>( i_pair.second->Rebin( new_binning.size() - 1, new_name.c_str(), &new_binning[0] // double* ) ); } } // Normalize the plots // Signal MC if (area_rescale_factor_ > 0) { // Normalize by area mc_histo->Scale(area_rescale_factor_); } else { // Normalize by luminosity mc_histo->Scale(get_rescaling(data_config_, mc_config_)); } // BG MC for (auto& i_pair : bg_histos) { // Locate the DataConfig by name auto it = bg_configs_.find(i_pair.first); if (it != bg_configs_.end()) { if (area_rescale_factor_ > 0) { // Normalize by area i_pair.second->Scale(area_rescale_factor_); } else { // Normalize by luminosity const double RESCALING = get_rescaling(data_config_, it->second); i_pair.second->Scale(RESCALING); } } else { std::cout << "Failed to normalize " << i_pair.first; std::cout << ". Scaling to 0!!" << std::endl; i_pair.second->Scale(0); } } // Update uncertainties after rescaling data_histo->Sumw2(); mc_histo->Sumw2(); for (auto& i_pair : bg_histos) { i_pair.second->Sumw2(); } // Make a stack to store the MC THStack* histo_stack = new THStack("hs", "Monte Carlo histrogram stack"); // Title data_histo->SetTitle(0); // Remove the title, we'll place it by hand //histo_stack->SetTitle(0); // Axis labels data_histo->GetXaxis()->SetTitle(plot_config.x_label.c_str()); //histo_stack->GetXaxis()->SetTitle(plot_config.x_label.c_str()); data_histo->GetYaxis()->SetTitle(plot_config.y_label.c_str()); //histo_stack->GetYaxis()->SetTitle(plot_config.y_label.c_str()); // Set up the legend using the plot edges to set its location const double LEG_HEIGHT = 0.15; const double LEG_LENGTH = 0.15; TLegend legend(RIGHT_EDGE_ - LEG_LENGTH, TOP_EDGE_ - LEG_HEIGHT, RIGHT_EDGE_, TOP_EDGE_); legend.SetFillColor(kWhite); legend.AddEntry(data_histo, data_config_.name.c_str(), "p"); legend.AddEntry(mc_histo, mc_config_.name.c_str(), "f"); legend.SetBorderSize(0); // Remove drop shadow and border legend.SetFillStyle(0); // Transparent // Set up the styles of the histograms style_->cd(); // Position of axis labels mc_histo->GetYaxis()->SetTitleOffset(1.25); mc_histo->GetXaxis()->SetTitleOffset(1.1); // Marker, line, and fill style data_histo->SetMarkerStyle(kFullCircle); data_histo->SetMarkerColor(kBlack); data_histo->SetLineColor(kBlack); mc_histo->SetLineColor(kBlue); mc_histo->SetFillColor(kBlue); mc_histo->SetFillStyle(SPARSEDOT_FILL); // Set up the background histograms' style, coloring, and legend entry. We // have to do this almost at the end because we need the legend to exist. unsigned int i_style = 0; for (auto& i_pair : bg_histos) { // Reset if we run beyond the array if (i_style >= color_styles_.size()) { i_style = 0; } std::pair<RootFill, int> style_pair = color_styles_[i_style]; ++i_style; // Set the color and fill i_pair.second->SetFillStyle(style_pair.first); i_pair.second->SetLineColor(style_pair.second); i_pair.second->SetFillColor(style_pair.second); // Add to the stack and legend histo_stack->Add(i_pair.second); legend.AddEntry(i_pair.second, i_pair.first.c_str() ,"f"); } histo_stack->Add(mc_histo); // Set the plot range maximum and minimum based on the highest peak in // either histo // Set the maximum const double DATA_MAX = data_histo->GetMaximum(); const double STACK_MAX = histo_stack->GetMaximum(); const double MAX_CONST = 1.2; if (DATA_MAX > STACK_MAX) { data_histo->SetMaximum(DATA_MAX * MAX_CONST); } else { data_histo->SetMaximum(STACK_MAX * MAX_CONST); } // Set the minimum double bg_min_max = -1; // The smallest maximum for (auto& i_pair : bg_histos) { const double BG_MAX = i_pair.second->GetMaximum(); if (BG_MAX < bg_min_max || bg_min_max < 0) { bg_min_max = BG_MAX; } }; // Set the minimum if sane, otherwise trust root to do it if (bg_min_max > 0) { data_histo->SetMinimum(bg_min_max * 0.1); } // Add title TLatex *plot_title = NULL; if (plot_config.title != "") { const std::string TITLE = plot_config.title; plot_title = new TLatex(0.18, 0.93, TITLE.c_str()); plot_title->SetNDC(); plot_title->SetTextFont(42); plot_title->SetTextColor(1); plot_title->SetTextSize(0.06); plot_title->SetTextAlign(22); plot_title->SetTextAngle(0); } // Make a canvas to hold the plot TCanvas canvas("canvas", "canvas", X_VAL_, Y_VAL_); canvas.cd(); canvas.SetLogy(plot_config.logy); // Draw the histograms data_histo->Draw("E"); // Set axis titles histo_stack->Draw("HIST SAME"); data_histo->Draw("E SAME"); legend.Draw(); if (plot_title != NULL) { plot_title->Draw(); } // Save the plot as a png canvas.Print(FILE_NAME.c_str(), "png"); // Clean up delete plot_title; delete histo_stack; }
void rasterize(std::ostream &output, const OsmAnd::EyePiece::Configuration& cfg) #endif { // Obtain and configure rasterization style context OsmAnd::MapStyles stylesCollection; for(auto itStyleFile = cfg.styleFiles.begin(); itStyleFile != cfg.styleFiles.end(); ++itStyleFile) { const auto& styleFile = *itStyleFile; if(!stylesCollection.registerStyle(styleFile.absoluteFilePath())) output << xT("Failed to parse metadata of '") << QStringToStlString(styleFile.fileName()) << xT("' or duplicate style") << std::endl; } std::shared_ptr<const OsmAnd::MapStyle> style; if(!stylesCollection.obtainStyle(cfg.styleName, style)) { output << xT("Failed to resolve style '") << QStringToStlString(cfg.styleName) << xT("'") << std::endl; return; } if(cfg.dumpRules) style->dump(); OsmAnd::ObfsCollection obfsCollection; obfsCollection.watchDirectory(cfg.obfsDir); // Collect all map objects (this should be replaced by something like RasterizerViewport/RasterizerContext) QList< std::shared_ptr<const OsmAnd::Model::MapObject> > mapObjects; OsmAnd::AreaI bbox31( OsmAnd::Utilities::get31TileNumberY(cfg.bbox.top), OsmAnd::Utilities::get31TileNumberX(cfg.bbox.left), OsmAnd::Utilities::get31TileNumberY(cfg.bbox.bottom), OsmAnd::Utilities::get31TileNumberX(cfg.bbox.right) ); const auto& obfDI = obfsCollection.obtainDataInterface(); OsmAnd::MapFoundationType mapFoundation; obfDI->obtainMapObjects(&mapObjects, &mapFoundation, bbox31, cfg.zoom, nullptr); bool basemapAvailable; obfDI->obtainBasemapPresenceFlag(basemapAvailable); // Calculate output size in pixels const auto tileWidth = OsmAnd::Utilities::getTileNumberX(cfg.zoom, cfg.bbox.right) - OsmAnd::Utilities::getTileNumberX(cfg.zoom, cfg.bbox.left); const auto tileHeight = OsmAnd::Utilities::getTileNumberY(cfg.zoom, cfg.bbox.bottom) - OsmAnd::Utilities::getTileNumberY(cfg.zoom, cfg.bbox.top); const auto pixelWidth = qCeil(tileWidth * cfg.tileSide); const auto pixelHeight = qCeil(tileHeight * cfg.tileSide); output << xT("Will rasterize ") << mapObjects.count() << xT(" objects onto ") << pixelWidth << xT("x") << pixelHeight << xT(" bitmap") << std::endl; // Allocate render target SkBitmap renderSurface; renderSurface.setConfig(cfg.is32bit ? SkBitmap::kARGB_8888_Config : SkBitmap::kRGB_565_Config, pixelWidth, pixelHeight); if(!renderSurface.allocPixels()) { output << xT("Failed to allocated render target ") << pixelWidth << xT("x") << pixelHeight; return; } SkDevice renderTarget(renderSurface); // Create render canvas SkCanvas canvas(&renderTarget); // Perform actual rendering OsmAnd::RasterizerEnvironment rasterizerEnv(style, basemapAvailable); OsmAnd::RasterizerContext rasterizerContext; OsmAnd::Rasterizer::prepareContext(rasterizerEnv, rasterizerContext, bbox31, cfg.zoom, cfg.tileSide, cfg.densityFactor, mapFoundation, mapObjects, OsmAnd::PointF(), nullptr); if(cfg.drawMap) OsmAnd::Rasterizer::rasterizeMap(rasterizerEnv, rasterizerContext, true, canvas, nullptr); /*if(cfg.drawText) OsmAnd::Rasterizer::rasterizeText(rasterizerContext, !cfg.drawMap, canvas, nullptr);*/ // Save rendered area if(!cfg.output.isEmpty()) { std::unique_ptr<SkImageEncoder> encoder(CreatePNGImageEncoder()); std::unique_ptr<SkImageEncoder> outputStream(CreatePNGImageEncoder()); encoder->encodeFile(cfg.output.toLocal8Bit(), renderSurface, 100); } return; }
bool SkTileImageFilter::onFilterImageDeprecated(Proxy* proxy, const SkBitmap& src, const Context& ctx, SkBitmap* dst, SkIPoint* offset) const { SkBitmap source = src; SkIPoint srcOffset = SkIPoint::Make(0, 0); if (!this->filterInputDeprecated(0, proxy, src, ctx, &source, &srcOffset)) { return false; } SkRect dstRect; ctx.ctm().mapRect(&dstRect, fDstRect); if (!dstRect.intersect(SkRect::Make(ctx.clipBounds()))) { offset->fX = offset->fY = 0; return true; } const SkIRect dstIRect = dstRect.roundOut(); int w = dstIRect.width(); int h = dstIRect.height(); if (!fSrcRect.width() || !fSrcRect.height() || !w || !h) { return false; } SkRect srcRect; ctx.ctm().mapRect(&srcRect, fSrcRect); SkIRect srcIRect; srcRect.roundOut(&srcIRect); srcIRect.offset(-srcOffset); SkBitmap subset; SkIRect srcBounds; source.getBounds(&srcBounds); if (!SkIRect::Intersects(srcIRect, srcBounds)) { offset->fX = offset->fY = 0; return true; } if (srcBounds.contains(srcIRect)) { if (!source.extractSubset(&subset, srcIRect)) { return false; } } else { SkAutoTUnref<SkBaseDevice> device(proxy->createDevice(srcIRect.width(), srcIRect.height(), kPossible_TileUsage)); if (!device) { return false; } SkCanvas canvas(device); canvas.drawBitmap(src, SkIntToScalar(srcOffset.x()), SkIntToScalar(srcOffset.y())); subset = device->accessBitmap(false); } SkASSERT(subset.width() == srcIRect.width()); SkASSERT(subset.height() == srcIRect.height()); SkAutoTUnref<SkBaseDevice> device(proxy->createDevice(w, h)); if (nullptr == device.get()) { return false; } SkCanvas canvas(device); SkPaint paint; paint.setXfermodeMode(SkXfermode::kSrc_Mode); paint.setShader(SkShader::MakeBitmapShader(subset, SkShader::kRepeat_TileMode, SkShader::kRepeat_TileMode)); canvas.translate(-dstRect.fLeft, -dstRect.fTop); canvas.drawRect(dstRect, paint); *dst = device->accessBitmap(false); offset->fX = dstIRect.fLeft; offset->fY = dstIRect.fTop; return true; }
DEF_GPUTEST(ReadWriteAlpha, reporter, factory) { for (int type = 0; type < GrContextFactory::kLastGLContextType; ++type) { GrContextFactory::GLContextType glType = static_cast<GrContextFactory::GLContextType>(type); if (!GrContextFactory::IsRenderingGLContext(glType)) { continue; } GrContext* context = factory->get(glType); if (NULL == context) { continue; } unsigned char textureData[X_SIZE][Y_SIZE]; memset(textureData, 0, X_SIZE * Y_SIZE); GrSurfaceDesc desc; // let Skia know we will be using this texture as a render target desc.fFlags = kRenderTarget_GrSurfaceFlag; // it is a single channel texture desc.fConfig = kAlpha_8_GrPixelConfig; desc.fWidth = X_SIZE; desc.fHeight = Y_SIZE; // We are initializing the texture with zeros here GrTexture* texture = context->textureProvider()->createTexture(desc, false, textureData, 0); if (!texture) { return; } SkAutoTUnref<GrTexture> au(texture); // create a distinctive texture for (int y = 0; y < Y_SIZE; ++y) { for (int x = 0; x < X_SIZE; ++x) { textureData[x][y] = x*Y_SIZE+y; } } // upload the texture texture->writePixels(0, 0, desc.fWidth, desc.fHeight, desc.fConfig, textureData, 0); unsigned char readback[X_SIZE][Y_SIZE]; // clear readback to something non-zero so we can detect readback failures memset(readback, 0x1, X_SIZE * Y_SIZE); // read the texture back texture->readPixels(0, 0, desc.fWidth, desc.fHeight, desc.fConfig, readback, 0); // make sure the original & read back versions match bool match = true; for (int y = 0; y < Y_SIZE; ++y) { for (int x = 0; x < X_SIZE; ++x) { if (textureData[x][y] != readback[x][y]) { match = false; } } } REPORTER_ASSERT(reporter, match); // Now try writing on the single channel texture SkSurfaceProps props(SkSurfaceProps::kLegacyFontHost_InitType); SkAutoTUnref<SkBaseDevice> device(SkGpuDevice::Create(texture->asRenderTarget(), &props, SkGpuDevice::kUninit_InitContents)); SkCanvas canvas(device); SkPaint paint; const SkRect rect = SkRect::MakeLTRB(-10, -10, X_SIZE + 10, Y_SIZE + 10); paint.setColor(SK_ColorWHITE); canvas.drawRect(rect, paint); texture->readPixels(0, 0, desc.fWidth, desc.fHeight, desc.fConfig, readback, 0); match = true; for (int y = 0; y < Y_SIZE; ++y) { for (int x = 0; x < X_SIZE; ++x) { if (0xFF != readback[x][y]) { match = false; } } } REPORTER_ASSERT(reporter, match); } }
void QwtPlot::printLegend(QPainter *painter, const QRect &rect) const { if ( !legend() || legend()->isEmpty() ) return; QLayout *l = legend()->contentsWidget()->layout(); if ( l == 0 || !l->inherits("QwtDynGridLayout") ) return; QwtDynGridLayout *legendLayout = (QwtDynGridLayout *)l; uint numCols = legendLayout->columnsForWidth(rect.width()); #if QT_VERSION < 0x040000 QValueList<QRect> itemRects = legendLayout->layoutItems(rect, numCols); #else QList<QRect> itemRects = legendLayout->layoutItems(rect, numCols); #endif int index = 0; #if QT_VERSION < 0x040000 QLayoutIterator layoutIterator = legendLayout->iterator(); for ( QLayoutItem *item = layoutIterator.current(); item != 0; item = ++layoutIterator) { #else for ( int i = 0; i < legendLayout->count(); i++ ) { QLayoutItem *item = legendLayout->itemAt(i); #endif QWidget *w = item->widget(); if ( w ) { painter->save(); painter->setClipping(true); QwtPainter::setClipRect(painter, itemRects[index]); printLegendItem(painter, w, itemRects[index]); index++; painter->restore(); } } } /*! Print the legend item into a given rectangle. \param painter Painter \param w Widget representing a legend item \param rect Bounding rectangle */ void QwtPlot::printLegendItem(QPainter *painter, const QWidget *w, const QRect &rect) const { if ( w->inherits("QwtLegendItem") ) { QwtLegendItem *item = (QwtLegendItem *)w; painter->setFont(item->font()); item->drawItem(painter, rect); } } /*! \brief Paint a scale into a given rectangle. Paint the scale into a given rectangle. \param painter Painter \param axisId Axis \param startDist Start border distance \param endDist End border distance \param baseDist Base distance \param rect Bounding rectangle */ void QwtPlot::printScale(QPainter *painter, int axisId, int startDist, int endDist, int baseDist, const QRect &rect) const { if (!axisEnabled(axisId)) return; const QwtScaleWidget *scaleWidget = axisWidget(axisId); if ( scaleWidget->isColorBarEnabled() && scaleWidget->colorBarWidth() > 0) { const QwtMetricsMap map = QwtPainter::metricsMap(); QRect r = map.layoutToScreen(rect); r.setWidth(r.width() - 1); r.setHeight(r.height() - 1); scaleWidget->drawColorBar(painter, scaleWidget->colorBarRect(r)); const int off = scaleWidget->colorBarWidth() + scaleWidget->spacing(); if ( scaleWidget->scaleDraw()->orientation() == Qt::Horizontal ) baseDist += map.screenToLayoutY(off); else baseDist += map.screenToLayoutX(off); } QwtScaleDraw::Alignment align; int x, y, w; switch(axisId) { case yLeft: { x = rect.right() - baseDist; y = rect.y() + startDist; w = rect.height() - startDist - endDist; align = QwtScaleDraw::LeftScale; break; } case yRight: { x = rect.left() + baseDist; y = rect.y() + startDist; w = rect.height() - startDist - endDist; align = QwtScaleDraw::RightScale; break; } case xTop: { x = rect.left() + startDist; y = rect.bottom() - baseDist; w = rect.width() - startDist - endDist; align = QwtScaleDraw::TopScale; break; } case xBottom: { x = rect.left() + startDist; y = rect.top() + baseDist; w = rect.width() - startDist - endDist; align = QwtScaleDraw::BottomScale; break; } default: return; } scaleWidget->drawTitle(painter, align, rect); painter->save(); painter->setFont(scaleWidget->font()); QPen pen = painter->pen(); pen.setWidth(scaleWidget->penWidth()); painter->setPen(pen); QwtScaleDraw *sd = (QwtScaleDraw *)scaleWidget->scaleDraw(); const QPoint sdPos = sd->pos(); const int sdLength = sd->length(); sd->move(x, y); sd->setLength(w); #if QT_VERSION < 0x040000 sd->draw(painter, scaleWidget->palette().active()); #else QPalette palette = scaleWidget->palette(); palette.setCurrentColorGroup(QPalette::Active); sd->draw(painter, palette); #endif // reset previous values sd->move(sdPos); sd->setLength(sdLength); painter->restore(); } /*! Print the canvas into a given rectangle. \param painter Painter \param map Maps mapping between plot and paint device coordinates \param boundingRect Bounding rectangle \param canvasRect Canvas rectangle \param pfilter Print filter \sa QwtPlotPrintFilter */ void QwtPlot::printCanvas(QPainter *painter, const QRect &boundingRect, const QRect &canvasRect, const QwtScaleMap map[axisCnt], const QwtPlotPrintFilter &pfilter) const { if ( pfilter.options() & QwtPlotPrintFilter::PrintBackground ) { QBrush bgBrush; #if QT_VERSION >= 0x040000 bgBrush = canvas()->palette().brush(backgroundRole()); #else QColorGroup::ColorRole role = QPalette::backgroundRoleFromMode( backgroundMode() ); bgBrush = canvas()->colorGroup().brush( role ); #endif QRect r = boundingRect; if ( !(pfilter.options() & QwtPlotPrintFilter::PrintFrameWithScales) ) { r = canvasRect; #if QT_VERSION >= 0x040000 // Unfortunately the paint engines do no always the same const QPaintEngine *pe = painter->paintEngine(); if ( pe ) { switch(painter->paintEngine()->type() ) { case QPaintEngine::Raster: case QPaintEngine::X11: break; default: r.setWidth(r.width() - 1); r.setHeight(r.height() - 1); break; } } #else if ( painter->device()->isExtDev() ) { r.setWidth(r.width() - 1); r.setHeight(r.height() - 1); } #endif } QwtPainter::fillRect(painter, r, bgBrush); } if ( pfilter.options() & QwtPlotPrintFilter::PrintFrameWithScales ) { painter->save(); painter->setPen(QPen(Qt::black)); painter->setBrush(QBrush(Qt::NoBrush)); QwtPainter::drawRect(painter, boundingRect); painter->restore(); } painter->setClipping(true); QwtPainter::setClipRect(painter, canvasRect); drawItems(painter, canvasRect, map, pfilter); }