text
stringlengths 5
1.04M
|
|---|
// g2o - General Graph Optimization
// Copyright (C) 2011 H. Strasdat
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
// TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
// PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <Eigen/StdVector>
#include <unordered_set>
#include <iostream>
#include <stdint.h>
#include "g2o/config.h"
#include "g2o/core/sparse_optimizer.h"
#include "g2o/core/block_solver.h"
#include "g2o/core/solver.h"
#include "g2o/core/robust_kernel_impl.h"
#include "g2o/core/optimization_algorithm_levenberg.h"
#include "g2o/solvers/dense/linear_solver_dense.h"
#include "g2o/types/icp/types_icp.h"
#include "g2o/solvers/structure_only/structure_only_solver.h"
#if defined G2O_HAVE_CHOLMOD
#include "g2o/solvers/cholmod/linear_solver_cholmod.h"
#elif defined G2O_HAVE_CSPARSE
#include "g2o/solvers/csparse/linear_solver_csparse.h"
#endif
using namespace Eigen;
using namespace std;
class Sample
{
public:
static int uniform(int from, int to);
static double uniform();
static double gaussian(double sigma);
};
static double uniform_rand(double lowerBndr, double upperBndr)
{
return lowerBndr + ((double) std::rand() / (RAND_MAX + 1.0)) * (upperBndr - lowerBndr);
}
static double gauss_rand(double mean, double sigma)
{
double x, y, r2;
do {
x = -1.0 + 2.0 * uniform_rand(0.0, 1.0);
y = -1.0 + 2.0 * uniform_rand(0.0, 1.0);
r2 = x * x + y * y;
} while (r2 > 1.0 || r2 == 0.0);
return mean + sigma * y * std::sqrt(-2.0 * log(r2) / r2);
}
int Sample::uniform(int from, int to)
{
return static_cast<int>(uniform_rand(from, to));
}
double Sample::uniform()
{
return uniform_rand(0., 1.);
}
double Sample::gaussian(double sigma)
{
return gauss_rand(0., sigma);
}
int main(int argc, const char* argv[])
{
if (argc<2)
{
cout << endl;
cout << "Please type: " << endl;
cout << "ba_demo [PIXEL_NOISE] [OUTLIER RATIO] [ROBUST_KERNEL] [STRUCTURE_ONLY] [DENSE]" << endl;
cout << endl;
cout << "PIXEL_NOISE: noise in image space (E.g.: 1)" << endl;
cout << "OUTLIER_RATIO: probability of spuroius observation (default: 0.0)" << endl;
cout << "ROBUST_KERNEL: use robust kernel (0 or 1; default: 0==false)" << endl;
cout << "STRUCTURE_ONLY: performe structure-only BA to get better point initializations (0 or 1; default: 0==false)" << endl;
cout << "DENSE: Use dense solver (0 or 1; default: 0==false)" << endl;
cout << endl;
cout << "Note, if OUTLIER_RATIO is above 0, ROBUST_KERNEL should be set to 1==true." << endl;
cout << endl;
exit(0);
}
double PIXEL_NOISE = atof(argv[1]);
double OUTLIER_RATIO = 0.0;
if (argc>2)
{
OUTLIER_RATIO = atof(argv[2]);
}
bool ROBUST_KERNEL = false;
if (argc>3)
{
ROBUST_KERNEL = atoi(argv[3]) != 0;
}
bool STRUCTURE_ONLY = false;
if (argc>4)
{
STRUCTURE_ONLY = atoi(argv[4]) != 0;
}
bool DENSE = false;
if (argc>5)
{
DENSE = atoi(argv[5]) != 0;
}
cout << "PIXEL_NOISE: " << PIXEL_NOISE << endl;
cout << "OUTLIER_RATIO: " << OUTLIER_RATIO<< endl;
cout << "ROBUST_KERNEL: " << ROBUST_KERNEL << endl;
cout << "STRUCTURE_ONLY: " << STRUCTURE_ONLY<< endl;
cout << "DENSE: "<< DENSE << endl;
g2o::SparseOptimizer optimizer;
optimizer.setVerbose(false);
g2o::BlockSolver_6_3::LinearSolverType * linearSolver;
if (DENSE)
{
linearSolver= new g2o::LinearSolverDense<g2o::BlockSolver_6_3::PoseMatrixType>();
cerr << "Using DENSE" << endl;
}
else
{
#ifdef G2O_HAVE_CHOLMOD
cerr << "Using CHOLMOD" << endl;
linearSolver = new g2o::LinearSolverCholmod<g2o::BlockSolver_6_3::PoseMatrixType>();
#elif defined G2O_HAVE_CSPARSE
linearSolver = new g2o::LinearSolverCSparse<g2o::BlockSolver_6_3::PoseMatrixType>();
cerr << "Using CSPARSE" << endl;
#else
#error neither CSparse nor Cholmod are available
#endif
}
g2o::BlockSolver_6_3 * solver_ptr
= new g2o::BlockSolver_6_3(linearSolver);
g2o::OptimizationAlgorithmLevenberg* solver = new g2o::OptimizationAlgorithmLevenberg(solver_ptr);
optimizer.setAlgorithm(solver);
// set up 500 points
vector<Vector3d> true_points;
for (size_t i=0;i<500; ++i)
{
true_points.push_back(Vector3d((Sample::uniform()-0.5)*3,
Sample::uniform()-0.5,
Sample::uniform()+10));
}
Vector2d focal_length(500,500); // pixels
Vector2d principal_point(320,240); // 640x480 image
double baseline = 0.075; // 7.5 cm baseline
vector<Eigen::Isometry3d,
aligned_allocator<Eigen::Isometry3d> > true_poses;
// set up camera params
g2o::VertexSCam::setKcam(focal_length[0],focal_length[1],
principal_point[0],principal_point[1],
baseline);
// set up 5 vertices, first 2 fixed
int vertex_id = 0;
for (size_t i=0; i<5; ++i)
{
Vector3d trans(i*0.04-1.,0,0);
Eigen:: Quaterniond q;
q.setIdentity();
Eigen::Isometry3d pose;
pose = q;
pose.translation() = trans;
g2o::VertexSCam * v_se3
= new g2o::VertexSCam();
v_se3->setId(vertex_id);
v_se3->setEstimate(pose);
v_se3->setAll(); // set aux transforms
if (i<2)
v_se3->setFixed(true);
optimizer.addVertex(v_se3);
true_poses.push_back(pose);
vertex_id++;
}
int point_id=vertex_id;
int point_num = 0;
double sum_diff2 = 0;
cout << endl;
unordered_map<int,int> pointid_2_trueid;
unordered_set<int> inliers;
// add point projections to this vertex
for (size_t i=0; i<true_points.size(); ++i)
{
g2o::VertexSBAPointXYZ * v_p
= new g2o::VertexSBAPointXYZ();
v_p->setId(point_id);
v_p->setMarginalized(true);
v_p->setEstimate(true_points.at(i)
+ Vector3d(Sample::gaussian(1),
Sample::gaussian(1),
Sample::gaussian(1)));
int num_obs = 0;
for (size_t j=0; j<true_poses.size(); ++j)
{
Vector3d z;
dynamic_cast<g2o::VertexSCam*>
(optimizer.vertices().find(j)->second)
->mapPoint(z,true_points.at(i));
if (z[0]>=0 && z[1]>=0 && z[0]<640 && z[1]<480)
{
++num_obs;
}
}
if (num_obs>=2)
{
optimizer.addVertex(v_p);
bool inlier = true;
for (size_t j=0; j<true_poses.size(); ++j)
{
Vector3d z;
dynamic_cast<g2o::VertexSCam*>
(optimizer.vertices().find(j)->second)
->mapPoint(z,true_points.at(i));
if (z[0]>=0 && z[1]>=0 && z[0]<640 && z[1]<480)
{
double sam = Sample::uniform();
if (sam<OUTLIER_RATIO)
{
z = Vector3d(Sample::uniform(64,640),
Sample::uniform(0,480),
Sample::uniform(0,64)); // disparity
z(2) = z(0) - z(2); // px' now
inlier= false;
}
z += Vector3d(Sample::gaussian(PIXEL_NOISE),
Sample::gaussian(PIXEL_NOISE),
Sample::gaussian(PIXEL_NOISE/16.0));
g2o::Edge_XYZ_VSC * e
= new g2o::Edge_XYZ_VSC();
e->vertices()[0]
= dynamic_cast<g2o::OptimizableGraph::Vertex*>(v_p);
e->vertices()[1]
= dynamic_cast<g2o::OptimizableGraph::Vertex*>
(optimizer.vertices().find(j)->second);
e->setMeasurement(z);
//e->inverseMeasurement() = -z;
e->information() = Matrix3d::Identity();
if (ROBUST_KERNEL) {
g2o::RobustKernelHuber* rk = new g2o::RobustKernelHuber;
e->setRobustKernel(rk);
}
optimizer.addEdge(e);
}
}
if (inlier)
{
inliers.insert(point_id);
Vector3d diff = v_p->estimate() - true_points[i];
sum_diff2 += diff.dot(diff);
}
// else
// cout << "Point: " << point_id << "has at least one spurious observation" <<endl;
pointid_2_trueid.insert(make_pair(point_id,i));
++point_id;
++point_num;
}
}
cout << endl;
optimizer.initializeOptimization();
optimizer.setVerbose(true);
if (STRUCTURE_ONLY)
{
cout << "Performing structure-only BA:" << endl;
g2o::StructureOnlySolver<3> structure_only_ba;
g2o::OptimizableGraph::VertexContainer points;
for (g2o::OptimizableGraph::VertexIDMap::const_iterator it = optimizer.vertices().begin(); it != optimizer.vertices().end(); ++it) {
g2o::OptimizableGraph::Vertex* v = static_cast<g2o::OptimizableGraph::Vertex*>(it->second);
if (v->dimension() == 3)
points.push_back(v);
}
structure_only_ba.calc(points, 10);
}
cout << endl;
cout << "Performing full BA:" << endl;
optimizer.optimize(10);
cout << endl;
cout << "Point error before optimisation (inliers only): " << sqrt(sum_diff2/point_num) << endl;
point_num = 0;
sum_diff2 = 0;
for (unordered_map<int,int>::iterator it=pointid_2_trueid.begin();
it!=pointid_2_trueid.end(); ++it)
{
g2o::HyperGraph::VertexIDMap::iterator v_it
= optimizer.vertices().find(it->first);
if (v_it==optimizer.vertices().end())
{
cerr << "Vertex " << it->first << " not in graph!" << endl;
exit(-1);
}
g2o::VertexSBAPointXYZ * v_p
= dynamic_cast< g2o::VertexSBAPointXYZ * > (v_it->second);
if (v_p==0)
{
cerr << "Vertex " << it->first << "is not a PointXYZ!" << endl;
exit(-1);
}
Vector3d diff = v_p->estimate()-true_points[it->second];
if (inliers.find(it->first)==inliers.end())
continue;
sum_diff2 += diff.dot(diff);
++point_num;
}
cout << "Point error after optimisation (inliers only): " << sqrt(sum_diff2/point_num) << endl;
cout << endl;
}
|
/*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014-2021 *
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy of this *
* software and associated documentation files (the "Software"), to deal in the Software *
* without restriction, including without limitation the rights to use, copy, modify, *
* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to *
* permit persons to whom the Software is furnished to do so, subject to the following *
* conditions: *
* *
* The above copyright notice and this permission notice shall be included in all copies *
* or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, *
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A *
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT *
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF *
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE *
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *
****************************************************************************************/
#include <modules/imgui/include/gui.h>
#include <modules/imgui/imguimodule.h>
#include <modules/imgui/include/imgui_include.h>
#include <openspace/engine/globals.h>
#include <openspace/engine/windowdelegate.h>
#include <openspace/mission/missionmanager.h>
#include <openspace/scripting/scriptengine.h>
#include <ghoul/fmt.h>
#include <ghoul/filesystem/cachemanager.h>
#include <ghoul/filesystem/filesystem.h>
#include <ghoul/logging/logmanager.h>
#include <ghoul/opengl/ghoul_gl.h>
#include <ghoul/opengl/programobject.h>
#include <ghoul/opengl/texture.h>
#include <ghoul/opengl/textureunit.h>
#include <filesystem>
namespace {
constexpr const char* _loggerCat = "GUI";
constexpr const char* configurationFile = "imgui.ini";
constexpr const char* GuiFont = "${FONTS}/arimo/Arimo-Regular.ttf";
constexpr const float FontSize = 14.f;
char* iniFileBuffer = nullptr;
ImFont* captionFont = nullptr;
constexpr const std::array<const char*, 2> UniformNames = { "tex", "ortho" };
void addScreenSpaceRenderableLocal(std::string identifier, std::string texturePath) {
if (!std::filesystem::is_regular_file(absPath(texturePath))) {
LWARNING(fmt::format("Could not find image '{}'", texturePath));
return;
}
std::string script;
if (identifier.empty()) {
script = fmt::format(
"openspace.addScreenSpaceRenderable({{\
Type = 'ScreenSpaceImageLocal',\
TexturePath = openspace.absPath('{}')\
}});",
texturePath
);
}
else {
script = fmt::format(
"openspace.addScreenSpaceRenderable({{\
Type = 'ScreenSpaceImageLocal',\
TexturePath = openspace.absPath('{}'),\
Identifier = '{}',\
Name = '{}'\
}});",
texturePath,
identifier,
identifier
);
}
openspace::global::scriptEngine->queueScript(
script,
openspace::scripting::ScriptEngine::RemoteScripting::Yes
);
}
void addScreenSpaceRenderableOnline(std::string identifier, std::string texturePath) {
std::string script;
if (identifier.empty()) {
script = fmt::format(
"openspace.addScreenSpaceRenderable({{\
Type = 'ScreenSpaceImageOnline',\
URL = '{}'\
}});",
texturePath
);
}
else {
script = fmt::format(
"openspace.addScreenSpaceRenderable({{\
Type = 'ScreenSpaceImageOnline',\
URL = '{}',\
Identifier = '{}',\
Name = '{}'\
}});",
texturePath,
identifier,
identifier
);
}
openspace::global::scriptEngine->queueScript(
script,
openspace::scripting::ScriptEngine::RemoteScripting::Yes
);
}
constexpr openspace::properties::Property::PropertyInfo ShowHelpInfo = {
"ShowHelpText",
"Show tooltip help",
"If this value is enabled these kinds of tooltips are shown for most properties "
"explaining what impact they have on the visuals."
};
constexpr openspace::properties::Property::PropertyInfo HelpTextDelayInfo = {
"HelpTextDelay",
"Tooltip Delay (in s)",
"This value determines the delay in seconds after which the tooltip is shown."
};
} // namespace
namespace openspace::gui {
void CaptionText(const char* text) {
ImGui::PushFont(captionFont);
ImGui::Text("%s", text);
ImGui::PopFont();
}
GUI::GUI()
: GuiComponent("Main")
, _globalProperty("Global", "Global Properties")
, _sceneProperty(
"SceneProperties", "Scene Properties",
GuiPropertyComponent::UseTreeLayout::Yes
)
, _screenSpaceProperty("ScreenSpaceProperties", "ScreenSpace Properties")
, _moduleProperty("ModuleProperties", "Module Properties")
, _virtualProperty("VirtualProperties", "Virtual Properties")
, _featuredProperties(
"FeaturedProperties",
"Featured Properties",
GuiPropertyComponent::UseTreeLayout::No
)
, _showHelpText(ShowHelpInfo, true)
, _helpTextDelay(HelpTextDelayInfo, 1.0, 0.0, 10.0)
{
for (GuiComponent* comp : _components) {
addPropertySubOwner(comp);
}
_spaceTime.setEnabled(true);
{
auto showHelpTextFunc = [this]() {
for (GuiComponent* comp : _components) {
comp->setShowHelpTooltip(_showHelpText);
}
};
showHelpTextFunc();
_showHelpText.onChange(std::move(showHelpTextFunc));
addProperty(_showHelpText);
}
{
auto helpTextDelayFunc = [this](){
for (GuiComponent* comp : _components) {
comp->setShowHelpTooltipDelay(_helpTextDelay);
}
};
helpTextDelayFunc();
_helpTextDelay.onChange(std::move(helpTextDelayFunc));
addProperty(_helpTextDelay);
}
}
GUI::~GUI() {} // NOLINT
void GUI::initialize() {}
void GUI::deinitialize() {
for (ImGuiContext* ctx : _contexts) {
ImGui::DestroyContext(ctx);
}
for (GuiComponent* comp : _components) {
comp->deinitialize();
}
delete iniFileBuffer;
}
void GUI::initializeGL() {
std::filesystem::path cachedFile = FileSys.cacheManager()->cachedFilename(
configurationFile,
""
);
LDEBUG(fmt::format("Using {} as ImGUI cache location", cachedFile));
iniFileBuffer = new char[cachedFile.string().size() + 1];
#ifdef WIN32
strcpy_s(iniFileBuffer, cachedFile.string().size() + 1, cachedFile.string().c_str());
#else
strcpy(iniFileBuffer, cachedFile.c_str());
#endif
int nWindows = global::windowDelegate->nWindows();
_contexts.resize(nWindows);
for (int i = 0; i < nWindows; ++i) {
_contexts[i] = ImGui::CreateContext();
ImGui::SetCurrentContext(_contexts[i]);
ImGuiIO& io = ImGui::GetIO();
io.IniFilename = iniFileBuffer;
io.DeltaTime = 1.f / 60.f;
io.KeyMap[ImGuiKey_Tab] = static_cast<int>(Key::Tab);
io.KeyMap[ImGuiKey_LeftArrow] = static_cast<int>(Key::Left);
io.KeyMap[ImGuiKey_RightArrow] = static_cast<int>(Key::Right);
io.KeyMap[ImGuiKey_UpArrow] = static_cast<int>(Key::Up);
io.KeyMap[ImGuiKey_DownArrow] = static_cast<int>(Key::Down);
io.KeyMap[ImGuiKey_Home] = static_cast<int>(Key::Home);
io.KeyMap[ImGuiKey_End] = static_cast<int>(Key::End);
io.KeyMap[ImGuiKey_Delete] = static_cast<int>(Key::Delete);
io.KeyMap[ImGuiKey_Backspace] = static_cast<int>(Key::BackSpace);
io.KeyMap[ImGuiKey_Enter] = static_cast<int>(Key::Enter);
io.KeyMap[ImGuiKey_Escape] = static_cast<int>(Key::Escape);
io.KeyMap[ImGuiKey_A] = static_cast<int>(Key::A);
io.KeyMap[ImGuiKey_C] = static_cast<int>(Key::C);
io.KeyMap[ImGuiKey_V] = static_cast<int>(Key::V);
io.KeyMap[ImGuiKey_X] = static_cast<int>(Key::X);
io.KeyMap[ImGuiKey_Y] = static_cast<int>(Key::Y);
io.KeyMap[ImGuiKey_Z] = static_cast<int>(Key::Z);
io.Fonts->AddFontFromFileTTF(absPath(GuiFont).string().c_str(), FontSize);
captionFont = io.Fonts->AddFontFromFileTTF(
absPath(GuiFont).string().c_str(),
FontSize * 1.5f
);
ImGuiStyle& style = ImGui::GetStyle();
style.WindowPadding = { 4.f, 4.f };
style.WindowRounding = 0.f;
style.FramePadding = { 3.f, 3.f };
style.FrameRounding = 0.f;
style.ItemSpacing = { 3.f, 2.f };
style.ItemInnerSpacing = { 3.f, 2.f };
style.TouchExtraPadding = { 1.f, 1.f };
style.IndentSpacing = 15.f;
style.ScrollbarSize = 10.f;
style.ScrollbarRounding = 0.f;
style.GrabMinSize = 10.f;
style.GrabRounding = 16.f;
style.Colors[ImGuiCol_Text] = ImVec4(0.90f, 0.90f, 0.90f, 1.00f);
style.Colors[ImGuiCol_TextDisabled] = ImVec4(0.60f, 0.60f, 0.60f, 1.00f);
style.Colors[ImGuiCol_WindowBg] = ImVec4(0.13f, 0.13f, 0.13f, 0.96f);
style.Colors[ImGuiCol_ChildBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f);
style.Colors[ImGuiCol_PopupBg] = ImVec4(0.05f, 0.05f, 0.10f, 0.90f);
style.Colors[ImGuiCol_Border] = ImVec4(0.65f, 0.65f, 0.65f, 0.59f);
style.Colors[ImGuiCol_BorderShadow] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f);
style.Colors[ImGuiCol_FrameBg] = ImVec4(0.80f, 0.80f, 0.80f, 0.30f);
style.Colors[ImGuiCol_FrameBgHovered] = ImVec4(0.91f, 0.94f, 0.99f, 0.40f);
style.Colors[ImGuiCol_FrameBgActive] = ImVec4(0.90f, 0.90f, 0.90f, 0.45f);
style.Colors[ImGuiCol_TitleBg] = ImVec4(0.71f, 0.81f, 1.00f, 0.45f);
style.Colors[ImGuiCol_TitleBgCollapsed] = ImVec4(0.71f, 0.81f, 1.00f, 0.45f);
style.Colors[ImGuiCol_TitleBgActive] = ImVec4(0.51f, 0.69f, 1.00f, 0.63f);
style.Colors[ImGuiCol_MenuBarBg] = ImVec4(0.26f, 0.27f, 0.33f, 0.80f);
style.Colors[ImGuiCol_ScrollbarBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f);
style.Colors[ImGuiCol_ScrollbarGrab] = ImVec4(0.40f, 0.75f, 0.80f, 0.43f);
style.Colors[ImGuiCol_ScrollbarGrabHovered] = ImVec4(0.40f, 0.75f, 0.80f, 0.65f);
style.Colors[ImGuiCol_ScrollbarGrabActive] = ImVec4(0.40f, 0.75f, 0.80f, 0.65f);
style.Colors[ImGuiCol_CheckMark] = ImVec4(1.00f, 1.00f, 1.00f, 0.50f);
style.Colors[ImGuiCol_SliderGrab] = ImVec4(1.00f, 1.00f, 1.00f, 0.30f);
style.Colors[ImGuiCol_SliderGrabActive] = ImVec4(0.50f, 0.80f, 0.76f, 1.00f);
style.Colors[ImGuiCol_Button] = ImVec4(0.36f, 0.54f, 0.68f, 0.62f);
style.Colors[ImGuiCol_ButtonHovered] = ImVec4(0.36f, 0.54f, 0.68f, 1.00f);
style.Colors[ImGuiCol_ButtonActive] = ImVec4(0.36f, 0.61f, 0.81f, 1.00f);
style.Colors[ImGuiCol_Header] = ImVec4(0.69f, 0.69f, 0.69f, 0.45f);
style.Colors[ImGuiCol_HeaderHovered] = ImVec4(0.36f, 0.54f, 0.68f, 0.62f);
style.Colors[ImGuiCol_HeaderActive] = ImVec4(0.53f, 0.63f, 0.87f, 0.80f);
style.Colors[ImGuiCol_Separator] = ImVec4(0.50f, 0.50f, 0.50f, 1.00f);
style.Colors[ImGuiCol_SeparatorHovered] = ImVec4(0.70f, 0.60f, 0.60f, 1.00f);
style.Colors[ImGuiCol_SeparatorActive] = ImVec4(0.90f, 0.70f, 0.70f, 1.00f);
style.Colors[ImGuiCol_ResizeGrip] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f);
style.Colors[ImGuiCol_ResizeGripHovered] = ImVec4(1.00f, 1.00f, 1.00f, 0.60f);
style.Colors[ImGuiCol_ResizeGripActive] = ImVec4(1.00f, 1.00f, 1.00f, 0.90f);
style.Colors[ImGuiCol_PlotLines] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f);
style.Colors[ImGuiCol_PlotLinesHovered] = ImVec4(0.90f, 0.70f, 0.00f, 1.00f);
style.Colors[ImGuiCol_PlotHistogram] = ImVec4(0.90f, 0.70f, 0.00f, 1.00f);
style.Colors[ImGuiCol_PlotHistogramHovered] = ImVec4(1.00f, 0.60f, 0.00f, 1.00f);
style.Colors[ImGuiCol_TextSelectedBg] = ImVec4(0.44f, 0.63f, 1.00f, 0.35f);
style.Colors[ImGuiCol_ModalWindowDimBg] = ImVec4(0.20f, 0.20f, 0.20f, 0.35f);
}
for (GuiComponent* comp : _components) {
comp->initialize();
}
_sceneProperty.setHasRegularProperties(true);
_screenSpaceProperty.setHasRegularProperties(true);
_globalProperty.setHasRegularProperties(true);
_moduleProperty.setHasRegularProperties(true);
_featuredProperties.setHasRegularProperties(true);
_program = ghoul::opengl::ProgramObject::Build(
"GUI",
absPath("${MODULE_IMGUI}/shaders/gui_vs.glsl"),
absPath("${MODULE_IMGUI}/shaders/gui_fs.glsl")
);
ghoul::opengl::updateUniformLocations(*_program, _uniformCache, UniformNames);
{
unsigned char* texData;
glm::ivec2 texSize = glm::ivec2(0);
for (int i = 0; i < nWindows; ++i) {
//_contexts[i] = ImGui::CreateContext();
ImGui::SetCurrentContext(_contexts[i]);
ImGui::GetIO().Fonts->GetTexDataAsRGBA32(&texData, &texSize.x, &texSize.y);
}
_fontTexture = std::make_unique<ghoul::opengl::Texture>(
texData,
glm::uvec3(texSize.x, texSize.y, 1)
);
_fontTexture->setName("Gui Text");
_fontTexture->setDataOwnership(ghoul::opengl::Texture::TakeOwnership::No);
_fontTexture->uploadTexture();
}
for (int i = 0; i < nWindows; ++i) {
uintptr_t texture = static_cast<GLuint>(*_fontTexture);
ImGui::SetCurrentContext(_contexts[i]);
ImGui::GetIO().Fonts->TexID = reinterpret_cast<void*>(texture);
}
glGenBuffers(1, &vbo);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, 0, nullptr, GL_DYNAMIC_DRAW);
glGenBuffers(1, &vboElements);
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
GLuint positionAttrib = _program->attributeLocation("in_position");
GLuint uvAttrib = _program->attributeLocation("in_uv");
GLuint colorAttrib = _program->attributeLocation("in_color");
glEnableVertexAttribArray(positionAttrib);
glVertexAttribPointer(
positionAttrib,
2,
GL_FLOAT,
GL_FALSE,
sizeof(ImDrawVert),
nullptr
);
glEnableVertexAttribArray(uvAttrib);
glVertexAttribPointer(
uvAttrib,
2,
GL_FLOAT,
GL_FALSE,
sizeof(ImDrawVert),
reinterpret_cast<GLvoid*>(offsetof(ImDrawVert, uv)) // NOLINT
);
glEnableVertexAttribArray(colorAttrib);
glVertexAttribPointer(
colorAttrib,
4,
GL_UNSIGNED_BYTE,
GL_TRUE,
sizeof(ImDrawVert),
reinterpret_cast<GLvoid*>(offsetof(ImDrawVert, col)) // NOLINT
);
glBindVertexArray(0);
for (GuiComponent* comp : _components) {
comp->initializeGL();
}
}
void GUI::deinitializeGL() {
_program = nullptr;
_fontTexture = nullptr;
glDeleteVertexArrays(1, &vao);
glDeleteBuffers(1, &vbo);
glDeleteBuffers(1, &vboElements);
for (GuiComponent* comp : _components) {
comp->deinitializeGL();
}
}
void GUI::startFrame(float deltaTime, const glm::vec2& windowSize,
const glm::vec2& dpiScaling, const glm::vec2& mousePos,
uint32_t mouseButtonsPressed)
{
const int iWindow = global::windowDelegate->currentWindowId();
ImGui::SetCurrentContext(_contexts[iWindow]);
ImGuiIO& io = ImGui::GetIO();
io.DisplaySize = ImVec2(windowSize.x, windowSize.y);
io.DisplayFramebufferScale = ImVec2(dpiScaling.x, dpiScaling.y);
io.DeltaTime = deltaTime;
io.MousePos = ImVec2(mousePos.x, mousePos.y);
io.MouseDown[0] = mouseButtonsPressed & (1 << 0);
io.MouseDown[1] = mouseButtonsPressed & (1 << 1);
ImGui::NewFrame();
}
void GUI::endFrame() {
if (_program->isDirty()) {
_program->rebuildFromFile();
ghoul::opengl::updateUniformLocations(*_program, _uniformCache, UniformNames);
}
if (_isEnabled) {
render();
for (GuiComponent* comp : _components) {
if (comp->isEnabled()) {
comp->render();
}
}
}
ImGui::Render();
if (!_isEnabled) {
return;
}
// Drawing
ImDrawData* drawData = ImGui::GetDrawData();
// Avoid rendering when minimized, scale coordinates for retina displays
// (screen coordinates != framebuffer coordinates)
ImGuiIO& io = ImGui::GetIO();
GLsizei fb_width = static_cast<GLsizei>(
io.DisplaySize.x * io.DisplayFramebufferScale.x
);
GLsizei fb_height = static_cast<GLsizei>(
io.DisplaySize.y * io.DisplayFramebufferScale.y
);
if (fb_width == 0 || fb_height == 0) {
return;
}
drawData->ScaleClipRects(io.DisplayFramebufferScale);
// Setup render state:
// alpha-blending enabled, no face culling, no depth testing, scissor enabled
glEnable(GL_BLEND);
glBlendEquation(GL_FUNC_ADD);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glDisable(GL_CULL_FACE);
glDisable(GL_DEPTH_TEST);
glEnable(GL_SCISSOR_TEST);
ghoul::opengl::TextureUnit unit;
unit.activate();
_fontTexture->bind();
// Setup orthographic projection matrix
const float width = ImGui::GetIO().DisplaySize.x;
const float height = ImGui::GetIO().DisplaySize.y;
glViewport(0, 0, fb_width, fb_height);
const glm::mat4 ortho(
2.f / width, 0.0f, 0.0f, 0.f,
0.0f, 2.0f / -height, 0.0f, 0.f,
0.0f, 0.0f, -1.0f, 0.0f,
-1.0f, 1.0f, 0.0f, 1.0f
);
_program->activate();
_program->setUniform(_uniformCache.tex, unit);
_program->setUniform(_uniformCache.ortho, ortho);
glBindVertexArray(vao);
for (int i = 0; i < drawData->CmdListsCount; ++i) {
const ImDrawList* cmdList = drawData->CmdLists[i];
const ImDrawIdx* indexBufferOffset = nullptr;
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(
GL_ARRAY_BUFFER,
cmdList->VtxBuffer.size() * sizeof(ImDrawVert),
reinterpret_cast<const GLvoid*>(&cmdList->VtxBuffer.front()),
GL_STREAM_DRAW
);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vboElements);
glBufferData(
GL_ELEMENT_ARRAY_BUFFER,
cmdList->IdxBuffer.size() * sizeof(ImDrawIdx),
reinterpret_cast<const GLvoid*>(&cmdList->IdxBuffer.front()),
GL_STREAM_DRAW
);
for (const ImDrawCmd* pcmd = cmdList->CmdBuffer.begin();
pcmd != cmdList->CmdBuffer.end();
pcmd++)
{
if (pcmd->UserCallback) {
pcmd->UserCallback(cmdList, pcmd);
}
else {
glBindTexture(
GL_TEXTURE_2D,
static_cast<GLuint>(reinterpret_cast<intptr_t>(pcmd->TextureId))
);
glScissor(
static_cast<int>(pcmd->ClipRect.x),
static_cast<int>(fb_height - pcmd->ClipRect.w),
static_cast<int>(pcmd->ClipRect.z - pcmd->ClipRect.x),
static_cast<int>(pcmd->ClipRect.w - pcmd->ClipRect.y)
);
glDrawElements(
GL_TRIANGLES,
static_cast<GLsizei>(pcmd->ElemCount),
sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT,
indexBufferOffset
);
}
indexBufferOffset += pcmd->ElemCount;
}
}
glBindVertexArray(0);
_program->deactivate();
glDisable(GL_SCISSOR_TEST);
}
bool GUI::mouseButtonCallback(MouseButton, MouseAction) {
ImGuiIO& io = ImGui::GetIO();
bool consumeEvent = io.WantCaptureMouse;
return consumeEvent;
}
bool GUI::mouseWheelCallback(double position) {
ImGuiIO& io = ImGui::GetIO();
bool consumeEvent = io.WantCaptureMouse;
if (consumeEvent) {
io.MouseWheel = static_cast<float>(position);
}
return consumeEvent;
}
bool GUI::keyCallback(Key key, KeyModifier modifier, KeyAction action) {
const int keyIndex = static_cast<int>(key);
if (keyIndex < 0) {
return false;
}
const bool hasShift = hasKeyModifier(modifier, KeyModifier::Shift);
const bool hasCtrl = hasKeyModifier(modifier, KeyModifier::Control);
const bool hasAlt = hasKeyModifier(modifier, KeyModifier::Alt);
ImGuiIO& io = ImGui::GetIO();
const bool consumeEvent = io.WantCaptureKeyboard;
if (consumeEvent) {
if (action == KeyAction::Press) {
io.KeysDown[keyIndex] = true;
}
io.KeyShift = hasShift;
io.KeyCtrl = hasCtrl;
io.KeyAlt = hasAlt;
}
// Even if the event is not consumed,
// set keys and modifiers to false when they are released.
if (action == KeyAction::Release) {
io.KeysDown[keyIndex] = false;
}
if (!hasShift) {
io.KeyShift = false;
}
if (!hasCtrl) {
io.KeyCtrl = false;
}
if (!hasAlt) {
io.KeyAlt = false;
}
return consumeEvent;
}
bool GUI::charCallback(unsigned int character, KeyModifier) {
ImGuiIO& io = ImGui::GetIO();
bool consumeEvent = io.WantCaptureKeyboard;
if (consumeEvent) {
io.AddInputCharacter(static_cast<unsigned short>(character));
}
return consumeEvent;
}
bool GUI::touchDetectedCallback(TouchInput input) {
ImGuiIO& io = ImGui::GetIO();
const glm::vec2 windowPos = input.currentWindowCoordinates();
const bool consumeEvent = io.WantCaptureMouse;
if (!consumeEvent) {
return false;
}
if (_validTouchStates.empty()) {
io.MousePos = {windowPos.x, windowPos.y};
io.MouseClicked[0] = true;
}
_validTouchStates.push_back(input);
return true;
}
bool GUI::touchUpdatedCallback(TouchInput input) {
if (_validTouchStates.empty()) {
return false;
}
ImGuiIO& io = ImGui::GetIO();
auto it = std::find_if(
_validTouchStates.cbegin(),
_validTouchStates.cend(),
[&](const TouchInput& state){
return state.fingerId == input.fingerId &&
state.touchDeviceId == input.touchDeviceId;
}
);
if (it == _validTouchStates.cbegin()) {
glm::vec2 windowPos = input.currentWindowCoordinates();
io.MousePos = {windowPos.x, windowPos.y};
io.MouseClicked[0] = true;
return true;
}
else if (it != _validTouchStates.cend()){
return true;
}
return false;
}
void GUI::touchExitCallback(TouchInput input) {
if (_validTouchStates.empty()) {
return;
}
const auto found = std::find_if(
_validTouchStates.cbegin(),
_validTouchStates.cend(),
[&](const TouchInput& state){
return state.fingerId == input.fingerId &&
state.touchDeviceId == input.touchDeviceId;
}
);
if (found == _validTouchStates.cend()) {
return;
}
ImGuiIO& io = ImGui::GetIO();
_validTouchStates.erase(found);
if (_validTouchStates.empty()) {
glm::vec2 windowPos = input.currentWindowCoordinates();
io.MousePos = {windowPos.x, windowPos.y};
io.MouseClicked[0] = false;
}
}
void GUI::render() {
ImGui::SetNextWindowCollapsed(_isCollapsed);
ImGui::Begin("OpenSpace GUI", nullptr);
_isCollapsed = ImGui::IsWindowCollapsed();
for (GuiComponent* comp : _components) {
bool enabled = comp->isEnabled();
ImGui::Checkbox(comp->guiName().c_str(), &enabled);
comp->setEnabled(enabled);
}
renderAndUpdatePropertyVisibility();
static const int addImageBufferSize = 256;
static char identifierBuffer[addImageBufferSize];
static char addImageLocalBuffer[addImageBufferSize];
static char addImageOnlineBuffer[addImageBufferSize];
ImGui::InputText(
"Identifier for Local/Online Images",
identifierBuffer,
addImageBufferSize
);
bool addImageLocal = ImGui::InputText(
"Add Local Image",
addImageLocalBuffer,
addImageBufferSize,
ImGuiInputTextFlags_EnterReturnsTrue
);
if (addImageLocal) {
addScreenSpaceRenderableLocal(
std::string(identifierBuffer),
std::string(addImageLocalBuffer)
);
}
bool addImageOnline = ImGui::InputText(
"Add Online Image",
addImageOnlineBuffer,
addImageBufferSize,
ImGuiInputTextFlags_EnterReturnsTrue
);
if (addImageOnline) {
addScreenSpaceRenderableOnline(
std::string(identifierBuffer),
std::string(addImageOnlineBuffer)
);
}
bool addDashboard = ImGui::Button("Add New Dashboard");
if (addDashboard) {
global::scriptEngine->queueScript(
"openspace.addScreenSpaceRenderable({ Type = 'ScreenSpaceDashboard' });",
openspace::scripting::ScriptEngine::RemoteScripting::Yes
);
}
bool addDashboardCopy = ImGui::Button("Add Copy of Main Dashboard");
if (addDashboardCopy) {
global::scriptEngine->queueScript(
"openspace.addScreenSpaceRenderable({ "
"Type = 'ScreenSpaceDashboard', UseMainDashboard = true "
"});",
openspace::scripting::ScriptEngine::RemoteScripting::Yes
);
}
#ifdef SHOW_IMGUI_HELPERS
ImGui::Checkbox("ImGUI Internals", &_showInternals);
if (_showInternals) {
ImGui::Begin("Style Editor");
ImGui::ShowStyleEditor();
ImGui::End();
ImGui::Begin("Test Window");
ImGui::ShowDemoWindow();
ImGui::End();
ImGui::Begin("Metrics Window");
ImGui::ShowMetricsWindow();
ImGui::End();
}
#endif
ImGui::End();
}
void GUI::renderAndUpdatePropertyVisibility() {
// Fragile! Keep this in sync with properties::Property::Visibility
using V = properties::Property::Visibility;
int t = static_cast<std::underlying_type_t<V>>(_currentVisibility);
// Array is sorted by importance
std::array<const char*, 4> items = { "User", "Developer", "Hidden", "All"};
ImGui::Combo("PropertyVisibility", &t, items.data(), static_cast<int>(items.size()));
_currentVisibility = static_cast<V>(t);
_globalProperty.setVisibility(_currentVisibility);
_moduleProperty.setVisibility(_currentVisibility);
_sceneProperty.setVisibility(_currentVisibility);
_screenSpaceProperty.setVisibility(_currentVisibility);
_virtualProperty.setVisibility(_currentVisibility);
_featuredProperties.setVisibility(_currentVisibility);
}
} // namespace openspace::gui
|
/*!
* Copyright (c) 2020 by Contributors
* \file array/cpu/array_nonzero.cc
* \brief Array nonzero CPU implementation
*/
#include <dgl/array.h>
namespace dgl {
using runtime::NDArray;
namespace aten {
namespace impl {
template <DLDeviceType XPU, typename IdType>
IdArray NonZero(IdArray array) {
std::vector<int64_t> ret;
const IdType* data = array.Ptr<IdType>();
for (int64_t i = 0; i < array->shape[0]; ++i)
if (data[i] != 0)
ret.push_back(i);
return NDArray::FromVector(ret, array->ctx);
}
template IdArray NonZero<kDLCPU, int32_t>(IdArray);
template IdArray NonZero<kDLCPU, int64_t>(IdArray);
} // namespace impl
} // namespace aten
} // namespace dgl
|
// MIT License
// Copyright (c) 2018 Neutralinojs
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#include <iostream>
#include <fstream>
#include "lib/json.hpp"
#include <windows.h>
using namespace std;
using json = nlohmann::json;
namespace fs {
string createDirectory(string jso) {
json input;
json output;
try {
input = json::parse(jso);
}
catch(exception e){
output["error"] = "JSON parse error is occurred!";
return output.dump();
}
string filename = input["dir"];
if(CreateDirectory(filename.c_str(), NULL)){
output["success"] = true;
}
else{
output["error"] = "Cannot create " + filename;
}
return output.dump();
}
string removeDirectory(string jso) {
json input;
json output;
try {
input = json::parse(jso);
}
catch(exception e){
output["error"] = "JSON parse error is occurred!";
return output.dump();
}
string dir = input["dir"];
if(RemoveDirectory(dir.c_str())){
output["success"] = true;
}
else{
output["error"] = "Cannot remove " + dir;
}
return output.dump();
}
string readFile(string jso) {
json input;
json output;
try {
input = json::parse(jso);
}
catch(exception e){
output["error"] = "JSON parse error is occurred!";
return output.dump();
}
string filename = input["filename"];
ifstream t;
t.open(filename);
if(!t.is_open())
return "";
string buffer = "";
string line;
while(!t.eof()){
getline(t, line);
buffer += line + "\n";
}
t.close();
output["content"] = buffer;
return output.dump();
}
string writeFile(string jso) {
json input;
json output;
try {
input = json::parse(jso);
}
catch(exception e){
output["error"] = "JSON parse error is occurred!";
return output.dump();
}
string filename = input["filename"];
string content = input["content"];
ofstream t(filename);
t << content;
t.close();
output["success"] = true;
return output.dump();
}
string removeFile(string jso) {
json input;
json output;
try {
input = json::parse(jso);
}
catch(exception e){
output["error"] = "JSON parse error is occurred!";
return output.dump();
}
string filename = input["filename"];
if(DeleteFile(filename.c_str())){
output["success"] = true;
}
else{
output["error"] = "Cannot remove " + filename;
}
return output.dump();
}
string readDirectory(string jso) {
json input;
json output;
try {
input = json::parse(jso);
}
catch(exception e){
output["error"] = "JSON parse error is occurred!";
return output.dump();
}
string path = input["path"];
string search_path = path + "/*.*";
WIN32_FIND_DATA fd;
HANDLE hFind = FindFirstFile(search_path.c_str(), &fd);
if(hFind != INVALID_HANDLE_VALUE) {
do {
string type = "other";
if((fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY)
type = "directory";
else if((fd.dwFileAttributes & FILE_ATTRIBUTE_ARCHIVE) == FILE_ATTRIBUTE_ARCHIVE)
type = "file";
json file = {
{"name", fd.cFileName},
{"type", type}
};
output["files"].push_back(file);
} while(FindNextFile(hFind, &fd));
FindClose(hFind);
}
return output.dump();
}
}
|
/**********************************************************************************/
/* MIT License */
/* */
/* Copyright (c) 2020, 2021 JetBrains-Research */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining a copy */
/* of this software and associated documentation files (the "Software"), to deal */
/* in the Software without restriction, including without limitation the rights */
/* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell */
/* copies of the Software, and to permit persons to whom the Software is */
/* furnished to do so, subject to the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be included in all */
/* copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR */
/* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, */
/* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE */
/* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER */
/* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, */
/* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE */
/* SOFTWARE. */
/**********************************************************************************/
#ifndef CUBOOL_ERROR_HPP
#define CUBOOL_ERROR_HPP
#include <cubool/cubool.h>
#include <exception>
#include <string>
#include <sstream>
namespace cubool {
/**
* Generic library exception.
* Use this one in particular backend implementations.
*/
class Exception: public std::exception {
public:
Exception(std::string message, std::string function, std::string file, size_t line, cuBool_Status status, bool critical)
: std::exception(),
mMessage(std::move(message)),
mFunction(std::move(function)),
mFile(std::move(file)),
mLine(line),
nStatus(status),
mCritical(critical) {
}
Exception(const Exception& e) noexcept = default;
Exception(Exception&& e) noexcept = default;
~Exception() noexcept override = default;
const char* what() const noexcept override {
if (!mCached) {
mCached = true;
std::stringstream s;
s << "\"" << getMessage() << "\" in" << std::endl
<< getFile() << ": line: " << getLine() << " function: " << getFunction();
mWhatCached = s.str();
}
return mWhatCached.c_str();
}
const std::string& getMessage() const noexcept {
return mMessage;
}
const std::string& getFunction() const noexcept {
return mFunction;
}
const std::string& getFile() const noexcept {
return mFile;
}
size_t getLine() const {
return mLine;
}
cuBool_Status getStatus() const noexcept {
return nStatus;
}
bool isCritical() const noexcept {
return mCritical;
}
private:
mutable std::string mWhatCached;
std::string mMessage;
std::string mFunction;
std::string mFile;
size_t mLine;
cuBool_Status nStatus;
bool mCritical;
mutable bool mCached = false;
};
/**
* Exceptions with cuBool_Status error code parametrisation.
* @tparam Type Exception error code (type)
*/
template<cuBool_Status Type>
class TException: public Exception {
public:
TException(std::string message, std::string&& function, std::string&& file, size_t line, bool critical)
: Exception(std::move(message), std::move(function), std::move(file), line, Type, critical) {
}
TException(const TException& other) noexcept = default;
TException(TException&& other) noexcept = default;
~TException() noexcept override = default;
};
// Errors exposed to the C API
using Error = TException<cuBool_Status::CUBOOL_STATUS_ERROR>;
using DeviceError = TException<cuBool_Status::CUBOOL_STATUS_DEVICE_ERROR>;
using DeviceNotPresent = TException<cuBool_Status::CUBOOL_STATUS_DEVICE_NOT_PRESENT>;
using MemOpFailed = TException<cuBool_Status::CUBOOL_STATUS_MEM_OP_FAILED>;
using InvalidArgument = TException<cuBool_Status::CUBOOL_STATUS_INVALID_ARGUMENT>;
using InvalidState = TException<cuBool_Status::CUBOOL_STATUS_INVALID_STATE>;
using BackendError = TException<cuBool_Status::CUBOOL_STATUS_BACKEND_ERROR>;
using NotImplemented = TException<cuBool_Status::CUBOOL_STATUS_NOT_IMPLEMENTED>;
}
// An error, in theory, can recover after this
#define RAISE_ERROR(type, message) \
do { \
throw ::cubool::type(message, __FUNCTION__, __FILE__, __LINE__, false); \
} while (0);
#define CHECK_RAISE_ERROR(condition, type, message) \
if (!(condition)) { RAISE_ERROR(type, #condition ": " message); } else { }
// Critical errors, cause library shutdown
#define RAISE_CRITICAL_ERROR(type, message) \
do { \
throw ::cubool::type(message, __FUNCTION__, __FILE__, __LINE__, true); \
} while (0);
#define CHECK_RAISE_CRITICAL_ERROR(condition, type, message) \
if (!(condition)) { RAISE_CRITICAL_ERROR(type, #condition ": " message); } else { }
#endif //CUBOOL_ERROR_HPP
|
#ifndef CLPROGRAM_HPP
#define CLPROGRAM_HPP
#include <iostream>
#include <vector>
#include <string>
#include <fstream>
#include <memory>
#include <utility>
#include <algorithm>
#define __CL_ENABLE_EXCEPTIONS
#include <CL/cl.hpp>
class CLProgram
{
public:
CLProgram(const std::string & file);
cl::Kernel & getKernel();
cl::CommandQueue & getCommandQueue();
cl::Context & getContext();
private:
std::vector<cl::Device> devices;
cl::Device device;
cl::Context context;
cl::CommandQueue queue;
cl::Program program;
cl::Kernel kernel;
};
#endif
|
// Copyright (c) 2011-2015 The Bitcoin Core developers
// Copyright (c) 2014-2017 The Hah Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "splashscreen.h"
#include "guiutil.h"
#include "networkstyle.h"
#include "clientversion.h"
#include "init.h"
#include "util.h"
#include "ui_interface.h"
#include "version.h"
#ifdef ENABLE_WALLET
#include "wallet/wallet.h"
#endif
#include <QApplication>
#include <QCloseEvent>
#include <QDesktopWidget>
#include <QPainter>
SplashScreen::SplashScreen(Qt::WindowFlags f, const NetworkStyle *networkStyle) :
QWidget(0, f), curAlignment(0)
{
// transparent background
setAttribute(Qt::WA_TranslucentBackground);
setStyleSheet("background:transparent;");
// no window decorations
setWindowFlags(Qt::FramelessWindowHint);
// set reference point, paddings
int paddingLeft = 14;
int paddingTop = 470;
int titleVersionVSpace = 17;
int titleCopyrightVSpace = 32;
float fontFactor = 1.0;
// define text to place
QString titleText = tr("Hah Core");
QString versionText = QString(tr("Version %1")).arg(QString::fromStdString(FormatFullVersion()));
QString copyrightTextBtc = QChar(0xA9)+QString(" 2009-%1 ").arg(COPYRIGHT_YEAR) + QString(tr("The Bitcoin Core developers"));
QString copyrightTextHah = QChar(0xA9)+QString(" 2014-%1 ").arg(COPYRIGHT_YEAR) + QString(tr("The Hah Core developers"));
QString titleAddText = networkStyle->getTitleAddText();
// networkstyle.cpp can't (yet) read themes, so we do it here to get the correct Splash-screen
QString splashScreenPath = ":/images/" + GUIUtil::getThemeName() + "/splash";
if(GetBoolArg("-regtest", false))
splashScreenPath = ":/images/" + GUIUtil::getThemeName() + "/splash_testnet";
if(GetBoolArg("-testnet", false))
splashScreenPath = ":/images/" + GUIUtil::getThemeName() + "/splash_testnet";
QString font = QApplication::font().toString();
// load the bitmap for writing some text over it
pixmap = QPixmap(splashScreenPath);
QPainter pixPaint(&pixmap);
pixPaint.setPen(QColor(100,100,100));
// check font size and drawing with
pixPaint.setFont(QFont(font, 28*fontFactor));
QFontMetrics fm = pixPaint.fontMetrics();
int titleTextWidth = fm.width(titleText);
if(titleTextWidth > 160) {
// strange font rendering, Arial probably not found
fontFactor = 0.75;
}
pixPaint.setFont(QFont(font, 28*fontFactor));
fm = pixPaint.fontMetrics();
titleTextWidth = fm.width(titleText);
pixPaint.drawText(paddingLeft,paddingTop,titleText);
pixPaint.setFont(QFont(font, 15*fontFactor));
pixPaint.drawText(paddingLeft,paddingTop+titleVersionVSpace,versionText);
// draw copyright stuff
pixPaint.setFont(QFont(font, 10*fontFactor));
pixPaint.drawText(paddingLeft,paddingTop+titleCopyrightVSpace,copyrightTextBtc);
pixPaint.drawText(paddingLeft,paddingTop+titleCopyrightVSpace+12,copyrightTextHah);
// draw additional text if special network
if(!titleAddText.isEmpty()) {
QFont boldFont = QFont(font, 10*fontFactor);
boldFont.setWeight(QFont::Bold);
pixPaint.setFont(boldFont);
fm = pixPaint.fontMetrics();
int titleAddTextWidth = fm.width(titleAddText);
pixPaint.drawText(pixmap.width()-titleAddTextWidth-10,pixmap.height()-25,titleAddText);
}
pixPaint.end();
// Resize window and move to center of desktop, disallow resizing
QRect r(QPoint(), pixmap.size());
resize(r.size());
setFixedSize(r.size());
move(QApplication::desktop()->screenGeometry().center() - r.center());
subscribeToCoreSignals();
installEventFilter(this);
}
SplashScreen::~SplashScreen()
{
unsubscribeFromCoreSignals();
}
bool SplashScreen::eventFilter(QObject * obj, QEvent * ev) {
if (ev->type() == QEvent::KeyPress) {
QKeyEvent *keyEvent = static_cast<QKeyEvent *>(ev);
if(keyEvent->text()[0] == 'q' && breakAction != nullptr) {
breakAction();
}
}
return QObject::eventFilter(obj, ev);
}
void SplashScreen::slotFinish(QWidget *mainWin)
{
Q_UNUSED(mainWin);
/* If the window is minimized, hide() will be ignored. */
/* Make sure we de-minimize the splashscreen window before hiding */
if (isMinimized())
showNormal();
hide();
deleteLater(); // No more need for this
}
static void InitMessage(SplashScreen *splash, const std::string &message)
{
QMetaObject::invokeMethod(splash, "showMessage",
Qt::QueuedConnection,
Q_ARG(QString, QString::fromStdString(message)),
Q_ARG(int, Qt::AlignBottom|Qt::AlignHCenter),
Q_ARG(QColor, QColor(55,55,55)));
}
static void ShowProgress(SplashScreen *splash, const std::string &title, int nProgress)
{
InitMessage(splash, title + strprintf("%d", nProgress) + "%");
}
void SplashScreen::setBreakAction(const std::function<void(void)> &action)
{
breakAction = action;
}
static void SetProgressBreakAction(SplashScreen *splash, const std::function<void(void)> &action)
{
QMetaObject::invokeMethod(splash, "setBreakAction",
Qt::QueuedConnection,
Q_ARG(std::function<void(void)>, action));
}
#ifdef ENABLE_WALLET
static void ConnectWallet(SplashScreen *splash, CWallet* wallet)
{
wallet->ShowProgress.connect(boost::bind(ShowProgress, splash, _1, _2));
}
#endif
void SplashScreen::subscribeToCoreSignals()
{
// Connect signals to client
uiInterface.InitMessage.connect(boost::bind(InitMessage, this, _1));
uiInterface.ShowProgress.connect(boost::bind(ShowProgress, this, _1, _2));
uiInterface.SetProgressBreakAction.connect(boost::bind(SetProgressBreakAction, this, _1));
#ifdef ENABLE_WALLET
uiInterface.LoadWallet.connect(boost::bind(ConnectWallet, this, _1));
#endif
}
void SplashScreen::unsubscribeFromCoreSignals()
{
// Disconnect signals from client
uiInterface.InitMessage.disconnect(boost::bind(InitMessage, this, _1));
uiInterface.ShowProgress.disconnect(boost::bind(ShowProgress, this, _1, _2));
#ifdef ENABLE_WALLET
if(pwalletMain)
pwalletMain->ShowProgress.disconnect(boost::bind(ShowProgress, this, _1, _2));
#endif
}
void SplashScreen::showMessage(const QString &message, int alignment, const QColor &color)
{
curMessage = message;
curAlignment = alignment;
curColor = color;
update();
}
void SplashScreen::paintEvent(QPaintEvent *event)
{
QPainter painter(this);
painter.drawPixmap(0, 0, pixmap);
QRect r = rect().adjusted(5, 5, -5, -5);
painter.setPen(curColor);
painter.drawText(r, curAlignment, curMessage);
}
void SplashScreen::closeEvent(QCloseEvent *event)
{
StartShutdown(); // allows an "emergency" shutdown during startup
event->ignore();
}
|
// Copyright (c) 2018 Doyub Kim
//
// I am making my contributions/submissions to this project solely in my
// personal capacity and am not conveying any rights to any intellectual
// property of any third parties.
#include "implicit_triangle_mesh.h"
#include "pybind11_utils.h"
#include <jet/implicit_triangle_mesh3.h>
namespace py = pybind11;
using namespace jet;
void addImplicitTriangleMesh3(pybind11::module& m) {
py::class_<ImplicitTriangleMesh3, ImplicitTriangleMesh3Ptr,
ImplicitSurface3>(m, "ImplicitTriangleMesh3",
R"pbdoc(
TriangleMesh3 to ImplicitSurface3 converter.
This class builds signed-distance field for given TriangleMesh3 instance so
that it can be used as an ImplicitSurface3 instance. The mesh is discretize
into a regular grid and the signed-distance is measured at each grid point.
Thus, there is a sampling error and its magnitude depends on the grid
resolution.
)pbdoc")
// CTOR
.def(py::init<TriangleMesh3Ptr, size_t, double, Transform3, bool>(),
R"pbdoc(
Constructs an ImplicitSurface3 with mesh and other grid parameters.
)pbdoc",
py::arg("mesh"), py::arg("resolutionX") = 32,
py::arg("margin") = 0.2, py::arg("transform") = Transform3(),
py::arg("isNormalFlipped") = false)
.def_property_readonly("grid", &ImplicitTriangleMesh3::grid,
R"pbdoc(The grid data.)pbdoc");
}
|
#pragma once
#if defined(_WIN32)
# define WIN32_LEAN_AND_MEAN
# define NOMINMAX
# include <Windows.h> // for FreeLibrary, GetProcAddress, HMODULE, LoadLibrary
using module_t = HMODULE;
#elif defined(__unix__)
# include <dlfcn.h> // for dlclose, dlsym, dlopen
// For cleaner syntax, match macros w/ Windows (not recommended for production as behaviors/flags can be different)
# define FreeLibrary(X) dlclose(X)
# define GetProcAddress(X, Y) dlsym(X, Y)
# define LoadLibrary(X) dlopen(X, RTLD_LOCAL | RTLD_LAZY)
using module_t = void*;
#endif
#include <rpc_adapters/rpc_njson.hpp>
#include <string>
using rpc::adapters::njson_adapter;
class RpcClient : public rpc::client::client_interface<njson_adapter>
{
public:
using remote_func_type = int (*)(char*, size_t);
~RpcClient() override
{
// Don't forget to release the module when done
if (m_module != nullptr)
{
FreeLibrary(m_module);
}
}
RpcClient(std::string module_path);
// Cannot copy a client, module could be unloaded by a copy
RpcClient(const RpcClient&) = delete;
RpcClient& operator=(const RpcClient&) = delete;
// Moving is OK, module pointer will not be unloaded
RpcClient(RpcClient&& other) noexcept
: m_module(other.m_module), m_func(other.m_func), m_result(std::move(other.m_result))
{
other.m_module = nullptr;
other.m_func = nullptr;
}
RpcClient& operator=(RpcClient&& other) & noexcept
{
m_module = other.m_module;
m_func = other.m_func;
m_result = std::move(other.m_result);
other.m_module = nullptr;
other.m_func = nullptr;
return *this;
}
private:
void send(const std::string& mesg) override;
std::string receive() override
{
// By moving, we indicate that the result is no longer valid after the function returns
return std::move(m_result);
}
module_t m_module{ nullptr };
remote_func_type m_func{ nullptr };
std::string m_result{};
};
|
/*
* Copyright 2017 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "logging/rtc_event_log/rtc_event_log_factory.h"
#include "absl/memory/memory.h"
#include "api/task_queue/global_task_queue_factory.h"
namespace webrtc {
std::unique_ptr<RtcEventLogFactoryInterface> CreateRtcEventLogFactory() {
return absl::make_unique<RtcEventLogFactory>(&GlobalTaskQueueFactory());
}
} // namespace webrtc
|
/*
Keyboard.cpp
Copyright (c) 2015, Arduino LLC
Original code (pre-library): Copyright (c) 2011, Peter Barrett
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "Keyboard.h"
#if defined(_USING_HID)
/*
#define kbd_es_es
*/
#ifdef kbd_be_be
#include "be_be.h"
#endif
#ifdef kbd_cz_cz
#include "cz_cz.h"
#endif
#ifdef kbd_da_dk
#include "da_dk.h"
#endif
#ifdef kbd_de_de
#include "de_de.h"
#endif
#ifdef kbd_es_es
#include "es_es.h"
#endif
#ifdef kbd_fi_fi
#include "fi_fi.h"
#endif
#ifdef kbd_fr_fr
#include "fr_fr.h"
#endif
#ifdef kbd_it_it
#include "it_it.h"
#endif
#ifdef kbd_pt_pt
#include "pt_pt.h"
#endif
#ifdef kbd_tr_tr
#include "tr_tr.h"
#endif
#ifndef _kbd_lang
#include "en_us.h"
#endif
//================================================================================
//================================================================================
// Keyboard
static const uint8_t _hidReportDescriptor[] PROGMEM = {
// Keyboard
0x05, 0x01, // USAGE_PAGE (Generic Desktop) // 47
0x09, 0x06, // USAGE (Keyboard)
0xa1, 0x01, // COLLECTION (Application)
0x85, 0x02, // REPORT_ID (2)
0x05, 0x07, // USAGE_PAGE (Keyboard)
0x19, 0xe0, // USAGE_MINIMUM (Keyboard LeftControl)
0x29, 0xe7, // USAGE_MAXIMUM (Keyboard Right GUI)
0x15, 0x00, // LOGICAL_MINIMUM (0)
0x25, 0x01, // LOGICAL_MAXIMUM (1)
0x75, 0x01, // REPORT_SIZE (1)
0x95, 0x08, // REPORT_COUNT (8)
0x81, 0x02, // INPUT (Data,Var,Abs)
0x95, 0x01, // REPORT_COUNT (1)
0x75, 0x08, // REPORT_SIZE (8)
0x81, 0x03, // INPUT (Cnst,Var,Abs)
0x95, 0x06, // REPORT_COUNT (6)
0x75, 0x08, // REPORT_SIZE (8)
0x15, 0x00, // LOGICAL_MINIMUM (0)
0x25, 0x65, // LOGICAL_MAXIMUM (101)
0x05, 0x07, // USAGE_PAGE (Keyboard)
0x19, 0x00, // USAGE_MINIMUM (Reserved (no event indicated))
0x29, 0x65, // USAGE_MAXIMUM (Keyboard Application)
0x81, 0x00, // INPUT (Data,Ary,Abs)
0xc0, // END_COLLECTION
};
Keyboard_::Keyboard_(void)
{
static HIDSubDescriptor node(_hidReportDescriptor, sizeof(_hidReportDescriptor));
HID().AppendDescriptor(&node);
}
void Keyboard_::begin(void)
{
}
void Keyboard_::end(void)
{
}
void Keyboard_::sendReport(KeyReport* keys)
{
HID().SendReport(2,keys,sizeof(KeyReport));
}
/*
extern
const uint8_t _asciimap[256] PROGMEM;
#define SHIFT 0x80
#define ALTGR 0x40
const uint8_t _asciimap[256] =
{
0x00, // NUL
0x00, // SOH
0x00, // STX
0x00, // ETX
0x00, // EOT
0x00, // ENQ
0x00, // ACK
0x00, // BEL
0x2a, // BS Backspace
0x2b, // TAB Tab
0x28, // LF Enter
0x00, // VT
0x00, // FF
0x00, // CR
0x00, // SO
0x00, // SI
0x00, // DEL
0x00, // DC1
0x00, // DC2
0x00, // DC3
0x00, // DC4
0x00, // NAK
0x00, // SYN
0x00, // ETB
0x00, // CAN
0x00, // EM
0x00, // SUB
0x00, // ESC
0x00, // FS
0x00, // GS
0x00, // RS
0x00, // US
0x2c, // ' ' (space)
0x1e|SHIFT, // !
0x1f|SHIFT, // "
0x20|ALTGR, // #
0x21|SHIFT, // $
0x22|SHIFT, // %
0x23|SHIFT, // &
0x2d, // '
0x25|SHIFT, // (
0x26|SHIFT, // )
0x30|SHIFT, // *
0x30, // +
0x36, // ,
0x38, // -
0x37, // .
0x24|SHIFT, // /
0x27, // 0
0x1e, // 1
0x1f, // 2
0x20, // 3
0x21, // 4
0x22, // 5
0x23, // 6
0x24, // 7
0x25, // 8
0x26, // 9
0x37|SHIFT, // :
0x36|SHIFT, // ;
0x03, // < //KEY_NON_US_100
0x27|SHIFT, // =
0x03|SHIFT, // > //KEY_NON_US_100 + SHIFT
0x2d|SHIFT, // ?
0x1f|ALTGR, // @
0x04|SHIFT, // A
0x05|SHIFT, // B
0x06|SHIFT, // C
0x07|SHIFT, // D
0x08|SHIFT, // E
0x09|SHIFT, // F
0x0a|SHIFT, // G
0x0b|SHIFT, // H
0x0c|SHIFT, // I
0x0d|SHIFT, // J
0x0e|SHIFT, // K
0x0f|SHIFT, // L
0x10|SHIFT, // M
0x11|SHIFT, // N
0x12|SHIFT, // O
0x13|SHIFT, // P
0x14|SHIFT, // Q
0x15|SHIFT, // R
0x16|SHIFT, // S
0x17|SHIFT, // T
0x18|SHIFT, // U
0x19|SHIFT, // V
0x1a|SHIFT, // W
0x1b|SHIFT, // X
0x1c|SHIFT, // Y
0x1d|SHIFT, // Z
0x2f|ALTGR, // [
0x35, // bslash
0x30|ALTGR, // ]
0x2f|SHIFT, // ^
0x38|SHIFT, // _
0x2f, // `
0x04, // a
0x05, // b
0x06, // c
0x07, // d
0x08, // e
0x09, // f
0x0a, // g
0x0b, // h
0x0c, // i
0x0d, // j
0x0e, // k
0x0f, // l
0x10, // m
0x11, // n
0x12, // o
0x13, // p
0x14, // q
0x15, // r
0x16, // s
0x17, // t
0x18, // u
0x19, // v
0x1a, // w
0x1b, // x
0x1c, // y
0x1d, // z
0x34|ALTGR, // {
0x1e|ALTGR, // |
0x32|ALTGR, // }
0x21|ALTGR, // ~
0x00, // DEL
0x00, // Ç Start extended ASCII
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00, // ç
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x33, // ñ
0x33|SHIFT, // Ñ
0x00,
0x00,
0x2e|SHIFT, // ¿
0x00,
0x00,
0x00,
0x00,
0x2e, // ¡
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
};
*/
/*
// Init var
bool _altGrMap[128];
bool _altFine = false;
// Individually define all needed char
void initAltGr() {
_altFine = true;
_altGrMap[126] = true; // ~
_altGrMap[123] = true; // {
_altGrMap[91] = true; // [
_altGrMap[93] = true; // ]
_altGrMap[125] = true; // }
_altGrMap[92] = true; // bslash
_altGrMap[124] = true; // |
_altGrMap[64] = true; // @
_altGrMap[35] = true; // #
}
*/
uint8_t USBPutChar(uint8_t c);
// press() adds the specified key (printing, non-printing, or modifier)
// to the persistent key report and sends the report. Because of the way
// USB HID works, the host acts like the key remains pressed until we
// call release(), releaseAll(), or otherwise clear the report and resend.
size_t Keyboard_::press(uint8_t k)
{
uint8_t i;
if(k>=0xB0 && k<=0xDA){ //it's a non-printing key
k = k - 136;
}
else {
if(k>=0x80 && k<=0x87){ //it's a modifier
_keyReport.modifiers |= (1<<(k-128));
k = 0;
}
else{ //it's a printable key
k = pgm_read_byte(_asciimap + k);
if (k & 0x80) { // it's a capital letter or other character reached with shift
_keyReport.modifiers |= 0x02; // the left shift modifier
k &= 0x7F;
}
if (k & 0x40) { // altgr modifier (RIGHT_ALT)
_keyReport.modifiers |= 0x40; // the left shift modifier
k &= 0x3F;
}
if (k == 0x03) { // special case 0x64
k = 0x64;
}
}
}
// Add k to the key report only if it's not already present
// and if there is an empty slot.
if (_keyReport.keys[0] != k && _keyReport.keys[1] != k &&
_keyReport.keys[2] != k && _keyReport.keys[3] != k &&
_keyReport.keys[4] != k && _keyReport.keys[5] != k) {
for (i=0; i<6; i++) {
if (_keyReport.keys[i] == 0x00) {
_keyReport.keys[i] = k;
break;
}
}
if (i == 6) {
setWriteError();
return 0;
}
}
sendReport(&_keyReport);
return 1;
}
// release() takes the specified key out of the persistent key report and
// sends the report. This tells the OS the key is no longer pressed and that
// it shouldn't be repeated any more.
size_t Keyboard_::release(uint8_t k)
{
uint8_t i;
if(k>=0xB0 && k<=0xDA){ //it's a non-printing key
k = k - 136;
}
else {
if(k>=0x80 && k<=0x87){ //it's a modifier
_keyReport.modifiers &= ~(1<<(k-128));
k = 0;
}
else{ //it's a printable key
k = pgm_read_byte(_asciimap + k);
if (k & 0x80) { // it's a capital letter or other character reached with shift
_keyReport.modifiers &= ~(0x02); // the left shift modifier
k &= 0x7F;
}
if (k & 0x40) {
_keyReport.modifiers &= ~(0x40); // the altgr shift modifier
k &= 0x3F;
}
if (k == 0x03) { // special case 0x64
k = 0x64;
}
if (k >= 136) { // it's a non-printing key (not a modifier)
k = k - 136;
}
}
}
// Test the key report to see if k is present. Clear it if it exists.
// Check all positions in case the key is present more than once (which it shouldn't be)
for (i=0; i<6; i++) {
if (0 != k && _keyReport.keys[i] == k) {
_keyReport.keys[i] = 0x00;
}
}
sendReport(&_keyReport);
return 1;
}
void Keyboard_::releaseAll(void)
{
_keyReport.keys[0] = 0;
_keyReport.keys[1] = 0;
_keyReport.keys[2] = 0;
_keyReport.keys[3] = 0;
_keyReport.keys[4] = 0;
_keyReport.keys[5] = 0;
_keyReport.modifiers = 0;
sendReport(&_keyReport);
}
size_t Keyboard_::write(uint8_t c)
{
uint8_t p = press(c); // Keydown
release(c); // Keyup
return p; // just return the result of press() since release() almost always returns 1
}
Keyboard_ Keyboard;
#endif
|
/*
-- MAGMA (version 2.5.4) --
Univ. of Tennessee, Knoxville
Univ. of California, Berkeley
Univ. of Colorado, Denver
@date October 2020
@author Mark Gates
@generated from src/cblas_z.cpp, normal z -> c, Thu Oct 8 23:05:22 2020
Wrappers around a few CBLAS functions.
Primarily, we use the standard Fortran BLAS interface in MAGMA. However,
functions that return a value (as opposed to subroutines that are void)
are not portable, as they depend on how Fortran returns values. The routines
here provide a portable interface. These are not identical to CBLAS, in
particular, [cz]dot[uc] return complex numbers (as in Fortran BLAS) rather
than return values via an argument.
Only these BLAS-1 functions are provided:
magma_cblas_scasum / dasum
magma_cblas_scnrm2 / dnrm2
magma_cblas_cdotc / ddot
magma_cblas_cdotu / ddot
*/
#include "magma_internal.h"
#define COMPLEX
/***************************************************************************//**
@return Sum of absolute values of vector x;
\f$ \sum_i | real(x_i) | + | imag(x_i) | \f$.
To avoid dependence on CBLAS and incompatability issues between BLAS
libraries, MAGMA uses its own implementation, following BLAS reference.
@param[in]
n Number of elements in vector x. n >= 0.
@param[in]
x COMPLEX array on CPU host.
The n element vector x of dimension (1 + (n-1)*incx).
@param[in]
incx Stride between consecutive elements of x. incx > 0.
@ingroup magma_asum
*******************************************************************************/
extern "C"
float magma_cblas_scasum(
magma_int_t n,
const magmaFloatComplex *x, magma_int_t incx )
{
if ( n <= 0 || incx <= 0 ) {
return 0;
}
float result = 0;
if ( incx == 1 ) {
for( magma_int_t i=0; i < n; ++i ) {
result += MAGMA_C_ABS1( x[i] );
}
}
else {
magma_int_t nincx = n*incx;
for( magma_int_t i=0; i < nincx; i += incx ) {
result += MAGMA_C_ABS1( x[i] );
}
}
return result;
}
static inline float sqr( float x ) { return x*x; }
/***************************************************************************//**
Returns 2-norm of vector x. Avoids unnecesary over/underflow.
To avoid dependence on CBLAS and incompatability issues between BLAS
libraries, MAGMA uses its own implementation, following BLAS reference.
@param[in]
n Number of elements in vector x. n >= 0.
@param[in]
x COMPLEX array on CPU host.
The n element vector x of dimension (1 + (n-1)*incx).
@param[in]
incx Stride between consecutive elements of x. incx > 0.
@ingroup magma_nrm2
*******************************************************************************/
extern "C"
float magma_cblas_scnrm2(
magma_int_t n,
const magmaFloatComplex *x, magma_int_t incx )
{
if (n <= 0 || incx <= 0) {
return 0;
}
else {
float scale = 0;
float ssq = 1;
// the following loop is equivalent to this call to the lapack
// auxiliary routine:
// call zlassq( n, x, incx, scale, ssq )
for( magma_int_t ix=0; ix < 1 + (n-1)*incx; ix += incx ) {
if ( real( x[ix] ) != 0 ) {
float temp = fabs( real( x[ix] ));
if (scale < temp) {
ssq = 1 + ssq * sqr(scale/temp);
scale = temp;
}
else {
ssq += sqr(temp/scale);
}
}
#ifdef COMPLEX
if ( imag( x[ix] ) != 0 ) {
float temp = fabs( imag( x[ix] ));
if (scale < temp) {
ssq = 1 + ssq * sqr(scale/temp);
scale = temp;
}
else {
ssq += sqr(temp/scale);
}
}
#endif
}
return scale*magma_ssqrt(ssq);
}
}
#ifdef COMPLEX
/***************************************************************************//**
Returns dot product of vectors x and y; \f$ x^H y \f$.
To avoid dependence on CBLAS and incompatability issues between BLAS
libraries, MAGMA uses its own implementation, following BLAS reference.
@param[in]
n Number of elements in vector x and y. n >= 0.
@param[in]
x COMPLEX array on CPU host.
The n element vector x of dimension (1 + (n-1)*incx).
@param[in]
incx Stride between consecutive elements of x. incx > 0.
@param[in]
y COMPLEX array on CPU host.
The n element vector y of dimension (1 + (n-1)*incy).
@param[in]
incy Stride between consecutive elements of dy. incy > 0.
@ingroup magma__dot
*******************************************************************************/
extern "C"
magmaFloatComplex magma_cblas_cdotc(
magma_int_t n,
const magmaFloatComplex *x, magma_int_t incx,
const magmaFloatComplex *y, magma_int_t incy )
{
// after too many issues with MKL and other BLAS, just write our own dot product!
magmaFloatComplex value = MAGMA_C_ZERO;
magma_int_t i;
if ( incx == 1 && incy == 1 ) {
for( i=0; i < n; ++i ) {
value += conj( x[i] ) * y[i];
}
}
else {
magma_int_t ix=0, iy=0;
if ( incx < 0 ) { ix = (-n + 1)*incx; }
if ( incy < 0 ) { iy = (-n + 1)*incy; }
for( i=0; i < n; ++i ) {
value += conj( x[ix] ) * y[iy];
ix += incx;
iy += incy;
}
}
return value;
}
#endif // COMPLEX
/***************************************************************************//**
@return dot product (unconjugated) of vectors x and y; \f$ x^T y \f$.
To avoid dependence on CBLAS and incompatability issues between BLAS
libraries, MAGMA uses its own implementation, following BLAS reference.
@param[in]
n Number of elements in vector x and y. n >= 0.
@param[in]
x COMPLEX array on CPU host.
The n element vector x of dimension (1 + (n-1)*incx).
@param[in]
incx Stride between consecutive elements of x. incx > 0.
@param[in]
y COMPLEX array on CPU host.
The n element vector y of dimension (1 + (n-1)*incy).
@param[in]
incy Stride between consecutive elements of dy. incy > 0.
@ingroup magma__dot
*******************************************************************************/
extern "C"
magmaFloatComplex magma_cblas_cdotu(
magma_int_t n,
const magmaFloatComplex *x, magma_int_t incx,
const magmaFloatComplex *y, magma_int_t incy )
{
// after too many issues with MKL and other BLAS, just write our own dot product!
magmaFloatComplex value = MAGMA_C_ZERO;
magma_int_t i;
if ( incx == 1 && incy == 1 ) {
for( i=0; i < n; ++i ) {
value += x[i] * y[i];
}
}
else {
magma_int_t ix=0, iy=0;
if ( incx < 0 ) { ix = (-n + 1)*incx; }
if ( incy < 0 ) { iy = (-n + 1)*incy; }
for( i=0; i < n; ++i ) {
value += x[ix] * y[iy];
ix += incx;
iy += incy;
}
}
return value;
}
#undef COMPLEX
|
/*
Open Asset Import Library (assimp)
----------------------------------------------------------------------
Copyright (c) 2006-2020, assimp team
All rights reserved.
Redistribution and use of this software in source and binary forms,
with or without modification, are permitted provided that the
following conditions are met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the
following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other
materials provided with the distribution.
* Neither the name of the assimp team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the assimp team.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
----------------------------------------------------------------------
*/
/// \file X3DImporter.cpp
/// \brief X3D-format files importer for Assimp: main algorithm implementation.
/// \date 2015-2016
/// \author smal.root@gmail.com
#ifndef ASSIMP_BUILD_NO_X3D_IMPORTER
#include "X3DImporter.hpp"
#include <assimp/StringUtils.h>
// Header files, Assimp.
#include <assimp/DefaultIOSystem.h>
#include <assimp/fast_atof.h>
// Header files, stdlib.
#include <iterator>
#include <memory>
#include <string>
namespace Assimp {
/// Constant which holds the importer description
const aiImporterDesc X3DImporter::Description = {
"Extensible 3D(X3D) Importer",
"smalcom",
"",
"See documentation in source code. Chapter: Limitations.",
aiImporterFlags_SupportTextFlavour | aiImporterFlags_SupportBinaryFlavour | aiImporterFlags_LimitedSupport | aiImporterFlags_Experimental,
0,
0,
0,
0,
"x3d x3db"
};
struct WordIterator {
using iterator_category = std::input_iterator_tag;
using value_type = const char *;
using difference_type = ptrdiff_t;
using pointer = value_type *;
using reference = value_type &;
static const char *whitespace;
const char *mStart, *mEnd;
WordIterator(const char *start, const char *end) :
mStart(start),
mEnd(end) {
mStart = start + ::strspn(start, whitespace);
if (mStart >= mEnd) {
mStart = 0;
}
}
WordIterator() :
mStart(0),
mEnd(0) {}
WordIterator(const WordIterator &other) :
mStart(other.mStart),
mEnd(other.mEnd) {}
WordIterator &operator=(const WordIterator &other) {
mStart = other.mStart;
mEnd = other.mEnd;
return *this;
}
bool operator==(const WordIterator &other) const { return mStart == other.mStart; }
bool operator!=(const WordIterator &other) const { return mStart != other.mStart; }
WordIterator &operator++() {
mStart += strcspn(mStart, whitespace);
mStart += strspn(mStart, whitespace);
if (mStart >= mEnd) {
mStart = 0;
}
return *this;
}
WordIterator operator++(int) {
WordIterator result(*this);
++(*this);
return result;
}
const char *operator*() const { return mStart; }
};
const char *WordIterator::whitespace = ", \t\r\n";
X3DImporter::X3DImporter() :
mNodeElementCur(nullptr) {
// empty
}
X3DImporter::~X3DImporter() {
// Clear() is accounting if data already is deleted. So, just check again if all data is deleted.
Clear();
}
void X3DImporter::Clear() {
mNodeElementCur = nullptr;
// Delete all elements
if (!NodeElement_List.empty()) {
for (std::list<X3DNodeElementBase *>::iterator it = NodeElement_List.begin(); it != NodeElement_List.end(); ++it) {
delete *it;
}
NodeElement_List.clear();
}
}
void X3DImporter::ParseFile(const std::string &file, IOSystem *pIOHandler) {
ai_assert(nullptr != pIOHandler);
static const std::string mode = "rb";
std::unique_ptr<IOStream> fileStream(pIOHandler->Open(file, mode));
if (!fileStream.get()) {
throw DeadlyImportError("Failed to open file " + file + ".");
}
}
bool X3DImporter::CanRead( const std::string &pFile, IOSystem * /*pIOHandler*/, bool checkSig ) const {
if (checkSig) {
std::string::size_type pos = pFile.find_last_of(".x3d");
if (pos != std::string::npos) {
return true;
}
}
return false;
}
void X3DImporter::GetExtensionList( std::set<std::string> &extensionList ) {
extensionList.insert("x3d");
}
void X3DImporter::InternReadFile( const std::string &pFile, aiScene *pScene, IOSystem *pIOHandler ) {
std::shared_ptr<IOStream> stream(pIOHandler->Open(pFile, "rb"));
if (!stream) {
throw DeadlyImportError("Could not open file for reading");
}
pScene->mRootNode = new aiNode(pFile);
}
const aiImporterDesc *X3DImporter::GetInfo() const {
return &Description;
}
}
#endif // !ASSIMP_BUILD_NO_X3D_IMPORTER
|
#include<iostream>
#include<bits/stdc++.h>
using namespace std;
#define rep(i,p,n) for( i = p; i<n;i++)
#define lld long long int
#define Clear(a,b) memset(a,b,sizeof(a))
template<class T>inline bool read(T &x) {
int c=getchar();
int sgn=1;
while(~c&&c<'0'||c>'9') {
if(c=='-')sgn=-1;
c=getchar();
}
for(x=0; ~c&&'0'<=c&&c<='9'; c=getchar())x=x*10+c-'0';
x*=sgn;
return ~c;
}
#define MAX 100010
int tree[3*MAX];
void build(int node, int start, int eend)
{
if(start==eend)
{
tree[node]=1;
return ;
}
int mid = (start+eend)>>1;
int left = node<<1;
int right = left+1;
build(left,start,mid);
build(right,mid+1,eend);
tree[node]=tree[left]+tree[right];
}
void update(int node, int start, int eend, int val)
{
if(start>val || eend<val)
{
return ;
}
if(start==val && eend==val)
{
tree[node]=0;
return ;
}
int mid = (start+eend)>>1;
int left = node<<1;
int right = left+1;
update(left,start,mid,val);
update(right,mid+1,eend,val);
tree[node]=tree[left]+tree[right];
}
int query(int node, int start, int eend, int pos)
{
if(start==eend)
{
return start;
}
int mid = (start+eend)>>1;
int left = node<<1;
int right = left+1;
if(pos<=tree[left])
{
query(left,start,mid,pos);
}
else
{
query(right,mid+1,eend,pos-tree[left]);
}
}
int main()
{
int test,i,j,Case,n,m;
read(test);
rep(Case,1,test+1)
{
read(n);
stack<int> stk;
rep(i,0,3*MAX)
tree[i]=0;
build(1,1,n);
for(int i=0;i<n;i++)
{
read(m);
stk.push(m);
}
int ret=0;
int pp=n;
while(!stk.empty())
{
int p = stk.top();
stk.pop();
ret = query(1,1,n,pp-p);
pp-=1;
update(1,1,n,ret);
}
printf("Case %d: %d\n",Case,ret);
}
return 0;
}
|
//*****************************************************************************
// Copyright 2017-2020 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//*****************************************************************************
#pragma once
#include <cstddef>
#include <memory>
#include <string>
#include <vector>
#include "ngraph/node.hpp"
#include "ngraph/op/util/activation_functions.hpp"
namespace ngraph
{
namespace op
{
namespace util
{
/// \brief Base class for all recurrent network cells.
///
/// \note It holds all common attributes.
///
class NGRAPH_API RNNCellBase
{
public:
///
/// \brief Constructs a RNNCellBase class.
///
/// \param[in] hidden_size The number of hidden units for recurrent cell.
/// \param[in] clip The value defining clipping range [-clip, clip]
/// on input of activation functions.
/// \param[in] activations The vector of activation functions used inside
/// recurrent cell.
/// \param[in] activations_alpha The vector of alpha parameters for activation
/// functions in order respective to activation list.
/// \param[in] activations_beta The vector of beta parameters for activation
/// functions in order respective to activation list.
///
RNNCellBase(std::size_t hidden_size,
float clip,
const std::vector<std::string>& activations,
const std::vector<float>& activations_alpha,
const std::vector<float>& activations_beta);
RNNCellBase() = default;
virtual ~RNNCellBase() = default;
virtual bool visit_attributes(AttributeVisitor& visitor);
std::size_t get_hidden_size() const { return m_hidden_size; }
float get_clip() const { return m_clip; }
const std::vector<std::string>& get_activations() const { return m_activations; }
const std::vector<float>& get_activations_alpha() const
{
return m_activations_alpha;
}
const std::vector<float>& get_activations_beta() const
{
return m_activations_beta;
}
protected:
///
/// \brief Constructs activation function object.
///
/// \param[in] idx The index of the activation function name.
///
/// \return The object representing activation function.
///
ActivationFunction get_activation_function(std::size_t idx) const;
///
/// \brief Creates node with element-wise add operation with numpy
/// broadcasting.
///
/// \param[in] lhs The left hand side argument node.
/// \param[in] rhs The right hand side argument node.
///
/// \return Node with element-wise add operation.
///
static std::shared_ptr<Node> add(const Output<Node>& lhs, const Output<Node>& rhs);
///
/// \brief Creates node with element-wise subtract operation with numpy
/// broadcasting.
///
/// \param[in] lhs The left hand side argument node.
/// \param[in] rhs The right hand side argument node.
///
/// \return Node with element-wise subtract operation.
///
static std::shared_ptr<Node> sub(const Output<Node>& lhs, const Output<Node>& rhs);
///
/// \brief Creates node with element-wise multiply operation with numpy
/// broadcasting.
///
/// \param[in] lhs The left hand side argument node.
/// \param[in] rhs The right hand side argument node.
///
/// \return Node with element-wise multiply operation.
///
static std::shared_ptr<Node> mul(const Output<Node>& lhs, const Output<Node>& rhs);
///
/// \brief Creates node with element-wise clip operation with numpy
/// broadcasting.
///
/// \param[in] data The input tensor for clipping.
///
/// \return Node with element-wise clip operation.
///
Output<Node> clip(const Output<Node>& data) const;
protected:
std::size_t m_hidden_size;
float m_clip;
std::vector<std::string> m_activations;
std::vector<float> m_activations_alpha;
std::vector<float> m_activations_beta;
};
}
}
}
|
/* -*-mode:c++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
#include <iostream>
#include <string>
#include "util/exception.hh"
#include "util/system_runner.hh"
using namespace std;
void usage( const char * argv0 )
{
cerr << argv0 << " COMMAND [ARG]..." << endl;
}
int main( int argc, char * argv[] )
{
try {
if ( argc <= 0 ) {
abort();
}
if ( argc < 2 ) {
usage( argv[ 0 ] );
return EXIT_FAILURE;
}
const string command = string( "gg-" ) + argv[ 1 ];
vector<string> args { command };
for ( int i = 2; i < argc; i++ ) {
args.emplace_back( argv[ i ] );
}
ezexec( command, args, {}, true, true );
cerr << "gg: '" << argv[ 1 ] << "' is not a gg command." << endl;
return EXIT_FAILURE;
}
catch ( const exception & e ) {
print_exception( argv[ 0 ], e );
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
|
/*
* Copyright (c) 2019, The OpenThread Authors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holder nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @file
* This file implements a simple CLI for the Joiner role.
*/
#include "cli_joiner.hpp"
#include "cli/cli.hpp"
#include "cli/cli_server.hpp"
#if OPENTHREAD_CONFIG_JOINER_ENABLE
namespace ot {
namespace Cli {
const struct Joiner::Command Joiner::sCommands[] = {
{"help", &Joiner::ProcessHelp},
{"id", &Joiner::ProcessId},
{"start", &Joiner::ProcessStart},
{"stop", &Joiner::ProcessStop},
};
otError Joiner::ProcessHelp(uint8_t aArgsLength, char *aArgs[])
{
OT_UNUSED_VARIABLE(aArgsLength);
OT_UNUSED_VARIABLE(aArgs);
for (size_t i = 0; i < OT_ARRAY_LENGTH(sCommands); i++)
{
mInterpreter.mServer->OutputFormat("%s\r\n", sCommands[i].mName);
}
return OT_ERROR_NONE;
}
otError Joiner::ProcessId(uint8_t aArgsLength, char *aArgs[])
{
OT_UNUSED_VARIABLE(aArgsLength);
OT_UNUSED_VARIABLE(aArgs);
otExtAddress joinerId;
otJoinerGetId(mInterpreter.mInstance, &joinerId);
mInterpreter.OutputBytes(joinerId.m8, sizeof(joinerId));
mInterpreter.mServer->OutputFormat("\r\n");
return OT_ERROR_NONE;
}
otError Joiner::ProcessStart(uint8_t aArgsLength, char *aArgs[])
{
otError error;
const char *provisioningUrl = NULL;
VerifyOrExit(aArgsLength > 1, error = OT_ERROR_INVALID_ARGS);
if (aArgsLength > 2)
{
provisioningUrl = aArgs[2];
}
error = otJoinerStart(mInterpreter.mInstance, aArgs[1], provisioningUrl, PACKAGE_NAME,
OPENTHREAD_CONFIG_PLATFORM_INFO, PACKAGE_VERSION, NULL, &Joiner::HandleCallback, this);
exit:
return error;
}
otError Joiner::ProcessStop(uint8_t aArgsLength, char *aArgs[])
{
OT_UNUSED_VARIABLE(aArgsLength);
OT_UNUSED_VARIABLE(aArgs);
otJoinerStop(mInterpreter.mInstance);
return OT_ERROR_NONE;
}
otError Joiner::Process(uint8_t aArgsLength, char *aArgs[])
{
otError error = OT_ERROR_INVALID_COMMAND;
if (aArgsLength < 1)
{
ProcessHelp(0, NULL);
}
else
{
for (size_t i = 0; i < OT_ARRAY_LENGTH(sCommands); i++)
{
if (strcmp(aArgs[0], sCommands[i].mName) == 0)
{
error = (this->*sCommands[i].mCommand)(aArgsLength, aArgs);
break;
}
}
}
return error;
}
void Joiner::HandleCallback(otError aError, void *aContext)
{
static_cast<Joiner *>(aContext)->HandleCallback(aError);
}
void Joiner::HandleCallback(otError aError)
{
switch (aError)
{
case OT_ERROR_NONE:
mInterpreter.mServer->OutputFormat("Join success\r\n");
break;
default:
mInterpreter.mServer->OutputFormat("Join failed [%s]\r\n", otThreadErrorToString(aError));
break;
}
}
} // namespace Cli
} // namespace ot
#endif // OPENTHREAD_CONFIG_JOINER_ENABLE
|
//------------------------------------------------------------------------------
// posteffectserver.cc
// (C) 2008 Radon Labs GmbH
// (C) 2013-2016 Individual contributors, see AUTHORS file
//------------------------------------------------------------------------------
#include "stdneb.h"
#include "posteffect/rt/posteffectserver.h"
#include "graphics/graphicsserver.h"
#include "graphics/view.h"
#include "graphics/modelentity.h"
#include "coregraphics/shaderserver.h"
#include "graphics/globallightentity.h"
#include "models/nodes/statenodeinstance.h"
#include "models/nodes/statenode.h"
#include "resources/managedtexture.h"
#include "resources/resourcemanager.h"
#include "coregraphics/shadersemantics.h"
#include "frame/frameserver.h"
#include "graphics/graphicsinterface.h"
#include "algorithm/algorithmprotocol.h"
namespace PostEffect
{
__ImplementClass(PostEffect::PostEffectServer, 'POSR', Core::RefCounted);
__ImplementSingleton(PostEffectServer);
using namespace Util;
using namespace CoreGraphics;
using namespace Graphics;
using namespace Resources;
using namespace Math;
using namespace Models;
//------------------------------------------------------------------------------
/**
*/
PostEffectServer::PostEffectServer():
lastTime(0.0),
fadeTime(0.0),
currentFadeValue(1.0f),
curFadeMode(NoFade),
postEffects(NumPostEffectTypes),
frameShader(0),
skyEntity(0),
skyLoaded(false)
{
__ConstructSingleton;
}
//------------------------------------------------------------------------------
/**
*/
PostEffectServer::~PostEffectServer()
{
this->Close();
__DestructSingleton;
}
//------------------------------------------------------------------------------
/**
*/
void
PostEffectServer::Open()
{
n_assert(!this->frameShader.isvalid());
// get frame shader from default view
this->frameShader = GraphicsServer::Instance()->GetDefaultView()->GetFrameShader();
// some variables belong in the compose shader
const Ptr<Shader>& composeShader = this->frameShader->GetFramePassBaseByName("Finalize")->GetShader();
const Ptr<Shader>& gatherShader = this->frameShader->GetFramePassBaseByName("Gather")->GetShader();
const Ptr<Shader>& vertBloom = this->frameShader->GetFramePassBaseByName("VerticalBloomBlur")->GetShader();
const Ptr<Shader>& horiBloom = this->frameShader->GetFramePassBaseByName("HorizontalBloomBlur")->GetShader();
// some variables belong in the brightpass
const Ptr<Shader>& brightPassShader = this->frameShader->GetFramePassBaseByName("BrightPass")->GetShader();
// lookup the shared post effect fade variable
this->fadeShaderVariable = composeShader->GetVariableByName(ShaderVariable::Name(NEBULA3_SEMANTIC_FADEVALUE));
// color stuff
this->saturationShaderVariable = composeShader->GetVariableByName(ShaderVariable::Name(NEBULA3_SEMANTIC_SATURATION));
this->balanceShaderVariable = composeShader->GetVariableByName(ShaderVariable::Name(NEBULA3_SEMANTIC_BALANCE));
this->maxLuminanceShaderVar = composeShader->GetVariableByName(ShaderVariable::Name(NEBULA3_SEMANTIC_MAXLUMINANCE));
// fog stuff
this->fogColorVariable = gatherShader->GetVariableByName(ShaderVariable::Name(NEBULA3_SEMANTIC_FOGCOLOR));
this->fogDistancesVariable = gatherShader->GetVariableByName(ShaderVariable::Name(NEBULA3_SEMANTIC_FOGDISTANCES));
// dof stuff
this->dofShaderVariable = composeShader->GetVariableByName(ShaderVariable::Name(NEBULA3_SEMANTIC_DOFDISTANCES));
// hdr stuff
this->hdrColorVariable = brightPassShader->GetVariableByName(ShaderVariable::Name(NEBULA3_SEMANTIC_HDRBLOOMCOLOR));
this->hdrThresholdVariable = brightPassShader->GetVariableByName(ShaderVariable::Name(NEBULA3_SEMANTIC_HDRBRIGHTPASSTHRESHOLD));
this->hdrVerticalScaleVariable = vertBloom->GetVariableByName(ShaderVariable::Name(NEBULA3_SEMANTIC_HDRBLOOMSCALE));
this->hdrHorizontalScaleVariable = horiBloom->GetVariableByName(ShaderVariable::Name(NEBULA3_SEMANTIC_HDRBLOOMSCALE));
// setup default blends
this->postEffects[Color].current = ColorParams::Create();
this->postEffects[DoF].current = DepthOfFieldParams::Create();
this->postEffects[Fog].current = FogParams::Create();
this->postEffects[Hdr].current = HdrParams::Create();
this->postEffects[Light].current = LightParams::Create();
this->postEffects[Sky].current = SkyParams::Create();
this->postEffects[AO].current = AoParams::Create();
// preload default sky
this->PreloadTexture("tex:system/sky_refl");
}
//------------------------------------------------------------------------------
/**
*/
bool
PostEffectServer::FindCurrentSkyEntities()
{
// check if our sky entity is set
if (this->skyEntity.isvalid())
{
// get model instance
Ptr<ModelInstance> inst = this->skyEntity->GetModelInstance();
if (inst.isvalid())
{
const Array<Ptr<ModelNodeInstance> > nodes = inst->GetNodeInstances();
IndexT i;
for (i = 0; i < nodes.Size(); i++)
{
const Ptr<ModelNodeInstance>& node = nodes[i];
if (node->IsA(StateNodeInstance::RTTI))
{
const Ptr<StateNodeInstance>& stateNodeInst = node.downcast<StateNodeInstance>();
const Ptr<StateNode>& stateNode = stateNodeInst->GetModelNode().downcast<StateNode>();
const Ptr<Materials::SurfaceInstance>& surface = stateNodeInst->GetSurfaceInstance();
// create variables
this->skyBaseTexture = surface->GetConstant(ShaderVariable::Name(NEBULA3_SEMANTIC_SKY1));
this->skyBlendTexture = surface->GetConstant(ShaderVariable::Name(NEBULA3_SEMANTIC_SKY2));
this->skyBlendFactor = surface->GetConstant(ShaderVariable::Name(NEBULA3_SEMANTIC_SKYBLENDFACTOR));
this->skyBrightness = surface->GetConstant(ShaderVariable::Name(NEBULA3_SEMANTIC_BRIGHTNESS));
this->skyContrast = surface->GetConstant(ShaderVariable::Name(NEBULA3_SEMANTIC_CONTRAST));
this->skyRotationFactor = surface->GetConstant(ShaderVariable::Name(NEBULA3_SEMANTIC_SKYROTATIONFACTOR));;
// set base texture
this->skyBaseTexture->SetTexture(this->FindTexture("tex:system/sky")->GetTexture());
return true;
}
}
}
}
return false;
}
//------------------------------------------------------------------------------
/**
*/
void
PostEffectServer::Close()
{
// delete all posteffect structs
IndexT index;
for (index = 0; index < this->postEffects.Size(); index++)
{
this->postEffects[index].current = 0;
this->postEffects[index].target = 0;
}
this->curFadeMode = NoFade;
this->currentFadeValue = 1.0f;
this->fadeShaderVariable = 0;
this->saturationShaderVariable = 0;
this->maxLuminanceShaderVar = 0;
this->balanceShaderVariable = 0;
this->fogDistancesVariable = 0;
this->fogColorVariable = 0;
this->hdrVerticalScaleVariable = 0;
this->hdrHorizontalScaleVariable = 0;
this->hdrColorVariable = 0;
this->hdrThresholdVariable = 0;
this->dofShaderVariable = 0;
this->skyEntity = 0;
this->skyContrast = 0;
this->skyBrightness = 0;
this->skyBlendFactor = 0;
this->skyRotationFactor = 0;
this->skyBlendTexture = 0;
this->skyBaseTexture = 0;
this->globalLight = 0;
this->skyLoaded = false;
this->frameShader = 0;
this->UnloadTextures();
}
//------------------------------------------------------------------------------
/**
*/
void
PostEffectServer::OnFrame(Timing::Time time)
{
// if the shader variables are not yet connected to the sky shader, try
if (!skyLoaded)
{
this->skyLoaded = this->FindCurrentSkyEntities();
}
// make sure to apply sky parameters
/*
if (this->skyBlendTexture.isvalid() &&
this->skyBaseTexture.isvalid() &&
this->skyBlendTexture->IsValid() &&
this->skyBaseTexture->IsValid())
{
this->skyBlendTexture->Apply();
this->skyBaseTexture->Apply();
}
*/
Timing::Time frameTime = time - this->lastTime;
this->lastTime = time;
// compute simple fading
if (this->curFadeMode != NoFade)
{
this->currentFadeValue = this->ComputeFadeValue(frameTime);
// apply fadeValue on shader variable
this->fadeShaderVariable->SetFloat(this->currentFadeValue);
}
else if (this->callback.IsValid())
{
this->callback(time);
this->callback = Delegate<Timing::Time>();
}
// if no global light entity set, find the new one
// (can be used for setting a new, in case of changing the view
// the old one should be reseted and here we will find the new one)
if (!this->globalLight.isvalid())
{
this->globalLight = Graphics::GraphicsServer::Instance()->GetCurrentGlobalLightEntity();
// return, the light still can be invalid
return;
}
// now compute further post effect blendings
IndexT index;
for(index = 0; index < NumPostEffectTypes; index++)
{
if(this->ComputeBlending((PostEffectType)index))
{
this->ApplyParameters((PostEffectType)index);
}
}
}
//------------------------------------------------------------------------------
/**
*/
bool
PostEffectServer::ComputeBlending(PostEffectType type)
{
const Ptr<ParamBase>& target = this->postEffects[(int)type].target;
const Ptr<ParamBase>& current = this->postEffects[(int)type].current;
if(target.isvalid())
{
n_assert(current.isvalid());
if (!current->Equals(target, TINY))
{
// how much have we progressed since last time?
// and how much time left to the end?
Timing::Time timeDiff = this->lastTime - this->postEffects[(int)type].lastTime;
Timing::Time timeToEnd = n_max(this->postEffects[(int)type].blendEndTime - this->lastTime, 0.0001);
// get normalized lerp value and perform blending
float lerpVal = n_saturate(float(timeDiff / timeToEnd));
current->BlendTo( target , lerpVal);
// store current time for parameterblend
this->postEffects[(int)type].lastTime = this->lastTime;
return true;
}
else if (current->Equals(target, TINY))
{
// do not blend, just set directly
this->postEffects[type].current->Copy(target);
this->StopBlending(type);
return true;
}
}
return false;
}
//------------------------------------------------------------------------------
/**
*/
void
PostEffectServer::ApplyParameters(PostEffectType type)
{
switch(type)
{
case Color:
this->ApplyColorParameters();
break;
case DoF:
this->ApplyDepthOfFieldParameters();
break;
case Fog:
this->ApplyFogParameters();
break;
case Hdr:
this->ApplyHdrParameters();
break;
case Sky:
this->ApplySkyParameters();
break;
case Light:
this->ApplyLightParameters();
break;
case AO:
this->ApplyAOParameters();
break;
default:
n_error("Wrong PostEffectParameter Type set!");
break;
}
}
//------------------------------------------------------------------------------
/**
*/
void
PostEffectServer::ApplyColorParameters()
{
this->balanceShaderVariable->SetFloat4(this->postEffects[Color].current.cast<ColorParams>()->GetColorBalance());
this->saturationShaderVariable->SetFloat(this->postEffects[Color].current.cast<ColorParams>()->GetColorSaturation());
this->maxLuminanceShaderVar->SetFloat4(this->postEffects[Color].current.cast<ColorParams>()->GetColorMaxLuminance());
}
//------------------------------------------------------------------------------
/**
*/
void
PostEffectServer::ApplyDepthOfFieldParameters()
{
// TODO
Math::vector dofDistances( this->postEffects[DoF].current.cast<DepthOfFieldParams>()->GetFocusDistance(),
this->postEffects[DoF].current.cast<DepthOfFieldParams>()->GetFocusLength(),
this->postEffects[DoF].current.cast<DepthOfFieldParams>()->GetFilterSize());
this->dofShaderVariable->SetFloat4(dofDistances);
}
//------------------------------------------------------------------------------
/**
*/
void
PostEffectServer::ApplyFogParameters()
{
this->fogColorVariable->SetFloat4(this->postEffects[Fog].current.cast<FogParams>()->GetFogColorAndIntensity());
// build distances stuff
Math::float4 fogDistances( this->postEffects[Fog].current.cast<FogParams>()->GetFogNearDistance(),
this->postEffects[Fog].current.cast<FogParams>()->GetFogFarDistance(),
this->postEffects[Fog].current.cast<FogParams>()->GetFogHeight(),
this->postEffects[Fog].current.cast<FogParams>()->GetFogFarDistance() - this->postEffects[Fog].current.cast<FogParams>()->GetFogNearDistance());
this->fogDistancesVariable->SetFloat4(fogDistances);
}
//------------------------------------------------------------------------------
/**
*/
void
PostEffectServer::ApplyHdrParameters()
{
this->hdrColorVariable->SetFloat4(this->postEffects[Hdr].current.cast<HdrParams>()->GetHdrBloomColor());
this->hdrVerticalScaleVariable->SetFloat(this->postEffects[Hdr].current.cast<HdrParams>()->GetHdrBloomIntensity());
this->hdrHorizontalScaleVariable->SetFloat(this->postEffects[Hdr].current.cast<HdrParams>()->GetHdrBloomIntensity());
this->hdrThresholdVariable->SetFloat(this->postEffects[Hdr].current.cast<HdrParams>()->GetHdrBloomThreshold());
}
//------------------------------------------------------------------------------
/**
*/
void
PostEffectServer::ApplyLightParameters()
{
// do not apply any shader variables,
// modify globallight instead
const Ptr<LightParams>& paras = this->postEffects[Light].current.cast<LightParams>();
this->globalLight->SetColor(paras->GetLightColor() * paras->GetLightIntensity());
this->globalLight->SetAmbientLightColor(paras->GetLightAmbientColor() * paras->GetLightIntensity());
this->globalLight->SetBackLightColor(paras->GetLightOppositeColor() * paras->GetLightIntensity());
#ifdef USE_POSTEFFECT_GLOBALLIGHTTRANSFORM
this->globalLight->SetTransform(paras->GetLightTransform());
#endif
this->globalLight->SetShadowIntensity(paras->GetLightShadowIntensity());
this->globalLight->SetShadowBias(paras->GetLightShadowBias());
this->globalLight->SetCastShadows(paras->GetLightCastsShadows());
this->globalLight->SetBackLightOffset(paras->GetBackLightFactor());
}
//------------------------------------------------------------------------------
/**
*/
void
PostEffectServer::ApplyAOParameters()
{
const Ptr<AoParams>& paras = this->postEffects[AO].current.cast<AoParams>();
Ptr<Algorithm::SetAmbientOcclusionParams> msg = Algorithm::SetAmbientOcclusionParams::Create();
msg->SetStrength(paras->GetStrength());
msg->SetAngleBias(paras->GetAngleBias());
msg->SetPowerExponent(paras->GetPower());
msg->SetRadius(paras->GetRadius());
Graphics::GraphicsInterface::Instance()->Send(msg.upcast<Messaging::Message>());
}
//------------------------------------------------------------------------------
/**
*/
void
PostEffectServer::ApplySkyParameters()
{
// if sky isn't loaded yet, do nothing
if (!this->skyLoaded || !this->skyEntity->GetModelInstance().isvalid())
{
// return
return;
}
// get textures
const Ptr<SkyParams>& targetPara = this->postEffects[Sky].target.cast<SkyParams>();
const Ptr<SkyParams>& currentPara = this->postEffects[Sky].current.cast<SkyParams>();
// preload textures
this->PreloadTexture(targetPara->GetSkyTexturePath());
this->PreloadTexture(currentPara->GetSkyTexturePath());
this->skyBrightness->SetValue(currentPara->GetSkyBrightness());
this->skyContrast->SetValue(currentPara->GetSkyContrast());
this->skyRotationFactor->SetValue(currentPara->GetSkyRotationFactor());
// if blending finished, apply blend texture as current
if(1.0f - currentPara->GetTextureBlendFactor() <= N_TINY || targetPara == currentPara)
{
// set current as target, reset blend factor and delete target
currentPara->ResetTextureBlendFactor();
currentPara->SetSkyTexturePath(targetPara->GetSkyTexturePath());
currentPara->SetIrradianceTexturePath(targetPara->GetIrradianceTexturePath());
currentPara->SetReflectanceTexturePath(targetPara->GetReflectanceTexturePath());
this->StopBlending(Sky);
// set texture
this->skyBaseTexture->SetTexture(this->FindTexture(currentPara->GetSkyTexturePath())->GetTexture());
// set base texture, other one is not needed
this->skyBlendFactor->SetValue(currentPara->GetTextureBlendFactor());
// apply reflectance and irradiance
Lighting::EnvironmentProbe::DefaultEnvironmentProbe->AssignReflectionMap(currentPara->GetReflectanceTexturePath() + NEBULA3_TEXTURE_EXTENSION);
Lighting::EnvironmentProbe::DefaultEnvironmentProbe->AssignIrradianceMap(currentPara->GetIrradianceTexturePath() + NEBULA3_TEXTURE_EXTENSION);
}
else
{
// set blend texture
this->skyBlendTexture->SetTexture(this->FindTexture(targetPara->GetSkyTexturePath())->GetTexture());
// set base and blend texture
this->skyBlendFactor->SetValue(currentPara->GetTextureBlendFactor());
}
}
//------------------------------------------------------------------------------
/**
*/
void
PostEffectServer::StartBlending(const Ptr<ParamBase>& target, Timing::Time fadeTime, PostEffectType postEffectType)
{
//n_printf("PostEffectServer: Starting Blending (%i) at '%f' - fadeTime (%f)\n", (int)postEffectType, this->lastTime, fadeTime);
// update times
this->postEffects[postEffectType].blendTime = fadeTime;
this->postEffects[postEffectType].blendEndTime = this->lastTime + fadeTime;
this->postEffects[postEffectType].lastTime = this->lastTime;
// set new target
this->postEffects[postEffectType].target = target;
}
//------------------------------------------------------------------------------
/**
*/
void
PostEffectServer::StopBlending(PostEffectType postEffectType)
{
//n_printf("PostEffectServer: Stopping Blending (%i) at '%f'\n", (int)postEffectType, this->lastTime);
this->postEffects[(int)postEffectType].target = 0;
}
//------------------------------------------------------------------------------
/**
*/
void
PostEffectServer::PreloadTexture(const Util::String &resource)
{
// soft check
ResourceId fullTexResId = String(resource + NEBULA3_TEXTURE_EXTENSION);
Ptr<ManagedTexture> managedTexture = ResourceManager::Instance()->CreateManagedResource(Texture::RTTI, fullTexResId, 0, true).downcast<ManagedTexture>();
ResourceManager::Instance()->RequestResourceForLoading(managedTexture.upcast<ManagedResource>());
this->texturePool.Append(managedTexture);
}
//------------------------------------------------------------------------------
/**
*/
void
PostEffectServer::UnloadTexture(const Util::String &resource)
{
ResourceId fullTexResId = String(resource + NEBULA3_TEXTURE_EXTENSION);
Ptr<ManagedTexture> tex = ResourceManager::Instance()->LookupManagedResource(fullTexResId).downcast<ManagedTexture>();
ResourceManager::Instance()->DiscardManagedResource(tex.upcast<ManagedResource>());
// just remove ANY reference to this texture, we don't really care which pointer we have
this->texturePool.EraseIndex(this->texturePool.FindIndex(tex));
}
//------------------------------------------------------------------------------
/**
*/
Ptr<ManagedTexture>
PostEffectServer::FindTexture(const Util::String& resource)
{
ResourceId fullTexResId = String(resource + NEBULA3_TEXTURE_EXTENSION);
return ResourceManager::Instance()->LookupManagedResource(fullTexResId).downcast<ManagedTexture>();
}
//------------------------------------------------------------------------------
/**
*/
void
PostEffectServer::UnloadTextures()
{
IndexT i;
for (i = 0; i < this->texturePool.Size(); i++)
{
ResourceManager::Instance()->DiscardManagedResource(this->texturePool[i].upcast<ManagedResource>());
}
this->texturePool.Clear();
}
//------------------------------------------------------------------------------
/**
*/
float
PostEffectServer::ComputeFadeValue(Timing::Time frameTime)
{
float result = this->currentFadeValue;
if (this->curFadeMode == FadeOut)
{
const float targetValue = this->currentFadeTarget;
if (this->fadeTime == 0.0f)
{
result = targetValue;
}
if (result <= targetValue)
{
this->curFadeMode = NoFade;
return targetValue;
}
else
{
// always compute time in ratio of full black and full transparent
float stepSize = (float)frameTime / (float)this->fadeTime;
result -= stepSize;
}
}
else
{
const float targetValue = this->currentFadeTarget;
if (this->fadeTime == 0.0f)
{
result = targetValue;
}
if (result >= targetValue)
{
this->curFadeMode = NoFade;
return targetValue;
}
else
{
// always compute time in ratio of full black and full transparent
float stepSize = (float)frameTime / (float)this->fadeTime;
result += stepSize;
}
}
return result;
}
//------------------------------------------------------------------------------
/**
*/
void
PostEffectServer::SetSkyEntity( const Ptr<Graphics::ModelEntity>& entity )
{
n_assert(entity.isvalid());
// remove current variables
if (this->skyEntity.isvalid())
{
this->skyContrast = 0;
this->skyBrightness = 0;
this->skyBlendFactor = 0;
this->skyRotationFactor = 0;
this->skyBlendTexture = 0;
this->skyBaseTexture = 0;
this->skyLoaded = false;
}
this->skyEntity = entity;
this->skyEntity->SetAlwaysVisible(true);
}
//------------------------------------------------------------------------------
/**
*/
void
PostEffectServer::StopAllBlending()
{
for (int i = 0; i < this->postEffects.Size(); i++)
{
this->postEffects[i].target = 0;
}
}
} // namespace PostEffect
|
/*----------------------------------------------------------------------------*/
/* Copyright (c) 2017-2018 FIRST. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
#include "commands/baseGoToDistance.h"
baseGoToDistance::baseGoToDistance(int distance, int angle)
{
// Use Requires() here to declare subsystem dependencies
// eg. Requires(Robot::chassis.get());
m_distance = distance;
m_angle = angle;
Requires(&Robot::m_base);
}
void baseGoToDistance::Initialize()
{
Robot::m_base.ZeroEncoder();
Robot::m_base.GyroZero();
upperLimit = m_distance + 1140;
lowerLimit = m_distance - 1140;
}
void baseGoToDistance::Execute()
{
Robot::m_base.SetEncoderControl(m_distance, m_angle);
}
bool baseGoToDistance::IsFinished()
{
return Robot::m_base.EncoderPosition < upperLimit && Robot::m_base.EncoderPosition > lowerLimit;
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
#ifndef KLL_QUANTILE_CALCULATOR_IMPL_HPP_
#define KLL_QUANTILE_CALCULATOR_IMPL_HPP_
#include <memory>
#include <cmath>
#include <algorithm>
#include "kll_helper.hpp"
namespace datasketches {
template <typename T, typename C, typename A>
kll_quantile_calculator<T, C, A>::kll_quantile_calculator(const T* items, const uint32_t* levels, uint8_t num_levels, uint64_t n, const A& allocator):
n_(n), levels_(num_levels + 1, 0, allocator), entries_(allocator)
{
const uint32_t num_items = levels[num_levels] - levels[0];
entries_.reserve(num_items);
populate_from_sketch(items, levels, num_levels);
merge_sorted_blocks(entries_, levels_.data(), levels_.size() - 1, num_items);
if (!is_sorted(entries_.begin(), entries_.end(), compare_pair_by_first<C>())) throw std::logic_error("entries must be sorted");
convert_to_preceding_cummulative();
}
template <typename T, typename C, typename A>
T kll_quantile_calculator<T, C, A>::get_quantile(double fraction) const {
return approximately_answer_positional_query(pos_of_phi(fraction, n_));
}
template <typename T, typename C, typename A>
void kll_quantile_calculator<T, C, A>::populate_from_sketch(const T* items, const uint32_t* levels, uint8_t num_levels) {
size_t src_level = 0;
size_t dst_level = 0;
uint64_t weight = 1;
uint32_t offset = levels[0];
while (src_level < num_levels) {
const uint32_t from_index(levels[src_level] - offset);
const uint32_t to_index(levels[src_level + 1] - offset); // exclusive
if (from_index < to_index) { // skip empty levels
for (uint32_t i = from_index; i < to_index; ++i) {
entries_.push_back(Entry(items[i + offset], weight));
}
levels_[dst_level] = from_index;
levels_[dst_level + 1] = to_index;
dst_level++;
}
src_level++;
weight *= 2;
}
if (levels_.size() > static_cast<size_t>(dst_level + 1)) levels_.resize(dst_level + 1);
}
template <typename T, typename C, typename A>
T kll_quantile_calculator<T, C, A>::approximately_answer_positional_query(uint64_t pos) const {
if (pos >= n_) throw std::logic_error("position out of range");
const uint32_t num_items = levels_[levels_.size() - 1];
if (pos > entries_[num_items - 1].second) return entries_[num_items - 1].first;
const uint32_t index = chunk_containing_pos(pos);
return entries_[index].first;
}
template <typename T, typename C, typename A>
void kll_quantile_calculator<T, C, A>::convert_to_preceding_cummulative() {
uint64_t subtotal = 0;
for (auto& entry: entries_) {
const uint64_t new_subtotal = subtotal + entry.second;
entry.second = subtotal;
subtotal = new_subtotal;
}
}
template <typename T, typename C, typename A>
uint64_t kll_quantile_calculator<T, C, A>::pos_of_phi(double phi, uint64_t n) {
const uint64_t pos = std::floor(phi * n);
return (pos == n) ? n - 1 : pos;
}
template <typename T, typename C, typename A>
uint32_t kll_quantile_calculator<T, C, A>::chunk_containing_pos(uint64_t pos) const {
if (entries_.size() < 1) throw std::logic_error("array too short");
if (pos < entries_[0].second) throw std::logic_error("position too small");
if (pos > entries_[entries_.size() - 1].second) throw std::logic_error("position too large");
return search_for_chunk_containing_pos(pos, 0, entries_.size());
}
template <typename T, typename C, typename A>
uint32_t kll_quantile_calculator<T, C, A>::search_for_chunk_containing_pos(uint64_t pos, uint32_t l, uint32_t r) const {
if (l + 1 == r) {
return l;
}
const uint32_t m(l + (r - l) / 2);
if (entries_[m].second <= pos) {
return search_for_chunk_containing_pos(pos, m, r);
}
return search_for_chunk_containing_pos(pos, l, m);
}
template <typename T, typename C, typename A>
void kll_quantile_calculator<T, C, A>::merge_sorted_blocks(Container& entries, const uint32_t* levels, uint8_t num_levels, uint32_t num_items) {
if (num_levels == 1) return;
Container temporary(entries.get_allocator());
temporary.reserve(num_items);
merge_sorted_blocks_direct(entries, temporary, levels, 0, num_levels);
}
template <typename T, typename C, typename A>
void kll_quantile_calculator<T, C, A>::merge_sorted_blocks_direct(Container& orig, Container& temp, const uint32_t* levels,
uint8_t starting_level, uint8_t num_levels) {
if (num_levels == 1) return;
const uint8_t num_levels_1 = num_levels / 2;
const uint8_t num_levels_2 = num_levels - num_levels_1;
const uint8_t starting_level_1 = starting_level;
const uint8_t starting_level_2 = starting_level + num_levels_1;
const auto initial_size = temp.size();
merge_sorted_blocks_reversed(orig, temp, levels, starting_level_1, num_levels_1);
merge_sorted_blocks_reversed(orig, temp, levels, starting_level_2, num_levels_2);
const uint32_t num_items_1 = levels[starting_level_1 + num_levels_1] - levels[starting_level_1];
const auto chunk_begin = temp.begin() + initial_size;
std::merge(
std::make_move_iterator(chunk_begin), std::make_move_iterator(chunk_begin + num_items_1),
std::make_move_iterator(chunk_begin + num_items_1), std::make_move_iterator(temp.end()),
orig.begin() + levels[starting_level], compare_pair_by_first<C>()
);
temp.erase(chunk_begin, temp.end());
}
template <typename T, typename C, typename A>
void kll_quantile_calculator<T, C, A>::merge_sorted_blocks_reversed(Container& orig, Container& temp, const uint32_t* levels,
uint8_t starting_level, uint8_t num_levels) {
if (num_levels == 1) {
std::move(orig.begin() + levels[starting_level], orig.begin() + levels[starting_level + 1], std::back_inserter(temp));
return;
}
const uint8_t num_levels_1 = num_levels / 2;
const uint8_t num_levels_2 = num_levels - num_levels_1;
const uint8_t starting_level_1 = starting_level;
const uint8_t starting_level_2 = starting_level + num_levels_1;
merge_sorted_blocks_direct(orig, temp, levels, starting_level_1, num_levels_1);
merge_sorted_blocks_direct(orig, temp, levels, starting_level_2, num_levels_2);
std::merge(
std::make_move_iterator(orig.begin() + levels[starting_level_1]),
std::make_move_iterator(orig.begin() + levels[starting_level_1 + num_levels_1]),
std::make_move_iterator(orig.begin() + levels[starting_level_2]),
std::make_move_iterator(orig.begin() + levels[starting_level_2 + num_levels_2]),
std::back_inserter(temp),
compare_pair_by_first<C>()
);
}
} /* namespace datasketches */
#endif // KLL_QUANTILE_CALCULATOR_IMPL_HPP_
|
// Copyright (c) 2015-2017 The Bitcoin Core developers
// Copyright (c) 2017-2019 The PIVX developers
// Copyright (c) 2020 The Simulacrum developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "httprpc.h"
#include "base58.h"
#include "chainparams.h"
#include "httpserver.h"
#include "rpc/protocol.h"
#include "rpc/server.h"
#include "random.h"
#include "sync.h"
#include "util.h"
#include "utilstrencodings.h"
#include "guiinterface.h"
#include <boost/algorithm/string.hpp> // boost::trim
/** Simple one-shot callback timer to be used by the RPC mechanism to e.g.
* re-lock the wellet.
*/
class HTTPRPCTimer : public RPCTimerBase
{
public:
HTTPRPCTimer(struct event_base* eventBase, boost::function<void(void)>& func, int64_t millis) :
ev(eventBase, false, func)
{
struct timeval tv;
tv.tv_sec = millis/1000;
tv.tv_usec = (millis%1000)*1000;
ev.trigger(&tv);
}
private:
HTTPEvent ev;
};
class HTTPRPCTimerInterface : public RPCTimerInterface
{
public:
HTTPRPCTimerInterface(struct event_base* base) : base(base)
{
}
const char* Name()
{
return "HTTP";
}
RPCTimerBase* NewTimer(boost::function<void(void)>& func, int64_t millis)
{
return new HTTPRPCTimer(base, func, millis);
}
private:
struct event_base* base;
};
/* Pre-base64-encoded authentication token */
static std::string strRPCUserColonPass;
/* Stored RPC timer interface (for unregistration) */
static HTTPRPCTimerInterface* httpRPCTimerInterface = 0;
static void JSONErrorReply(HTTPRequest* req, const UniValue& objError, const UniValue& id)
{
// Send error reply from json-rpc error object
int nStatus = HTTP_INTERNAL_SERVER_ERROR;
int code = find_value(objError, "code").get_int();
if (code == RPC_INVALID_REQUEST)
nStatus = HTTP_BAD_REQUEST;
else if (code == RPC_METHOD_NOT_FOUND)
nStatus = HTTP_NOT_FOUND;
std::string strReply = JSONRPCReply(NullUniValue, objError, id);
req->WriteHeader("Content-Type", "application/json");
req->WriteReply(nStatus, strReply);
}
static bool RPCAuthorized(const std::string& strAuth)
{
if (strRPCUserColonPass.empty()) // Belt-and-suspenders measure if InitRPCAuthentication was not called
return false;
if (strAuth.substr(0, 6) != "Basic ")
return false;
std::string strUserPass64 = strAuth.substr(6);
boost::trim(strUserPass64);
std::string strUserPass = DecodeBase64(strUserPass64);
return TimingResistantEqual(strUserPass, strRPCUserColonPass);
}
static bool HTTPReq_JSONRPC(HTTPRequest* req, const std::string &)
{
// JSONRPC handles only POST
if (req->GetRequestMethod() != HTTPRequest::POST) {
req->WriteReply(HTTP_BAD_METHOD, "JSONRPC server handles only POST requests");
return false;
}
// Check authorization
std::pair<bool, std::string> authHeader = req->GetHeader("authorization");
if (!authHeader.first) {
req->WriteReply(HTTP_UNAUTHORIZED);
return false;
}
if (!RPCAuthorized(authHeader.second)) {
LogPrintf("ThreadRPCServer incorrect password attempt from %s\n", req->GetPeer().ToString());
/* Deter brute-forcing
If this results in a DoS the user really
shouldn't have their RPC port exposed. */
MilliSleep(250);
req->WriteReply(HTTP_UNAUTHORIZED);
return false;
}
JSONRequest jreq;
try {
// Parse request
UniValue valRequest;
if (!valRequest.read(req->ReadBody()))
throw JSONRPCError(RPC_PARSE_ERROR, "Parse error");
std::string strReply;
// singleton request
if (valRequest.isObject()) {
jreq.parse(valRequest);
UniValue result = tableRPC.execute(jreq.strMethod, jreq.params);
// Send reply
strReply = JSONRPCReply(result, NullUniValue, jreq.id);
// array of requests
} else if (valRequest.isArray())
strReply = JSONRPCExecBatch(valRequest.get_array());
else
throw JSONRPCError(RPC_PARSE_ERROR, "Top-level object parse error");
req->WriteHeader("Content-Type", "application/json");
req->WriteReply(HTTP_OK, strReply);
} catch (const UniValue& objError) {
JSONErrorReply(req, objError, jreq.id);
return false;
} catch (const std::exception& e) {
JSONErrorReply(req, JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id);
return false;
}
return true;
}
static bool InitRPCAuthentication()
{
if (mapArgs["-rpcpassword"] == "")
{
LogPrintf("No rpcpassword set - using random cookie authentication\n");
if (!GenerateAuthCookie(&strRPCUserColonPass)) {
uiInterface.ThreadSafeMessageBox(
_("Error: A fatal internal error occurred, see debug.log for details"), // Same message as AbortNode
"", CClientUIInterface::MSG_ERROR);
return false;
}
} else {
strRPCUserColonPass = mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"];
}
return true;
}
bool StartHTTPRPC()
{
LogPrint("rpc", "Starting HTTP RPC server\n");
if (!InitRPCAuthentication())
return false;
RegisterHTTPHandler("/", true, HTTPReq_JSONRPC);
assert(EventBase());
httpRPCTimerInterface = new HTTPRPCTimerInterface(EventBase());
RPCSetTimerInterface(httpRPCTimerInterface);
return true;
}
void InterruptHTTPRPC()
{
LogPrint("rpc", "Interrupting HTTP RPC server\n");
}
void StopHTTPRPC()
{
LogPrint("rpc", "Stopping HTTP RPC server\n");
UnregisterHTTPHandler("/", true);
if (httpRPCTimerInterface) {
RPCUnsetTimerInterface(httpRPCTimerInterface);
delete httpRPCTimerInterface;
httpRPCTimerInterface = 0;
}
}
|
//
// HostEntry.cpp
//
// Library: Net
// Package: NetCore
// Module: HostEntry
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#include "Poco/Net/HostEntry.h"
#include "Poco/Exception.h"
#include <algorithm>
namespace Poco {
namespace Net {
HostEntry::HostEntry()
{
}
HostEntry::HostEntry(struct hostent* entry)
{
poco_check_ptr (entry);
_name = entry->h_name;
char** alias = entry->h_aliases;
if (alias)
{
while (*alias)
{
_aliases.push_back(std::string(*alias));
++alias;
}
}
removeDuplicates(_aliases);
char** address = entry->h_addr_list;
if (address)
{
while (*address)
{
_addresses.push_back(IPAddress(*address, entry->h_length));
++address;
}
}
removeDuplicates(_addresses);
}
#if defined(POCO_HAVE_IPv6) || defined(POCO_HAVE_ADDRINFO)
HostEntry::HostEntry(struct addrinfo* ainfo)
{
poco_check_ptr (ainfo);
for (struct addrinfo* ai = ainfo; ai; ai = ai->ai_next)
{
if (ai->ai_canonname)
{
_name.assign(ai->ai_canonname);
}
if (ai->ai_addrlen && ai->ai_addr)
{
switch (ai->ai_addr->sa_family)
{
#ifdef USE_LIBZT
case ZTS_AF_INET:
_addresses.push_back(IPAddress(&reinterpret_cast<struct zts_sockaddr_in*>(ai->ai_addr)->sin_addr, sizeof(zts_in_addr)));
break;
#else
case AF_INET:
_addresses.push_back(IPAddress(&reinterpret_cast<struct sockaddr_in*>(ai->ai_addr)->sin_addr, sizeof(in_addr)));
break;
#endif
#if defined(POCO_HAVE_IPv6)
#ifdef USE_LIBZT
case ZTS_AF_INET6:
#else
case AF_INET6:
#endif
_addresses.push_back(IPAddress(&reinterpret_cast<struct sockaddr_in6*>(ai->ai_addr)->sin6_addr, sizeof(in6_addr), reinterpret_cast<struct sockaddr_in6*>(ai->ai_addr)->sin6_scope_id));
break;
#endif
}
}
}
removeDuplicates(_addresses);
}
#endif // POCO_HAVE_IPv6
#if defined(POCO_VXWORKS)
HostEntry::HostEntry(const std::string& name, const IPAddress& addr):
_name(name)
{
_addresses.push_back(addr);
}
#endif // POCO_VXWORKS
HostEntry::HostEntry(const HostEntry& entry):
_name(entry._name),
_aliases(entry._aliases),
_addresses(entry._addresses)
{
}
HostEntry& HostEntry::operator = (const HostEntry& entry)
{
if (&entry != this)
{
_name = entry._name;
_aliases = entry._aliases;
_addresses = entry._addresses;
}
return *this;
}
void HostEntry::swap(HostEntry& hostEntry)
{
std::swap(_name, hostEntry._name);
std::swap(_aliases, hostEntry._aliases);
std::swap(_addresses, hostEntry._addresses);
}
HostEntry::~HostEntry()
{
}
} } // namespace Poco::Net
|
// license:BSD-3-Clause
// copyright-holders:Wilbert Pol
#include "emu.h"
#include "keyboards.h"
#include "ec1841.h"
#include "iskr1030.h"
#include "keytro.h"
#include "msnat.h"
#include "pc83.h"
#include "pcxt83.h"
#include "pcat84.h"
#include "pcat101.h"
#include "hle_mouse.h"
void pc_xt_keyboards(device_slot_interface &device)
{
device.option_add(STR_KBD_KEYTRONIC_PC3270, PC_KBD_KEYTRONIC_PC3270);
device.option_add(STR_KBD_IBM_PC_83, PC_KBD_IBM_PC_83);
device.option_add(STR_KBD_IBM_PC_XT_83, PC_KBD_IBM_PC_XT_83);
device.option_add(STR_KBD_EC_1841, PC_KBD_EC_1841);
device.option_add(STR_KBD_ISKR_1030, PC_KBD_ISKR_1030);
}
void pc_at_keyboards(device_slot_interface &device)
{
device.option_add(STR_KBD_KEYTRONIC_PC3270, PC_KBD_KEYTRONIC_PC3270_AT);
device.option_add(STR_KBD_MICROSOFT_NATURAL, PC_KBD_MICROSOFT_NATURAL);
device.option_add(STR_KBD_IBM_PC_AT_84, PC_KBD_IBM_PC_AT_84);
device.option_add(STR_KBD_IBM_3270PC_122, PC_KBD_IBM_3270PC_122);
device.option_add(STR_KBD_IBM_PC_AT_101, PC_KBD_IBM_PC_AT_101);
}
void ps2_mice(device_slot_interface &device)
{
device.option_add(STR_HLE_PS2_MOUSE, HLE_PS2_MOUSE);
}
|
//===-test_constant_xnnpack.cc-----------------------------------------------------------===//
//
// Copyright (C) 2019-2020 Alibaba Group Holding Limited.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// =============================================================================
// clang-format off
// Testing CXX Code Gen using ODLA API on xnnpack
// RUN: %halo_compiler -target cxx -o %data_path/test_constant/test_data_set_0/output_0.cc -x onnx -emit-data-as-c %data_path/test_constant/test_data_set_0/output_0.pb
// RUN: %halo_compiler -target cxx -batch-size 1 %halo_compile_flags %data_path/test_constant/model.onnx -o %t.cc
// RUN: %cxx -c -fPIC -o %t.o %t.cc -I%odla_path/include
// RUN: %cxx -g %s %t.o %t.bin -I%T -I%odla_path/include -I%unittests_path -I%data_path/test_constant/test_data_set_0 %odla_link %device_link -lodla_xnnpack -o %t_xnnpack.exe -Wno-deprecated-declarations
// RUN: %t_xnnpack.exe 0.0001 0 xnnpack %data_path/test_constant | FileCheck %s
// CHECK: Result Pass
// clang-format on
// XFAIL: *
#include "test_constant_xnnpack.cc.tmp.main.cc.in"
|
#include <nano/secure/versioning.hpp>
#include <nano/test_common/system.hpp>
#include <nano/test_common/testutil.hpp>
#include <gtest/gtest.h>
using namespace std::chrono_literals;
TEST (wallets, open_create)
{
nano::system system (1);
bool error (false);
nano::wallets wallets (error, *system.nodes[0]);
ASSERT_FALSE (error);
ASSERT_EQ (1, wallets.items.size ()); // it starts out with a default wallet
auto id = nano::random_wallet_id ();
ASSERT_EQ (nullptr, wallets.open (id));
auto wallet (wallets.create (id));
ASSERT_NE (nullptr, wallet);
ASSERT_EQ (wallet, wallets.open (id));
}
TEST (wallets, open_existing)
{
nano::system system (1);
auto id (nano::random_wallet_id ());
{
bool error (false);
nano::wallets wallets (error, *system.nodes[0]);
ASSERT_FALSE (error);
ASSERT_EQ (1, wallets.items.size ());
auto wallet (wallets.create (id));
ASSERT_NE (nullptr, wallet);
ASSERT_EQ (wallet, wallets.open (id));
nano::raw_key password;
password.clear ();
system.deadline_set (10s);
while (password == 0)
{
ASSERT_NO_ERROR (system.poll ());
wallet->store.password.value (password);
}
}
{
bool error (false);
nano::wallets wallets (error, *system.nodes[0]);
ASSERT_FALSE (error);
ASSERT_EQ (2, wallets.items.size ());
ASSERT_NE (nullptr, wallets.open (id));
}
}
TEST (wallets, remove)
{
nano::system system (1);
nano::wallet_id one (1);
{
bool error (false);
nano::wallets wallets (error, *system.nodes[0]);
ASSERT_FALSE (error);
ASSERT_EQ (1, wallets.items.size ());
auto wallet (wallets.create (one));
ASSERT_NE (nullptr, wallet);
ASSERT_EQ (2, wallets.items.size ());
wallets.destroy (one);
ASSERT_EQ (1, wallets.items.size ());
}
{
bool error (false);
nano::wallets wallets (error, *system.nodes[0]);
ASSERT_FALSE (error);
ASSERT_EQ (1, wallets.items.size ());
}
}
TEST (wallets, reload)
{
nano::system system (1);
auto & node1 (*system.nodes[0]);
nano::wallet_id one (1);
bool error (false);
ASSERT_FALSE (error);
ASSERT_EQ (1, node1.wallets.items.size ());
{
nano::lock_guard<nano::mutex> lock_wallet (node1.wallets.mutex);
nano::inactive_node node (node1.application_path, nano::inactive_node_flag_defaults ());
auto wallet (node.node->wallets.create (one));
ASSERT_NE (wallet, nullptr);
}
ASSERT_TIMELY (5s, node1.wallets.open (one) != nullptr);
ASSERT_EQ (2, node1.wallets.items.size ());
}
TEST (wallets, vote_minimum)
{
nano::system system (1);
auto & node1 (*system.nodes[0]);
nano::keypair key1;
nano::keypair key2;
nano::genesis genesis;
nano::state_block send1 (nano::dev_genesis_key.pub, genesis.hash (), nano::dev_genesis_key.pub, std::numeric_limits<nano::uint128_t>::max () - node1.config.vote_minimum.number (), key1.pub, nano::dev_genesis_key.prv, nano::dev_genesis_key.pub, *system.work.generate (genesis.hash ()));
ASSERT_EQ (nano::process_result::progress, node1.process (send1).code);
nano::state_block open1 (key1.pub, 0, key1.pub, node1.config.vote_minimum.number (), send1.hash (), key1.prv, key1.pub, *system.work.generate (key1.pub));
ASSERT_EQ (nano::process_result::progress, node1.process (open1).code);
// send2 with amount vote_minimum - 1 (not voting representative)
nano::state_block send2 (nano::dev_genesis_key.pub, send1.hash (), nano::dev_genesis_key.pub, std::numeric_limits<nano::uint128_t>::max () - 2 * node1.config.vote_minimum.number () + 1, key2.pub, nano::dev_genesis_key.prv, nano::dev_genesis_key.pub, *system.work.generate (send1.hash ()));
ASSERT_EQ (nano::process_result::progress, node1.process (send2).code);
nano::state_block open2 (key2.pub, 0, key2.pub, node1.config.vote_minimum.number () - 1, send2.hash (), key2.prv, key2.pub, *system.work.generate (key2.pub));
ASSERT_EQ (nano::process_result::progress, node1.process (open2).code);
auto wallet (node1.wallets.items.begin ()->second);
nano::unique_lock<nano::mutex> representatives_lk (wallet->representatives_mutex);
ASSERT_EQ (0, wallet->representatives.size ());
representatives_lk.unlock ();
wallet->insert_adhoc (nano::dev_genesis_key.prv);
wallet->insert_adhoc (key1.prv);
wallet->insert_adhoc (key2.prv);
node1.wallets.compute_reps ();
representatives_lk.lock ();
ASSERT_EQ (2, wallet->representatives.size ());
}
TEST (wallets, exists)
{
nano::system system (1);
auto & node (*system.nodes[0]);
nano::keypair key1;
nano::keypair key2;
{
auto transaction (node.wallets.tx_begin_read ());
ASSERT_FALSE (node.wallets.exists (transaction, key1.pub));
ASSERT_FALSE (node.wallets.exists (transaction, key2.pub));
}
system.wallet (0)->insert_adhoc (key1.prv);
{
auto transaction (node.wallets.tx_begin_read ());
ASSERT_TRUE (node.wallets.exists (transaction, key1.pub));
ASSERT_FALSE (node.wallets.exists (transaction, key2.pub));
}
system.wallet (0)->insert_adhoc (key2.prv);
{
auto transaction (node.wallets.tx_begin_read ());
ASSERT_TRUE (node.wallets.exists (transaction, key1.pub));
ASSERT_TRUE (node.wallets.exists (transaction, key2.pub));
}
}
TEST (wallets, search_pending)
{
for (auto search_all : { false, true })
{
nano::system system;
nano::node_config config (nano::get_available_port (), system.logging);
config.enable_voting = false;
config.frontiers_confirmation = nano::frontiers_confirmation_mode::disabled;
nano::node_flags flags;
flags.disable_search_pending = true;
auto & node (*system.add_node (config, flags));
nano::unique_lock<nano::mutex> lk (node.wallets.mutex);
auto wallets = node.wallets.get_wallets ();
lk.unlock ();
ASSERT_EQ (1, wallets.size ());
auto wallet_id = wallets.begin ()->first;
auto wallet = wallets.begin ()->second;
wallet->insert_adhoc (nano::dev_genesis_key.prv);
nano::block_builder builder;
auto send = builder.state ()
.account (nano::genesis_account)
.previous (nano::genesis_hash)
.representative (nano::genesis_account)
.balance (nano::genesis_amount - node.config.receive_minimum.number ())
.link (nano::genesis_account)
.sign (nano::dev_genesis_key.prv, nano::dev_genesis_key.pub)
.work (*system.work.generate (nano::genesis_hash))
.build ();
ASSERT_EQ (nano::process_result::progress, node.process (*send).code);
// Pending search should start an election
ASSERT_TRUE (node.active.empty ());
if (search_all)
{
node.wallets.search_pending_all ();
}
else
{
node.wallets.search_pending (wallet_id);
}
auto election = node.active.election (send->qualified_root ());
ASSERT_NE (nullptr, election);
// Erase the key so the confirmation does not trigger an automatic receive
wallet->store.erase (node.wallets.tx_begin_write (), nano::genesis_account);
// Now confirm the election
election->force_confirm ();
ASSERT_TIMELY (5s, node.block_confirmed (send->hash ()) && node.active.empty ());
// Re-insert the key
wallet->insert_adhoc (nano::dev_genesis_key.prv);
// Pending search should create the receive block
ASSERT_EQ (2, node.ledger.cache.block_count);
if (search_all)
{
node.wallets.search_pending_all ();
}
else
{
node.wallets.search_pending (wallet_id);
}
ASSERT_TIMELY (3s, node.balance (nano::genesis_account) == nano::genesis_amount);
auto receive_hash = node.ledger.latest (node.store.tx_begin_read (), nano::genesis_account);
auto receive = node.block (receive_hash);
ASSERT_NE (nullptr, receive);
ASSERT_EQ (receive->sideband ().height, 3);
ASSERT_EQ (send->hash (), receive->link ().as_block_hash ());
}
}
|
#include "L1Trigger/L1TMuonEndCap/interface/EMTFSubsystemCollector.h"
#include "DataFormats/L1TMuon/interface/L1TMuonSubsystems.h"
#include "FWCore/Framework/interface/Event.h"
#include "DataFormats/Common/interface/Handle.h"
#include "Geometry/RPCGeometry/interface/RPCGeometry.h" // needed to handle RPCRecHit
#include "helper.h" // adjacent_cluster
// _____________________________________________________________________________
// Specialized for DT
template <>
void EMTFSubsystemCollector::extractPrimitives(emtf::DTTag tag,
const GeometryTranslator* tp_geom,
const edm::Event& iEvent,
const edm::EDGetToken& token1,
const edm::EDGetToken& token2,
TriggerPrimitiveCollection& out) const {
edm::Handle<emtf::DTTag::digi_collection> phiContainer;
iEvent.getByToken(token1, phiContainer);
edm::Handle<emtf::DTTag::theta_digi_collection> thetaContainer;
iEvent.getByToken(token2, thetaContainer);
TriggerPrimitiveCollection muon_primitives;
// Adapted from L1Trigger/L1TMuonBarrel/src/L1TMuonBarrelKalmanStubProcessor.cc
constexpr int minPhiQuality = 0;
constexpr int minBX = -3;
constexpr int maxBX = 3;
for (int bx = minBX; bx <= maxBX; bx++) {
for (int wheel = -2; wheel <= 2; wheel++) {
for (int sector = 0; sector < 12; sector++) {
for (int station = 1; station < 5; station++) {
if (wheel == -1 || wheel == 0 || wheel == 1)
continue; // do not include wheels -1, 0, +1
if (station == 4)
continue; // do not include MB4
// According to Michalis, in legacy BMTF, the second stub was coming as BXNUM=-1.
// This is a code convention now, but you need bx-1 to get the proper second stub.
emtf::DTTag::theta_digi_type const* theta_segm = thetaContainer->chThetaSegm(wheel, station, sector, bx);
emtf::DTTag::digi_type const* phi_segm_high = phiContainer->chPhiSegm1(wheel, station, sector, bx);
emtf::DTTag::digi_type const* phi_segm_low = phiContainer->chPhiSegm2(wheel, station, sector, bx - 1);
// Find theta BTI group(s)
bool has_theta_segm = false;
int bti_group1 = -1;
int bti_group2 = -1;
// Case with theta segment
if (theta_segm != nullptr) {
has_theta_segm = true;
for (unsigned int i = 0; i < 7; ++i) {
if (theta_segm->position(i) != 0) {
if (bti_group1 < 0) {
bti_group1 = i;
bti_group2 = i;
} else {
bti_group2 = i;
}
}
}
emtf_assert(bti_group1 != -1 && bti_group2 != -1);
}
// 1st phi segment
if (phi_segm_high != nullptr) {
if (phi_segm_high->code() >= minPhiQuality) {
DTChamberId detid(phi_segm_high->whNum(), phi_segm_high->stNum(), phi_segm_high->scNum() + 1);
if (has_theta_segm) {
muon_primitives.emplace_back(detid, *phi_segm_high, *theta_segm, bti_group1);
} else {
muon_primitives.emplace_back(detid, *phi_segm_high, 1);
}
}
}
// 2nd phi segment
if (phi_segm_low != nullptr) {
if (phi_segm_low->code() >= minPhiQuality) {
DTChamberId detid(phi_segm_low->whNum(), phi_segm_low->stNum(), phi_segm_low->scNum() + 1);
if (has_theta_segm) {
muon_primitives.emplace_back(detid, *phi_segm_low, *theta_segm, bti_group2);
} else {
muon_primitives.emplace_back(detid, *phi_segm_low, 2);
}
}
}
// Duplicate DT muon primitives, if more than one theta segment, but only one phi segment
if (phi_segm_high != nullptr && phi_segm_low == nullptr && bti_group1 != bti_group2) {
DTChamberId detid(phi_segm_high->whNum(), phi_segm_high->stNum(), phi_segm_high->scNum() + 1);
muon_primitives.emplace_back(detid, *phi_segm_high, *theta_segm, bti_group2);
}
} // end loop over station
} // end loop over sector
} // end loop over wheel
} // end loop over bx
// Remove duplicates using erase-remove idiom,
// assuming the vector is already sorted
muon_primitives.erase(std::unique(muon_primitives.begin(), muon_primitives.end()), muon_primitives.end());
std::copy(muon_primitives.begin(), muon_primitives.end(), std::back_inserter(out));
return;
}
// _____________________________________________________________________________
// Specialized for CSC
template <>
void EMTFSubsystemCollector::extractPrimitives(emtf::CSCTag tag,
const GeometryTranslator* tp_geom,
const edm::Event& iEvent,
const edm::EDGetToken& token,
TriggerPrimitiveCollection& out) const {
edm::Handle<emtf::CSCTag::digi_collection> cscDigis;
iEvent.getByToken(token, cscDigis);
auto chamber = cscDigis->begin();
auto chend = cscDigis->end();
for (; chamber != chend; ++chamber) {
auto digi = (*chamber).second.first;
auto dend = (*chamber).second.second;
for (; digi != dend; ++digi) {
out.emplace_back((*chamber).first, *digi);
}
}
return;
}
// _____________________________________________________________________________
// Specialized for RPC
template <>
void EMTFSubsystemCollector::extractPrimitives(emtf::RPCTag tag,
const GeometryTranslator* tp_geom,
const edm::Event& iEvent,
const edm::EDGetToken& token,
TriggerPrimitiveCollection& out) const {
edm::Handle<emtf::RPCTag::digi_collection> rpcDigis;
iEvent.getByToken(token, rpcDigis);
TriggerPrimitiveCollection muon_primitives;
auto chamber = rpcDigis->begin();
auto chend = rpcDigis->end();
for (; chamber != chend; ++chamber) {
auto digi = (*chamber).second.first;
auto dend = (*chamber).second.second;
for (; digi != dend; ++digi) {
if ((*chamber).first.region() != 0) { // 0 is barrel
if ((*chamber).first.station() <= 2 && (*chamber).first.ring() == 3)
continue; // do not include RE1/3, RE2/3
if ((*chamber).first.station() >= 3 && (*chamber).first.ring() == 1)
continue; // do not include RE3/1, RE4/1 (iRPC)
muon_primitives.emplace_back((*chamber).first, *digi);
}
}
}
// Cluster the RPC digis
TriggerPrimitiveCollection clus_muon_primitives;
cluster_rpc(muon_primitives, clus_muon_primitives);
// Output
std::copy(clus_muon_primitives.begin(), clus_muon_primitives.end(), std::back_inserter(out));
return;
}
// Specialized for RPC (using RecHits)
template <>
void EMTFSubsystemCollector::extractPrimitives(emtf::RPCTag tag,
const GeometryTranslator* tp_geom,
const edm::Event& iEvent,
const edm::EDGetToken& token1,
const edm::EDGetToken& token2,
TriggerPrimitiveCollection& out) const {
constexpr int maxClusterSize = 3;
//edm::Handle<RPCTag::digi_collection> rpcDigis;
//iEvent.getByToken(token1, rpcDigis);
edm::Handle<emtf::RPCTag::rechit_collection> rpcRecHits;
iEvent.getByToken(token2, rpcRecHits);
auto rechit = rpcRecHits->begin();
auto rhend = rpcRecHits->end();
for (; rechit != rhend; ++rechit) {
const RPCDetId& detid = rechit->rpcId();
const RPCRoll* roll = dynamic_cast<const RPCRoll*>(tp_geom->getRPCGeometry().roll(detid));
if (roll == nullptr)
continue;
if (detid.region() != 0) { // 0 is barrel
if (detid.station() <= 2 && detid.ring() == 3)
continue; // do not include RE1/3, RE2/3
if (detid.station() >= 3 && detid.ring() == 1)
continue; // do not include RE3/1, RE4/1 (iRPC)
if (rechit->clusterSize() <= maxClusterSize) {
out.emplace_back(detid, *rechit);
}
}
}
return;
}
// _____________________________________________________________________________
// Specialized for iRPC
template <>
void EMTFSubsystemCollector::extractPrimitives(emtf::IRPCTag tag,
const GeometryTranslator* tp_geom,
const edm::Event& iEvent,
const edm::EDGetToken& token,
TriggerPrimitiveCollection& out) const {
edm::Handle<emtf::IRPCTag::digi_collection> irpcDigis;
iEvent.getByToken(token, irpcDigis);
TriggerPrimitiveCollection muon_primitives;
auto chamber = irpcDigis->begin();
auto chend = irpcDigis->end();
for (; chamber != chend; ++chamber) {
auto digi = (*chamber).second.first;
auto dend = (*chamber).second.second;
for (; digi != dend; ++digi) {
if ((*chamber).first.region() != 0) { // 0 is barrel
if (!((*chamber).first.station() >= 3 && (*chamber).first.ring() == 1))
continue; // only RE3/1, RE4/1 (iRPC)
muon_primitives.emplace_back((*chamber).first, *digi);
}
}
}
// Cluster the iRPC digis
TriggerPrimitiveCollection clus_muon_primitives;
cluster_rpc(muon_primitives, clus_muon_primitives);
// Output
std::copy(clus_muon_primitives.begin(), clus_muon_primitives.end(), std::back_inserter(out));
return;
}
// Specialized for iRPC (using RecHits)
template <>
void EMTFSubsystemCollector::extractPrimitives(emtf::IRPCTag tag,
const GeometryTranslator* tp_geom,
const edm::Event& iEvent,
const edm::EDGetToken& token1,
const edm::EDGetToken& token2,
TriggerPrimitiveCollection& out) const {
constexpr int maxClusterSize = 6;
//edm::Handle<emtf::IRPCTag::digi_collection> irpcDigis;
//iEvent.getByToken(token1, irpcDigis);
edm::Handle<emtf::IRPCTag::rechit_collection> irpcRecHits;
iEvent.getByToken(token2, irpcRecHits);
auto rechit = irpcRecHits->begin();
auto rhend = irpcRecHits->end();
for (; rechit != rhend; ++rechit) {
const RPCDetId& detid = rechit->rpcId();
const RPCRoll* roll = dynamic_cast<const RPCRoll*>(tp_geom->getRPCGeometry().roll(detid));
if (roll == nullptr)
continue;
if (detid.region() != 0) { // 0 is barrel
if (!(detid.station() >= 3 && detid.ring() == 1))
continue; // only RE3/1, RE4/1 (iRPC)
if (rechit->clusterSize() <= maxClusterSize) {
out.emplace_back(detid, *rechit);
}
}
}
return;
}
// _____________________________________________________________________________
// Specialized for CPPF
template <>
void EMTFSubsystemCollector::extractPrimitives(emtf::CPPFTag tag,
const GeometryTranslator* tp_geom,
const edm::Event& iEvent,
const edm::EDGetToken& token,
TriggerPrimitiveCollection& out) const {
edm::Handle<emtf::CPPFTag::digi_collection> cppfDigis;
iEvent.getByToken(token, cppfDigis);
for (const auto& digi : *cppfDigis) {
out.emplace_back(digi.rpcId(), digi);
}
return;
}
// _____________________________________________________________________________
// Specialized for GEM
template <>
void EMTFSubsystemCollector::extractPrimitives(emtf::GEMTag tag,
const GeometryTranslator* tp_geom,
const edm::Event& iEvent,
const edm::EDGetToken& token,
TriggerPrimitiveCollection& out) const {
edm::Handle<emtf::GEMTag::digi_collection> gemDigis;
iEvent.getByToken(token, gemDigis);
TriggerPrimitiveCollection muon_primitives;
auto chamber = gemDigis->begin();
auto chend = gemDigis->end();
for (; chamber != chend; ++chamber) {
auto digi = (*chamber).second.first;
auto dend = (*chamber).second.second;
for (; digi != dend; ++digi) {
auto detid = (*chamber).first;
// temporarily ignore 16-partition GE2/1 clusters, because the EMTF
// is not yet adapted to handle these objects
if (detid.isGE21() and digi->nPartitions() == GEMPadDigi::GE21SplitStrip)
continue;
muon_primitives.emplace_back((*chamber).first, *digi);
}
}
// Make GEM coincidence pads
TriggerPrimitiveCollection copad_muon_primitives;
make_copad_gem(muon_primitives, copad_muon_primitives);
// Output
std::copy(copad_muon_primitives.begin(), copad_muon_primitives.end(), std::back_inserter(out));
return;
}
// _____________________________________________________________________________
// Specialized for ME0
template <>
void EMTFSubsystemCollector::extractPrimitives(emtf::ME0Tag tag,
const GeometryTranslator* tp_geom,
const edm::Event& iEvent,
const edm::EDGetToken& token,
TriggerPrimitiveCollection& out) const {
edm::Handle<emtf::ME0Tag::digi_collection> me0Digis;
iEvent.getByToken(token, me0Digis);
auto chamber = me0Digis->begin();
auto chend = me0Digis->end();
for (; chamber != chend; ++chamber) {
auto digi = (*chamber).second.first;
auto dend = (*chamber).second.second;
for (; digi != dend; ++digi) {
out.emplace_back((*chamber).first, *digi);
}
}
return;
}
// _____________________________________________________________________________
// RPC functions
void EMTFSubsystemCollector::cluster_rpc(const TriggerPrimitiveCollection& muon_primitives,
TriggerPrimitiveCollection& clus_muon_primitives) const {
// Define operator to select RPC digis
struct {
typedef TriggerPrimitive value_type;
bool operator()(const value_type& x) const { return (x.subsystem() == L1TMuon::kRPC); }
} rpc_digi_select;
// Define operator to sort the RPC digis prior to clustering.
// Use rawId, bx and strip as the sorting id. RPC rawId fully specifies
// sector, subsector, endcap, station, ring, layer, roll. Strip is used as
// the least significant sorting id.
struct {
typedef TriggerPrimitive value_type;
bool operator()(const value_type& lhs, const value_type& rhs) const {
bool cmp = (std::make_pair(std::make_pair(lhs.rawId(), lhs.getRPCData().bx), lhs.getRPCData().strip) <
std::make_pair(std::make_pair(rhs.rawId(), rhs.getRPCData().bx), rhs.getRPCData().strip));
return cmp;
}
} rpc_digi_less;
struct {
typedef TriggerPrimitive value_type;
bool operator()(const value_type& lhs, const value_type& rhs) const {
bool cmp = (std::make_pair(std::make_pair(lhs.rawId(), lhs.getRPCData().bx), lhs.getRPCData().strip) ==
std::make_pair(std::make_pair(rhs.rawId(), rhs.getRPCData().bx), rhs.getRPCData().strip));
return cmp;
}
} rpc_digi_equal;
// Define operators for the nearest-neighbor clustering algorithm.
// If two digis are next to each other (check strip_hi on the 'left', and
// strip_low on the 'right'), cluster them (increment strip_hi on the 'left')
struct {
typedef TriggerPrimitive value_type;
bool operator()(const value_type& lhs, const value_type& rhs) const {
bool cmp = ((lhs.rawId() == rhs.rawId()) && (lhs.getRPCData().bx == rhs.getRPCData().bx) &&
(lhs.getRPCData().strip_hi + 1 == rhs.getRPCData().strip_low));
return cmp;
}
} rpc_digi_adjacent;
struct {
typedef TriggerPrimitive value_type;
void operator()(value_type& lhs, value_type& rhs) { // pass by reference
lhs.accessRPCData().strip_hi += 1;
}
} rpc_digi_cluster;
// ___________________________________________________________________________
// Do clustering using C++ <algorithm> functions
// 1. Select RPC digis
clus_muon_primitives.clear();
std::copy_if(
muon_primitives.begin(), muon_primitives.end(), std::back_inserter(clus_muon_primitives), rpc_digi_select);
// 2. Sort
std::stable_sort(clus_muon_primitives.begin(), clus_muon_primitives.end(), rpc_digi_less);
// 3. Remove duplicates
clus_muon_primitives.erase(std::unique(clus_muon_primitives.begin(), clus_muon_primitives.end(), rpc_digi_equal),
clus_muon_primitives.end());
// 4. Cluster adjacent digis
clus_muon_primitives.erase(
adjacent_cluster(clus_muon_primitives.begin(), clus_muon_primitives.end(), rpc_digi_adjacent, rpc_digi_cluster),
clus_muon_primitives.end());
}
// _____________________________________________________________________________
// GEM functions
void EMTFSubsystemCollector::make_copad_gem(const TriggerPrimitiveCollection& muon_primitives,
TriggerPrimitiveCollection& copad_muon_primitives) const {
// Use the inner layer (layer 1) hit coordinates as output, and the outer
// layer (layer 2) as coincidence
// Adapted from L1Trigger/CSCTriggerPrimitives/src/GEMCoPadProcessor.cc
constexpr unsigned int maxDeltaBX = 1;
constexpr unsigned int maxDeltaRoll = 1;
constexpr unsigned int maxDeltaPadGE11 = 3; // it was 2
constexpr unsigned int maxDeltaPadGE21 = 2;
// Make sure that the difference is calculated using signed integer, and
// output the absolute difference (as unsigned integer)
auto calculate_delta = [](int a, int b) -> unsigned int { return std::abs(a - b); };
// Create maps of GEM pads (key = detid), split by layer
std::map<uint32_t, TriggerPrimitiveCollection> in_pads_layer1, in_pads_layer2;
auto tp_it = muon_primitives.begin();
auto tp_end = muon_primitives.end();
for (; tp_it != tp_end; ++tp_it) {
GEMDetId detid = tp_it->detId<GEMDetId>();
emtf_assert(detid.layer() == 1 || detid.layer() == 2);
emtf_assert(1 <= detid.roll() && detid.roll() <= 8);
uint32_t layer = detid.layer();
// Remove layer number and roll number from detid
detid = GEMDetId(detid.region(), detid.ring(), detid.station(), 0, detid.chamber(), 0);
if (layer == 1) {
in_pads_layer1[detid.rawId()].push_back(*tp_it);
} else {
in_pads_layer2[detid.rawId()].push_back(*tp_it);
}
}
// Build coincidences
copad_muon_primitives.clear();
auto map_tp_it = in_pads_layer1.begin();
auto map_tp_end = in_pads_layer1.end();
for (; map_tp_it != map_tp_end; ++map_tp_it) {
const GEMDetId& detid = map_tp_it->first;
const TriggerPrimitiveCollection& pads = map_tp_it->second;
// find all corresponding ids with layer 2
auto found = in_pads_layer2.find(detid);
// empty range = no possible coincidence pads
if (found == in_pads_layer2.end())
continue;
// now let's correlate the pads in two layers of this partition
const TriggerPrimitiveCollection& co_pads = found->second;
for (auto p = pads.begin(); p != pads.end(); ++p) {
bool has_copad = false;
for (auto co_p = co_pads.begin(); co_p != co_pads.end() && !has_copad; ++co_p) {
// check the match in pad
unsigned int deltaPad = calculate_delta(p->getGEMData().pad, co_p->getGEMData().pad);
if ((detid.station() == 1 && deltaPad > maxDeltaPadGE11) ||
(detid.station() == 2 && deltaPad > maxDeltaPadGE21))
continue;
// check the match in BX
unsigned int deltaBX = calculate_delta(p->getGEMData().bx, co_p->getGEMData().bx);
if (deltaBX > maxDeltaBX)
continue;
// check the match in roll
unsigned int deltaRoll = calculate_delta(p->detId<GEMDetId>().roll(), co_p->detId<GEMDetId>().roll());
if (deltaRoll > maxDeltaRoll)
continue;
has_copad = true;
} // end loop over co_pads
// make a new coincidence pad digi
if (has_copad) {
copad_muon_primitives.push_back(*p);
}
} // end loop over pads
} // end loop over in_pads_layer1
}
|
/* $Id: once.cpp 69111 2017-10-17 14:26:02Z vboxsync $ */
/** @file
* IPRT - Execute Once.
*/
/*
* Copyright (C) 2007-2017 Oracle Corporation
*
* This file is part of VirtualBox Open Source Edition (OSE), as
* available from http://www.virtualbox.org. This file is free software;
* you can redistribute it and/or modify it under the terms of the GNU
* General Public License (GPL) as published by the Free Software
* Foundation, in version 2 as it comes in the "COPYING" file of the
* VirtualBox OSE distribution. VirtualBox OSE is distributed in the
* hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
*
* The contents of this file may alternatively be used under the terms
* of the Common Development and Distribution License Version 1.0
* (CDDL) only, as it comes in the "COPYING.CDDL" file of the
* VirtualBox OSE distribution, in which case the provisions of the
* CDDL are applicable instead of those of the GPL.
*
* You may elect to license modified versions of this file under the
* terms and conditions of either the GPL or the CDDL or both.
*/
/*********************************************************************************************************************************
* Header Files *
*********************************************************************************************************************************/
#include <iprt/once.h>
#include "internal/iprt.h"
#include <iprt/asm.h>
#include <iprt/assert.h>
#ifdef IN_RING3
# include <iprt/critsect.h>
# define RTONCE_USE_CRITSECT_FOR_TERM
#elif defined(IN_RING0)
# include <iprt/spinlock.h>
# define RTONCE_USE_SPINLOCK_FOR_TERM
#else
# define RTONCE_NO_TERM
#endif
#include <iprt/err.h>
#include <iprt/initterm.h>
#include <iprt/semaphore.h>
#include <iprt/thread.h>
/*********************************************************************************************************************************
* Global Variables *
*********************************************************************************************************************************/
#ifndef RTONCE_NO_TERM
/** For initializing the clean-up list code. */
static RTONCE g_OnceCleanUp = RTONCE_INITIALIZER;
/** Lock protecting the clean-up list. */
#ifdef RTONCE_USE_CRITSECT_FOR_TERM
static RTCRITSECT g_CleanUpCritSect;
#else
static RTSEMFASTMUTEX g_hCleanUpLock;
#endif
/** The clean-up list. */
static RTLISTANCHOR g_CleanUpList;
/** Locks the clean-up list. */
#ifdef RTONCE_USE_CRITSECT_FOR_TERM
# define RTONCE_CLEANUP_LOCK() RTCritSectEnter(&g_CleanUpCritSect)
#else
# define RTONCE_CLEANUP_LOCK() RTSemFastMutexRequest(g_hCleanUpLock);
#endif
/** Unlocks the clean-up list. */
#ifdef RTONCE_USE_CRITSECT_FOR_TERM
# define RTONCE_CLEANUP_UNLOCK() RTCritSectLeave(&g_CleanUpCritSect);
#else
# define RTONCE_CLEANUP_UNLOCK() RTSemFastMutexRelease(g_hCleanUpLock);
#endif
/** @callback_method_impl{FNRTTERMCALLBACK} */
static DECLCALLBACK(void) rtOnceTermCallback(RTTERMREASON enmReason, int32_t iStatus, void *pvUser)
{
bool const fLazyCleanUpOk = RTTERMREASON_IS_LAZY_CLEANUP_OK(enmReason);
RTONCE_CLEANUP_LOCK(); /* Potentially dangerous. */
PRTONCE pCur, pPrev;
RTListForEachReverseSafe(&g_CleanUpList, pCur, pPrev, RTONCE, CleanUpNode)
{
/*
* Mostly reset it before doing the callback.
*
* Should probably introduce some new states here, but I'm not sure
* it's really worth it at this point.
*/
PFNRTONCECLEANUP pfnCleanUp = pCur->pfnCleanUp;
void *pvUserCleanUp = pCur->pvUser;
pCur->pvUser = NULL;
pCur->pfnCleanUp = NULL;
ASMAtomicWriteS32(&pCur->rc, VERR_WRONG_ORDER);
pfnCleanUp(pvUserCleanUp, fLazyCleanUpOk);
/*
* Reset the reset of the state if we're being unloaded or smth.
*/
if (!fLazyCleanUpOk)
{
ASMAtomicWriteS32(&pCur->rc, VERR_INTERNAL_ERROR);
ASMAtomicWriteS32(&pCur->iState, RTONCESTATE_UNINITIALIZED);
}
}
RTONCE_CLEANUP_UNLOCK();
/*
* Reset our own structure and the critsect / mutex.
*/
if (!fLazyCleanUpOk)
{
# ifdef RTONCE_USE_CRITSECT_FOR_TERM
RTCritSectDelete(&g_CleanUpCritSect);
# else
RTSemFastMutexDestroy(g_hCleanUpLock);
g_hCleanUpLock = NIL_RTSEMFASTMUTEX;
# endif
ASMAtomicWriteS32(&g_OnceCleanUp.rc, VERR_INTERNAL_ERROR);
ASMAtomicWriteS32(&g_OnceCleanUp.iState, RTONCESTATE_UNINITIALIZED);
}
NOREF(pvUser); NOREF(iStatus);
}
/**
* Initializes the globals (using RTOnce).
*
* @returns IPRT status code
* @param pvUser Unused.
*/
static DECLCALLBACK(int32_t) rtOnceInitCleanUp(void *pvUser)
{
NOREF(pvUser);
RTListInit(&g_CleanUpList);
# ifdef RTONCE_USE_CRITSECT_FOR_TERM
int rc = RTCritSectInit(&g_CleanUpCritSect);
# else
int rc = RTSemFastMutexCreate(&g_hCleanUpLock);
# endif
if (RT_SUCCESS(rc))
{
rc = RTTermRegisterCallback(rtOnceTermCallback, NULL);
if (RT_SUCCESS(rc))
return rc;
# ifdef RTONCE_USE_CRITSECT_FOR_TERM
RTCritSectDelete(&g_CleanUpCritSect);
# else
RTSemFastMutexDestroy(g_hCleanUpLock);
g_hCleanUpLock = NIL_RTSEMFASTMUTEX;
# endif
}
return rc;
}
#endif /* !RTONCE_NO_TERM */
/**
* The state loop of the other threads.
*
* @returns VINF_SUCCESS when everything went smoothly. IPRT status code if we
* encountered trouble.
* @param pOnce The execute once structure.
* @param phEvtM Where to store the semaphore handle so the caller
* can do the cleaning up for us.
*/
static int rtOnceOtherThread(PRTONCE pOnce, PRTSEMEVENTMULTI phEvtM)
{
uint32_t cYields = 0;
for (;;)
{
int32_t iState = ASMAtomicReadS32(&pOnce->iState);
switch (iState)
{
/*
* No semaphore, try create one.
*/
case RTONCESTATE_BUSY_NO_SEM:
if (ASMAtomicCmpXchgS32(&pOnce->iState, RTONCESTATE_BUSY_CREATING_SEM, RTONCESTATE_BUSY_NO_SEM))
{
int rc = RTSemEventMultiCreate(phEvtM);
if (RT_SUCCESS(rc))
{
ASMAtomicWriteHandle(&pOnce->hEventMulti, *phEvtM);
int32_t cRefs = ASMAtomicIncS32(&pOnce->cEventRefs); Assert(cRefs == 1); NOREF(cRefs);
if (!ASMAtomicCmpXchgS32(&pOnce->iState, RTONCESTATE_BUSY_HAVE_SEM, RTONCESTATE_BUSY_CREATING_SEM))
{
/* Too slow. */
AssertReturn(ASMAtomicCmpXchgS32(&pOnce->iState, RTONCESTATE_DONE, RTONCESTATE_DONE_CREATING_SEM)
, VERR_INTERNAL_ERROR_5);
ASMAtomicWriteHandle(&pOnce->hEventMulti, NIL_RTSEMEVENTMULTI);
cRefs = ASMAtomicDecS32(&pOnce->cEventRefs); Assert(cRefs == 0);
RTSemEventMultiDestroy(*phEvtM);
*phEvtM = NIL_RTSEMEVENTMULTI;
}
}
else
{
AssertReturn( ASMAtomicCmpXchgS32(&pOnce->iState, RTONCESTATE_BUSY_SPIN, RTONCESTATE_BUSY_CREATING_SEM)
|| ASMAtomicCmpXchgS32(&pOnce->iState, RTONCESTATE_DONE, RTONCESTATE_DONE_CREATING_SEM)
, VERR_INTERNAL_ERROR_4);
*phEvtM = NIL_RTSEMEVENTMULTI;
}
}
break;
/*
* This isn't nice, but it's the easy way out.
*/
case RTONCESTATE_BUSY_CREATING_SEM:
case RTONCESTATE_BUSY_SPIN:
cYields++;
if (!(++cYields % 8))
RTThreadSleep(1);
else
RTThreadYield();
break;
/*
* There is a semaphore, try wait on it.
*
* We continue waiting after reaching DONE_HAVE_SEM if we
* already got the semaphore to avoid racing the first thread.
*/
case RTONCESTATE_DONE_HAVE_SEM:
if (*phEvtM == NIL_RTSEMEVENTMULTI)
return VINF_SUCCESS;
RT_FALL_THRU();
case RTONCESTATE_BUSY_HAVE_SEM:
{
/*
* Grab the semaphore if we haven't got it yet.
* We must take care not to increment the counter if it
* is 0. This may happen if we're racing a state change.
*/
if (*phEvtM == NIL_RTSEMEVENTMULTI)
{
int32_t cEventRefs = ASMAtomicUoReadS32(&pOnce->cEventRefs);
while ( cEventRefs > 0
&& ASMAtomicUoReadS32(&pOnce->iState) == RTONCESTATE_BUSY_HAVE_SEM)
{
if (ASMAtomicCmpXchgExS32(&pOnce->cEventRefs, cEventRefs + 1, cEventRefs, &cEventRefs))
break;
ASMNopPause();
}
if (cEventRefs <= 0)
break;
ASMAtomicReadHandle(&pOnce->hEventMulti, phEvtM);
AssertReturn(*phEvtM != NIL_RTSEMEVENTMULTI, VERR_INTERNAL_ERROR_2);
}
/*
* We've got a sempahore, do the actual waiting.
*/
do
RTSemEventMultiWaitNoResume(*phEvtM, RT_INDEFINITE_WAIT);
while (ASMAtomicReadS32(&pOnce->iState) == RTONCESTATE_BUSY_HAVE_SEM);
break;
}
case RTONCESTATE_DONE_CREATING_SEM:
case RTONCESTATE_DONE:
return VINF_SUCCESS;
default:
AssertMsgFailedReturn(("%d\n", iState), VERR_INTERNAL_ERROR_3);
}
}
}
RTDECL(int) RTOnceSlow(PRTONCE pOnce, PFNRTONCE pfnOnce, PFNRTONCECLEANUP pfnCleanUp, void *pvUser)
{
/*
* Validate input (strict builds only).
*/
AssertPtr(pOnce);
AssertPtr(pfnOnce);
/*
* Deal with the 'initialized' case first
*/
int32_t iState = ASMAtomicUoReadS32(&pOnce->iState);
if (RT_LIKELY( iState == RTONCESTATE_DONE
|| iState == RTONCESTATE_DONE_CREATING_SEM
|| iState == RTONCESTATE_DONE_HAVE_SEM
))
return ASMAtomicUoReadS32(&pOnce->rc);
AssertReturn( iState == RTONCESTATE_UNINITIALIZED
|| iState == RTONCESTATE_BUSY_NO_SEM
|| iState == RTONCESTATE_BUSY_SPIN
|| iState == RTONCESTATE_BUSY_CREATING_SEM
|| iState == RTONCESTATE_BUSY_HAVE_SEM
, VERR_INTERNAL_ERROR);
#ifdef RTONCE_NO_TERM
AssertReturn(!pfnCleanUp, VERR_NOT_SUPPORTED);
#else /* !RTONCE_NO_TERM */
/*
* Make sure our clean-up bits are working if needed later.
*/
if (pfnCleanUp)
{
int rc = RTOnce(&g_OnceCleanUp, rtOnceInitCleanUp, NULL);
if (RT_FAILURE(rc))
return rc;
}
#endif /* !RTONCE_NO_TERM */
/*
* Do we initialize it?
*/
int32_t rcOnce;
if ( iState == RTONCESTATE_UNINITIALIZED
&& ASMAtomicCmpXchgS32(&pOnce->iState, RTONCESTATE_BUSY_NO_SEM, RTONCESTATE_UNINITIALIZED))
{
/*
* Yes, so do the execute once stuff.
*/
rcOnce = pfnOnce(pvUser);
ASMAtomicWriteS32(&pOnce->rc, rcOnce);
#ifndef RTONCE_NO_TERM
/*
* Register clean-up if requested and we were successful.
*/
if (pfnCleanUp && RT_SUCCESS(rcOnce))
{
RTONCE_CLEANUP_LOCK();
pOnce->pfnCleanUp = pfnCleanUp;
pOnce->pvUser = pvUser;
RTListAppend(&g_CleanUpList, &pOnce->CleanUpNode);
RTONCE_CLEANUP_UNLOCK();
}
#endif /* !RTONCE_NO_TERM */
/*
* If there is a sempahore to signal, we're in for some extra work here.
*/
if ( !ASMAtomicCmpXchgS32(&pOnce->iState, RTONCESTATE_DONE, RTONCESTATE_BUSY_NO_SEM)
&& !ASMAtomicCmpXchgS32(&pOnce->iState, RTONCESTATE_DONE, RTONCESTATE_BUSY_SPIN)
&& !ASMAtomicCmpXchgS32(&pOnce->iState, RTONCESTATE_DONE_CREATING_SEM, RTONCESTATE_BUSY_CREATING_SEM)
)
{
/* Grab the sempahore by switching to 'DONE_HAVE_SEM' before reaching 'DONE'. */
AssertReturn(ASMAtomicCmpXchgS32(&pOnce->iState, RTONCESTATE_DONE_HAVE_SEM, RTONCESTATE_BUSY_HAVE_SEM),
VERR_INTERNAL_ERROR_2);
int32_t cRefs = ASMAtomicIncS32(&pOnce->cEventRefs);
Assert(cRefs > 1); NOREF(cRefs);
RTSEMEVENTMULTI hEvtM;
ASMAtomicReadHandle(&pOnce->hEventMulti, &hEvtM);
Assert(hEvtM != NIL_RTSEMEVENTMULTI);
ASMAtomicWriteS32(&pOnce->iState, RTONCESTATE_DONE);
/* Signal it and return. */
RTSemEventMultiSignal(hEvtM);
}
}
else
{
/*
* Wait for the first thread to complete. Delegate this to a helper
* function to simplify cleanup and keep things a bit shorter.
*/
RTSEMEVENTMULTI hEvtM = NIL_RTSEMEVENTMULTI;
rcOnce = rtOnceOtherThread(pOnce, &hEvtM);
if (hEvtM != NIL_RTSEMEVENTMULTI)
{
if (ASMAtomicDecS32(&pOnce->cEventRefs) == 0)
{
bool fRc;
ASMAtomicCmpXchgHandle(&pOnce->hEventMulti, NIL_RTSEMEVENTMULTI, hEvtM, fRc); Assert(fRc);
fRc = ASMAtomicCmpXchgS32(&pOnce->iState, RTONCESTATE_DONE, RTONCESTATE_DONE_HAVE_SEM); Assert(fRc);
RTSemEventMultiDestroy(hEvtM);
}
}
if (RT_SUCCESS(rcOnce))
rcOnce = ASMAtomicUoReadS32(&pOnce->rc);
}
return rcOnce;
}
RT_EXPORT_SYMBOL(RTOnceSlow);
RTDECL(void) RTOnceReset(PRTONCE pOnce)
{
/* Cannot be done while busy! */
AssertPtr(pOnce);
Assert(pOnce->hEventMulti == NIL_RTSEMEVENTMULTI);
int32_t iState = ASMAtomicUoReadS32(&pOnce->iState);
AssertMsg( iState == RTONCESTATE_DONE
|| iState == RTONCESTATE_UNINITIALIZED,
("%d\n", iState));
NOREF(iState);
#ifndef RTONCE_NO_TERM
/* Unregister clean-up. */
if (pOnce->pfnCleanUp)
{
RTONCE_CLEANUP_LOCK();
RTListNodeRemove(&pOnce->CleanUpNode);
pOnce->pfnCleanUp = NULL;
pOnce->pvUser = NULL;
RTONCE_CLEANUP_UNLOCK();
}
#endif /* !RTONCE_NO_TERM */
/* Do the same as RTONCE_INITIALIZER does. */
ASMAtomicWriteS32(&pOnce->rc, VERR_INTERNAL_ERROR);
ASMAtomicWriteS32(&pOnce->iState, RTONCESTATE_UNINITIALIZED);
}
RT_EXPORT_SYMBOL(RTOnceReset);
|
/* Copyright 2015 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
// See docs in ../ops/math_ops.cc.
#define EIGEN_USE_THREADS
#include <vector>
#include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor"
#include "tensorflow/core/framework/op.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/types.h"
#include "tensorflow/core/kernels/fill_functor.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/port.h"
#include "tensorflow/core/public/tensor.h"
#include "tensorflow/core/public/tensor_shape.h"
#include "tensorflow/core/util/work_sharder.h"
#if GOOGLE_CUDA
#include "tensorflow/core/common_runtime/gpu_device_context.h"
#include "tensorflow/core/platform/stream_executor.h"
#endif // GOOGLE_CUDA
namespace tensorflow {
typedef Eigen::ThreadPoolDevice CPUDevice;
typedef Eigen::GpuDevice GPUDevice;
template <typename Device, typename Scalar>
struct LaunchBatchMatMul;
template <typename Scalar>
struct LaunchBatchMatMul<CPUDevice, Scalar> {
static void Launch(OpKernelContext* context, const Tensor& in_x,
const Tensor& in_y, bool adj_x, bool adj_y, Tensor* out) {
auto Tx = in_x.tensor<Scalar, 3>();
auto Ty = in_y.tensor<Scalar, 3>();
auto Tz = out->tensor<Scalar, 3>();
// Shards "n"-matmuls into "num" shards. Each shard is
// dispatched to a thread.
auto worker_threads = *(context->device()->tensorflow_cpu_worker_threads());
const int64 num_units = in_x.dim_size(0);
const int64 cost_per_unit =
in_x.dim_size(0) * in_x.dim_size(1) * out->dim_size(2);
Shard(worker_threads.num_threads, worker_threads.workers, num_units,
cost_per_unit, [&Tx, &Ty, adj_x, adj_y, &Tz](int start, int limit) {
LaunchBatchMatMul<CPUDevice, Scalar>::Run(Tx, Ty, adj_x, adj_y, Tz,
start, limit);
});
}
template <typename In, typename Out>
static void Run(In Tx, In Ty, bool adj_x, bool adj_y, Out Tz, int start,
int limit) {
Eigen::array<Eigen::IndexPair<Eigen::DenseIndex>, 1> contract_pairs;
Eigen::internal::scalar_conjugate_op<Scalar> conj;
if (!adj_x && !adj_y) {
for (int i = start; i < limit; ++i) {
auto x = Tx.template chip<0>(i);
auto y = Ty.template chip<0>(i);
auto z = Tz.template chip<0>(i);
contract_pairs[0] = Eigen::IndexPair<Eigen::DenseIndex>(1, 0);
z = x.contract(y, contract_pairs); // matmul
}
} else if (!adj_x && adj_y) {
for (int i = start; i < limit; ++i) {
auto x = Tx.template chip<0>(i);
auto y = Ty.template chip<0>(i).unaryExpr(conj);
auto z = Tz.template chip<0>(i);
contract_pairs[0] = Eigen::IndexPair<Eigen::DenseIndex>(1, 1);
z = x.contract(y, contract_pairs); // matmul
}
} else if (adj_x && !adj_y) {
for (int i = start; i < limit; ++i) {
auto x = Tx.template chip<0>(i).unaryExpr(conj);
auto y = Ty.template chip<0>(i);
auto z = Tz.template chip<0>(i);
contract_pairs[0] = Eigen::IndexPair<Eigen::DenseIndex>(0, 0);
z = x.contract(y, contract_pairs); // matmul
}
} else {
for (int i = start; i < limit; ++i) {
auto x = Tx.template chip<0>(i).unaryExpr(conj);
auto y = Ty.template chip<0>(i).unaryExpr(conj);
auto z = Tz.template chip<0>(i);
contract_pairs[0] = Eigen::IndexPair<Eigen::DenseIndex>(0, 1);
z = x.contract(y, contract_pairs); // matmul
}
}
}
};
#if GOOGLE_CUDA
namespace {
template <typename T>
perftools::gputools::DeviceMemory<T> AsDeviceMemory(const T* cuda_memory) {
perftools::gputools::DeviceMemoryBase wrapped(const_cast<T*>(cuda_memory));
perftools::gputools::DeviceMemory<T> typed(wrapped);
return typed;
}
} // namespace
template <typename Scalar>
struct LaunchBatchMatMul<GPUDevice, Scalar> {
static void Launch(OpKernelContext* context, const Tensor& in_x,
const Tensor& in_y, bool adj_x, bool adj_y, Tensor* out) {
perftools::gputools::blas::Transpose trans[] = {
perftools::gputools::blas::Transpose::kNoTranspose,
perftools::gputools::blas::Transpose::kTranspose};
const uint64 m = in_x.dim_size(adj_x ? 2 : 1);
const uint64 k = in_x.dim_size(adj_x ? 1 : 2);
const uint64 n = in_y.dim_size(adj_y ? 1 : 2);
const uint64 batch_size = in_x.dim_size(0);
auto blas_transpose_a = trans[adj_x];
auto blas_transpose_b = trans[adj_y];
auto* stream = context->op_device_context<GPUDeviceContext>()->stream();
OP_REQUIRES(context, stream, errors::Internal("No GPU stream available."));
typedef perftools::gputools::DeviceMemory<Scalar> DeviceMemoryType;
std::vector<DeviceMemoryType> a_device_memory;
std::vector<DeviceMemoryType> b_device_memory;
std::vector<DeviceMemoryType> c_device_memory;
std::vector<DeviceMemoryType*> a_ptrs;
std::vector<DeviceMemoryType*> b_ptrs;
std::vector<DeviceMemoryType*> c_ptrs;
a_device_memory.reserve(batch_size);
b_device_memory.reserve(batch_size);
c_device_memory.reserve(batch_size);
a_ptrs.reserve(batch_size);
b_ptrs.reserve(batch_size);
c_ptrs.reserve(batch_size);
auto* a_base_ptr = in_x.template flat<Scalar>().data();
auto* b_base_ptr = in_y.template flat<Scalar>().data();
auto* c_base_ptr = out->template flat<Scalar>().data();
for (int64 i = 0; i < batch_size; ++i) {
a_device_memory.push_back(AsDeviceMemory(a_base_ptr + i * m * k));
b_device_memory.push_back(AsDeviceMemory(b_base_ptr + i * k * n));
c_device_memory.push_back(AsDeviceMemory(c_base_ptr + i * m * n));
a_ptrs.push_back(&a_device_memory.back());
b_ptrs.push_back(&b_device_memory.back());
c_ptrs.push_back(&c_device_memory.back());
}
// Cublas does
// C = A x B
// where A, B and C are assumed to be in column major.
// We want the output to be in row-major, so we can compute
// C' = B' x A' (' stands for transpose)
bool blas_launch_status =
stream->ThenBlasGemmBatched(blas_transpose_b, blas_transpose_a, n, m, k,
static_cast<Scalar>(1.0), b_ptrs,
adj_y ? k : n, a_ptrs, adj_x ? m : k,
static_cast<Scalar>(0.0), c_ptrs, n,
batch_size)
.ok();
if (!blas_launch_status) {
context->SetStatus(errors::Internal(
"Blas SGEMMBatched launch failed : a.shape=",
in_x.shape().DebugString(), ", b.shape=", in_y.shape().DebugString(),
", m=", m, ", n=", n, ", k=", k, ", batch_size=", batch_size));
}
}
};
#endif // GOOGLE_CUDA
template <typename Device, typename Scalar>
class BatchMatMul : public OpKernel {
public:
explicit BatchMatMul(OpKernelConstruction* context) : OpKernel(context) {
OP_REQUIRES_OK(context, context->GetAttr("adj_x", &adj_x_));
OP_REQUIRES_OK(context, context->GetAttr("adj_y", &adj_y_));
}
virtual ~BatchMatMul() {}
void Compute(OpKernelContext* ctx) override {
const Tensor& in0 = ctx->input(0);
const Tensor& in1 = ctx->input(1);
OP_REQUIRES(ctx, in0.dims() == in1.dims(),
errors::InvalidArgument("In[0] and In[1] has different ndims: ",
in0.shape().DebugString(), " vs. ",
in1.shape().DebugString()));
const int ndims = in0.dims();
OP_REQUIRES(
ctx, ndims >= 3,
errors::InvalidArgument("In[0] and In[1] ndims must be >= 3: ", ndims));
TensorShape out_shape;
for (int i = 0; i < ndims - 2; ++i) {
OP_REQUIRES(ctx, in0.dim_size(i) == in1.dim_size(i),
errors::InvalidArgument("In[0].dim(", i, ") and In[1].dim(",
i, ") must be the same: ",
in0.shape().DebugString(), " vs ",
in1.shape().DebugString()));
out_shape.AddDim(in0.dim_size(i));
}
auto n = out_shape.num_elements();
auto d0 = in0.dim_size(ndims - 2);
auto d1 = in0.dim_size(ndims - 1);
Tensor in0_reshaped;
CHECK(in0_reshaped.CopyFrom(in0, TensorShape({n, d0, d1})));
auto d2 = in1.dim_size(ndims - 2);
auto d3 = in1.dim_size(ndims - 1);
Tensor in1_reshaped;
CHECK(in1_reshaped.CopyFrom(in1, TensorShape({n, d2, d3})));
if (adj_x_) std::swap(d0, d1);
if (adj_y_) std::swap(d2, d3);
OP_REQUIRES(ctx, d1 == d2,
errors::InvalidArgument(
"In[0] mismatch In[1] shape: ", d1, " vs. ", d2, ": ",
in0.shape().DebugString(), " ", in1.shape().DebugString(),
" ", adj_x_, " ", adj_y_));
out_shape.AddDim(d0);
out_shape.AddDim(d3);
Tensor* out = nullptr;
OP_REQUIRES_OK(ctx, ctx->allocate_output(0, out_shape, &out));
if (out->NumElements() == 0) {
return;
}
if (in0.NumElements() == 0 || in1.NumElements() == 0) {
functor::SetZeroFunctor<Device, Scalar> f;
f(ctx->eigen_device<Device>(), out->flat<Scalar>());
return;
}
Tensor out_reshaped;
CHECK(out_reshaped.CopyFrom(*out, TensorShape({n, d0, d3})));
LaunchBatchMatMul<Device, Scalar>::Launch(ctx, in0_reshaped, in1_reshaped,
adj_x_, adj_y_, &out_reshaped);
}
private:
bool adj_x_;
bool adj_y_;
};
#define REGISTER_CPU(TYPE) \
REGISTER_KERNEL_BUILDER( \
Name("BatchMatMul").Device(DEVICE_CPU).TypeConstraint<TYPE>("T"), \
BatchMatMul<CPUDevice, TYPE>)
#define REGISTER_GPU(TYPE) \
REGISTER_KERNEL_BUILDER( \
Name("BatchMatMul").Device(DEVICE_GPU).TypeConstraint<TYPE>("T"), \
BatchMatMul<GPUDevice, TYPE>)
REGISTER_CPU(float);
REGISTER_CPU(double);
REGISTER_CPU(int32);
REGISTER_CPU(complex64);
#ifdef GOOGLE_CUDA
// TODO(kalakris): The GPU implementation is currently disabled due to issues
// encountered in practice. See b/24534272.
// REGISTER_GPU(float);
#endif // GOOGLE_CUDA
#undef REGISTER_CPU
#undef REGISTER_GPU
} // end namespace tensorflow
|
/*
* Copyright (c) 2017 [Ribose Inc](https://www.ribose.com).
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/** String utilities
* @file
*/
#include <cstddef>
#include <cstring>
#include "str-utils.h"
#ifdef _WIN32
#include <locale>
#include <codecvt>
#endif
using std::size_t;
using std::strlen;
char *
rnp_strip_eol(char *s)
{
size_t len = strlen(s);
while ((len > 0) && ((s[len - 1] == '\n') || (s[len - 1] == '\r'))) {
s[--len] = '\0';
}
return s;
}
bool
rnp_is_blank_line(const char *line, size_t len)
{
for (size_t i = 0; i < len && line[i]; i++) {
if (line[i] != ' ' && line[i] != '\t' && line[i] != '\r') {
return false;
}
}
return true;
}
#ifdef _WIN32
std::wstring
wstr_from_utf8(const char *s)
{
std::wstring_convert<std::codecvt_utf8<wchar_t>> utf8conv;
return utf8conv.from_bytes(s);
}
std::wstring
wstr_from_utf8(const char *first, const char *last)
{
std::wstring_convert<std::codecvt_utf8<wchar_t>> utf8conv;
return utf8conv.from_bytes(first, last);
}
std::wstring
wstr_from_utf8(const std::string &s)
{
return wstr_from_utf8(s.c_str());
}
std::string
wstr_to_utf8(const wchar_t *ws)
{
std::wstring_convert<std::codecvt_utf8<wchar_t>> utf8conv;
return utf8conv.to_bytes(ws);
}
std::string
wstr_to_utf8(const std::wstring &ws)
{
return wstr_to_utf8(ws.c_str());
}
#endif
|
/****************************************************************************************
Copyright (C) 2015 Autodesk, Inc.
All rights reserved.
Use of this software is subject to the terms of the Autodesk license agreement
provided at the time of installation or download, or which otherwise accompanies
this software in either electronic or hard copy form.
****************************************************************************************/
/////////////////////////////////////////////////////////////////////////
//
// Illustrates the use of animation stacks, layers, curvenodes and curves.
//
// 1. Create a stack.
// 2. Add the mandatory base layer.
// 3. Show how to set the layer blend mode bypass.
// 4. Animate the layers's weight property.
// 5. Show how to use AddChannel and ResetChannels.
// 6. Create a 3 components curvenode and animate two of the three channels.
// 7. Add the curve node to the animation layer.
// 8. Create curves and add keys.
// 9. Create an extra layer with a different blend mode.
// 10. Show how to share the same animation curve on two layers (different channels)
// 11. Evaluate the overall result.
/////////////////////////////////////////////////////////////////////////
#include <fbxsdk.h>
#include "../Common/Common.h"
// Function prototypes.
bool CreateScene(FbxManager* pSdkManager, FbxScene* pScene);
int main(int /*argc*/, char** /*argv*/)
{
FbxManager* lSdkManager = NULL;
FbxScene* lScene = NULL;
// Prepare the FBX SDK.
InitializeSdkObjects(lSdkManager, lScene);
// Create the scene.
if( !CreateScene(lSdkManager, lScene) )
{
FBXSDK_printf("\n\nAn error occurred while creating the scene...\n");
DestroySdkObjects(lSdkManager, false);
return 0;
}
// Destroy all objects created by the FBX SDK.
DestroySdkObjects(lSdkManager, true);
return 0;
}
bool CreateScene(FbxManager* /*pSdkManager*/, FbxScene* pScene)
{
int i;
FbxTime lTime;
FbxAnimCurveKey key;
FbxAnimCurve* lCurve = NULL;
// Create one animation stack
FbxAnimStack* lAnimStack = FbxAnimStack::Create(pScene, "Stack001");
// this stack animation range is limited from 0 to 1 second
lAnimStack->LocalStop = FBXSDK_TIME_ONE_SECOND;
lAnimStack->Description = "This is the animation stack description field.";
// all animation stacks need, at least, one layer.
FbxAnimLayer* lAnimLayer = FbxAnimLayer::Create(pScene, "Base Layer"); // the AnimLayer object name is "Base Layer"
lAnimStack->AddMember(lAnimLayer); // add the layer to the stack
// Set and get the blend mode bypass of the layer
bool val;
lAnimLayer->SetBlendModeBypass(eFbxTypeCount, true); // set the bypass to all the datatypes.
val = lAnimLayer->GetBlendModeBypass(eFbxBool); // val = true
lAnimLayer->SetBlendModeBypass(eFbxBool, false); // overwrite just for the bool datatype.
val = lAnimLayer->GetBlendModeBypass(eFbxBool); // val = false
val = lAnimLayer->GetBlendModeBypass(eFbxChar); // val = true
val = lAnimLayer->GetBlendModeBypass(eFbxDateTime); // val = true
val = lAnimLayer->GetBlendModeBypass((EFbxType)-1); // invalid type, val = false
val = lAnimLayer->GetBlendModeBypass((EFbxType)120); // invalid type (>MAX_TYPES), val = false
// we want to animate the layer's weight property.
FbxAnimCurveNode* wcn = lAnimLayer->CreateCurveNode(lAnimLayer->Weight);
if (wcn)
{
// the curve node from the Weight property already contains 1 channel (Weight).
i = wcn->GetChannelsCount(); // i = 1
// Now, let's add a second channel to the animation node. Note that this code
// is useless and has only been provided to show the usage of the AddChannel and
// ResetChannels
bool ret;
ret = wcn->AddChannel<int>("MyAddedIntChannel", 99); // this call will succed
i = wcn->GetChannelsCount(); // i = 2
ret = wcn->AddChannel<int>("MyAddedIntChannel", 10); // this call will fail, since the channel already exists.
i = wcn->GetChannelsCount(); // i = 2
wcn->ResetChannels(); // remove any added channels
i = wcn->GetChannelsCount(); // i = 1
}
// get the Weight curve (and create it if it does not exist, wich is the case!)
lCurve = lAnimLayer->Weight.GetCurve(lAnimLayer, true);
if (lCurve)
{
// add two keys at time 0 sec and 1 sec with values 0 and 100 respectively.
lCurve->KeyModifyBegin();
for (i = 0; i < 2; i++)
{
lTime.SetSecondDouble((float)i);
key.Set(lTime, i*100.0f);
lCurve->KeyAdd(lTime, key);
}
lCurve->KeyModifyEnd();
}
//
// now create a 3 components curvenode and animate two of the three channels.
//
// first, we need a "dummy" property so we can call the CreateTypedCurveNode
FbxProperty p = FbxProperty::Create(pScene, FbxDouble3DT, "Vector3Property");
p.Set(FbxDouble3(1.1, 2.2, 3.3));
FbxAnimCurveNode* lCurveNode = FbxAnimCurveNode::CreateTypedCurveNode(p, pScene);
// let's make sure the curveNode is added to the animation layer.
lAnimLayer->AddMember(lCurveNode);
// and to the "Vector3Property" since CreateTypedCurveNode does not make any connection
p.ConnectSrcObject(lCurveNode);
//Example of channel get value:
//double v1 = lCurveNode->GetChannelValue<double>(0U, 0.0); // v1 = 1.1
//float v2 = lCurveNode->GetChannelValue<float> (1U, 0.0f); // v2 = 2.2
//int v3 = lCurveNode->GetChannelValue<int> (2U, 0); // v3 = 3
//
// create two free curves (not connected to anything)
//
// first curve
lCurve = FbxAnimCurve::Create(pScene, "curve1");
if (lCurve)
{
// add two keys at time 0 sec and 1 sec with values 0 and 10 respectively.
lCurve->KeyModifyBegin();
for (i = 0; i < 2; i++)
{
lTime.SetSecondDouble((float)i);
key.Set(lTime, i*10.0f);
lCurve->KeyAdd(lTime, key);
}
lCurve->KeyModifyEnd();
}
// connect it to the second channel
lCurveNode->ConnectToChannel(lCurve, 1);
// second curve
lCurve = FbxAnimCurve::Create(pScene, "curve2");
if (lCurve)
{
// add three keys at time 1, 2 and 3 sec with values 3.33, 6.66 and 9.99 respectively
lCurve->KeyModifyBegin();
for (i = 1; i < 4; i++)
{
lTime.SetSecondDouble((float)i);
key.Set(lTime, i*3.33f);
lCurve->KeyAdd(lTime, key);
}
lCurve->KeyModifyEnd();
}
// connect it to the third channel
lCurveNode->ConnectToChannel(lCurve, "Z"); // for backward compatibility, string identifier are still
// allowed for the X,Y,Z and W components or "0", "1", ... "9", "A", "B", ... "F" for the Matrix44 datatype
// ======================================================================
//
// Add a second animation layer and evaluate using the FbxAnimEvaluator
//
// ======================================================================
lAnimLayer = FbxAnimLayer::Create(pScene, "Layer2");
lAnimStack->AddMember(lAnimLayer);
// get the number of animation layers in the stack
// int nbLayers = lAnimStack->GetMemberCount<FbxAnimLayer>(); // nblayers = 2
lAnimLayer = lAnimStack->GetMember<FbxAnimLayer>(1); // get the second layer
// set its blend mode to Additive
lAnimLayer->BlendMode.Set(FbxAnimLayer::eBlendAdditive);
// Now, let's animate the first channel of the "Vector3Property" (remember, we animated the second and
// third ones on the base layer - when we connected "curve1" and "curve2" on lCurveNode above)
// but first, make sure the property is animatable otherwise the creation of the curveNode is prohibited.
p.ModifyFlag(FbxPropertyFlags::eAnimatable, true);
lCurveNode = p.GetCurveNode(lAnimLayer, true); // create it since it does not exist yet
// use "curve2" to animate it on channel 0
lCurveNode->ConnectToChannel(lCurve, 0U);
// and set the other two channels values
lCurveNode->SetChannelValue<double>(1U, 5.0);
lCurveNode->SetChannelValue<double>(2U, 0.0);
// evaluate the "Vector3Property" value at three different times
// with the use of the FbxAnimEvaluator so we take into account the two layers
// make sure the evaluator is using the correct context (context == animstack)
pScene->SetCurrentAnimationStack(lAnimStack);
for (i = 0; i < 3; i++)
{
lTime.SetSecondDouble((float)i);
FbxDouble3 value = p.EvaluateValue<FbxDouble3>(lTime);
}
/*
The base layer has a weight curve:
Time | 0 | 1 | 2 |
Weight +-------------+----------------+--------------|
Base Layer | 0.0 | 100.0% | (100.0%) |
Layer2 | <100.0%> | <100.0%> | <100.0%> |
+-------------+----------------+--------------|
() Querying values outside the first and/or last keys in a curve will return
the first/last key defined.
<> Since it has never been set, it defaults to the multiplication neutral element (in percent).
At the specified times each channel value on their respective layers is:
Time | 0 | 1 | 2 |
Channel +-------------+----------------+--------------|
0 Base | 0* | 1.1* | 1.1* |
Layer2 | (3.33) | 3.33 | 6.66 | (curve2)
+-------------+----------------+--------------|
1 Base | 0* | 10.0* | (10.0) | (curve1)
Layer2 | 5.0 | 5.0 | 5.0 |
+-------------+----------------+--------------|
2 Base | 0* | 3.3* | 6.66* | (curve2)
Layer2 | 0.0 | 0.0 | 0.0 |
+-------------+----------------+--------------|
* key (or property, if not animated) value multiplied by the weight.
() same as value at time 1 since there is no key here.
therefore, considering that the second animation layer's blend mode is set
to additive, the evaluated values for v at 0, 1 and 2 seconds are:
time | 0 | 1 | 2 |
v +-------------+----------------+--------------|
0 | 3.33 | 4.43 | 7.76 |
1 | 5.0 | 15.00 | 15.00 |
2 | 0.0 | 3.33 | 6.66 |
+-------------+----------------+--------------|
*/
return true;
}
|
// dear imgui, v1.79 WIP
// (main code and documentation)
// Help:
// - Read FAQ at http://dearimgui.org/faq
// - Newcomers, read 'Programmer guide' below for notes on how to setup Dear ImGui in your codebase.
// - Call and read ImGui::ShowDemoWindow() in imgui_demo.cpp. All applications in examples/ are doing that.
// Read imgui.cpp for details, links and comments.
// Resources:
// - FAQ http://dearimgui.org/faq
// - Homepage & latest https://github.com/ocornut/imgui
// - Releases & changelog https://github.com/ocornut/imgui/releases
// - Gallery https://github.com/ocornut/imgui/issues/3075 (please post your screenshots/video there!)
// - Glossary https://github.com/ocornut/imgui/wiki/Glossary
// - Wiki https://github.com/ocornut/imgui/wiki
// - Issues & support https://github.com/ocornut/imgui/issues
// Developed by Omar Cornut and every direct or indirect contributors to the GitHub.
// See LICENSE.txt for copyright and licensing details (standard MIT License).
// This library is free but needs your support to sustain development and maintenance.
// Businesses: you can support continued development via invoiced technical support, maintenance and sponsoring contracts. Please reach out to "contact AT dearimgui.org".
// Individuals: you can support continued development via donations. See docs/README or web page.
// It is recommended that you don't modify imgui.cpp! It will become difficult for you to update the library.
// Note that 'ImGui::' being a namespace, you can add functions into the namespace from your own source files, without
// modifying imgui.h or imgui.cpp. You may include imgui_internal.h to access internal data structures, but it doesn't
// come with any guarantee of forward compatibility. Discussing your changes on the GitHub Issue Tracker may lead you
// to a better solution or official support for them.
/*
Index of this file:
DOCUMENTATION
- MISSION STATEMENT
- END-USER GUIDE
- PROGRAMMER GUIDE
- READ FIRST
- HOW TO UPDATE TO A NEWER VERSION OF DEAR IMGUI
- GETTING STARTED WITH INTEGRATING DEAR IMGUI IN YOUR CODE/ENGINE
- HOW A SIMPLE APPLICATION MAY LOOK LIKE
- HOW A SIMPLE RENDERING FUNCTION MAY LOOK LIKE
- USING GAMEPAD/KEYBOARD NAVIGATION CONTROLS
- API BREAKING CHANGES (read me when you update!)
- FREQUENTLY ASKED QUESTIONS (FAQ)
- Read all answers online: https://www.dearimgui.org/faq, or in docs/FAQ.md (with a Markdown viewer)
CODE
(search for "[SECTION]" in the code to find them)
// [SECTION] INCLUDES
// [SECTION] FORWARD DECLARATIONS
// [SECTION] CONTEXT AND MEMORY ALLOCATORS
// [SECTION] USER FACING STRUCTURES (ImGuiStyle, ImGuiIO)
// [SECTION] MISC HELPERS/UTILITIES (Geometry functions)
// [SECTION] MISC HELPERS/UTILITIES (String, Format, Hash functions)
// [SECTION] MISC HELPERS/UTILITIES (File functions)
// [SECTION] MISC HELPERS/UTILITIES (ImText* functions)
// [SECTION] MISC HELPERS/UTILITIES (Color functions)
// [SECTION] ImGuiStorage
// [SECTION] ImGuiTextFilter
// [SECTION] ImGuiTextBuffer
// [SECTION] ImGuiListClipper
// [SECTION] STYLING
// [SECTION] RENDER HELPERS
// [SECTION] MAIN CODE (most of the code! lots of stuff, needs tidying up!)
// [SECTION] ERROR CHECKING
// [SECTION] LAYOUT
// [SECTION] SCROLLING
// [SECTION] TOOLTIPS
// [SECTION] POPUPS
// [SECTION] KEYBOARD/GAMEPAD NAVIGATION
// [SECTION] DRAG AND DROP
// [SECTION] LOGGING/CAPTURING
// [SECTION] SETTINGS
// [SECTION] PLATFORM DEPENDENT HELPERS
// [SECTION] METRICS/DEBUG WINDOW
*/
//-----------------------------------------------------------------------------
// DOCUMENTATION
//-----------------------------------------------------------------------------
/*
MISSION STATEMENT
=================
- Easy to use to create code-driven and data-driven tools.
- Easy to use to create ad hoc short-lived tools and long-lived, more elaborate tools.
- Easy to hack and improve.
- Minimize screen real-estate usage.
- Minimize setup and maintenance.
- Minimize state storage on user side.
- Portable, minimize dependencies, run on target (consoles, phones, etc.).
- Efficient runtime and memory consumption (NB- we do allocate when "growing" content e.g. creating a window,.
opening a tree node for the first time, etc. but a typical frame should not allocate anything).
Designed for developers and content-creators, not the typical end-user! Some of the weaknesses includes:
- Doesn't look fancy, doesn't animate.
- Limited layout features, intricate layouts are typically crafted in code.
END-USER GUIDE
==============
- Double-click on title bar to collapse window.
- Click upper right corner to close a window, available when 'bool* p_open' is passed to ImGui::Begin().
- Click and drag on lower right corner to resize window (double-click to auto fit window to its contents).
- Click and drag on any empty space to move window.
- TAB/SHIFT+TAB to cycle through keyboard editable fields.
- CTRL+Click on a slider or drag box to input value as text.
- Use mouse wheel to scroll.
- Text editor:
- Hold SHIFT or use mouse to select text.
- CTRL+Left/Right to word jump.
- CTRL+Shift+Left/Right to select words.
- CTRL+A our Double-Click to select all.
- CTRL+X,CTRL+C,CTRL+V to use OS clipboard/
- CTRL+Z,CTRL+Y to undo/redo.
- ESCAPE to revert text to its original value.
- You can apply arithmetic operators +,*,/ on numerical values. Use +- to subtract (because - would set a negative value!)
- Controls are automatically adjusted for OSX to match standard OSX text editing operations.
- General Keyboard controls: enable with ImGuiConfigFlags_NavEnableKeyboard.
- General Gamepad controls: enable with ImGuiConfigFlags_NavEnableGamepad. See suggested mappings in imgui.h ImGuiNavInput_ + download PNG/PSD at http://goo.gl/9LgVZW
PROGRAMMER GUIDE
================
READ FIRST
----------
- Remember to read the FAQ (https://www.dearimgui.org/faq)
- Your code creates the UI, if your code doesn't run the UI is gone! The UI can be highly dynamic, there are no construction
or destruction steps, less superfluous data retention on your side, less state duplication, less state synchronization, less bugs.
- Call and read ImGui::ShowDemoWindow() for demo code demonstrating most features.
- The library is designed to be built from sources. Avoid pre-compiled binaries and packaged versions. See imconfig.h to configure your build.
- Dear ImGui is an implementation of the IMGUI paradigm (immediate-mode graphical user interface, a term coined by Casey Muratori).
You can learn about IMGUI principles at http://www.johno.se/book/imgui.html, http://mollyrocket.com/861 & more links in the FAQ.
- Dear ImGui is a "single pass" rasterizing implementation of the IMGUI paradigm, aimed at ease of use and high-performances.
For every application frame your UI code will be called only once. This is in contrast to e.g. Unity's own implementation of an IMGUI,
where the UI code is called multiple times ("multiple passes") from a single entry point. There are pros and cons to both approaches.
- Our origin are on the top-left. In axis aligned bounding boxes, Min = top-left, Max = bottom-right.
- This codebase is also optimized to yield decent performances with typical "Debug" builds settings.
- Please make sure you have asserts enabled (IM_ASSERT redirects to assert() by default, but can be redirected).
If you get an assert, read the messages and comments around the assert.
- C++: this is a very C-ish codebase: we don't rely on C++11, we don't include any C++ headers, and ImGui:: is a namespace.
- C++: ImVec2/ImVec4 do not expose math operators by default, because it is expected that you use your own math types.
See FAQ "How can I use my own math types instead of ImVec2/ImVec4?" for details about setting up imconfig.h for that.
However, imgui_internal.h can optionally export math operators for ImVec2/ImVec4, which we use in this codebase.
- C++: pay attention that ImVector<> manipulates plain-old-data and does not honor construction/destruction (avoid using it in your code!).
HOW TO UPDATE TO A NEWER VERSION OF DEAR IMGUI
----------------------------------------------
- Overwrite all the sources files except for imconfig.h (if you have made modification to your copy of imconfig.h)
- Or maintain your own branch where you have imconfig.h modified.
- Read the "API BREAKING CHANGES" section (below). This is where we list occasional API breaking changes.
If a function/type has been renamed / or marked obsolete, try to fix the name in your code before it is permanently removed
from the public API. If you have a problem with a missing function/symbols, search for its name in the code, there will
likely be a comment about it. Please report any issue to the GitHub page!
- Try to keep your copy of dear imgui reasonably up to date.
GETTING STARTED WITH INTEGRATING DEAR IMGUI IN YOUR CODE/ENGINE
---------------------------------------------------------------
- Run and study the examples and demo in imgui_demo.cpp to get acquainted with the library.
- In the majority of cases you should be able to use unmodified back-ends files available in the examples/ folder.
- Add the Dear ImGui source files + selected back-end source files to your projects or using your preferred build system.
It is recommended you build and statically link the .cpp files as part of your project and NOT as shared library (DLL).
- You can later customize the imconfig.h file to tweak some compile-time behavior, such as integrating Dear ImGui types with your own maths types.
- When using Dear ImGui, your programming IDE is your friend: follow the declaration of variables, functions and types to find comments about them.
- Dear ImGui never touches or knows about your GPU state. The only function that knows about GPU is the draw function that you provide.
Effectively it means you can create widgets at any time in your code, regardless of considerations of being in "update" vs "render"
phases of your own application. All rendering information are stored into command-lists that you will retrieve after calling ImGui::Render().
- Refer to the bindings and demo applications in the examples/ folder for instruction on how to setup your code.
- If you are running over a standard OS with a common graphics API, you should be able to use unmodified imgui_impl_*** files from the examples/ folder.
HOW A SIMPLE APPLICATION MAY LOOK LIKE
--------------------------------------
EXHIBIT 1: USING THE EXAMPLE BINDINGS (= imgui_impl_XXX.cpp files from the examples/ folder).
The sub-folders in examples/ contains examples applications following this structure.
// Application init: create a dear imgui context, setup some options, load fonts
ImGui::CreateContext();
ImGuiIO& io = ImGui::GetIO();
// TODO: Set optional io.ConfigFlags values, e.g. 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard' to enable keyboard controls.
// TODO: Fill optional fields of the io structure later.
// TODO: Load TTF/OTF fonts if you don't want to use the default font.
// Initialize helper Platform and Renderer bindings (here we are using imgui_impl_win32.cpp and imgui_impl_dx11.cpp)
ImGui_ImplWin32_Init(hwnd);
ImGui_ImplDX11_Init(g_pd3dDevice, g_pd3dDeviceContext);
// Application main loop
while (true)
{
// Feed inputs to dear imgui, start new frame
ImGui_ImplDX11_NewFrame();
ImGui_ImplWin32_NewFrame();
ImGui::NewFrame();
// Any application code here
ImGui::Text("Hello, world!");
// Render dear imgui into screen
ImGui::Render();
ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData());
g_pSwapChain->Present(1, 0);
}
// Shutdown
ImGui_ImplDX11_Shutdown();
ImGui_ImplWin32_Shutdown();
ImGui::DestroyContext();
EXHIBIT 2: IMPLEMENTING CUSTOM BINDING / CUSTOM ENGINE
// Application init: create a dear imgui context, setup some options, load fonts
ImGui::CreateContext();
ImGuiIO& io = ImGui::GetIO();
// TODO: Set optional io.ConfigFlags values, e.g. 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard' to enable keyboard controls.
// TODO: Fill optional fields of the io structure later.
// TODO: Load TTF/OTF fonts if you don't want to use the default font.
// Build and load the texture atlas into a texture
// (In the examples/ app this is usually done within the ImGui_ImplXXX_Init() function from one of the demo Renderer)
int width, height;
unsigned char* pixels = NULL;
io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
// At this point you've got the texture data and you need to upload that your your graphic system:
// After we have created the texture, store its pointer/identifier (_in whichever format your engine uses_) in 'io.Fonts->TexID'.
// This will be passed back to your via the renderer. Basically ImTextureID == void*. Read FAQ for details about ImTextureID.
MyTexture* texture = MyEngine::CreateTextureFromMemoryPixels(pixels, width, height, TEXTURE_TYPE_RGBA32)
io.Fonts->TexID = (void*)texture;
// Application main loop
while (true)
{
// Setup low-level inputs, e.g. on Win32: calling GetKeyboardState(), or write to those fields from your Windows message handlers, etc.
// (In the examples/ app this is usually done within the ImGui_ImplXXX_NewFrame() function from one of the demo Platform bindings)
io.DeltaTime = 1.0f/60.0f; // set the time elapsed since the previous frame (in seconds)
io.DisplaySize.x = 1920.0f; // set the current display width
io.DisplaySize.y = 1280.0f; // set the current display height here
io.MousePos = my_mouse_pos; // set the mouse position
io.MouseDown[0] = my_mouse_buttons[0]; // set the mouse button states
io.MouseDown[1] = my_mouse_buttons[1];
// Call NewFrame(), after this point you can use ImGui::* functions anytime
// (So you want to try calling NewFrame() as early as you can in your mainloop to be able to use Dear ImGui everywhere)
ImGui::NewFrame();
// Most of your application code here
ImGui::Text("Hello, world!");
MyGameUpdate(); // may use any Dear ImGui functions, e.g. ImGui::Begin("My window"); ImGui::Text("Hello, world!"); ImGui::End();
MyGameRender(); // may use any Dear ImGui functions as well!
// Render dear imgui, swap buffers
// (You want to try calling EndFrame/Render as late as you can, to be able to use Dear ImGui in your own game rendering code)
ImGui::EndFrame();
ImGui::Render();
ImDrawData* draw_data = ImGui::GetDrawData();
MyImGuiRenderFunction(draw_data);
SwapBuffers();
}
// Shutdown
ImGui::DestroyContext();
To decide whether to dispatch mouse/keyboard inputs to Dear ImGui to the rest your application,
you should read the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags!
Please read the FAQ and example applications for details about this!
HOW A SIMPLE RENDERING FUNCTION MAY LOOK LIKE
---------------------------------------------
The bindings in impl_impl_XXX.cpp files contains many working implementations of a rendering function.
void void MyImGuiRenderFunction(ImDrawData* draw_data)
{
// TODO: Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled
// TODO: Setup viewport covering draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize
// TODO: Setup orthographic projection matrix cover draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize
// TODO: Setup shader: vertex { float2 pos, float2 uv, u32 color }, fragment shader sample color from 1 texture, multiply by vertex color.
for (int n = 0; n < draw_data->CmdListsCount; n++)
{
const ImDrawList* cmd_list = draw_data->CmdLists[n];
const ImDrawVert* vtx_buffer = cmd_list->VtxBuffer.Data; // vertex buffer generated by Dear ImGui
const ImDrawIdx* idx_buffer = cmd_list->IdxBuffer.Data; // index buffer generated by Dear ImGui
for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
{
const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
if (pcmd->UserCallback)
{
pcmd->UserCallback(cmd_list, pcmd);
}
else
{
// The texture for the draw call is specified by pcmd->TextureId.
// The vast majority of draw calls will use the Dear ImGui texture atlas, which value you have set yourself during initialization.
MyEngineBindTexture((MyTexture*)pcmd->TextureId);
// We are using scissoring to clip some objects. All low-level graphics API should supports it.
// - If your engine doesn't support scissoring yet, you may ignore this at first. You will get some small glitches
// (some elements visible outside their bounds) but you can fix that once everything else works!
// - Clipping coordinates are provided in imgui coordinates space (from draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize)
// In a single viewport application, draw_data->DisplayPos will always be (0,0) and draw_data->DisplaySize will always be == io.DisplaySize.
// However, in the interest of supporting multi-viewport applications in the future (see 'viewport' branch on github),
// always subtract draw_data->DisplayPos from clipping bounds to convert them to your viewport space.
// - Note that pcmd->ClipRect contains Min+Max bounds. Some graphics API may use Min+Max, other may use Min+Size (size being Max-Min)
ImVec2 pos = draw_data->DisplayPos;
MyEngineScissor((int)(pcmd->ClipRect.x - pos.x), (int)(pcmd->ClipRect.y - pos.y), (int)(pcmd->ClipRect.z - pos.x), (int)(pcmd->ClipRect.w - pos.y));
// Render 'pcmd->ElemCount/3' indexed triangles.
// By default the indices ImDrawIdx are 16-bit, you can change them to 32-bit in imconfig.h if your engine doesn't support 16-bit indices.
MyEngineDrawIndexedTriangles(pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer, vtx_buffer);
}
idx_buffer += pcmd->ElemCount;
}
}
}
USING GAMEPAD/KEYBOARD NAVIGATION CONTROLS
------------------------------------------
- The gamepad/keyboard navigation is fairly functional and keeps being improved.
- Gamepad support is particularly useful to use Dear ImGui on a console system (e.g. PS4, Switch, XB1) without a mouse!
- You can ask questions and report issues at https://github.com/ocornut/imgui/issues/787
- The initial focus was to support game controllers, but keyboard is becoming increasingly and decently usable.
- Keyboard:
- Set io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard to enable.
NewFrame() will automatically fill io.NavInputs[] based on your io.KeysDown[] + io.KeyMap[] arrays.
- When keyboard navigation is active (io.NavActive + ImGuiConfigFlags_NavEnableKeyboard), the io.WantCaptureKeyboard flag
will be set. For more advanced uses, you may want to read from:
- io.NavActive: true when a window is focused and it doesn't have the ImGuiWindowFlags_NoNavInputs flag set.
- io.NavVisible: true when the navigation cursor is visible (and usually goes false when mouse is used).
- or query focus information with e.g. IsWindowFocused(ImGuiFocusedFlags_AnyWindow), IsItemFocused() etc. functions.
Please reach out if you think the game vs navigation input sharing could be improved.
- Gamepad:
- Set io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad to enable.
- Backend: Set io.BackendFlags |= ImGuiBackendFlags_HasGamepad + fill the io.NavInputs[] fields before calling NewFrame().
Note that io.NavInputs[] is cleared by EndFrame().
- See 'enum ImGuiNavInput_' in imgui.h for a description of inputs. For each entry of io.NavInputs[], set the following values:
0.0f= not held. 1.0f= fully held. Pass intermediate 0.0f..1.0f values for analog triggers/sticks.
- We uses a simple >0.0f test for activation testing, and won't attempt to test for a dead-zone.
Your code will probably need to transform your raw inputs (such as e.g. remapping your 0.2..0.9 raw input range to 0.0..1.0 imgui range, etc.).
- You can download PNG/PSD files depicting the gamepad controls for common controllers at: http://goo.gl/9LgVZW.
- If you need to share inputs between your game and the imgui parts, the easiest approach is to go all-or-nothing, with a buttons combo
to toggle the target. Please reach out if you think the game vs navigation input sharing could be improved.
- Mouse:
- PS4 users: Consider emulating a mouse cursor with DualShock4 touch pad or a spare analog stick as a mouse-emulation fallback.
- Consoles/Tablet/Phone users: Consider using a Synergy 1.x server (on your PC) + uSynergy.c (on your console/tablet/phone app) to share your PC mouse/keyboard.
- On a TV/console system where readability may be lower or mouse inputs may be awkward, you may want to set the ImGuiConfigFlags_NavEnableSetMousePos flag.
Enabling ImGuiConfigFlags_NavEnableSetMousePos + ImGuiBackendFlags_HasSetMousePos instructs dear imgui to move your mouse cursor along with navigation movements.
When enabled, the NewFrame() function may alter 'io.MousePos' and set 'io.WantSetMousePos' to notify you that it wants the mouse cursor to be moved.
When that happens your back-end NEEDS to move the OS or underlying mouse cursor on the next frame. Some of the binding in examples/ do that.
(If you set the NavEnableSetMousePos flag but don't honor 'io.WantSetMousePos' properly, imgui will misbehave as it will see your mouse as moving back and forth!)
(In a setup when you may not have easy control over the mouse cursor, e.g. uSynergy.c doesn't expose moving remote mouse cursor, you may want
to set a boolean to ignore your other external mouse positions until the external source is moved again.)
API BREAKING CHANGES
====================
Occasionally introducing changes that are breaking the API. We try to make the breakage minor and easy to fix.
Below is a change-log of API breaking changes only. If you are using one of the functions listed, expect to have to fix some code.
When you are not sure about a old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all imgui files.
You can read releases logs https://github.com/ocornut/imgui/releases for more details.
- 2020/08/17 (1.78) - obsoleted use of the trailing 'float power=1.0f' parameter for DragFloat(), DragFloat2(), DragFloat3(), DragFloat4(), DragFloatRange2(), DragScalar(), DragScalarN(), SliderFloat(), SliderFloat2(), SliderFloat3(), SliderFloat4(), SliderScalar(), SliderScalarN(), VSliderFloat() and VSliderScalar().
replaced the 'float power=1.0f' argument with integer-based flags defaulting to 0 (as with all our flags).
worked out a backward-compatibility scheme so hopefully most C++ codebase should not be affected. in short, when calling those functions:
- if you omitted the 'power' parameter (likely!), you are not affected.
- if you set the 'power' parameter to 1.0f (same as previous default value): 1/ your compiler may warn on float>int conversion, 2/ everything else will work. 3/ you can replace the 1.0f value with 0 to fix the warning, and be technically correct.
- if you set the 'power' parameter to >1.0f (to enable non-linear editing): 1/ your compiler may warn on float>int conversion, 2/ code will assert at runtime, 3/ in case asserts are disabled, the code will not crash and enable the _Logarithmic flag. 4/ you can replace the >1.0f value with ImGuiSliderFlags_Logarithmic to fix the warning/assert and get a _similar_ effect as previous uses of power >1.0f.
see https://github.com/ocornut/imgui/issues/3361 for all details.
kept inline redirection functions (will obsolete) apart for: DragFloatRange2(), VSliderFloat(), VSliderScalar(). For those three the 'float power=1.0f' version were removed directly as they were most unlikely ever used.
for shared code, you can version check at compile-time with `#if IMGUI_VERSION_NUM >= 17704`.
- obsoleted use of v_min > v_max in DragInt, DragFloat, DragScalar to lock edits (introduced in 1.73, was not demoed nor documented very), will be replaced by a more generic ReadOnly feature. You may use the ImGuiSliderFlags_ReadOnly internal flag in the meantime.
- 2020/06/23 (1.77) - removed BeginPopupContextWindow(const char*, int mouse_button, bool also_over_items) in favor of BeginPopupContextWindow(const char*, ImGuiPopupFlags flags) with ImGuiPopupFlags_NoOverItems.
- 2020/06/15 (1.77) - renamed OpenPopupOnItemClick() to OpenPopupContextItem(). Kept inline redirection function (will obsolete).
- 2020/06/15 (1.77) - removed CalcItemRectClosestPoint() entry point which was made obsolete and asserting in December 2017.
- 2020/04/23 (1.77) - removed unnecessary ID (first arg) of ImFontAtlas::AddCustomRectRegular().
- 2020/01/22 (1.75) - ImDrawList::AddCircle()/AddCircleFilled() functions don't accept negative radius any more.
- 2019/12/17 (1.75) - [undid this change in 1.76] made Columns() limited to 64 columns by asserting above that limit. While the current code technically supports it, future code may not so we're putting the restriction ahead.
- 2019/12/13 (1.75) - [imgui_internal.h] changed ImRect() default constructor initializes all fields to 0.0f instead of (FLT_MAX,FLT_MAX,-FLT_MAX,-FLT_MAX). If you used ImRect::Add() to create bounding boxes by adding multiple points into it, you may need to fix your initial value.
- 2019/12/08 (1.75) - removed redirecting functions/enums that were marked obsolete in 1.53 (December 2017):
- ShowTestWindow() -> use ShowDemoWindow()
- IsRootWindowFocused() -> use IsWindowFocused(ImGuiFocusedFlags_RootWindow)
- IsRootWindowOrAnyChildFocused() -> use IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows)
- SetNextWindowContentWidth(w) -> use SetNextWindowContentSize(ImVec2(w, 0.0f)
- GetItemsLineHeightWithSpacing() -> use GetFrameHeightWithSpacing()
- ImGuiCol_ChildWindowBg -> use ImGuiCol_ChildBg
- ImGuiStyleVar_ChildWindowRounding -> use ImGuiStyleVar_ChildRounding
- ImGuiTreeNodeFlags_AllowOverlapMode -> use ImGuiTreeNodeFlags_AllowItemOverlap
- IMGUI_DISABLE_TEST_WINDOWS -> use IMGUI_DISABLE_DEMO_WINDOWS
- 2019/12/08 (1.75) - obsoleted calling ImDrawList::PrimReserve() with a negative count (which was the vaguely documented and rarely if ever used). Instead we added an explicit PrimUnreserve() API.
- 2019/12/06 (1.75) - removed implicit default parameter to IsMouseDragging(int button = 0) to be consistent with other mouse functions (none of the other functions have it).
- 2019/11/21 (1.74) - ImFontAtlas::AddCustomRectRegular() now requires an ID larger than 0x110000 (instead of 0x10000) to conform with supporting Unicode planes 1-16 in a future update. ID below 0x110000 will now assert.
- 2019/11/19 (1.74) - renamed IMGUI_DISABLE_FORMAT_STRING_FUNCTIONS to IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS for consistency.
- 2019/11/19 (1.74) - renamed IMGUI_DISABLE_MATH_FUNCTIONS to IMGUI_DISABLE_DEFAULT_MATH_FUNCTIONS for consistency.
- 2019/10/22 (1.74) - removed redirecting functions/enums that were marked obsolete in 1.52 (October 2017):
- Begin() [old 5 args version] -> use Begin() [3 args], use SetNextWindowSize() SetNextWindowBgAlpha() if needed
- IsRootWindowOrAnyChildHovered() -> use IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows)
- AlignFirstTextHeightToWidgets() -> use AlignTextToFramePadding()
- SetNextWindowPosCenter() -> use SetNextWindowPos() with a pivot of (0.5f, 0.5f)
- ImFont::Glyph -> use ImFontGlyph
- 2019/10/14 (1.74) - inputs: Fixed a miscalculation in the keyboard/mouse "typematic" repeat delay/rate calculation, used by keys and e.g. repeating mouse buttons as well as the GetKeyPressedAmount() function.
if you were using a non-default value for io.KeyRepeatRate (previous default was 0.250), you can add +io.KeyRepeatDelay to it to compensate for the fix.
The function was triggering on: 0.0 and (delay+rate*N) where (N>=1). Fixed formula responds to (N>=0). Effectively it made io.KeyRepeatRate behave like it was set to (io.KeyRepeatRate + io.KeyRepeatDelay).
If you never altered io.KeyRepeatRate nor used GetKeyPressedAmount() this won't affect you.
- 2019/07/15 (1.72) - removed TreeAdvanceToLabelPos() which is rarely used and only does SetCursorPosX(GetCursorPosX() + GetTreeNodeToLabelSpacing()). Kept redirection function (will obsolete).
- 2019/07/12 (1.72) - renamed ImFontAtlas::CustomRect to ImFontAtlasCustomRect. Kept redirection typedef (will obsolete).
- 2019/06/14 (1.72) - removed redirecting functions/enums names that were marked obsolete in 1.51 (June 2017): ImGuiCol_Column*, ImGuiSetCond_*, IsItemHoveredRect(), IsPosHoveringAnyWindow(), IsMouseHoveringAnyWindow(), IsMouseHoveringWindow(), IMGUI_ONCE_UPON_A_FRAME. Grep this log for details and new names, or see how they were implemented until 1.71.
- 2019/06/07 (1.71) - rendering of child window outer decorations (bg color, border, scrollbars) is now performed as part of the parent window. If you have
overlapping child windows in a same parent, and relied on their relative z-order to be mapped to their submission order, this will affect your rendering.
This optimization is disabled if the parent window has no visual output, because it appears to be the most common situation leading to the creation of overlapping child windows.
Please reach out if you are affected.
- 2019/05/13 (1.71) - renamed SetNextTreeNodeOpen() to SetNextItemOpen(). Kept inline redirection function (will obsolete).
- 2019/05/11 (1.71) - changed io.AddInputCharacter(unsigned short c) signature to io.AddInputCharacter(unsigned int c).
- 2019/04/29 (1.70) - improved ImDrawList thick strokes (>1.0f) preserving correct thickness up to 90 degrees angles (e.g. rectangles). If you have custom rendering using thick lines, they will appear thicker now.
- 2019/04/29 (1.70) - removed GetContentRegionAvailWidth(), use GetContentRegionAvail().x instead. Kept inline redirection function (will obsolete).
- 2019/03/04 (1.69) - renamed GetOverlayDrawList() to GetForegroundDrawList(). Kept redirection function (will obsolete).
- 2019/02/26 (1.69) - renamed ImGuiColorEditFlags_RGB/ImGuiColorEditFlags_HSV/ImGuiColorEditFlags_HEX to ImGuiColorEditFlags_DisplayRGB/ImGuiColorEditFlags_DisplayHSV/ImGuiColorEditFlags_DisplayHex. Kept redirection enums (will obsolete).
- 2019/02/14 (1.68) - made it illegal/assert when io.DisplayTime == 0.0f (with an exception for the first frame). If for some reason your time step calculation gives you a zero value, replace it with an arbitrary small value!
- 2019/02/01 (1.68) - removed io.DisplayVisibleMin/DisplayVisibleMax (which were marked obsolete and removed from viewport/docking branch already).
- 2019/01/06 (1.67) - renamed io.InputCharacters[], marked internal as was always intended. Please don't access directly, and use AddInputCharacter() instead!
- 2019/01/06 (1.67) - renamed ImFontAtlas::GlyphRangesBuilder to ImFontGlyphRangesBuilder. Kept redirection typedef (will obsolete).
- 2018/12/20 (1.67) - made it illegal to call Begin("") with an empty string. This somehow half-worked before but had various undesirable side-effects.
- 2018/12/10 (1.67) - renamed io.ConfigResizeWindowsFromEdges to io.ConfigWindowsResizeFromEdges as we are doing a large pass on configuration flags.
- 2018/10/12 (1.66) - renamed misc/stl/imgui_stl.* to misc/cpp/imgui_stdlib.* in prevision for other C++ helper files.
- 2018/09/28 (1.66) - renamed SetScrollHere() to SetScrollHereY(). Kept redirection function (will obsolete).
- 2018/09/06 (1.65) - renamed stb_truetype.h to imstb_truetype.h, stb_textedit.h to imstb_textedit.h, and stb_rect_pack.h to imstb_rectpack.h.
If you were conveniently using the imgui copy of those STB headers in your project you will have to update your include paths.
- 2018/09/05 (1.65) - renamed io.OptCursorBlink/io.ConfigCursorBlink to io.ConfigInputTextCursorBlink. (#1427)
- 2018/08/31 (1.64) - added imgui_widgets.cpp file, extracted and moved widgets code out of imgui.cpp into imgui_widgets.cpp. Re-ordered some of the code remaining in imgui.cpp.
NONE OF THE FUNCTIONS HAVE CHANGED. THE CODE IS SEMANTICALLY 100% IDENTICAL, BUT _EVERY_ FUNCTION HAS BEEN MOVED.
Because of this, any local modifications to imgui.cpp will likely conflict when you update. Read docs/CHANGELOG.txt for suggestions.
- 2018/08/22 (1.63) - renamed IsItemDeactivatedAfterChange() to IsItemDeactivatedAfterEdit() for consistency with new IsItemEdited() API. Kept redirection function (will obsolete soonish as IsItemDeactivatedAfterChange() is very recent).
- 2018/08/21 (1.63) - renamed ImGuiTextEditCallback to ImGuiInputTextCallback, ImGuiTextEditCallbackData to ImGuiInputTextCallbackData for consistency. Kept redirection types (will obsolete).
- 2018/08/21 (1.63) - removed ImGuiInputTextCallbackData::ReadOnly since it is a duplication of (ImGuiInputTextCallbackData::Flags & ImGuiInputTextFlags_ReadOnly).
- 2018/08/01 (1.63) - removed per-window ImGuiWindowFlags_ResizeFromAnySide beta flag in favor of a global io.ConfigResizeWindowsFromEdges [update 1.67 renamed to ConfigWindowsResizeFromEdges] to enable the feature.
- 2018/08/01 (1.63) - renamed io.OptCursorBlink to io.ConfigCursorBlink [-> io.ConfigInputTextCursorBlink in 1.65], io.OptMacOSXBehaviors to ConfigMacOSXBehaviors for consistency.
- 2018/07/22 (1.63) - changed ImGui::GetTime() return value from float to double to avoid accumulating floating point imprecisions over time.
- 2018/07/08 (1.63) - style: renamed ImGuiCol_ModalWindowDarkening to ImGuiCol_ModalWindowDimBg for consistency with other features. Kept redirection enum (will obsolete).
- 2018/06/08 (1.62) - examples: the imgui_impl_xxx files have been split to separate platform (Win32, Glfw, SDL2, etc.) from renderer (DX11, OpenGL, Vulkan, etc.).
old bindings will still work as is, however prefer using the separated bindings as they will be updated to support multi-viewports.
when adopting new bindings follow the main.cpp code of your preferred examples/ folder to know which functions to call.
in particular, note that old bindings called ImGui::NewFrame() at the end of their ImGui_ImplXXXX_NewFrame() function.
- 2018/06/06 (1.62) - renamed GetGlyphRangesChinese() to GetGlyphRangesChineseFull() to distinguish other variants and discourage using the full set.
- 2018/06/06 (1.62) - TreeNodeEx()/TreeNodeBehavior(): the ImGuiTreeNodeFlags_CollapsingHeader helper now include the ImGuiTreeNodeFlags_NoTreePushOnOpen flag. See Changelog for details.
- 2018/05/03 (1.61) - DragInt(): the default compile-time format string has been changed from "%.0f" to "%d", as we are not using integers internally any more.
If you used DragInt() with custom format strings, make sure you change them to use %d or an integer-compatible format.
To honor backward-compatibility, the DragInt() code will currently parse and modify format strings to replace %*f with %d, giving time to users to upgrade their code.
If you have IMGUI_DISABLE_OBSOLETE_FUNCTIONS enabled, the code will instead assert! You may run a reg-exp search on your codebase for e.g. "DragInt.*%f" to help you find them.
- 2018/04/28 (1.61) - obsoleted InputFloat() functions taking an optional "int decimal_precision" in favor of an equivalent and more flexible "const char* format",
consistent with other functions. Kept redirection functions (will obsolete).
- 2018/04/09 (1.61) - IM_DELETE() helper function added in 1.60 doesn't clear the input _pointer_ reference, more consistent with expectation and allows passing r-value.
- 2018/03/20 (1.60) - renamed io.WantMoveMouse to io.WantSetMousePos for consistency and ease of understanding (was added in 1.52, _not_ used by core and only honored by some binding ahead of merging the Nav branch).
- 2018/03/12 (1.60) - removed ImGuiCol_CloseButton, ImGuiCol_CloseButtonActive, ImGuiCol_CloseButtonHovered as the closing cross uses regular button colors now.
- 2018/03/08 (1.60) - changed ImFont::DisplayOffset.y to default to 0 instead of +1. Fixed rounding of Ascent/Descent to match TrueType renderer. If you were adding or subtracting to ImFont::DisplayOffset check if your fonts are correctly aligned vertically.
- 2018/03/03 (1.60) - renamed ImGuiStyleVar_Count_ to ImGuiStyleVar_COUNT and ImGuiMouseCursor_Count_ to ImGuiMouseCursor_COUNT for consistency with other public enums.
- 2018/02/18 (1.60) - BeginDragDropSource(): temporarily removed the optional mouse_button=0 parameter because it is not really usable in many situations at the moment.
- 2018/02/16 (1.60) - obsoleted the io.RenderDrawListsFn callback, you can call your graphics engine render function after ImGui::Render(). Use ImGui::GetDrawData() to retrieve the ImDrawData* to display.
- 2018/02/07 (1.60) - reorganized context handling to be more explicit,
- YOU NOW NEED TO CALL ImGui::CreateContext() AT THE BEGINNING OF YOUR APP, AND CALL ImGui::DestroyContext() AT THE END.
- removed Shutdown() function, as DestroyContext() serve this purpose.
- you may pass a ImFontAtlas* pointer to CreateContext() to share a font atlas between contexts. Otherwise CreateContext() will create its own font atlas instance.
- removed allocator parameters from CreateContext(), they are now setup with SetAllocatorFunctions(), and shared by all contexts.
- removed the default global context and font atlas instance, which were confusing for users of DLL reloading and users of multiple contexts.
- 2018/01/31 (1.60) - moved sample TTF files from extra_fonts/ to misc/fonts/. If you loaded files directly from the imgui repo you may need to update your paths.
- 2018/01/11 (1.60) - obsoleted IsAnyWindowHovered() in favor of IsWindowHovered(ImGuiHoveredFlags_AnyWindow). Kept redirection function (will obsolete).
- 2018/01/11 (1.60) - obsoleted IsAnyWindowFocused() in favor of IsWindowFocused(ImGuiFocusedFlags_AnyWindow). Kept redirection function (will obsolete).
- 2018/01/03 (1.60) - renamed ImGuiSizeConstraintCallback to ImGuiSizeCallback, ImGuiSizeConstraintCallbackData to ImGuiSizeCallbackData.
- 2017/12/29 (1.60) - removed CalcItemRectClosestPoint() which was weird and not really used by anyone except demo code. If you need it it's easy to replicate on your side.
- 2017/12/24 (1.53) - renamed the emblematic ShowTestWindow() function to ShowDemoWindow(). Kept redirection function (will obsolete).
- 2017/12/21 (1.53) - ImDrawList: renamed style.AntiAliasedShapes to style.AntiAliasedFill for consistency and as a way to explicitly break code that manipulate those flag at runtime. You can now manipulate ImDrawList::Flags
- 2017/12/21 (1.53) - ImDrawList: removed 'bool anti_aliased = true' final parameter of ImDrawList::AddPolyline() and ImDrawList::AddConvexPolyFilled(). Prefer manipulating ImDrawList::Flags if you need to toggle them during the frame.
- 2017/12/14 (1.53) - using the ImGuiWindowFlags_NoScrollWithMouse flag on a child window forwards the mouse wheel event to the parent window, unless either ImGuiWindowFlags_NoInputs or ImGuiWindowFlags_NoScrollbar are also set.
- 2017/12/13 (1.53) - renamed GetItemsLineHeightWithSpacing() to GetFrameHeightWithSpacing(). Kept redirection function (will obsolete).
- 2017/12/13 (1.53) - obsoleted IsRootWindowFocused() in favor of using IsWindowFocused(ImGuiFocusedFlags_RootWindow). Kept redirection function (will obsolete).
- obsoleted IsRootWindowOrAnyChildFocused() in favor of using IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows). Kept redirection function (will obsolete).
- 2017/12/12 (1.53) - renamed ImGuiTreeNodeFlags_AllowOverlapMode to ImGuiTreeNodeFlags_AllowItemOverlap. Kept redirection enum (will obsolete).
- 2017/12/10 (1.53) - removed SetNextWindowContentWidth(), prefer using SetNextWindowContentSize(). Kept redirection function (will obsolete).
- 2017/11/27 (1.53) - renamed ImGuiTextBuffer::append() helper to appendf(), appendv() to appendfv(). If you copied the 'Log' demo in your code, it uses appendv() so that needs to be renamed.
- 2017/11/18 (1.53) - Style, Begin: removed ImGuiWindowFlags_ShowBorders window flag. Borders are now fully set up in the ImGuiStyle structure (see e.g. style.FrameBorderSize, style.WindowBorderSize). Use ImGui::ShowStyleEditor() to look them up.
Please note that the style system will keep evolving (hopefully stabilizing in Q1 2018), and so custom styles will probably subtly break over time. It is recommended you use the StyleColorsClassic(), StyleColorsDark(), StyleColorsLight() functions.
- 2017/11/18 (1.53) - Style: removed ImGuiCol_ComboBg in favor of combo boxes using ImGuiCol_PopupBg for consistency.
- 2017/11/18 (1.53) - Style: renamed ImGuiCol_ChildWindowBg to ImGuiCol_ChildBg.
- 2017/11/18 (1.53) - Style: renamed style.ChildWindowRounding to style.ChildRounding, ImGuiStyleVar_ChildWindowRounding to ImGuiStyleVar_ChildRounding.
- 2017/11/02 (1.53) - obsoleted IsRootWindowOrAnyChildHovered() in favor of using IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows);
- 2017/10/24 (1.52) - renamed IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCS/IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCS to IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS/IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS for consistency.
- 2017/10/20 (1.52) - changed IsWindowHovered() default parameters behavior to return false if an item is active in another window (e.g. click-dragging item from another window to this window). You can use the newly introduced IsWindowHovered() flags to requests this specific behavior if you need it.
- 2017/10/20 (1.52) - marked IsItemHoveredRect()/IsMouseHoveringWindow() as obsolete, in favor of using the newly introduced flags for IsItemHovered() and IsWindowHovered(). See https://github.com/ocornut/imgui/issues/1382 for details.
removed the IsItemRectHovered()/IsWindowRectHovered() names introduced in 1.51 since they were merely more consistent names for the two functions we are now obsoleting.
IsItemHoveredRect() --> IsItemHovered(ImGuiHoveredFlags_RectOnly)
IsMouseHoveringAnyWindow() --> IsWindowHovered(ImGuiHoveredFlags_AnyWindow)
IsMouseHoveringWindow() --> IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup | ImGuiHoveredFlags_AllowWhenBlockedByActiveItem) [weird, old behavior]
- 2017/10/17 (1.52) - marked the old 5-parameters version of Begin() as obsolete (still available). Use SetNextWindowSize()+Begin() instead!
- 2017/10/11 (1.52) - renamed AlignFirstTextHeightToWidgets() to AlignTextToFramePadding(). Kept inline redirection function (will obsolete).
- 2017/09/26 (1.52) - renamed ImFont::Glyph to ImFontGlyph. Kept redirection typedef (will obsolete).
- 2017/09/25 (1.52) - removed SetNextWindowPosCenter() because SetNextWindowPos() now has the optional pivot information to do the same and more. Kept redirection function (will obsolete).
- 2017/08/25 (1.52) - io.MousePos needs to be set to ImVec2(-FLT_MAX,-FLT_MAX) when mouse is unavailable/missing. Previously ImVec2(-1,-1) was enough but we now accept negative mouse coordinates. In your binding if you need to support unavailable mouse, make sure to replace "io.MousePos = ImVec2(-1,-1)" with "io.MousePos = ImVec2(-FLT_MAX,-FLT_MAX)".
- 2017/08/22 (1.51) - renamed IsItemHoveredRect() to IsItemRectHovered(). Kept inline redirection function (will obsolete). -> (1.52) use IsItemHovered(ImGuiHoveredFlags_RectOnly)!
- renamed IsMouseHoveringAnyWindow() to IsAnyWindowHovered() for consistency. Kept inline redirection function (will obsolete).
- renamed IsMouseHoveringWindow() to IsWindowRectHovered() for consistency. Kept inline redirection function (will obsolete).
- 2017/08/20 (1.51) - renamed GetStyleColName() to GetStyleColorName() for consistency.
- 2017/08/20 (1.51) - added PushStyleColor(ImGuiCol idx, ImU32 col) overload, which _might_ cause an "ambiguous call" compilation error if you are using ImColor() with implicit cast. Cast to ImU32 or ImVec4 explicily to fix.
- 2017/08/15 (1.51) - marked the weird IMGUI_ONCE_UPON_A_FRAME helper macro as obsolete. prefer using the more explicit ImGuiOnceUponAFrame type.
- 2017/08/15 (1.51) - changed parameter order for BeginPopupContextWindow() from (const char*,int buttons,bool also_over_items) to (const char*,int buttons,bool also_over_items). Note that most calls relied on default parameters completely.
- 2017/08/13 (1.51) - renamed ImGuiCol_Column to ImGuiCol_Separator, ImGuiCol_ColumnHovered to ImGuiCol_SeparatorHovered, ImGuiCol_ColumnActive to ImGuiCol_SeparatorActive. Kept redirection enums (will obsolete).
- 2017/08/11 (1.51) - renamed ImGuiSetCond_Always to ImGuiCond_Always, ImGuiSetCond_Once to ImGuiCond_Once, ImGuiSetCond_FirstUseEver to ImGuiCond_FirstUseEver, ImGuiSetCond_Appearing to ImGuiCond_Appearing. Kept redirection enums (will obsolete).
- 2017/08/09 (1.51) - removed ValueColor() helpers, they are equivalent to calling Text(label) + SameLine() + ColorButton().
- 2017/08/08 (1.51) - removed ColorEditMode() and ImGuiColorEditMode in favor of ImGuiColorEditFlags and parameters to the various Color*() functions. The SetColorEditOptions() allows to initialize default but the user can still change them with right-click context menu.
- changed prototype of 'ColorEdit4(const char* label, float col[4], bool show_alpha = true)' to 'ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flags = 0)', where passing flags = 0x01 is a safe no-op (hello dodgy backward compatibility!). - check and run the demo window, under "Color/Picker Widgets", to understand the various new options.
- changed prototype of rarely used 'ColorButton(ImVec4 col, bool small_height = false, bool outline_border = true)' to 'ColorButton(const char* desc_id, ImVec4 col, ImGuiColorEditFlags flags = 0, ImVec2 size = ImVec2(0, 0))'
- 2017/07/20 (1.51) - removed IsPosHoveringAnyWindow(ImVec2), which was partly broken and misleading. ASSERT + redirect user to io.WantCaptureMouse
- 2017/05/26 (1.50) - removed ImFontConfig::MergeGlyphCenterV in favor of a more multipurpose ImFontConfig::GlyphOffset.
- 2017/05/01 (1.50) - renamed ImDrawList::PathFill() (rarely used directly) to ImDrawList::PathFillConvex() for clarity.
- 2016/11/06 (1.50) - BeginChild(const char*) now applies the stack id to the provided label, consistently with other functions as it should always have been. It shouldn't affect you unless (extremely unlikely) you were appending multiple times to a same child from different locations of the stack id. If that's the case, generate an id with GetId() and use it instead of passing string to BeginChild().
- 2016/10/15 (1.50) - avoid 'void* user_data' parameter to io.SetClipboardTextFn/io.GetClipboardTextFn pointers. We pass io.ClipboardUserData to it.
- 2016/09/25 (1.50) - style.WindowTitleAlign is now a ImVec2 (ImGuiAlign enum was removed). set to (0.5f,0.5f) for horizontal+vertical centering, (0.0f,0.0f) for upper-left, etc.
- 2016/07/30 (1.50) - SameLine(x) with x>0.0f is now relative to left of column/group if any, and not always to left of window. This was sort of always the intent and hopefully breakage should be minimal.
- 2016/05/12 (1.49) - title bar (using ImGuiCol_TitleBg/ImGuiCol_TitleBgActive colors) isn't rendered over a window background (ImGuiCol_WindowBg color) anymore.
If your TitleBg/TitleBgActive alpha was 1.0f or you are using the default theme it will not affect you, otherwise if <1.0f you need tweak your custom theme to readjust for the fact that we don't draw a WindowBg background behind the title bar.
This helper function will convert an old TitleBg/TitleBgActive color into a new one with the same visual output, given the OLD color and the OLD WindowBg color:
ImVec4 ConvertTitleBgCol(const ImVec4& win_bg_col, const ImVec4& title_bg_col) { float new_a = 1.0f - ((1.0f - win_bg_col.w) * (1.0f - title_bg_col.w)), k = title_bg_col.w / new_a; return ImVec4((win_bg_col.x * win_bg_col.w + title_bg_col.x) * k, (win_bg_col.y * win_bg_col.w + title_bg_col.y) * k, (win_bg_col.z * win_bg_col.w + title_bg_col.z) * k, new_a); }
If this is confusing, pick the RGB value from title bar from an old screenshot and apply this as TitleBg/TitleBgActive. Or you may just create TitleBgActive from a tweaked TitleBg color.
- 2016/05/07 (1.49) - removed confusing set of GetInternalState(), GetInternalStateSize(), SetInternalState() functions. Now using CreateContext(), DestroyContext(), GetCurrentContext(), SetCurrentContext().
- 2016/05/02 (1.49) - renamed SetNextTreeNodeOpened() to SetNextTreeNodeOpen(), no redirection.
- 2016/05/01 (1.49) - obsoleted old signature of CollapsingHeader(const char* label, const char* str_id = NULL, bool display_frame = true, bool default_open = false) as extra parameters were badly designed and rarely used. You can replace the "default_open = true" flag in new API with CollapsingHeader(label, ImGuiTreeNodeFlags_DefaultOpen).
- 2016/04/26 (1.49) - changed ImDrawList::PushClipRect(ImVec4 rect) to ImDrawList::PushClipRect(Imvec2 min,ImVec2 max,bool intersect_with_current_clip_rect=false). Note that higher-level ImGui::PushClipRect() is preferable because it will clip at logic/widget level, whereas ImDrawList::PushClipRect() only affect your renderer.
- 2016/04/03 (1.48) - removed style.WindowFillAlphaDefault setting which was redundant. Bake default BG alpha inside style.Colors[ImGuiCol_WindowBg] and all other Bg color values. (ref github issue #337).
- 2016/04/03 (1.48) - renamed ImGuiCol_TooltipBg to ImGuiCol_PopupBg, used by popups/menus and tooltips. popups/menus were previously using ImGuiCol_WindowBg. (ref github issue #337)
- 2016/03/21 (1.48) - renamed GetWindowFont() to GetFont(), GetWindowFontSize() to GetFontSize(). Kept inline redirection function (will obsolete).
- 2016/03/02 (1.48) - InputText() completion/history/always callbacks: if you modify the text buffer manually (without using DeleteChars()/InsertChars() helper) you need to maintain the BufTextLen field. added an assert.
- 2016/01/23 (1.48) - fixed not honoring exact width passed to PushItemWidth(), previously it would add extra FramePadding.x*2 over that width. if you had manual pixel-perfect alignment in place it might affect you.
- 2015/12/27 (1.48) - fixed ImDrawList::AddRect() which used to render a rectangle 1 px too large on each axis.
- 2015/12/04 (1.47) - renamed Color() helpers to ValueColor() - dangerously named, rarely used and probably to be made obsolete.
- 2015/08/29 (1.45) - with the addition of horizontal scrollbar we made various fixes to inconsistencies with dealing with cursor position.
GetCursorPos()/SetCursorPos() functions now include the scrolled amount. It shouldn't affect the majority of users, but take note that SetCursorPosX(100.0f) puts you at +100 from the starting x position which may include scrolling, not at +100 from the window left side.
GetContentRegionMax()/GetWindowContentRegionMin()/GetWindowContentRegionMax() functions allow include the scrolled amount. Typically those were used in cases where no scrolling would happen so it may not be a problem, but watch out!
- 2015/08/29 (1.45) - renamed style.ScrollbarWidth to style.ScrollbarSize
- 2015/08/05 (1.44) - split imgui.cpp into extra files: imgui_demo.cpp imgui_draw.cpp imgui_internal.h that you need to add to your project.
- 2015/07/18 (1.44) - fixed angles in ImDrawList::PathArcTo(), PathArcToFast() (introduced in 1.43) being off by an extra PI for no justifiable reason
- 2015/07/14 (1.43) - add new ImFontAtlas::AddFont() API. For the old AddFont***, moved the 'font_no' parameter of ImFontAtlas::AddFont** functions to the ImFontConfig structure.
you need to render your textured triangles with bilinear filtering to benefit from sub-pixel positioning of text.
- 2015/07/08 (1.43) - switched rendering data to use indexed rendering. this is saving a fair amount of CPU/GPU and enables us to get anti-aliasing for a marginal cost.
this necessary change will break your rendering function! the fix should be very easy. sorry for that :(
- if you are using a vanilla copy of one of the imgui_impl_XXXX.cpp provided in the example, you just need to update your copy and you can ignore the rest.
- the signature of the io.RenderDrawListsFn handler has changed!
old: ImGui_XXXX_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_count)
new: ImGui_XXXX_RenderDrawLists(ImDrawData* draw_data).
parameters: 'cmd_lists' becomes 'draw_data->CmdLists', 'cmd_lists_count' becomes 'draw_data->CmdListsCount'
ImDrawList: 'commands' becomes 'CmdBuffer', 'vtx_buffer' becomes 'VtxBuffer', 'IdxBuffer' is new.
ImDrawCmd: 'vtx_count' becomes 'ElemCount', 'clip_rect' becomes 'ClipRect', 'user_callback' becomes 'UserCallback', 'texture_id' becomes 'TextureId'.
- each ImDrawList now contains both a vertex buffer and an index buffer. For each command, render ElemCount/3 triangles using indices from the index buffer.
- if you REALLY cannot render indexed primitives, you can call the draw_data->DeIndexAllBuffers() method to de-index the buffers. This is slow and a waste of CPU/GPU. Prefer using indexed rendering!
- refer to code in the examples/ folder or ask on the GitHub if you are unsure of how to upgrade. please upgrade!
- 2015/07/10 (1.43) - changed SameLine() parameters from int to float.
- 2015/07/02 (1.42) - renamed SetScrollPosHere() to SetScrollFromCursorPos(). Kept inline redirection function (will obsolete).
- 2015/07/02 (1.42) - renamed GetScrollPosY() to GetScrollY(). Necessary to reduce confusion along with other scrolling functions, because positions (e.g. cursor position) are not equivalent to scrolling amount.
- 2015/06/14 (1.41) - changed ImageButton() default bg_col parameter from (0,0,0,1) (black) to (0,0,0,0) (transparent) - makes a difference when texture have transparence
- 2015/06/14 (1.41) - changed Selectable() API from (label, selected, size) to (label, selected, flags, size). Size override should have been rarely be used. Sorry!
- 2015/05/31 (1.40) - renamed GetWindowCollapsed() to IsWindowCollapsed() for consistency. Kept inline redirection function (will obsolete).
- 2015/05/31 (1.40) - renamed IsRectClipped() to IsRectVisible() for consistency. Note that return value is opposite! Kept inline redirection function (will obsolete).
- 2015/05/27 (1.40) - removed the third 'repeat_if_held' parameter from Button() - sorry! it was rarely used and inconsistent. Use PushButtonRepeat(true) / PopButtonRepeat() to enable repeat on desired buttons.
- 2015/05/11 (1.40) - changed BeginPopup() API, takes a string identifier instead of a bool. ImGui needs to manage the open/closed state of popups. Call OpenPopup() to actually set the "open" state of a popup. BeginPopup() returns true if the popup is opened.
- 2015/05/03 (1.40) - removed style.AutoFitPadding, using style.WindowPadding makes more sense (the default values were already the same).
- 2015/04/13 (1.38) - renamed IsClipped() to IsRectClipped(). Kept inline redirection function until 1.50.
- 2015/04/09 (1.38) - renamed ImDrawList::AddArc() to ImDrawList::AddArcFast() for compatibility with future API
- 2015/04/03 (1.38) - removed ImGuiCol_CheckHovered, ImGuiCol_CheckActive, replaced with the more general ImGuiCol_FrameBgHovered, ImGuiCol_FrameBgActive.
- 2014/04/03 (1.38) - removed support for passing -FLT_MAX..+FLT_MAX as the range for a SliderFloat(). Use DragFloat() or Inputfloat() instead.
- 2015/03/17 (1.36) - renamed GetItemBoxMin()/GetItemBoxMax()/IsMouseHoveringBox() to GetItemRectMin()/GetItemRectMax()/IsMouseHoveringRect(). Kept inline redirection function until 1.50.
- 2015/03/15 (1.36) - renamed style.TreeNodeSpacing to style.IndentSpacing, ImGuiStyleVar_TreeNodeSpacing to ImGuiStyleVar_IndentSpacing
- 2015/03/13 (1.36) - renamed GetWindowIsFocused() to IsWindowFocused(). Kept inline redirection function until 1.50.
- 2015/03/08 (1.35) - renamed style.ScrollBarWidth to style.ScrollbarWidth (casing)
- 2015/02/27 (1.34) - renamed OpenNextNode(bool) to SetNextTreeNodeOpened(bool, ImGuiSetCond). Kept inline redirection function until 1.50.
- 2015/02/27 (1.34) - renamed ImGuiSetCondition_*** to ImGuiSetCond_***, and _FirstUseThisSession becomes _Once.
- 2015/02/11 (1.32) - changed text input callback ImGuiTextEditCallback return type from void-->int. reserved for future use, return 0 for now.
- 2015/02/10 (1.32) - renamed GetItemWidth() to CalcItemWidth() to clarify its evolving behavior
- 2015/02/08 (1.31) - renamed GetTextLineSpacing() to GetTextLineHeightWithSpacing()
- 2015/02/01 (1.31) - removed IO.MemReallocFn (unused)
- 2015/01/19 (1.30) - renamed ImGuiStorage::GetIntPtr()/GetFloatPtr() to GetIntRef()/GetIntRef() because Ptr was conflicting with actual pointer storage functions.
- 2015/01/11 (1.30) - big font/image API change! now loads TTF file. allow for multiple fonts. no need for a PNG loader.
- 2015/01/11 (1.30) - removed GetDefaultFontData(). uses io.Fonts->GetTextureData*() API to retrieve uncompressed pixels.
- old: const void* png_data; unsigned int png_size; ImGui::GetDefaultFontData(NULL, NULL, &png_data, &png_size); [..Upload texture to GPU..];
- new: unsigned char* pixels; int width, height; io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); [..Upload texture to GPU..]; io.Fonts->TexId = YourTexIdentifier;
you now have more flexibility to load multiple TTF fonts and manage the texture buffer for internal needs. It is now recommended that you sample the font texture with bilinear interpolation.
- 2015/01/11 (1.30) - added texture identifier in ImDrawCmd passed to your render function (we can now render images). make sure to set io.Fonts->TexID.
- 2015/01/11 (1.30) - removed IO.PixelCenterOffset (unnecessary, can be handled in user projection matrix)
- 2015/01/11 (1.30) - removed ImGui::IsItemFocused() in favor of ImGui::IsItemActive() which handles all widgets
- 2014/12/10 (1.18) - removed SetNewWindowDefaultPos() in favor of new generic API SetNextWindowPos(pos, ImGuiSetCondition_FirstUseEver)
- 2014/11/28 (1.17) - moved IO.Font*** options to inside the IO.Font-> structure (FontYOffset, FontTexUvForWhite, FontBaseScale, FontFallbackGlyph)
- 2014/11/26 (1.17) - reworked syntax of IMGUI_ONCE_UPON_A_FRAME helper macro to increase compiler compatibility
- 2014/11/07 (1.15) - renamed IsHovered() to IsItemHovered()
- 2014/10/02 (1.14) - renamed IMGUI_INCLUDE_IMGUI_USER_CPP to IMGUI_INCLUDE_IMGUI_USER_INL and imgui_user.cpp to imgui_user.inl (more IDE friendly)
- 2014/09/25 (1.13) - removed 'text_end' parameter from IO.SetClipboardTextFn (the string is now always zero-terminated for simplicity)
- 2014/09/24 (1.12) - renamed SetFontScale() to SetWindowFontScale()
- 2014/09/24 (1.12) - moved IM_MALLOC/IM_REALLOC/IM_FREE preprocessor defines to IO.MemAllocFn/IO.MemReallocFn/IO.MemFreeFn
- 2014/08/30 (1.09) - removed IO.FontHeight (now computed automatically)
- 2014/08/30 (1.09) - moved IMGUI_FONT_TEX_UV_FOR_WHITE preprocessor define to IO.FontTexUvForWhite
- 2014/08/28 (1.09) - changed the behavior of IO.PixelCenterOffset following various rendering fixes
FREQUENTLY ASKED QUESTIONS (FAQ)
================================
Read all answers online:
https://www.dearimgui.org/faq or https://github.com/ocornut/imgui/blob/master/docs/FAQ.md (same url)
Read all answers locally (with a text editor or ideally a Markdown viewer):
docs/FAQ.md
Some answers are copied down here to facilitate searching in code.
Q&A: Basics
===========
Q: Where is the documentation?
A: This library is poorly documented at the moment and expects of the user to be acquainted with C/C++.
- Run the examples/ and explore them.
- See demo code in imgui_demo.cpp and particularly the ImGui::ShowDemoWindow() function.
- The demo covers most features of Dear ImGui, so you can read the code and see its output.
- See documentation and comments at the top of imgui.cpp + effectively imgui.h.
- Dozens of standalone example applications using e.g. OpenGL/DirectX are provided in the
examples/ folder to explain how to integrate Dear ImGui with your own engine/application.
- The Wiki (https://github.com/ocornut/imgui/wiki) has many resources and links.
- The Glossary (https://github.com/ocornut/imgui/wiki/Glossary) page also may be useful.
- Your programming IDE is your friend, find the type or function declaration to find comments
associated to it.
Q: What is this library called?
Q: Which version should I get?
>> This library is called "Dear ImGui", please don't call it "ImGui" :)
>> See https://www.dearimgui.org/faq for details.
Q&A: Integration
================
Q: How to get started?
A: Read 'PROGRAMMER GUIDE' above. Read examples/README.txt.
Q: How can I tell whether to dispatch mouse/keyboard to Dear ImGui or to my application?
A: You should read the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags!
>> See https://www.dearimgui.org/faq for fully detailed answer. You really want to read this.
Q. How can I enable keyboard controls?
Q: How can I use this without a mouse, without a keyboard or without a screen? (gamepad, input share, remote display)
Q: I integrated Dear ImGui in my engine and little squares are showing instead of text..
Q: I integrated Dear ImGui in my engine and some elements are clipping or disappearing when I move windows around..
Q: I integrated Dear ImGui in my engine and some elements are displaying outside their expected windows boundaries..
>> See https://www.dearimgui.org/faq
Q&A: Usage
----------
Q: Why is my widget not reacting when I click on it?
Q: How can I have widgets with an empty label?
Q: How can I have multiple widgets with the same label?
Q: How can I display an image? What is ImTextureID, how does it works?
Q: How can I use my own math types instead of ImVec2/ImVec4?
Q: How can I interact with standard C++ types (such as std::string and std::vector)?
Q: How can I display custom shapes? (using low-level ImDrawList API)
>> See https://www.dearimgui.org/faq
Q&A: Fonts, Text
================
Q: How should I handle DPI in my application?
Q: How can I load a different font than the default?
Q: How can I easily use icons in my application?
Q: How can I load multiple fonts?
Q: How can I display and input non-Latin characters such as Chinese, Japanese, Korean, Cyrillic?
>> See https://www.dearimgui.org/faq and https://github.com/ocornut/imgui/edit/master/docs/FONTS.md
Q&A: Concerns
=============
Q: Who uses Dear ImGui?
Q: Can you create elaborate/serious tools with Dear ImGui?
Q: Can you reskin the look of Dear ImGui?
Q: Why using C++ (as opposed to C)?
>> See https://www.dearimgui.org/faq
Q&A: Community
==============
Q: How can I help?
A: - Businesses: please reach out to "contact AT dearimgui.org" if you work in a place using Dear ImGui!
We can discuss ways for your company to fund development via invoiced technical support, maintenance or sponsoring contacts.
This is among the most useful thing you can do for Dear ImGui. With increased funding we can hire more people working on this project.
- Individuals: you can support continued development via PayPal donations. See README.
- If you are experienced with Dear ImGui and C++, look at the github issues, look at the Wiki, read docs/TODO.txt
and see how you want to help and can help!
- Disclose your usage of Dear ImGui via a dev blog post, a tweet, a screenshot, a mention somewhere etc.
You may post screenshot or links in the gallery threads (github.com/ocornut/imgui/issues/3075). Visuals are ideal as they inspire other programmers.
But even without visuals, disclosing your use of dear imgui help the library grow credibility, and help other teams and programmers with taking decisions.
- If you have issues or if you need to hack into the library, even if you don't expect any support it is useful that you share your issues (on github or privately).
*/
//-------------------------------------------------------------------------
// [SECTION] INCLUDES
//-------------------------------------------------------------------------
#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS)
#define _CRT_SECURE_NO_WARNINGS
#endif
#include "imgui.h"
#ifndef IMGUI_DISABLE
#ifndef IMGUI_DEFINE_MATH_OPERATORS
#define IMGUI_DEFINE_MATH_OPERATORS
#endif
#include "imgui_internal.h"
// System includes
#include <ctype.h> // toupper
#include <stdio.h> // vsnprintf, sscanf, printf
#if defined(_MSC_VER) && _MSC_VER <= 1500 // MSVC 2008 or earlier
#include <stddef.h> // intptr_t
#else
#include <stdint.h> // intptr_t
#endif
// [Windows] OS specific includes (optional)
#if defined(_WIN32) && defined(IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS) && defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS) && defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS)
#define IMGUI_DISABLE_WIN32_FUNCTIONS
#endif
#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS)
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#ifndef NOMINMAX
#define NOMINMAX
#endif
#ifndef __MINGW32__
#include <Windows.h> // _wfopen, OpenClipboard
#else
#include <windows.h>
#endif
#if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP) // UWP doesn't have all Win32 functions
#define IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS
#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS
#endif
#endif
// [Apple] OS specific includes
#if defined(__APPLE__)
#include <TargetConditionals.h>
#endif
// Visual Studio warnings
#ifdef _MSC_VER
#pragma warning (disable: 4127) // condition expression is constant
#pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen
#if defined(_MSC_VER) && _MSC_VER >= 1922 // MSVC 2019 16.2 or later
#pragma warning (disable: 5054) // operator '|': deprecated between enumerations of different types
#endif
#endif
// Clang/GCC warnings with -Weverything
#if defined(__clang__)
#if __has_warning("-Wunknown-warning-option")
#pragma clang diagnostic ignored "-Wunknown-warning-option" // warning: unknown warning group 'xxx' // not all warnings are known by all Clang versions and they tend to be rename-happy.. so ignoring warnings triggers new warnings on some configuration. Great!
#endif
#pragma clang diagnostic ignored "-Wunknown-pragmas" // warning: unknown warning group 'xxx'
#pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast // yes, they are more terse.
#pragma clang diagnostic ignored "-Wfloat-equal" // warning: comparing floating point with == or != is unsafe // storing and comparing against same constants (typically 0.0f) is ok.
#pragma clang diagnostic ignored "-Wformat-nonliteral" // warning: format string is not a string literal // passing non-literal to vsnformat(). yes, user passing incorrect format strings can crash the code.
#pragma clang diagnostic ignored "-Wexit-time-destructors" // warning: declaration requires an exit-time destructor // exit-time destruction order is undefined. if MemFree() leads to users code that has been disabled before exit it might cause problems. ImGui coding style welcomes static/globals.
#pragma clang diagnostic ignored "-Wglobal-constructors" // warning: declaration requires a global destructor // similar to above, not sure what the exact difference is.
#pragma clang diagnostic ignored "-Wsign-conversion" // warning: implicit conversion changes signedness
#pragma clang diagnostic ignored "-Wformat-pedantic" // warning: format specifies type 'void *' but the argument has type 'xxxx *' // unreasonable, would lead to casting every %p arg to void*. probably enabled by -pedantic.
#pragma clang diagnostic ignored "-Wint-to-void-pointer-cast" // warning: cast to 'void *' from smaller integer type 'int'
#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" // warning: zero as null pointer constant // some standard header variations use #define NULL 0
#pragma clang diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function // using printf() is a misery with this as C++ va_arg ellipsis changes float to double.
#pragma clang diagnostic ignored "-Wimplicit-int-float-conversion" // warning: implicit conversion from 'xxx' to 'float' may lose precision
#elif defined(__GNUC__)
// We disable -Wpragmas because GCC doesn't provide an has_warning equivalent and some forks/patches may not following the warning/version association.
#pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind
#pragma GCC diagnostic ignored "-Wunused-function" // warning: 'xxxx' defined but not used
#pragma GCC diagnostic ignored "-Wint-to-pointer-cast" // warning: cast to pointer from integer of different size
#pragma GCC diagnostic ignored "-Wformat" // warning: format '%p' expects argument of type 'void*', but argument 6 has type 'ImGuiWindow*'
#pragma GCC diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function
#pragma GCC diagnostic ignored "-Wconversion" // warning: conversion to 'xxxx' from 'xxxx' may alter its value
#pragma GCC diagnostic ignored "-Wformat-nonliteral" // warning: format not a string literal, format string not checked
#pragma GCC diagnostic ignored "-Wstrict-overflow" // warning: assuming signed overflow does not occur when assuming that (X - c) > X is always false
#pragma GCC diagnostic ignored "-Wclass-memaccess" // [__GNUC__ >= 8] warning: 'memset/memcpy' clearing/writing an object of type 'xxxx' with no trivial copy-assignment; use assignment or value-initialization instead
#endif
// Debug options
#define IMGUI_DEBUG_NAV_SCORING 0 // Display navigation scoring preview when hovering items. Display last moving direction matches when holding CTRL
#define IMGUI_DEBUG_NAV_RECTS 0 // Display the reference navigation rectangle for each window
#define IMGUI_DEBUG_INI_SETTINGS 0 // Save additional comments in .ini file (particularly helps for Docking, but makes saving slower)
// When using CTRL+TAB (or Gamepad Square+L/R) we delay the visual a little in order to reduce visual noise doing a fast switch.
static const float NAV_WINDOWING_HIGHLIGHT_DELAY = 0.20f; // Time before the highlight and screen dimming starts fading in
static const float NAV_WINDOWING_LIST_APPEAR_DELAY = 0.15f; // Time before the window list starts to appear
// Window resizing from edges (when io.ConfigWindowsResizeFromEdges = true and ImGuiBackendFlags_HasMouseCursors is set in io.BackendFlags by back-end)
static const float WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS = 4.0f; // Extend outside and inside windows. Affect FindHoveredWindow().
static const float WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER = 0.04f; // Reduce visual noise by only highlighting the border after a certain time.
static const float WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER = 2.00f; // Lock scrolled window (so it doesn't pick child windows that are scrolling through) for a certain time, unless mouse moved.
//-------------------------------------------------------------------------
// [SECTION] FORWARD DECLARATIONS
//-------------------------------------------------------------------------
static void SetCurrentWindow(ImGuiWindow* window);
static void FindHoveredWindow();
static ImGuiWindow* CreateNewWindow(const char* name, ImGuiWindowFlags flags);
static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window);
static void AddDrawListToDrawData(ImVector<ImDrawList*>* out_list, ImDrawList* draw_list);
static void AddWindowToSortBuffer(ImVector<ImGuiWindow*>* out_sorted_windows, ImGuiWindow* window);
static ImRect GetViewportRect();
// Settings
static void WindowSettingsHandler_ClearAll(ImGuiContext*, ImGuiSettingsHandler*);
static void* WindowSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name);
static void WindowSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line);
static void WindowSettingsHandler_ApplyAll(ImGuiContext*, ImGuiSettingsHandler*);
static void WindowSettingsHandler_WriteAll(ImGuiContext*, ImGuiSettingsHandler*, ImGuiTextBuffer* buf);
// Platform Dependents default implementation for IO functions
static const char* GetClipboardTextFn_DefaultImpl(void* user_data);
static void SetClipboardTextFn_DefaultImpl(void* user_data, const char* text);
static void ImeSetInputScreenPosFn_DefaultImpl(int x, int y);
namespace ImGui
{
// Navigation
static void NavUpdate();
static void NavUpdateWindowing();
static void NavUpdateWindowingOverlay();
static void NavUpdateMoveResult();
static float NavUpdatePageUpPageDown();
static inline void NavUpdateAnyRequestFlag();
static void NavEndFrame();
static bool NavScoreItem(ImGuiNavMoveResult* result, ImRect cand);
static void NavProcessItem(ImGuiWindow* window, const ImRect& nav_bb, ImGuiID id);
static ImVec2 NavCalcPreferredRefPos();
static void NavSaveLastChildNavWindowIntoParent(ImGuiWindow* nav_window);
static ImGuiWindow* NavRestoreLastChildNavWindow(ImGuiWindow* window);
static int FindWindowFocusIndex(ImGuiWindow* window);
// Error Checking
static void ErrorCheckNewFrameSanityChecks();
static void ErrorCheckEndFrameSanityChecks();
static void ErrorCheckBeginEndCompareStacksSize(ImGuiWindow* window, bool write);
// Misc
static void UpdateSettings();
static void UpdateMouseInputs();
static void UpdateMouseWheel();
static void UpdateTabFocus();
static void UpdateDebugToolItemPicker();
static bool UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4], const ImRect& visibility_rect);
static void RenderWindowOuterBorders(ImGuiWindow* window);
static void RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar_rect, bool title_bar_is_highlight, int resize_grip_count, const ImU32 resize_grip_col[4], float resize_grip_draw_size);
static void RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& title_bar_rect, const char* name, bool* p_open);
}
//-----------------------------------------------------------------------------
// [SECTION] CONTEXT AND MEMORY ALLOCATORS
//-----------------------------------------------------------------------------
// Current context pointer. Implicitly used by all Dear ImGui functions. Always assumed to be != NULL.
// ImGui::CreateContext() will automatically set this pointer if it is NULL. Change to a different context by calling ImGui::SetCurrentContext().
// 1) Important: globals are not shared across DLL boundaries! If you use DLLs or any form of hot-reloading: you will need to call
// SetCurrentContext() (with the pointer you got from CreateContext) from each unique static/DLL boundary, and after each hot-reloading.
// In your debugger, add GImGui to your watch window and notice how its value changes depending on which location you are currently stepping into.
// 2) Important: Dear ImGui functions are not thread-safe because of this pointer.
// If you want thread-safety to allow N threads to access N different contexts, you can:
// - Change this variable to use thread local storage so each thread can refer to a different context, in imconfig.h:
// struct ImGuiContext;
// extern thread_local ImGuiContext* MyImGuiTLS;
// #define GImGui MyImGuiTLS
// And then define MyImGuiTLS in one of your cpp file. Note that thread_local is a C++11 keyword, earlier C++ uses compiler-specific keyword.
// - Future development aim to make this context pointer explicit to all calls. Also read https://github.com/ocornut/imgui/issues/586
// - If you need a finite number of contexts, you may compile and use multiple instances of the ImGui code from different namespace.
#ifndef GImGui
ImGuiContext* GImGui = NULL;
#endif
// Memory Allocator functions. Use SetAllocatorFunctions() to change them.
// If you use DLL hotreloading you might need to call SetAllocatorFunctions() after reloading code from this file.
// Otherwise, you probably don't want to modify them mid-program, and if you use global/static e.g. ImVector<> instances you may need to keep them accessible during program destruction.
#ifndef IMGUI_DISABLE_DEFAULT_ALLOCATORS
static void* MallocWrapper(size_t size, void* user_data) { IM_UNUSED(user_data); return malloc(size); }
static void FreeWrapper(void* ptr, void* user_data) { IM_UNUSED(user_data); free(ptr); }
#else
static void* MallocWrapper(size_t size, void* user_data) { IM_UNUSED(user_data); IM_UNUSED(size); IM_ASSERT(0); return NULL; }
static void FreeWrapper(void* ptr, void* user_data) { IM_UNUSED(user_data); IM_UNUSED(ptr); IM_ASSERT(0); }
#endif
static void* (*GImAllocatorAllocFunc)(size_t size, void* user_data) = MallocWrapper;
static void (*GImAllocatorFreeFunc)(void* ptr, void* user_data) = FreeWrapper;
static void* GImAllocatorUserData = NULL;
//-----------------------------------------------------------------------------
// [SECTION] USER FACING STRUCTURES (ImGuiStyle, ImGuiIO)
//-----------------------------------------------------------------------------
ImGuiStyle::ImGuiStyle()
{
Alpha = 1.0f; // Global alpha applies to everything in ImGui
WindowPadding = ImVec2(8,8); // Padding within a window
WindowRounding = 7.0f; // Radius of window corners rounding. Set to 0.0f to have rectangular windows. Large values tend to lead to variety of artifacts and are not recommended.
WindowBorderSize = 1.0f; // Thickness of border around windows. Generally set to 0.0f or 1.0f. Other values not well tested.
WindowMinSize = ImVec2(32,32); // Minimum window size
WindowTitleAlign = ImVec2(0.0f,0.5f);// Alignment for title bar text
WindowMenuButtonPosition= ImGuiDir_Left; // Position of the collapsing/docking button in the title bar (left/right). Defaults to ImGuiDir_Left.
ChildRounding = 0.0f; // Radius of child window corners rounding. Set to 0.0f to have rectangular child windows
ChildBorderSize = 1.0f; // Thickness of border around child windows. Generally set to 0.0f or 1.0f. Other values not well tested.
PopupRounding = 0.0f; // Radius of popup window corners rounding. Set to 0.0f to have rectangular child windows
PopupBorderSize = 1.0f; // Thickness of border around popup or tooltip windows. Generally set to 0.0f or 1.0f. Other values not well tested.
FramePadding = ImVec2(4,3); // Padding within a framed rectangle (used by most widgets)
FrameRounding = 0.0f; // Radius of frame corners rounding. Set to 0.0f to have rectangular frames (used by most widgets).
FrameBorderSize = 0.0f; // Thickness of border around frames. Generally set to 0.0f or 1.0f. Other values not well tested.
ItemSpacing = ImVec2(8,4); // Horizontal and vertical spacing between widgets/lines
ItemInnerSpacing = ImVec2(4,4); // Horizontal and vertical spacing between within elements of a composed widget (e.g. a slider and its label)
TouchExtraPadding = ImVec2(0,0); // Expand reactive bounding box for touch-based system where touch position is not accurate enough. Unfortunately we don't sort widgets so priority on overlap will always be given to the first widget. So don't grow this too much!
IndentSpacing = 21.0f; // Horizontal spacing when e.g. entering a tree node. Generally == (FontSize + FramePadding.x*2).
ColumnsMinSpacing = 6.0f; // Minimum horizontal spacing between two columns. Preferably > (FramePadding.x + 1).
ScrollbarSize = 14.0f; // Width of the vertical scrollbar, Height of the horizontal scrollbar
ScrollbarRounding = 9.0f; // Radius of grab corners rounding for scrollbar
GrabMinSize = 10.0f; // Minimum width/height of a grab box for slider/scrollbar
GrabRounding = 0.0f; // Radius of grabs corners rounding. Set to 0.0f to have rectangular slider grabs.
LogSliderDeadzone = 4.0f; // The size in pixels of the dead-zone around zero on logarithmic sliders that cross zero.
TabRounding = 4.0f; // Radius of upper corners of a tab. Set to 0.0f to have rectangular tabs.
TabBorderSize = 0.0f; // Thickness of border around tabs.
TabMinWidthForUnselectedCloseButton = 0.0f; // Minimum width for close button to appears on an unselected tab when hovered. Set to 0.0f to always show when hovering, set to FLT_MAX to never show close button unless selected.
ColorButtonPosition = ImGuiDir_Right; // Side of the color button in the ColorEdit4 widget (left/right). Defaults to ImGuiDir_Right.
ButtonTextAlign = ImVec2(0.5f,0.5f);// Alignment of button text when button is larger than text.
SelectableTextAlign = ImVec2(0.0f,0.0f);// Alignment of selectable text. Defaults to (0.0f, 0.0f) (top-left aligned). It's generally important to keep this left-aligned if you want to lay multiple items on a same line.
DisplayWindowPadding = ImVec2(19,19); // Window position are clamped to be visible within the display area or monitors by at least this amount. Only applies to regular windows.
DisplaySafeAreaPadding = ImVec2(3,3); // If you cannot see the edge of your screen (e.g. on a TV) increase the safe area padding. Covers popups/tooltips as well regular windows.
MouseCursorScale = 1.0f; // Scale software rendered mouse cursor (when io.MouseDrawCursor is enabled). May be removed later.
AntiAliasedLines = true; // Enable anti-aliased lines/borders. Disable if you are really tight on CPU/GPU.
AntiAliasedLinesUseTex = true; // Enable anti-aliased lines/borders using textures where possible. Require back-end to render with bilinear filtering.
AntiAliasedFill = true; // Enable anti-aliased filled shapes (rounded rectangles, circles, etc.).
CurveTessellationTol = 1.25f; // Tessellation tolerance when using PathBezierCurveTo() without a specific number of segments. Decrease for highly tessellated curves (higher quality, more polygons), increase to reduce quality.
CircleSegmentMaxError = 1.60f; // Maximum error (in pixels) allowed when using AddCircle()/AddCircleFilled() or drawing rounded corner rectangles with no explicit segment count specified. Decrease for higher quality but more geometry.
// Default theme
ImGui::StyleColorsDark(this);
}
// To scale your entire UI (e.g. if you want your app to use High DPI or generally be DPI aware) you may use this helper function. Scaling the fonts is done separately and is up to you.
// Important: This operation is lossy because we round all sizes to integer. If you need to change your scale multiples, call this over a freshly initialized ImGuiStyle structure rather than scaling multiple times.
void ImGuiStyle::ScaleAllSizes(float scale_factor)
{
WindowPadding = ImFloor(WindowPadding * scale_factor);
WindowRounding = ImFloor(WindowRounding * scale_factor);
WindowMinSize = ImFloor(WindowMinSize * scale_factor);
ChildRounding = ImFloor(ChildRounding * scale_factor);
PopupRounding = ImFloor(PopupRounding * scale_factor);
FramePadding = ImFloor(FramePadding * scale_factor);
FrameRounding = ImFloor(FrameRounding * scale_factor);
ItemSpacing = ImFloor(ItemSpacing * scale_factor);
ItemInnerSpacing = ImFloor(ItemInnerSpacing * scale_factor);
TouchExtraPadding = ImFloor(TouchExtraPadding * scale_factor);
IndentSpacing = ImFloor(IndentSpacing * scale_factor);
ColumnsMinSpacing = ImFloor(ColumnsMinSpacing * scale_factor);
ScrollbarSize = ImFloor(ScrollbarSize * scale_factor);
ScrollbarRounding = ImFloor(ScrollbarRounding * scale_factor);
GrabMinSize = ImFloor(GrabMinSize * scale_factor);
GrabRounding = ImFloor(GrabRounding * scale_factor);
LogSliderDeadzone = ImFloor(LogSliderDeadzone * scale_factor);
TabRounding = ImFloor(TabRounding * scale_factor);
if (TabMinWidthForUnselectedCloseButton != FLT_MAX)
TabMinWidthForUnselectedCloseButton = ImFloor(TabMinWidthForUnselectedCloseButton * scale_factor);
DisplayWindowPadding = ImFloor(DisplayWindowPadding * scale_factor);
DisplaySafeAreaPadding = ImFloor(DisplaySafeAreaPadding * scale_factor);
MouseCursorScale = ImFloor(MouseCursorScale * scale_factor);
}
ImGuiIO::ImGuiIO()
{
// Most fields are initialized with zero
memset(this, 0, sizeof(*this));
IM_ASSERT(IM_ARRAYSIZE(ImGuiIO::MouseDown) == ImGuiMouseButton_COUNT && IM_ARRAYSIZE(ImGuiIO::MouseClicked) == ImGuiMouseButton_COUNT); // Our pre-C++11 IM_STATIC_ASSERT() macros triggers warning on modern compilers so we don't use it here.
// Settings
ConfigFlags = ImGuiConfigFlags_None;
BackendFlags = ImGuiBackendFlags_None;
DisplaySize = ImVec2(-1.0f, -1.0f);
DeltaTime = 1.0f / 60.0f;
IniSavingRate = 5.0f;
IniFilename = "imgui.ini";
LogFilename = "imgui_log.txt";
MouseDoubleClickTime = 0.30f;
MouseDoubleClickMaxDist = 6.0f;
for (int i = 0; i < ImGuiKey_COUNT; i++)
KeyMap[i] = -1;
KeyRepeatDelay = 0.275f;
KeyRepeatRate = 0.050f;
UserData = NULL;
Fonts = NULL;
FontGlobalScale = 1.0f;
FontDefault = NULL;
FontAllowUserScaling = false;
DisplayFramebufferScale = ImVec2(1.0f, 1.0f);
// Miscellaneous options
MouseDrawCursor = false;
#ifdef __APPLE__
ConfigMacOSXBehaviors = true; // Set Mac OS X style defaults based on __APPLE__ compile time flag
#else
ConfigMacOSXBehaviors = false;
#endif
ConfigInputTextCursorBlink = true;
ConfigWindowsResizeFromEdges = true;
ConfigWindowsMoveFromTitleBarOnly = false;
ConfigWindowsMemoryCompactTimer = 60.0f;
// Platform Functions
BackendPlatformName = BackendRendererName = NULL;
BackendPlatformUserData = BackendRendererUserData = BackendLanguageUserData = NULL;
GetClipboardTextFn = GetClipboardTextFn_DefaultImpl; // Platform dependent default implementations
SetClipboardTextFn = SetClipboardTextFn_DefaultImpl;
ClipboardUserData = NULL;
ImeSetInputScreenPosFn = ImeSetInputScreenPosFn_DefaultImpl;
ImeWindowHandle = NULL;
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
RenderDrawListsFn = NULL;
#endif
// Input (NB: we already have memset zero the entire structure!)
MousePos = ImVec2(-FLT_MAX, -FLT_MAX);
MousePosPrev = ImVec2(-FLT_MAX, -FLT_MAX);
MouseDragThreshold = 6.0f;
for (int i = 0; i < IM_ARRAYSIZE(MouseDownDuration); i++) MouseDownDuration[i] = MouseDownDurationPrev[i] = -1.0f;
for (int i = 0; i < IM_ARRAYSIZE(KeysDownDuration); i++) KeysDownDuration[i] = KeysDownDurationPrev[i] = -1.0f;
for (int i = 0; i < IM_ARRAYSIZE(NavInputsDownDuration); i++) NavInputsDownDuration[i] = -1.0f;
}
// Pass in translated ASCII characters for text input.
// - with glfw you can get those from the callback set in glfwSetCharCallback()
// - on Windows you can get those using ToAscii+keyboard state, or via the WM_CHAR message
void ImGuiIO::AddInputCharacter(unsigned int c)
{
if (c != 0)
InputQueueCharacters.push_back(c <= IM_UNICODE_CODEPOINT_MAX ? (ImWchar)c : IM_UNICODE_CODEPOINT_INVALID);
}
// UTF16 strings use surrogate pairs to encode codepoints >= 0x10000, so
// we should save the high surrogate.
void ImGuiIO::AddInputCharacterUTF16(ImWchar16 c)
{
if (c == 0 && InputQueueSurrogate == 0)
return;
if ((c & 0xFC00) == 0xD800) // High surrogate, must save
{
if (InputQueueSurrogate != 0)
InputQueueCharacters.push_back(IM_UNICODE_CODEPOINT_INVALID);
InputQueueSurrogate = c;
return;
}
ImWchar cp = c;
if (InputQueueSurrogate != 0)
{
if ((c & 0xFC00) != 0xDC00) // Invalid low surrogate
InputQueueCharacters.push_back(IM_UNICODE_CODEPOINT_INVALID);
else if (IM_UNICODE_CODEPOINT_MAX == (0xFFFF)) // Codepoint will not fit in ImWchar (extra parenthesis around 0xFFFF somehow fixes -Wunreachable-code with Clang)
cp = IM_UNICODE_CODEPOINT_INVALID;
else
cp = (ImWchar)(((InputQueueSurrogate - 0xD800) << 10) + (c - 0xDC00) + 0x10000);
InputQueueSurrogate = 0;
}
InputQueueCharacters.push_back(cp);
}
void ImGuiIO::AddInputCharactersUTF8(const char* utf8_chars)
{
while (*utf8_chars != 0)
{
unsigned int c = 0;
utf8_chars += ImTextCharFromUtf8(&c, utf8_chars, NULL);
if (c != 0)
InputQueueCharacters.push_back((ImWchar)c);
}
}
void ImGuiIO::ClearInputCharacters()
{
InputQueueCharacters.resize(0);
}
//-----------------------------------------------------------------------------
// [SECTION] MISC HELPERS/UTILITIES (Geometry functions)
//-----------------------------------------------------------------------------
ImVec2 ImBezierClosestPoint(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& p, int num_segments)
{
IM_ASSERT(num_segments > 0); // Use ImBezierClosestPointCasteljau()
ImVec2 p_last = p1;
ImVec2 p_closest;
float p_closest_dist2 = FLT_MAX;
float t_step = 1.0f / (float)num_segments;
for (int i_step = 1; i_step <= num_segments; i_step++)
{
ImVec2 p_current = ImBezierCalc(p1, p2, p3, p4, t_step * i_step);
ImVec2 p_line = ImLineClosestPoint(p_last, p_current, p);
float dist2 = ImLengthSqr(p - p_line);
if (dist2 < p_closest_dist2)
{
p_closest = p_line;
p_closest_dist2 = dist2;
}
p_last = p_current;
}
return p_closest;
}
// Closely mimics PathBezierToCasteljau() in imgui_draw.cpp
static void BezierClosestPointCasteljauStep(const ImVec2& p, ImVec2& p_closest, ImVec2& p_last, float& p_closest_dist2, float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4, float tess_tol, int level)
{
float dx = x4 - x1;
float dy = y4 - y1;
float d2 = ((x2 - x4) * dy - (y2 - y4) * dx);
float d3 = ((x3 - x4) * dy - (y3 - y4) * dx);
d2 = (d2 >= 0) ? d2 : -d2;
d3 = (d3 >= 0) ? d3 : -d3;
if ((d2 + d3) * (d2 + d3) < tess_tol * (dx * dx + dy * dy))
{
ImVec2 p_current(x4, y4);
ImVec2 p_line = ImLineClosestPoint(p_last, p_current, p);
float dist2 = ImLengthSqr(p - p_line);
if (dist2 < p_closest_dist2)
{
p_closest = p_line;
p_closest_dist2 = dist2;
}
p_last = p_current;
}
else if (level < 10)
{
float x12 = (x1 + x2)*0.5f, y12 = (y1 + y2)*0.5f;
float x23 = (x2 + x3)*0.5f, y23 = (y2 + y3)*0.5f;
float x34 = (x3 + x4)*0.5f, y34 = (y3 + y4)*0.5f;
float x123 = (x12 + x23)*0.5f, y123 = (y12 + y23)*0.5f;
float x234 = (x23 + x34)*0.5f, y234 = (y23 + y34)*0.5f;
float x1234 = (x123 + x234)*0.5f, y1234 = (y123 + y234)*0.5f;
BezierClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, x1, y1, x12, y12, x123, y123, x1234, y1234, tess_tol, level + 1);
BezierClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, x1234, y1234, x234, y234, x34, y34, x4, y4, tess_tol, level + 1);
}
}
// tess_tol is generally the same value you would find in ImGui::GetStyle().CurveTessellationTol
// Because those ImXXX functions are lower-level than ImGui:: we cannot access this value automatically.
ImVec2 ImBezierClosestPointCasteljau(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& p, float tess_tol)
{
IM_ASSERT(tess_tol > 0.0f);
ImVec2 p_last = p1;
ImVec2 p_closest;
float p_closest_dist2 = FLT_MAX;
BezierClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, p1.x, p1.y, p2.x, p2.y, p3.x, p3.y, p4.x, p4.y, tess_tol, 0);
return p_closest;
}
ImVec2 ImLineClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& p)
{
ImVec2 ap = p - a;
ImVec2 ab_dir = b - a;
float dot = ap.x * ab_dir.x + ap.y * ab_dir.y;
if (dot < 0.0f)
return a;
float ab_len_sqr = ab_dir.x * ab_dir.x + ab_dir.y * ab_dir.y;
if (dot > ab_len_sqr)
return b;
return a + ab_dir * dot / ab_len_sqr;
}
bool ImTriangleContainsPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p)
{
bool b1 = ((p.x - b.x) * (a.y - b.y) - (p.y - b.y) * (a.x - b.x)) < 0.0f;
bool b2 = ((p.x - c.x) * (b.y - c.y) - (p.y - c.y) * (b.x - c.x)) < 0.0f;
bool b3 = ((p.x - a.x) * (c.y - a.y) - (p.y - a.y) * (c.x - a.x)) < 0.0f;
return ((b1 == b2) && (b2 == b3));
}
void ImTriangleBarycentricCoords(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p, float& out_u, float& out_v, float& out_w)
{
ImVec2 v0 = b - a;
ImVec2 v1 = c - a;
ImVec2 v2 = p - a;
const float denom = v0.x * v1.y - v1.x * v0.y;
out_v = (v2.x * v1.y - v1.x * v2.y) / denom;
out_w = (v0.x * v2.y - v2.x * v0.y) / denom;
out_u = 1.0f - out_v - out_w;
}
ImVec2 ImTriangleClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p)
{
ImVec2 proj_ab = ImLineClosestPoint(a, b, p);
ImVec2 proj_bc = ImLineClosestPoint(b, c, p);
ImVec2 proj_ca = ImLineClosestPoint(c, a, p);
float dist2_ab = ImLengthSqr(p - proj_ab);
float dist2_bc = ImLengthSqr(p - proj_bc);
float dist2_ca = ImLengthSqr(p - proj_ca);
float m = ImMin(dist2_ab, ImMin(dist2_bc, dist2_ca));
if (m == dist2_ab)
return proj_ab;
if (m == dist2_bc)
return proj_bc;
return proj_ca;
}
//-----------------------------------------------------------------------------
// [SECTION] MISC HELPERS/UTILITIES (String, Format, Hash functions)
//-----------------------------------------------------------------------------
// Consider using _stricmp/_strnicmp under Windows or strcasecmp/strncasecmp. We don't actually use either ImStricmp/ImStrnicmp in the codebase any more.
int ImStricmp(const char* str1, const char* str2)
{
int d;
while ((d = toupper(*str2) - toupper(*str1)) == 0 && *str1) { str1++; str2++; }
return d;
}
int ImStrnicmp(const char* str1, const char* str2, size_t count)
{
int d = 0;
while (count > 0 && (d = toupper(*str2) - toupper(*str1)) == 0 && *str1) { str1++; str2++; count--; }
return d;
}
void ImStrncpy(char* dst, const char* src, size_t count)
{
if (count < 1)
return;
if (count > 1)
strncpy(dst, src, count - 1);
dst[count - 1] = 0;
}
char* ImStrdup(const char* str)
{
size_t len = strlen(str);
void* buf = IM_ALLOC(len + 1);
return (char*)memcpy(buf, (const void*)str, len + 1);
}
char* ImStrdupcpy(char* dst, size_t* p_dst_size, const char* src)
{
size_t dst_buf_size = p_dst_size ? *p_dst_size : strlen(dst) + 1;
size_t src_size = strlen(src) + 1;
if (dst_buf_size < src_size)
{
IM_FREE(dst);
dst = (char*)IM_ALLOC(src_size);
if (p_dst_size)
*p_dst_size = src_size;
}
return (char*)memcpy(dst, (const void*)src, src_size);
}
const char* ImStrchrRange(const char* str, const char* str_end, char c)
{
const char* p = (const char*)memchr(str, (int)c, str_end - str);
return p;
}
int ImStrlenW(const ImWchar* str)
{
//return (int)wcslen((const wchar_t*)str); // FIXME-OPT: Could use this when wchar_t are 16-bit
int n = 0;
while (*str++) n++;
return n;
}
// Find end-of-line. Return pointer will point to either first \n, either str_end.
const char* ImStreolRange(const char* str, const char* str_end)
{
const char* p = (const char*)memchr(str, '\n', str_end - str);
return p ? p : str_end;
}
const ImWchar* ImStrbolW(const ImWchar* buf_mid_line, const ImWchar* buf_begin) // find beginning-of-line
{
while (buf_mid_line > buf_begin && buf_mid_line[-1] != '\n')
buf_mid_line--;
return buf_mid_line;
}
const char* ImStristr(const char* haystack, const char* haystack_end, const char* needle, const char* needle_end)
{
if (!needle_end)
needle_end = needle + strlen(needle);
const char un0 = (char)toupper(*needle);
while ((!haystack_end && *haystack) || (haystack_end && haystack < haystack_end))
{
if (toupper(*haystack) == un0)
{
const char* b = needle + 1;
for (const char* a = haystack + 1; b < needle_end; a++, b++)
if (toupper(*a) != toupper(*b))
break;
if (b == needle_end)
return haystack;
}
haystack++;
}
return NULL;
}
// Trim str by offsetting contents when there's leading data + writing a \0 at the trailing position. We use this in situation where the cost is negligible.
void ImStrTrimBlanks(char* buf)
{
char* p = buf;
while (p[0] == ' ' || p[0] == '\t') // Leading blanks
p++;
char* p_start = p;
while (*p != 0) // Find end of string
p++;
while (p > p_start && (p[-1] == ' ' || p[-1] == '\t')) // Trailing blanks
p--;
if (p_start != buf) // Copy memory if we had leading blanks
memmove(buf, p_start, p - p_start);
buf[p - p_start] = 0; // Zero terminate
}
const char* ImStrSkipBlank(const char* str)
{
while (str[0] == ' ' || str[0] == '\t')
str++;
return str;
}
// A) MSVC version appears to return -1 on overflow, whereas glibc appears to return total count (which may be >= buf_size).
// Ideally we would test for only one of those limits at runtime depending on the behavior the vsnprintf(), but trying to deduct it at compile time sounds like a pandora can of worm.
// B) When buf==NULL vsnprintf() will return the output size.
#ifndef IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
// We support stb_sprintf which is much faster (see: https://github.com/nothings/stb/blob/master/stb_sprintf.h)
// You may set IMGUI_USE_STB_SPRINTF to use our default wrapper, or set IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
// and setup the wrapper yourself. (FIXME-OPT: Some of our high-level operations such as ImGuiTextBuffer::appendfv() are
// designed using two-passes worst case, which probably could be improved using the stbsp_vsprintfcb() function.)
#ifdef IMGUI_USE_STB_SPRINTF
#define STB_SPRINTF_IMPLEMENTATION
#include "stb_sprintf.h"
#endif
#if defined(_MSC_VER) && !defined(vsnprintf)
#define vsnprintf _vsnprintf
#endif
int ImFormatString(char* buf, size_t buf_size, const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
#ifdef IMGUI_USE_STB_SPRINTF
int w = stbsp_vsnprintf(buf, (int)buf_size, fmt, args);
#else
int w = vsnprintf(buf, buf_size, fmt, args);
#endif
va_end(args);
if (buf == NULL)
return w;
if (w == -1 || w >= (int)buf_size)
w = (int)buf_size - 1;
buf[w] = 0;
return w;
}
int ImFormatStringV(char* buf, size_t buf_size, const char* fmt, va_list args)
{
#ifdef IMGUI_USE_STB_SPRINTF
int w = stbsp_vsnprintf(buf, (int)buf_size, fmt, args);
#else
int w = vsnprintf(buf, buf_size, fmt, args);
#endif
if (buf == NULL)
return w;
if (w == -1 || w >= (int)buf_size)
w = (int)buf_size - 1;
buf[w] = 0;
return w;
}
#endif // #ifdef IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
// CRC32 needs a 1KB lookup table (not cache friendly)
// Although the code to generate the table is simple and shorter than the table itself, using a const table allows us to easily:
// - avoid an unnecessary branch/memory tap, - keep the ImHashXXX functions usable by static constructors, - make it thread-safe.
static const ImU32 GCrc32LookupTable[256] =
{
0x00000000,0x77073096,0xEE0E612C,0x990951BA,0x076DC419,0x706AF48F,0xE963A535,0x9E6495A3,0x0EDB8832,0x79DCB8A4,0xE0D5E91E,0x97D2D988,0x09B64C2B,0x7EB17CBD,0xE7B82D07,0x90BF1D91,
0x1DB71064,0x6AB020F2,0xF3B97148,0x84BE41DE,0x1ADAD47D,0x6DDDE4EB,0xF4D4B551,0x83D385C7,0x136C9856,0x646BA8C0,0xFD62F97A,0x8A65C9EC,0x14015C4F,0x63066CD9,0xFA0F3D63,0x8D080DF5,
0x3B6E20C8,0x4C69105E,0xD56041E4,0xA2677172,0x3C03E4D1,0x4B04D447,0xD20D85FD,0xA50AB56B,0x35B5A8FA,0x42B2986C,0xDBBBC9D6,0xACBCF940,0x32D86CE3,0x45DF5C75,0xDCD60DCF,0xABD13D59,
0x26D930AC,0x51DE003A,0xC8D75180,0xBFD06116,0x21B4F4B5,0x56B3C423,0xCFBA9599,0xB8BDA50F,0x2802B89E,0x5F058808,0xC60CD9B2,0xB10BE924,0x2F6F7C87,0x58684C11,0xC1611DAB,0xB6662D3D,
0x76DC4190,0x01DB7106,0x98D220BC,0xEFD5102A,0x71B18589,0x06B6B51F,0x9FBFE4A5,0xE8B8D433,0x7807C9A2,0x0F00F934,0x9609A88E,0xE10E9818,0x7F6A0DBB,0x086D3D2D,0x91646C97,0xE6635C01,
0x6B6B51F4,0x1C6C6162,0x856530D8,0xF262004E,0x6C0695ED,0x1B01A57B,0x8208F4C1,0xF50FC457,0x65B0D9C6,0x12B7E950,0x8BBEB8EA,0xFCB9887C,0x62DD1DDF,0x15DA2D49,0x8CD37CF3,0xFBD44C65,
0x4DB26158,0x3AB551CE,0xA3BC0074,0xD4BB30E2,0x4ADFA541,0x3DD895D7,0xA4D1C46D,0xD3D6F4FB,0x4369E96A,0x346ED9FC,0xAD678846,0xDA60B8D0,0x44042D73,0x33031DE5,0xAA0A4C5F,0xDD0D7CC9,
0x5005713C,0x270241AA,0xBE0B1010,0xC90C2086,0x5768B525,0x206F85B3,0xB966D409,0xCE61E49F,0x5EDEF90E,0x29D9C998,0xB0D09822,0xC7D7A8B4,0x59B33D17,0x2EB40D81,0xB7BD5C3B,0xC0BA6CAD,
0xEDB88320,0x9ABFB3B6,0x03B6E20C,0x74B1D29A,0xEAD54739,0x9DD277AF,0x04DB2615,0x73DC1683,0xE3630B12,0x94643B84,0x0D6D6A3E,0x7A6A5AA8,0xE40ECF0B,0x9309FF9D,0x0A00AE27,0x7D079EB1,
0xF00F9344,0x8708A3D2,0x1E01F268,0x6906C2FE,0xF762575D,0x806567CB,0x196C3671,0x6E6B06E7,0xFED41B76,0x89D32BE0,0x10DA7A5A,0x67DD4ACC,0xF9B9DF6F,0x8EBEEFF9,0x17B7BE43,0x60B08ED5,
0xD6D6A3E8,0xA1D1937E,0x38D8C2C4,0x4FDFF252,0xD1BB67F1,0xA6BC5767,0x3FB506DD,0x48B2364B,0xD80D2BDA,0xAF0A1B4C,0x36034AF6,0x41047A60,0xDF60EFC3,0xA867DF55,0x316E8EEF,0x4669BE79,
0xCB61B38C,0xBC66831A,0x256FD2A0,0x5268E236,0xCC0C7795,0xBB0B4703,0x220216B9,0x5505262F,0xC5BA3BBE,0xB2BD0B28,0x2BB45A92,0x5CB36A04,0xC2D7FFA7,0xB5D0CF31,0x2CD99E8B,0x5BDEAE1D,
0x9B64C2B0,0xEC63F226,0x756AA39C,0x026D930A,0x9C0906A9,0xEB0E363F,0x72076785,0x05005713,0x95BF4A82,0xE2B87A14,0x7BB12BAE,0x0CB61B38,0x92D28E9B,0xE5D5BE0D,0x7CDCEFB7,0x0BDBDF21,
0x86D3D2D4,0xF1D4E242,0x68DDB3F8,0x1FDA836E,0x81BE16CD,0xF6B9265B,0x6FB077E1,0x18B74777,0x88085AE6,0xFF0F6A70,0x66063BCA,0x11010B5C,0x8F659EFF,0xF862AE69,0x616BFFD3,0x166CCF45,
0xA00AE278,0xD70DD2EE,0x4E048354,0x3903B3C2,0xA7672661,0xD06016F7,0x4969474D,0x3E6E77DB,0xAED16A4A,0xD9D65ADC,0x40DF0B66,0x37D83BF0,0xA9BCAE53,0xDEBB9EC5,0x47B2CF7F,0x30B5FFE9,
0xBDBDF21C,0xCABAC28A,0x53B39330,0x24B4A3A6,0xBAD03605,0xCDD70693,0x54DE5729,0x23D967BF,0xB3667A2E,0xC4614AB8,0x5D681B02,0x2A6F2B94,0xB40BBE37,0xC30C8EA1,0x5A05DF1B,0x2D02EF8D,
};
// Known size hash
// It is ok to call ImHashData on a string with known length but the ### operator won't be supported.
// FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements.
ImU32 ImHashData(const void* data_p, size_t data_size, ImU32 seed)
{
ImU32 crc = ~seed;
const unsigned char* data = (const unsigned char*)data_p;
const ImU32* crc32_lut = GCrc32LookupTable;
while (data_size-- != 0)
crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ *data++];
return ~crc;
}
// Zero-terminated string hash, with support for ### to reset back to seed value
// We support a syntax of "label###id" where only "###id" is included in the hash, and only "label" gets displayed.
// Because this syntax is rarely used we are optimizing for the common case.
// - If we reach ### in the string we discard the hash so far and reset to the seed.
// - We don't do 'current += 2; continue;' after handling ### to keep the code smaller/faster (measured ~10% diff in Debug build)
// FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements.
ImU32 ImHashStr(const char* data_p, size_t data_size, ImU32 seed)
{
seed = ~seed;
ImU32 crc = seed;
const unsigned char* data = (const unsigned char*)data_p;
const ImU32* crc32_lut = GCrc32LookupTable;
if (data_size != 0)
{
while (data_size-- != 0)
{
unsigned char c = *data++;
if (c == '#' && data_size >= 2 && data[0] == '#' && data[1] == '#')
crc = seed;
crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c];
}
}
else
{
while (unsigned char c = *data++)
{
if (c == '#' && data[0] == '#' && data[1] == '#')
crc = seed;
crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c];
}
}
return ~crc;
}
//-----------------------------------------------------------------------------
// [SECTION] MISC HELPERS/UTILITIES (File functions)
//-----------------------------------------------------------------------------
// Default file functions
#ifndef IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS
ImFileHandle ImFileOpen(const char* filename, const char* mode)
{
#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(__CYGWIN__) && !defined(__GNUC__)
// We need a fopen() wrapper because MSVC/Windows fopen doesn't handle UTF-8 filenames.
// Previously we used ImTextCountCharsFromUtf8/ImTextStrFromUtf8 here but we now need to support ImWchar16 and ImWchar32!
const int filename_wsize = ::MultiByteToWideChar(CP_UTF8, 0, filename, -1, NULL, 0);
const int mode_wsize = ::MultiByteToWideChar(CP_UTF8, 0, mode, -1, NULL, 0);
ImVector<ImWchar> buf;
buf.resize(filename_wsize + mode_wsize);
::MultiByteToWideChar(CP_UTF8, 0, filename, -1, (wchar_t*)&buf[0], filename_wsize);
::MultiByteToWideChar(CP_UTF8, 0, mode, -1, (wchar_t*)&buf[filename_wsize], mode_wsize);
return ::_wfopen((const wchar_t*)&buf[0], (const wchar_t*)&buf[filename_wsize]);
#else
return fopen(filename, mode);
#endif
}
// We should in theory be using fseeko()/ftello() with off_t and _fseeki64()/_ftelli64() with __int64, waiting for the PR that does that in a very portable pre-C++11 zero-warnings way.
bool ImFileClose(ImFileHandle f) { return fclose(f) == 0; }
ImU64 ImFileGetSize(ImFileHandle f) { long off = 0, sz = 0; return ((off = ftell(f)) != -1 && !fseek(f, 0, SEEK_END) && (sz = ftell(f)) != -1 && !fseek(f, off, SEEK_SET)) ? (ImU64)sz : (ImU64)-1; }
ImU64 ImFileRead(void* data, ImU64 sz, ImU64 count, ImFileHandle f) { return fread(data, (size_t)sz, (size_t)count, f); }
ImU64 ImFileWrite(const void* data, ImU64 sz, ImU64 count, ImFileHandle f) { return fwrite(data, (size_t)sz, (size_t)count, f); }
#endif // #ifndef IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS
// Helper: Load file content into memory
// Memory allocated with IM_ALLOC(), must be freed by user using IM_FREE() == ImGui::MemFree()
// This can't really be used with "rt" because fseek size won't match read size.
void* ImFileLoadToMemory(const char* filename, const char* mode, size_t* out_file_size, int padding_bytes)
{
IM_ASSERT(filename && mode);
if (out_file_size)
*out_file_size = 0;
ImFileHandle f;
if ((f = ImFileOpen(filename, mode)) == NULL)
return NULL;
size_t file_size = (size_t)ImFileGetSize(f);
if (file_size == (size_t)-1)
{
ImFileClose(f);
return NULL;
}
void* file_data = IM_ALLOC(file_size + padding_bytes);
if (file_data == NULL)
{
ImFileClose(f);
return NULL;
}
if (ImFileRead(file_data, 1, file_size, f) != file_size)
{
ImFileClose(f);
IM_FREE(file_data);
return NULL;
}
if (padding_bytes > 0)
memset((void*)(((char*)file_data) + file_size), 0, (size_t)padding_bytes);
ImFileClose(f);
if (out_file_size)
*out_file_size = file_size;
return file_data;
}
//-----------------------------------------------------------------------------
// [SECTION] MISC HELPERS/UTILITIES (ImText* functions)
//-----------------------------------------------------------------------------
// Convert UTF-8 to 32-bit character, process single character input.
// Based on stb_from_utf8() from github.com/nothings/stb/
// We handle UTF-8 decoding error by skipping forward.
int ImTextCharFromUtf8(unsigned int* out_char, const char* in_text, const char* in_text_end)
{
unsigned int c = (unsigned int)-1;
const unsigned char* str = (const unsigned char*)in_text;
if (!(*str & 0x80))
{
c = (unsigned int)(*str++);
*out_char = c;
return 1;
}
if ((*str & 0xe0) == 0xc0)
{
*out_char = IM_UNICODE_CODEPOINT_INVALID; // will be invalid but not end of string
if (in_text_end && in_text_end - (const char*)str < 2) return 1;
if (*str < 0xc2) return 2;
c = (unsigned int)((*str++ & 0x1f) << 6);
if ((*str & 0xc0) != 0x80) return 2;
c += (*str++ & 0x3f);
*out_char = c;
return 2;
}
if ((*str & 0xf0) == 0xe0)
{
*out_char = IM_UNICODE_CODEPOINT_INVALID; // will be invalid but not end of string
if (in_text_end && in_text_end - (const char*)str < 3) return 1;
if (*str == 0xe0 && (str[1] < 0xa0 || str[1] > 0xbf)) return 3;
if (*str == 0xed && str[1] > 0x9f) return 3; // str[1] < 0x80 is checked below
c = (unsigned int)((*str++ & 0x0f) << 12);
if ((*str & 0xc0) != 0x80) return 3;
c += (unsigned int)((*str++ & 0x3f) << 6);
if ((*str & 0xc0) != 0x80) return 3;
c += (*str++ & 0x3f);
*out_char = c;
return 3;
}
if ((*str & 0xf8) == 0xf0)
{
*out_char = IM_UNICODE_CODEPOINT_INVALID; // will be invalid but not end of string
if (in_text_end && in_text_end - (const char*)str < 4) return 1;
if (*str > 0xf4) return 4;
if (*str == 0xf0 && (str[1] < 0x90 || str[1] > 0xbf)) return 4;
if (*str == 0xf4 && str[1] > 0x8f) return 4; // str[1] < 0x80 is checked below
c = (unsigned int)((*str++ & 0x07) << 18);
if ((*str & 0xc0) != 0x80) return 4;
c += (unsigned int)((*str++ & 0x3f) << 12);
if ((*str & 0xc0) != 0x80) return 4;
c += (unsigned int)((*str++ & 0x3f) << 6);
if ((*str & 0xc0) != 0x80) return 4;
c += (*str++ & 0x3f);
// utf-8 encodings of values used in surrogate pairs are invalid
if ((c & 0xFFFFF800) == 0xD800) return 4;
// If codepoint does not fit in ImWchar, use replacement character U+FFFD instead
if (c > IM_UNICODE_CODEPOINT_MAX) c = IM_UNICODE_CODEPOINT_INVALID;
*out_char = c;
return 4;
}
*out_char = 0;
return 0;
}
int ImTextStrFromUtf8(ImWchar* buf, int buf_size, const char* in_text, const char* in_text_end, const char** in_text_remaining)
{
ImWchar* buf_out = buf;
ImWchar* buf_end = buf + buf_size;
while (buf_out < buf_end - 1 && (!in_text_end || in_text < in_text_end) && *in_text)
{
unsigned int c;
in_text += ImTextCharFromUtf8(&c, in_text, in_text_end);
if (c == 0)
break;
*buf_out++ = (ImWchar)c;
}
*buf_out = 0;
if (in_text_remaining)
*in_text_remaining = in_text;
return (int)(buf_out - buf);
}
int ImTextCountCharsFromUtf8(const char* in_text, const char* in_text_end)
{
int char_count = 0;
while ((!in_text_end || in_text < in_text_end) && *in_text)
{
unsigned int c;
in_text += ImTextCharFromUtf8(&c, in_text, in_text_end);
if (c == 0)
break;
char_count++;
}
return char_count;
}
// Based on stb_to_utf8() from github.com/nothings/stb/
static inline int ImTextCharToUtf8(char* buf, int buf_size, unsigned int c)
{
if (c < 0x80)
{
buf[0] = (char)c;
return 1;
}
if (c < 0x800)
{
if (buf_size < 2) return 0;
buf[0] = (char)(0xc0 + (c >> 6));
buf[1] = (char)(0x80 + (c & 0x3f));
return 2;
}
if (c < 0x10000)
{
if (buf_size < 3) return 0;
buf[0] = (char)(0xe0 + (c >> 12));
buf[1] = (char)(0x80 + ((c >> 6) & 0x3f));
buf[2] = (char)(0x80 + ((c ) & 0x3f));
return 3;
}
if (c <= 0x10FFFF)
{
if (buf_size < 4) return 0;
buf[0] = (char)(0xf0 + (c >> 18));
buf[1] = (char)(0x80 + ((c >> 12) & 0x3f));
buf[2] = (char)(0x80 + ((c >> 6) & 0x3f));
buf[3] = (char)(0x80 + ((c ) & 0x3f));
return 4;
}
// Invalid code point, the max unicode is 0x10FFFF
return 0;
}
// Not optimal but we very rarely use this function.
int ImTextCountUtf8BytesFromChar(const char* in_text, const char* in_text_end)
{
unsigned int unused = 0;
return ImTextCharFromUtf8(&unused, in_text, in_text_end);
}
static inline int ImTextCountUtf8BytesFromChar(unsigned int c)
{
if (c < 0x80) return 1;
if (c < 0x800) return 2;
if (c < 0x10000) return 3;
if (c <= 0x10FFFF) return 4;
return 3;
}
int ImTextStrToUtf8(char* buf, int buf_size, const ImWchar* in_text, const ImWchar* in_text_end)
{
char* buf_out = buf;
const char* buf_end = buf + buf_size;
while (buf_out < buf_end - 1 && (!in_text_end || in_text < in_text_end) && *in_text)
{
unsigned int c = (unsigned int)(*in_text++);
if (c < 0x80)
*buf_out++ = (char)c;
else
buf_out += ImTextCharToUtf8(buf_out, (int)(buf_end - buf_out - 1), c);
}
*buf_out = 0;
return (int)(buf_out - buf);
}
int ImTextCountUtf8BytesFromStr(const ImWchar* in_text, const ImWchar* in_text_end)
{
int bytes_count = 0;
while ((!in_text_end || in_text < in_text_end) && *in_text)
{
unsigned int c = (unsigned int)(*in_text++);
if (c < 0x80)
bytes_count++;
else
bytes_count += ImTextCountUtf8BytesFromChar(c);
}
return bytes_count;
}
//-----------------------------------------------------------------------------
// [SECTION] MISC HELPERS/UTILITIES (Color functions)
// Note: The Convert functions are early design which are not consistent with other API.
//-----------------------------------------------------------------------------
IMGUI_API ImU32 ImAlphaBlendColors(ImU32 col_a, ImU32 col_b)
{
float t = ((col_b >> IM_COL32_A_SHIFT) & 0xFF) / 255.f;
int r = ImLerp((int)(col_a >> IM_COL32_R_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_R_SHIFT) & 0xFF, t);
int g = ImLerp((int)(col_a >> IM_COL32_G_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_G_SHIFT) & 0xFF, t);
int b = ImLerp((int)(col_a >> IM_COL32_B_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_B_SHIFT) & 0xFF, t);
return IM_COL32(r, g, b, 0xFF);
}
ImVec4 ImGui::ColorConvertU32ToFloat4(ImU32 in)
{
float s = 1.0f / 255.0f;
return ImVec4(
((in >> IM_COL32_R_SHIFT) & 0xFF) * s,
((in >> IM_COL32_G_SHIFT) & 0xFF) * s,
((in >> IM_COL32_B_SHIFT) & 0xFF) * s,
((in >> IM_COL32_A_SHIFT) & 0xFF) * s);
}
ImU32 ImGui::ColorConvertFloat4ToU32(const ImVec4& in)
{
ImU32 out;
out = ((ImU32)IM_F32_TO_INT8_SAT(in.x)) << IM_COL32_R_SHIFT;
out |= ((ImU32)IM_F32_TO_INT8_SAT(in.y)) << IM_COL32_G_SHIFT;
out |= ((ImU32)IM_F32_TO_INT8_SAT(in.z)) << IM_COL32_B_SHIFT;
out |= ((ImU32)IM_F32_TO_INT8_SAT(in.w)) << IM_COL32_A_SHIFT;
return out;
}
// Convert rgb floats ([0-1],[0-1],[0-1]) to hsv floats ([0-1],[0-1],[0-1]), from Foley & van Dam p592
// Optimized http://lolengine.net/blog/2013/01/13/fast-rgb-to-hsv
void ImGui::ColorConvertRGBtoHSV(float r, float g, float b, float& out_h, float& out_s, float& out_v)
{
float K = 0.f;
if (g < b)
{
ImSwap(g, b);
K = -1.f;
}
if (r < g)
{
ImSwap(r, g);
K = -2.f / 6.f - K;
}
const float chroma = r - (g < b ? g : b);
out_h = ImFabs(K + (g - b) / (6.f * chroma + 1e-20f));
out_s = chroma / (r + 1e-20f);
out_v = r;
}
// Convert hsv floats ([0-1],[0-1],[0-1]) to rgb floats ([0-1],[0-1],[0-1]), from Foley & van Dam p593
// also http://en.wikipedia.org/wiki/HSL_and_HSV
void ImGui::ColorConvertHSVtoRGB(float h, float s, float v, float& out_r, float& out_g, float& out_b)
{
if (s == 0.0f)
{
// gray
out_r = out_g = out_b = v;
return;
}
h = ImFmod(h, 1.0f) / (60.0f / 360.0f);
int i = (int)h;
float f = h - (float)i;
float p = v * (1.0f - s);
float q = v * (1.0f - s * f);
float t = v * (1.0f - s * (1.0f - f));
switch (i)
{
case 0: out_r = v; out_g = t; out_b = p; break;
case 1: out_r = q; out_g = v; out_b = p; break;
case 2: out_r = p; out_g = v; out_b = t; break;
case 3: out_r = p; out_g = q; out_b = v; break;
case 4: out_r = t; out_g = p; out_b = v; break;
case 5: default: out_r = v; out_g = p; out_b = q; break;
}
}
//-----------------------------------------------------------------------------
// [SECTION] ImGuiStorage
// Helper: Key->value storage
//-----------------------------------------------------------------------------
// std::lower_bound but without the bullshit
static ImGuiStorage::ImGuiStoragePair* LowerBound(ImVector<ImGuiStorage::ImGuiStoragePair>& data, ImGuiID key)
{
ImGuiStorage::ImGuiStoragePair* first = data.Data;
ImGuiStorage::ImGuiStoragePair* last = data.Data + data.Size;
size_t count = (size_t)(last - first);
while (count > 0)
{
size_t count2 = count >> 1;
ImGuiStorage::ImGuiStoragePair* mid = first + count2;
if (mid->key < key)
{
first = ++mid;
count -= count2 + 1;
}
else
{
count = count2;
}
}
return first;
}
// For quicker full rebuild of a storage (instead of an incremental one), you may add all your contents and then sort once.
void ImGuiStorage::BuildSortByKey()
{
struct StaticFunc
{
static int IMGUI_CDECL PairCompareByID(const void* lhs, const void* rhs)
{
// We can't just do a subtraction because qsort uses signed integers and subtracting our ID doesn't play well with that.
if (((const ImGuiStoragePair*)lhs)->key > ((const ImGuiStoragePair*)rhs)->key) return +1;
if (((const ImGuiStoragePair*)lhs)->key < ((const ImGuiStoragePair*)rhs)->key) return -1;
return 0;
}
};
if (Data.Size > 1)
ImQsort(Data.Data, (size_t)Data.Size, sizeof(ImGuiStoragePair), StaticFunc::PairCompareByID);
}
int ImGuiStorage::GetInt(ImGuiID key, int default_val) const
{
ImGuiStoragePair* it = LowerBound(const_cast<ImVector<ImGuiStoragePair>&>(Data), key);
if (it == Data.end() || it->key != key)
return default_val;
return it->val_i;
}
bool ImGuiStorage::GetBool(ImGuiID key, bool default_val) const
{
return GetInt(key, default_val ? 1 : 0) != 0;
}
float ImGuiStorage::GetFloat(ImGuiID key, float default_val) const
{
ImGuiStoragePair* it = LowerBound(const_cast<ImVector<ImGuiStoragePair>&>(Data), key);
if (it == Data.end() || it->key != key)
return default_val;
return it->val_f;
}
void* ImGuiStorage::GetVoidPtr(ImGuiID key) const
{
ImGuiStoragePair* it = LowerBound(const_cast<ImVector<ImGuiStoragePair>&>(Data), key);
if (it == Data.end() || it->key != key)
return NULL;
return it->val_p;
}
// References are only valid until a new value is added to the storage. Calling a Set***() function or a Get***Ref() function invalidates the pointer.
int* ImGuiStorage::GetIntRef(ImGuiID key, int default_val)
{
ImGuiStoragePair* it = LowerBound(Data, key);
if (it == Data.end() || it->key != key)
it = Data.insert(it, ImGuiStoragePair(key, default_val));
return &it->val_i;
}
bool* ImGuiStorage::GetBoolRef(ImGuiID key, bool default_val)
{
return (bool*)GetIntRef(key, default_val ? 1 : 0);
}
float* ImGuiStorage::GetFloatRef(ImGuiID key, float default_val)
{
ImGuiStoragePair* it = LowerBound(Data, key);
if (it == Data.end() || it->key != key)
it = Data.insert(it, ImGuiStoragePair(key, default_val));
return &it->val_f;
}
void** ImGuiStorage::GetVoidPtrRef(ImGuiID key, void* default_val)
{
ImGuiStoragePair* it = LowerBound(Data, key);
if (it == Data.end() || it->key != key)
it = Data.insert(it, ImGuiStoragePair(key, default_val));
return &it->val_p;
}
// FIXME-OPT: Need a way to reuse the result of lower_bound when doing GetInt()/SetInt() - not too bad because it only happens on explicit interaction (maximum one a frame)
void ImGuiStorage::SetInt(ImGuiID key, int val)
{
ImGuiStoragePair* it = LowerBound(Data, key);
if (it == Data.end() || it->key != key)
{
Data.insert(it, ImGuiStoragePair(key, val));
return;
}
it->val_i = val;
}
void ImGuiStorage::SetBool(ImGuiID key, bool val)
{
SetInt(key, val ? 1 : 0);
}
void ImGuiStorage::SetFloat(ImGuiID key, float val)
{
ImGuiStoragePair* it = LowerBound(Data, key);
if (it == Data.end() || it->key != key)
{
Data.insert(it, ImGuiStoragePair(key, val));
return;
}
it->val_f = val;
}
void ImGuiStorage::SetVoidPtr(ImGuiID key, void* val)
{
ImGuiStoragePair* it = LowerBound(Data, key);
if (it == Data.end() || it->key != key)
{
Data.insert(it, ImGuiStoragePair(key, val));
return;
}
it->val_p = val;
}
void ImGuiStorage::SetAllInt(int v)
{
for (int i = 0; i < Data.Size; i++)
Data[i].val_i = v;
}
//-----------------------------------------------------------------------------
// [SECTION] ImGuiTextFilter
//-----------------------------------------------------------------------------
// Helper: Parse and apply text filters. In format "aaaaa[,bbbb][,ccccc]"
ImGuiTextFilter::ImGuiTextFilter(const char* default_filter)
{
if (default_filter)
{
ImStrncpy(InputBuf, default_filter, IM_ARRAYSIZE(InputBuf));
Build();
}
else
{
InputBuf[0] = 0;
CountGrep = 0;
}
}
bool ImGuiTextFilter::Draw(const char* label, float width)
{
if (width != 0.0f)
ImGui::SetNextItemWidth(width);
bool value_changed = ImGui::InputText(label, InputBuf, IM_ARRAYSIZE(InputBuf));
if (value_changed)
Build();
return value_changed;
}
void ImGuiTextFilter::ImGuiTextRange::split(char separator, ImVector<ImGuiTextRange>* out) const
{
out->resize(0);
const char* wb = b;
const char* we = wb;
while (we < e)
{
if (*we == separator)
{
out->push_back(ImGuiTextRange(wb, we));
wb = we + 1;
}
we++;
}
if (wb != we)
out->push_back(ImGuiTextRange(wb, we));
}
void ImGuiTextFilter::Build()
{
Filters.resize(0);
ImGuiTextRange input_range(InputBuf, InputBuf + strlen(InputBuf));
input_range.split(',', &Filters);
CountGrep = 0;
for (int i = 0; i != Filters.Size; i++)
{
ImGuiTextRange& f = Filters[i];
while (f.b < f.e && ImCharIsBlankA(f.b[0]))
f.b++;
while (f.e > f.b && ImCharIsBlankA(f.e[-1]))
f.e--;
if (f.empty())
continue;
if (Filters[i].b[0] != '-')
CountGrep += 1;
}
}
bool ImGuiTextFilter::PassFilter(const char* text, const char* text_end) const
{
if (Filters.empty())
return true;
if (text == NULL)
text = "";
for (int i = 0; i != Filters.Size; i++)
{
const ImGuiTextRange& f = Filters[i];
if (f.empty())
continue;
if (f.b[0] == '-')
{
// Subtract
if (ImStristr(text, text_end, f.b + 1, f.e) != NULL)
return false;
}
else
{
// Grep
if (ImStristr(text, text_end, f.b, f.e) != NULL)
return true;
}
}
// Implicit * grep
if (CountGrep == 0)
return true;
return false;
}
//-----------------------------------------------------------------------------
// [SECTION] ImGuiTextBuffer
//-----------------------------------------------------------------------------
// On some platform vsnprintf() takes va_list by reference and modifies it.
// va_copy is the 'correct' way to copy a va_list but Visual Studio prior to 2013 doesn't have it.
#ifndef va_copy
#if defined(__GNUC__) || defined(__clang__)
#define va_copy(dest, src) __builtin_va_copy(dest, src)
#else
#define va_copy(dest, src) (dest = src)
#endif
#endif
char ImGuiTextBuffer::EmptyString[1] = { 0 };
void ImGuiTextBuffer::append(const char* str, const char* str_end)
{
int len = str_end ? (int)(str_end - str) : (int)strlen(str);
// Add zero-terminator the first time
const int write_off = (Buf.Size != 0) ? Buf.Size : 1;
const int needed_sz = write_off + len;
if (write_off + len >= Buf.Capacity)
{
int new_capacity = Buf.Capacity * 2;
Buf.reserve(needed_sz > new_capacity ? needed_sz : new_capacity);
}
Buf.resize(needed_sz);
memcpy(&Buf[write_off - 1], str, (size_t)len);
Buf[write_off - 1 + len] = 0;
}
void ImGuiTextBuffer::appendf(const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
appendfv(fmt, args);
va_end(args);
}
// Helper: Text buffer for logging/accumulating text
void ImGuiTextBuffer::appendfv(const char* fmt, va_list args)
{
va_list args_copy;
va_copy(args_copy, args);
int len = ImFormatStringV(NULL, 0, fmt, args); // FIXME-OPT: could do a first pass write attempt, likely successful on first pass.
if (len <= 0)
{
va_end(args_copy);
return;
}
// Add zero-terminator the first time
const int write_off = (Buf.Size != 0) ? Buf.Size : 1;
const int needed_sz = write_off + len;
if (write_off + len >= Buf.Capacity)
{
int new_capacity = Buf.Capacity * 2;
Buf.reserve(needed_sz > new_capacity ? needed_sz : new_capacity);
}
Buf.resize(needed_sz);
ImFormatStringV(&Buf[write_off - 1], (size_t)len + 1, fmt, args_copy);
va_end(args_copy);
}
//-----------------------------------------------------------------------------
// [SECTION] ImGuiListClipper
// This is currently not as flexible/powerful as it should be and really confusing/spaghetti, mostly because we changed
// the API mid-way through development and support two ways to using the clipper, needs some rework (see TODO)
//-----------------------------------------------------------------------------
// Helper to calculate coarse clipping of large list of evenly sized items.
// NB: Prefer using the ImGuiListClipper higher-level helper if you can! Read comments and instructions there on how those use this sort of pattern.
// NB: 'items_count' is only used to clamp the result, if you don't know your count you can use INT_MAX
void ImGui::CalcListClipping(int items_count, float items_height, int* out_items_display_start, int* out_items_display_end)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (g.LogEnabled)
{
// If logging is active, do not perform any clipping
*out_items_display_start = 0;
*out_items_display_end = items_count;
return;
}
if (window->SkipItems)
{
*out_items_display_start = *out_items_display_end = 0;
return;
}
// We create the union of the ClipRect and the NavScoringRect which at worst should be 1 page away from ClipRect
ImRect unclipped_rect = window->ClipRect;
if (g.NavMoveRequest)
unclipped_rect.Add(g.NavScoringRect);
if (g.NavJustMovedToId && window->NavLastIds[0] == g.NavJustMovedToId)
unclipped_rect.Add(ImRect(window->Pos + window->NavRectRel[0].Min, window->Pos + window->NavRectRel[0].Max));
const ImVec2 pos = window->DC.CursorPos;
int start = (int)((unclipped_rect.Min.y - pos.y) / items_height);
int end = (int)((unclipped_rect.Max.y - pos.y) / items_height);
// When performing a navigation request, ensure we have one item extra in the direction we are moving to
if (g.NavMoveRequest && g.NavMoveClipDir == ImGuiDir_Up)
start--;
if (g.NavMoveRequest && g.NavMoveClipDir == ImGuiDir_Down)
end++;
start = ImClamp(start, 0, items_count);
end = ImClamp(end + 1, start, items_count);
*out_items_display_start = start;
*out_items_display_end = end;
}
static void SetCursorPosYAndSetupForPrevLine(float pos_y, float line_height)
{
// Set cursor position and a few other things so that SetScrollHereY() and Columns() can work when seeking cursor.
// FIXME: It is problematic that we have to do that here, because custom/equivalent end-user code would stumble on the same issue.
// The clipper should probably have a 4th step to display the last item in a regular manner.
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
window->DC.CursorPos.y = pos_y;
window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, pos_y);
window->DC.CursorPosPrevLine.y = window->DC.CursorPos.y - line_height; // Setting those fields so that SetScrollHereY() can properly function after the end of our clipper usage.
window->DC.PrevLineSize.y = (line_height - g.Style.ItemSpacing.y); // If we end up needing more accurate data (to e.g. use SameLine) we may as well make the clipper have a fourth step to let user process and display the last item in their list.
if (ImGuiColumns* columns = window->DC.CurrentColumns)
columns->LineMinY = window->DC.CursorPos.y; // Setting this so that cell Y position are set properly
}
// Use case A: Begin() called from constructor with items_height<0, then called again from Sync() in StepNo 1
// Use case B: Begin() called from constructor with items_height>0
// FIXME-LEGACY: Ideally we should remove the Begin/End functions but they are part of the legacy API we still support. This is why some of the code in Step() calling Begin() and reassign some fields, spaghetti style.
void ImGuiListClipper::Begin(int count, float items_height)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
StartPosY = window->DC.CursorPos.y;
ItemsHeight = items_height;
ItemsCount = count;
StepNo = 0;
DisplayEnd = DisplayStart = -1;
if (ItemsHeight > 0.0f)
{
ImGui::CalcListClipping(ItemsCount, ItemsHeight, &DisplayStart, &DisplayEnd); // calculate how many to clip/display
if (DisplayStart > 0)
SetCursorPosYAndSetupForPrevLine(StartPosY + DisplayStart * ItemsHeight, ItemsHeight); // advance cursor
StepNo = 2;
}
}
void ImGuiListClipper::End()
{
if (ItemsCount < 0)
return;
// In theory here we should assert that ImGui::GetCursorPosY() == StartPosY + DisplayEnd * ItemsHeight, but it feels saner to just seek at the end and not assert/crash the user.
if (ItemsCount < INT_MAX)
SetCursorPosYAndSetupForPrevLine(StartPosY + ItemsCount * ItemsHeight, ItemsHeight); // advance cursor
ItemsCount = -1;
StepNo = 3;
}
bool ImGuiListClipper::Step()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (ItemsCount == 0 || window->SkipItems)
{
ItemsCount = -1;
return false;
}
if (StepNo == 0) // Step 0: the clipper let you process the first element, regardless of it being visible or not, so we can measure the element height.
{
DisplayStart = 0;
DisplayEnd = 1;
StartPosY = window->DC.CursorPos.y;
StepNo = 1;
return true;
}
if (StepNo == 1) // Step 1: the clipper infer height from first element, calculate the actual range of elements to display, and position the cursor before the first element.
{
if (ItemsCount == 1) { ItemsCount = -1; return false; }
float items_height = window->DC.CursorPos.y - StartPosY;
IM_ASSERT(items_height > 0.0f); // If this triggers, it means Item 0 hasn't moved the cursor vertically
Begin(ItemsCount - 1, items_height);
DisplayStart++;
DisplayEnd++;
StepNo = 3;
return true;
}
if (StepNo == 2) // Step 2: empty step only required if an explicit items_height was passed to constructor or Begin() and user still call Step(). Does nothing and switch to Step 3.
{
IM_ASSERT(DisplayStart >= 0 && DisplayEnd >= 0);
StepNo = 3;
return true;
}
if (StepNo == 3) // Step 3: the clipper validate that we have reached the expected Y position (corresponding to element DisplayEnd), advance the cursor to the end of the list and then returns 'false' to end the loop.
End();
return false;
}
//-----------------------------------------------------------------------------
// [SECTION] STYLING
//-----------------------------------------------------------------------------
ImGuiStyle& ImGui::GetStyle()
{
IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
return GImGui->Style;
}
ImU32 ImGui::GetColorU32(ImGuiCol idx, float alpha_mul)
{
ImGuiStyle& style = GImGui->Style;
ImVec4 c = style.Colors[idx];
c.w *= style.Alpha * alpha_mul;
return ColorConvertFloat4ToU32(c);
}
ImU32 ImGui::GetColorU32(const ImVec4& col)
{
ImGuiStyle& style = GImGui->Style;
ImVec4 c = col;
c.w *= style.Alpha;
return ColorConvertFloat4ToU32(c);
}
const ImVec4& ImGui::GetStyleColorVec4(ImGuiCol idx)
{
ImGuiStyle& style = GImGui->Style;
return style.Colors[idx];
}
ImU32 ImGui::GetColorU32(ImU32 col)
{
ImGuiStyle& style = GImGui->Style;
if (style.Alpha >= 1.0f)
return col;
ImU32 a = (col & IM_COL32_A_MASK) >> IM_COL32_A_SHIFT;
a = (ImU32)(a * style.Alpha); // We don't need to clamp 0..255 because Style.Alpha is in 0..1 range.
return (col & ~IM_COL32_A_MASK) | (a << IM_COL32_A_SHIFT);
}
// FIXME: This may incur a round-trip (if the end user got their data from a float4) but eventually we aim to store the in-flight colors as ImU32
void ImGui::PushStyleColor(ImGuiCol idx, ImU32 col)
{
ImGuiContext& g = *GImGui;
ImGuiColorMod backup;
backup.Col = idx;
backup.BackupValue = g.Style.Colors[idx];
g.ColorModifiers.push_back(backup);
g.Style.Colors[idx] = ColorConvertU32ToFloat4(col);
}
void ImGui::PushStyleColor(ImGuiCol idx, const ImVec4& col)
{
ImGuiContext& g = *GImGui;
ImGuiColorMod backup;
backup.Col = idx;
backup.BackupValue = g.Style.Colors[idx];
g.ColorModifiers.push_back(backup);
g.Style.Colors[idx] = col;
}
void ImGui::PopStyleColor(int count)
{
ImGuiContext& g = *GImGui;
while (count > 0)
{
ImGuiColorMod& backup = g.ColorModifiers.back();
g.Style.Colors[backup.Col] = backup.BackupValue;
g.ColorModifiers.pop_back();
count--;
}
}
struct ImGuiStyleVarInfo
{
ImGuiDataType Type;
ImU32 Count;
ImU32 Offset;
void* GetVarPtr(ImGuiStyle* style) const { return (void*)((unsigned char*)style + Offset); }
};
static const ImGuiStyleVarInfo GStyleVarInfo[] =
{
{ ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, Alpha) }, // ImGuiStyleVar_Alpha
{ ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowPadding) }, // ImGuiStyleVar_WindowPadding
{ ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowRounding) }, // ImGuiStyleVar_WindowRounding
{ ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowBorderSize) }, // ImGuiStyleVar_WindowBorderSize
{ ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowMinSize) }, // ImGuiStyleVar_WindowMinSize
{ ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowTitleAlign) }, // ImGuiStyleVar_WindowTitleAlign
{ ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ChildRounding) }, // ImGuiStyleVar_ChildRounding
{ ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ChildBorderSize) }, // ImGuiStyleVar_ChildBorderSize
{ ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, PopupRounding) }, // ImGuiStyleVar_PopupRounding
{ ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, PopupBorderSize) }, // ImGuiStyleVar_PopupBorderSize
{ ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, FramePadding) }, // ImGuiStyleVar_FramePadding
{ ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, FrameRounding) }, // ImGuiStyleVar_FrameRounding
{ ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, FrameBorderSize) }, // ImGuiStyleVar_FrameBorderSize
{ ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, ItemSpacing) }, // ImGuiStyleVar_ItemSpacing
{ ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, ItemInnerSpacing) }, // ImGuiStyleVar_ItemInnerSpacing
{ ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, IndentSpacing) }, // ImGuiStyleVar_IndentSpacing
{ ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ScrollbarSize) }, // ImGuiStyleVar_ScrollbarSize
{ ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ScrollbarRounding) }, // ImGuiStyleVar_ScrollbarRounding
{ ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, GrabMinSize) }, // ImGuiStyleVar_GrabMinSize
{ ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, GrabRounding) }, // ImGuiStyleVar_GrabRounding
{ ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, TabRounding) }, // ImGuiStyleVar_TabRounding
{ ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, ButtonTextAlign) }, // ImGuiStyleVar_ButtonTextAlign
{ ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, SelectableTextAlign) }, // ImGuiStyleVar_SelectableTextAlign
};
static const ImGuiStyleVarInfo* GetStyleVarInfo(ImGuiStyleVar idx)
{
IM_ASSERT(idx >= 0 && idx < ImGuiStyleVar_COUNT);
IM_ASSERT(IM_ARRAYSIZE(GStyleVarInfo) == ImGuiStyleVar_COUNT);
return &GStyleVarInfo[idx];
}
void ImGui::PushStyleVar(ImGuiStyleVar idx, float val)
{
const ImGuiStyleVarInfo* var_info = GetStyleVarInfo(idx);
if (var_info->Type == ImGuiDataType_Float && var_info->Count == 1)
{
ImGuiContext& g = *GImGui;
float* pvar = (float*)var_info->GetVarPtr(&g.Style);
g.StyleModifiers.push_back(ImGuiStyleMod(idx, *pvar));
*pvar = val;
return;
}
IM_ASSERT(0 && "Called PushStyleVar() float variant but variable is not a float!");
}
void ImGui::PushStyleVar(ImGuiStyleVar idx, const ImVec2& val)
{
const ImGuiStyleVarInfo* var_info = GetStyleVarInfo(idx);
if (var_info->Type == ImGuiDataType_Float && var_info->Count == 2)
{
ImGuiContext& g = *GImGui;
ImVec2* pvar = (ImVec2*)var_info->GetVarPtr(&g.Style);
g.StyleModifiers.push_back(ImGuiStyleMod(idx, *pvar));
*pvar = val;
return;
}
IM_ASSERT(0 && "Called PushStyleVar() ImVec2 variant but variable is not a ImVec2!");
}
void ImGui::PopStyleVar(int count)
{
ImGuiContext& g = *GImGui;
while (count > 0)
{
// We avoid a generic memcpy(data, &backup.Backup.., GDataTypeSize[info->Type] * info->Count), the overhead in Debug is not worth it.
ImGuiStyleMod& backup = g.StyleModifiers.back();
const ImGuiStyleVarInfo* info = GetStyleVarInfo(backup.VarIdx);
void* data = info->GetVarPtr(&g.Style);
if (info->Type == ImGuiDataType_Float && info->Count == 1) { ((float*)data)[0] = backup.BackupFloat[0]; }
else if (info->Type == ImGuiDataType_Float && info->Count == 2) { ((float*)data)[0] = backup.BackupFloat[0]; ((float*)data)[1] = backup.BackupFloat[1]; }
g.StyleModifiers.pop_back();
count--;
}
}
const char* ImGui::GetStyleColorName(ImGuiCol idx)
{
// Create switch-case from enum with regexp: ImGuiCol_{.*}, --> case ImGuiCol_\1: return "\1";
switch (idx)
{
case ImGuiCol_Text: return "Text";
case ImGuiCol_TextDisabled: return "TextDisabled";
case ImGuiCol_WindowBg: return "WindowBg";
case ImGuiCol_ChildBg: return "ChildBg";
case ImGuiCol_PopupBg: return "PopupBg";
case ImGuiCol_Border: return "Border";
case ImGuiCol_BorderShadow: return "BorderShadow";
case ImGuiCol_FrameBg: return "FrameBg";
case ImGuiCol_FrameBgHovered: return "FrameBgHovered";
case ImGuiCol_FrameBgActive: return "FrameBgActive";
case ImGuiCol_TitleBg: return "TitleBg";
case ImGuiCol_TitleBgActive: return "TitleBgActive";
case ImGuiCol_TitleBgCollapsed: return "TitleBgCollapsed";
case ImGuiCol_MenuBarBg: return "MenuBarBg";
case ImGuiCol_ScrollbarBg: return "ScrollbarBg";
case ImGuiCol_ScrollbarGrab: return "ScrollbarGrab";
case ImGuiCol_ScrollbarGrabHovered: return "ScrollbarGrabHovered";
case ImGuiCol_ScrollbarGrabActive: return "ScrollbarGrabActive";
case ImGuiCol_CheckMark: return "CheckMark";
case ImGuiCol_SliderGrab: return "SliderGrab";
case ImGuiCol_SliderGrabActive: return "SliderGrabActive";
case ImGuiCol_Button: return "Button";
case ImGuiCol_ButtonHovered: return "ButtonHovered";
case ImGuiCol_ButtonActive: return "ButtonActive";
case ImGuiCol_Header: return "Header";
case ImGuiCol_HeaderHovered: return "HeaderHovered";
case ImGuiCol_HeaderActive: return "HeaderActive";
case ImGuiCol_Separator: return "Separator";
case ImGuiCol_SeparatorHovered: return "SeparatorHovered";
case ImGuiCol_SeparatorActive: return "SeparatorActive";
case ImGuiCol_ResizeGrip: return "ResizeGrip";
case ImGuiCol_ResizeGripHovered: return "ResizeGripHovered";
case ImGuiCol_ResizeGripActive: return "ResizeGripActive";
case ImGuiCol_Tab: return "Tab";
case ImGuiCol_TabHovered: return "TabHovered";
case ImGuiCol_TabActive: return "TabActive";
case ImGuiCol_TabUnfocused: return "TabUnfocused";
case ImGuiCol_TabUnfocusedActive: return "TabUnfocusedActive";
case ImGuiCol_PlotLines: return "PlotLines";
case ImGuiCol_PlotLinesHovered: return "PlotLinesHovered";
case ImGuiCol_PlotHistogram: return "PlotHistogram";
case ImGuiCol_PlotHistogramHovered: return "PlotHistogramHovered";
case ImGuiCol_TextSelectedBg: return "TextSelectedBg";
case ImGuiCol_DragDropTarget: return "DragDropTarget";
case ImGuiCol_NavHighlight: return "NavHighlight";
case ImGuiCol_NavWindowingHighlight: return "NavWindowingHighlight";
case ImGuiCol_NavWindowingDimBg: return "NavWindowingDimBg";
case ImGuiCol_ModalWindowDimBg: return "ModalWindowDimBg";
}
IM_ASSERT(0);
return "Unknown";
}
//-----------------------------------------------------------------------------
// [SECTION] RENDER HELPERS
// Some of those (internal) functions are currently quite a legacy mess - their signature and behavior will change,
// we need a nicer separation between low-level functions and high-level functions relying on the ImGui context.
// Also see imgui_draw.cpp for some more which have been reworked to not rely on ImGui:: context.
//-----------------------------------------------------------------------------
const char* ImGui::FindRenderedTextEnd(const char* text, const char* text_end)
{
const char* text_display_end = text;
if (!text_end)
text_end = (const char*)-1;
while (text_display_end < text_end && *text_display_end != '\0' && (text_display_end[0] != '#' || text_display_end[1] != '#'))
text_display_end++;
return text_display_end;
}
// Internal ImGui functions to render text
// RenderText***() functions calls ImDrawList::AddText() calls ImBitmapFont::RenderText()
void ImGui::RenderText(ImVec2 pos, const char* text, const char* text_end, bool hide_text_after_hash)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
// Hide anything after a '##' string
const char* text_display_end;
if (hide_text_after_hash)
{
text_display_end = FindRenderedTextEnd(text, text_end);
}
else
{
if (!text_end)
text_end = text + strlen(text); // FIXME-OPT
text_display_end = text_end;
}
if (text != text_display_end)
{
window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_display_end);
if (g.LogEnabled)
LogRenderedText(&pos, text, text_display_end);
}
}
void ImGui::RenderTextWrapped(ImVec2 pos, const char* text, const char* text_end, float wrap_width)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (!text_end)
text_end = text + strlen(text); // FIXME-OPT
if (text != text_end)
{
window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_end, wrap_width);
if (g.LogEnabled)
LogRenderedText(&pos, text, text_end);
}
}
// Default clip_rect uses (pos_min,pos_max)
// Handle clipping on CPU immediately (vs typically let the GPU clip the triangles that are overlapping the clipping rectangle edges)
void ImGui::RenderTextClippedEx(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_display_end, const ImVec2* text_size_if_known, const ImVec2& align, const ImRect* clip_rect)
{
// Perform CPU side clipping for single clipped element to avoid using scissor state
ImVec2 pos = pos_min;
const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_display_end, false, 0.0f);
const ImVec2* clip_min = clip_rect ? &clip_rect->Min : &pos_min;
const ImVec2* clip_max = clip_rect ? &clip_rect->Max : &pos_max;
bool need_clipping = (pos.x + text_size.x >= clip_max->x) || (pos.y + text_size.y >= clip_max->y);
if (clip_rect) // If we had no explicit clipping rectangle then pos==clip_min
need_clipping |= (pos.x < clip_min->x) || (pos.y < clip_min->y);
// Align whole block. We should defer that to the better rendering function when we'll have support for individual line alignment.
if (align.x > 0.0f) pos.x = ImMax(pos.x, pos.x + (pos_max.x - pos.x - text_size.x) * align.x);
if (align.y > 0.0f) pos.y = ImMax(pos.y, pos.y + (pos_max.y - pos.y - text_size.y) * align.y);
// Render
if (need_clipping)
{
ImVec4 fine_clip_rect(clip_min->x, clip_min->y, clip_max->x, clip_max->y);
draw_list->AddText(NULL, 0.0f, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, &fine_clip_rect);
}
else
{
draw_list->AddText(NULL, 0.0f, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, NULL);
}
}
void ImGui::RenderTextClipped(const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_end, const ImVec2* text_size_if_known, const ImVec2& align, const ImRect* clip_rect)
{
// Hide anything after a '##' string
const char* text_display_end = FindRenderedTextEnd(text, text_end);
const int text_len = (int)(text_display_end - text);
if (text_len == 0)
return;
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
RenderTextClippedEx(window->DrawList, pos_min, pos_max, text, text_display_end, text_size_if_known, align, clip_rect);
if (g.LogEnabled)
LogRenderedText(&pos_min, text, text_display_end);
}
// Another overly complex function until we reorganize everything into a nice all-in-one helper.
// This is made more complex because we have dissociated the layout rectangle (pos_min..pos_max) which define _where_ the ellipsis is, from actual clipping of text and limit of the ellipsis display.
// This is because in the context of tabs we selectively hide part of the text when the Close Button appears, but we don't want the ellipsis to move.
void ImGui::RenderTextEllipsis(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, float clip_max_x, float ellipsis_max_x, const char* text, const char* text_end_full, const ImVec2* text_size_if_known)
{
ImGuiContext& g = *GImGui;
if (text_end_full == NULL)
text_end_full = FindRenderedTextEnd(text);
const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_end_full, false, 0.0f);
//draw_list->AddLine(ImVec2(pos_max.x, pos_min.y - 4), ImVec2(pos_max.x, pos_max.y + 4), IM_COL32(0, 0, 255, 255));
//draw_list->AddLine(ImVec2(ellipsis_max_x, pos_min.y-2), ImVec2(ellipsis_max_x, pos_max.y+2), IM_COL32(0, 255, 0, 255));
//draw_list->AddLine(ImVec2(clip_max_x, pos_min.y), ImVec2(clip_max_x, pos_max.y), IM_COL32(255, 0, 0, 255));
// FIXME: We could technically remove (last_glyph->AdvanceX - last_glyph->X1) from text_size.x here and save a few pixels.
if (text_size.x > pos_max.x - pos_min.x)
{
// Hello wo...
// | | |
// min max ellipsis_max
// <-> this is generally some padding value
const ImFont* font = draw_list->_Data->Font;
const float font_size = draw_list->_Data->FontSize;
const char* text_end_ellipsis = NULL;
ImWchar ellipsis_char = font->EllipsisChar;
int ellipsis_char_count = 1;
if (ellipsis_char == (ImWchar)-1)
{
ellipsis_char = (ImWchar)'.';
ellipsis_char_count = 3;
}
const ImFontGlyph* glyph = font->FindGlyph(ellipsis_char);
float ellipsis_glyph_width = glyph->X1; // Width of the glyph with no padding on either side
float ellipsis_total_width = ellipsis_glyph_width; // Full width of entire ellipsis
if (ellipsis_char_count > 1)
{
// Full ellipsis size without free spacing after it.
const float spacing_between_dots = 1.0f * (draw_list->_Data->FontSize / font->FontSize);
ellipsis_glyph_width = glyph->X1 - glyph->X0 + spacing_between_dots;
ellipsis_total_width = ellipsis_glyph_width * (float)ellipsis_char_count - spacing_between_dots;
}
// We can now claim the space between pos_max.x and ellipsis_max.x
const float text_avail_width = ImMax((ImMax(pos_max.x, ellipsis_max_x) - ellipsis_total_width) - pos_min.x, 1.0f);
float text_size_clipped_x = font->CalcTextSizeA(font_size, text_avail_width, 0.0f, text, text_end_full, &text_end_ellipsis).x;
if (text == text_end_ellipsis && text_end_ellipsis < text_end_full)
{
// Always display at least 1 character if there's no room for character + ellipsis
text_end_ellipsis = text + ImTextCountUtf8BytesFromChar(text, text_end_full);
text_size_clipped_x = font->CalcTextSizeA(font_size, FLT_MAX, 0.0f, text, text_end_ellipsis).x;
}
while (text_end_ellipsis > text && ImCharIsBlankA(text_end_ellipsis[-1]))
{
// Trim trailing space before ellipsis (FIXME: Supporting non-ascii blanks would be nice, for this we need a function to backtrack in UTF-8 text)
text_end_ellipsis--;
text_size_clipped_x -= font->CalcTextSizeA(font_size, FLT_MAX, 0.0f, text_end_ellipsis, text_end_ellipsis + 1).x; // Ascii blanks are always 1 byte
}
// Render text, render ellipsis
RenderTextClippedEx(draw_list, pos_min, ImVec2(clip_max_x, pos_max.y), text, text_end_ellipsis, &text_size, ImVec2(0.0f, 0.0f));
float ellipsis_x = pos_min.x + text_size_clipped_x;
if (ellipsis_x + ellipsis_total_width <= ellipsis_max_x)
for (int i = 0; i < ellipsis_char_count; i++)
{
font->RenderChar(draw_list, font_size, ImVec2(ellipsis_x, pos_min.y), GetColorU32(ImGuiCol_Text), ellipsis_char);
ellipsis_x += ellipsis_glyph_width;
}
}
else
{
RenderTextClippedEx(draw_list, pos_min, ImVec2(clip_max_x, pos_max.y), text, text_end_full, &text_size, ImVec2(0.0f, 0.0f));
}
if (g.LogEnabled)
LogRenderedText(&pos_min, text, text_end_full);
}
// Render a rectangle shaped with optional rounding and borders
void ImGui::RenderFrame(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, bool border, float rounding)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
window->DrawList->AddRectFilled(p_min, p_max, fill_col, rounding);
const float border_size = g.Style.FrameBorderSize;
if (border && border_size > 0.0f)
{
window->DrawList->AddRect(p_min + ImVec2(1, 1), p_max + ImVec2(1, 1), GetColorU32(ImGuiCol_BorderShadow), rounding, ImDrawCornerFlags_All, border_size);
window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding, ImDrawCornerFlags_All, border_size);
}
}
void ImGui::RenderFrameBorder(ImVec2 p_min, ImVec2 p_max, float rounding)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
const float border_size = g.Style.FrameBorderSize;
if (border_size > 0.0f)
{
window->DrawList->AddRect(p_min + ImVec2(1, 1), p_max + ImVec2(1, 1), GetColorU32(ImGuiCol_BorderShadow), rounding, ImDrawCornerFlags_All, border_size);
window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding, ImDrawCornerFlags_All, border_size);
}
}
void ImGui::RenderNavHighlight(const ImRect& bb, ImGuiID id, ImGuiNavHighlightFlags flags)
{
ImGuiContext& g = *GImGui;
if (id != g.NavId)
return;
if (g.NavDisableHighlight && !(flags & ImGuiNavHighlightFlags_AlwaysDraw))
return;
ImGuiWindow* window = g.CurrentWindow;
if (window->DC.NavHideHighlightOneFrame)
return;
float rounding = (flags & ImGuiNavHighlightFlags_NoRounding) ? 0.0f : g.Style.FrameRounding;
ImRect display_rect = bb;
display_rect.ClipWith(window->ClipRect);
if (flags & ImGuiNavHighlightFlags_TypeDefault)
{
const float THICKNESS = 2.0f;
const float DISTANCE = 3.0f + THICKNESS * 0.5f;
display_rect.Expand(ImVec2(DISTANCE, DISTANCE));
bool fully_visible = window->ClipRect.Contains(display_rect);
if (!fully_visible)
window->DrawList->PushClipRect(display_rect.Min, display_rect.Max);
window->DrawList->AddRect(display_rect.Min + ImVec2(THICKNESS * 0.5f, THICKNESS * 0.5f), display_rect.Max - ImVec2(THICKNESS * 0.5f, THICKNESS * 0.5f), GetColorU32(ImGuiCol_NavHighlight), rounding, ImDrawCornerFlags_All, THICKNESS);
if (!fully_visible)
window->DrawList->PopClipRect();
}
if (flags & ImGuiNavHighlightFlags_TypeThin)
{
window->DrawList->AddRect(display_rect.Min, display_rect.Max, GetColorU32(ImGuiCol_NavHighlight), rounding, ~0, 1.0f);
}
}
//-----------------------------------------------------------------------------
// [SECTION] MAIN CODE (most of the code! lots of stuff, needs tidying up!)
//-----------------------------------------------------------------------------
// ImGuiWindow is mostly a dumb struct. It merely has a constructor and a few helper methods
ImGuiWindow::ImGuiWindow(ImGuiContext* context, const char* name)
: DrawListInst(&context->DrawListSharedData)
{
Name = ImStrdup(name);
ID = ImHashStr(name);
IDStack.push_back(ID);
Flags = ImGuiWindowFlags_None;
Pos = ImVec2(0.0f, 0.0f);
Size = SizeFull = ImVec2(0.0f, 0.0f);
ContentSize = ContentSizeExplicit = ImVec2(0.0f, 0.0f);
WindowPadding = ImVec2(0.0f, 0.0f);
WindowRounding = 0.0f;
WindowBorderSize = 0.0f;
NameBufLen = (int)strlen(name) + 1;
MoveId = GetID("#MOVE");
ChildId = 0;
Scroll = ImVec2(0.0f, 0.0f);
ScrollTarget = ImVec2(FLT_MAX, FLT_MAX);
ScrollTargetCenterRatio = ImVec2(0.5f, 0.5f);
ScrollbarSizes = ImVec2(0.0f, 0.0f);
ScrollbarX = ScrollbarY = false;
Active = WasActive = false;
WriteAccessed = false;
Collapsed = false;
WantCollapseToggle = false;
SkipItems = false;
Appearing = false;
Hidden = false;
IsFallbackWindow = false;
HasCloseButton = false;
ResizeBorderHeld = -1;
BeginCount = 0;
BeginOrderWithinParent = -1;
BeginOrderWithinContext = -1;
PopupId = 0;
AutoFitFramesX = AutoFitFramesY = -1;
AutoFitChildAxises = 0x00;
AutoFitOnlyGrows = false;
AutoPosLastDirection = ImGuiDir_None;
HiddenFramesCanSkipItems = HiddenFramesCannotSkipItems = 0;
SetWindowPosAllowFlags = SetWindowSizeAllowFlags = SetWindowCollapsedAllowFlags = ImGuiCond_Always | ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing;
SetWindowPosVal = SetWindowPosPivot = ImVec2(FLT_MAX, FLT_MAX);
InnerRect = ImRect(0.0f, 0.0f, 0.0f, 0.0f); // Clear so the InnerRect.GetSize() code in Begin() doesn't lead to overflow even if the result isn't used.
LastFrameActive = -1;
LastTimeActive = -1.0f;
ItemWidthDefault = 0.0f;
FontWindowScale = 1.0f;
SettingsOffset = -1;
DrawList = &DrawListInst;
DrawList->_OwnerName = Name;
ParentWindow = NULL;
RootWindow = NULL;
RootWindowForTitleBarHighlight = NULL;
RootWindowForNav = NULL;
NavLastIds[0] = NavLastIds[1] = 0;
NavRectRel[0] = NavRectRel[1] = ImRect();
NavLastChildNavWindow = NULL;
MemoryCompacted = false;
MemoryDrawListIdxCapacity = MemoryDrawListVtxCapacity = 0;
}
ImGuiWindow::~ImGuiWindow()
{
IM_ASSERT(DrawList == &DrawListInst);
IM_DELETE(Name);
for (int i = 0; i != ColumnsStorage.Size; i++)
ColumnsStorage[i].~ImGuiColumns();
}
ImGuiID ImGuiWindow::GetID(const char* str, const char* str_end)
{
ImGuiID seed = IDStack.back();
ImGuiID id = ImHashStr(str, str_end ? (str_end - str) : 0, seed);
ImGui::KeepAliveID(id);
#ifdef IMGUI_ENABLE_TEST_ENGINE
ImGuiContext& g = *GImGui;
IMGUI_TEST_ENGINE_ID_INFO2(id, ImGuiDataType_String, str, str_end);
#endif
return id;
}
ImGuiID ImGuiWindow::GetID(const void* ptr)
{
ImGuiID seed = IDStack.back();
ImGuiID id = ImHashData(&ptr, sizeof(void*), seed);
ImGui::KeepAliveID(id);
#ifdef IMGUI_ENABLE_TEST_ENGINE
ImGuiContext& g = *GImGui;
IMGUI_TEST_ENGINE_ID_INFO(id, ImGuiDataType_Pointer, ptr);
#endif
return id;
}
ImGuiID ImGuiWindow::GetID(int n)
{
ImGuiID seed = IDStack.back();
ImGuiID id = ImHashData(&n, sizeof(n), seed);
ImGui::KeepAliveID(id);
#ifdef IMGUI_ENABLE_TEST_ENGINE
ImGuiContext& g = *GImGui;
IMGUI_TEST_ENGINE_ID_INFO(id, ImGuiDataType_S32, (intptr_t)n);
#endif
return id;
}
ImGuiID ImGuiWindow::GetIDNoKeepAlive(const char* str, const char* str_end)
{
ImGuiID seed = IDStack.back();
ImGuiID id = ImHashStr(str, str_end ? (str_end - str) : 0, seed);
#ifdef IMGUI_ENABLE_TEST_ENGINE
ImGuiContext& g = *GImGui;
IMGUI_TEST_ENGINE_ID_INFO2(id, ImGuiDataType_String, str, str_end);
#endif
return id;
}
ImGuiID ImGuiWindow::GetIDNoKeepAlive(const void* ptr)
{
ImGuiID seed = IDStack.back();
ImGuiID id = ImHashData(&ptr, sizeof(void*), seed);
#ifdef IMGUI_ENABLE_TEST_ENGINE
ImGuiContext& g = *GImGui;
IMGUI_TEST_ENGINE_ID_INFO(id, ImGuiDataType_Pointer, ptr);
#endif
return id;
}
ImGuiID ImGuiWindow::GetIDNoKeepAlive(int n)
{
ImGuiID seed = IDStack.back();
ImGuiID id = ImHashData(&n, sizeof(n), seed);
#ifdef IMGUI_ENABLE_TEST_ENGINE
ImGuiContext& g = *GImGui;
IMGUI_TEST_ENGINE_ID_INFO(id, ImGuiDataType_S32, (intptr_t)n);
#endif
return id;
}
// This is only used in rare/specific situations to manufacture an ID out of nowhere.
ImGuiID ImGuiWindow::GetIDFromRectangle(const ImRect& r_abs)
{
ImGuiID seed = IDStack.back();
const int r_rel[4] = { (int)(r_abs.Min.x - Pos.x), (int)(r_abs.Min.y - Pos.y), (int)(r_abs.Max.x - Pos.x), (int)(r_abs.Max.y - Pos.y) };
ImGuiID id = ImHashData(&r_rel, sizeof(r_rel), seed);
ImGui::KeepAliveID(id);
return id;
}
static void SetCurrentWindow(ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
g.CurrentWindow = window;
if (window)
g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize();
}
// Free up/compact internal window buffers, we can use this when a window becomes unused.
// This is currently unused by the library, but you may call this yourself for easy GC.
// Not freed:
// - ImGuiWindow, ImGuiWindowSettings, Name
// - StateStorage, ColumnsStorage (may hold useful data)
// This should have no noticeable visual effect. When the window reappear however, expect new allocation/buffer growth/copy cost.
void ImGui::GcCompactTransientWindowBuffers(ImGuiWindow* window)
{
window->MemoryCompacted = true;
window->MemoryDrawListIdxCapacity = window->DrawList->IdxBuffer.Capacity;
window->MemoryDrawListVtxCapacity = window->DrawList->VtxBuffer.Capacity;
window->IDStack.clear();
window->DrawList->_ClearFreeMemory();
window->DC.ChildWindows.clear();
window->DC.ItemFlagsStack.clear();
window->DC.ItemWidthStack.clear();
window->DC.TextWrapPosStack.clear();
window->DC.GroupStack.clear();
}
void ImGui::GcAwakeTransientWindowBuffers(ImGuiWindow* window)
{
// We stored capacity of the ImDrawList buffer to reduce growth-caused allocation/copy when awakening.
// The other buffers tends to amortize much faster.
window->MemoryCompacted = false;
window->DrawList->IdxBuffer.reserve(window->MemoryDrawListIdxCapacity);
window->DrawList->VtxBuffer.reserve(window->MemoryDrawListVtxCapacity);
window->MemoryDrawListIdxCapacity = window->MemoryDrawListVtxCapacity = 0;
}
void ImGui::SetActiveID(ImGuiID id, ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
g.ActiveIdIsJustActivated = (g.ActiveId != id);
if (g.ActiveIdIsJustActivated)
{
g.ActiveIdTimer = 0.0f;
g.ActiveIdHasBeenPressedBefore = false;
g.ActiveIdHasBeenEditedBefore = false;
if (id != 0)
{
g.LastActiveId = id;
g.LastActiveIdTimer = 0.0f;
}
}
g.ActiveId = id;
g.ActiveIdAllowOverlap = false;
g.ActiveIdNoClearOnFocusLoss = false;
g.ActiveIdWindow = window;
g.ActiveIdHasBeenEditedThisFrame = false;
if (id)
{
g.ActiveIdIsAlive = id;
g.ActiveIdSource = (g.NavActivateId == id || g.NavInputId == id || g.NavJustTabbedId == id || g.NavJustMovedToId == id) ? ImGuiInputSource_Nav : ImGuiInputSource_Mouse;
}
// Clear declaration of inputs claimed by the widget
// (Please note that this is WIP and not all keys/inputs are thoroughly declared by all widgets yet)
g.ActiveIdUsingNavDirMask = 0x00;
g.ActiveIdUsingNavInputMask = 0x00;
g.ActiveIdUsingKeyInputMask = 0x00;
}
void ImGui::ClearActiveID()
{
SetActiveID(0, NULL); // g.ActiveId = 0;
}
void ImGui::SetHoveredID(ImGuiID id)
{
ImGuiContext& g = *GImGui;
g.HoveredId = id;
g.HoveredIdAllowOverlap = false;
if (id != 0 && g.HoveredIdPreviousFrame != id)
g.HoveredIdTimer = g.HoveredIdNotActiveTimer = 0.0f;
}
ImGuiID ImGui::GetHoveredID()
{
ImGuiContext& g = *GImGui;
return g.HoveredId ? g.HoveredId : g.HoveredIdPreviousFrame;
}
void ImGui::KeepAliveID(ImGuiID id)
{
ImGuiContext& g = *GImGui;
if (g.ActiveId == id)
g.ActiveIdIsAlive = id;
if (g.ActiveIdPreviousFrame == id)
g.ActiveIdPreviousFrameIsAlive = true;
}
void ImGui::MarkItemEdited(ImGuiID id)
{
// This marking is solely to be able to provide info for IsItemDeactivatedAfterEdit().
// ActiveId might have been released by the time we call this (as in the typical press/release button behavior) but still need need to fill the data.
ImGuiContext& g = *GImGui;
IM_ASSERT(g.ActiveId == id || g.ActiveId == 0 || g.DragDropActive);
IM_UNUSED(id); // Avoid unused variable warnings when asserts are compiled out.
//IM_ASSERT(g.CurrentWindow->DC.LastItemId == id);
g.ActiveIdHasBeenEditedThisFrame = true;
g.ActiveIdHasBeenEditedBefore = true;
g.CurrentWindow->DC.LastItemStatusFlags |= ImGuiItemStatusFlags_Edited;
}
static inline bool IsWindowContentHoverable(ImGuiWindow* window, ImGuiHoveredFlags flags)
{
// An active popup disable hovering on other windows (apart from its own children)
// FIXME-OPT: This could be cached/stored within the window.
ImGuiContext& g = *GImGui;
if (g.NavWindow)
if (ImGuiWindow* focused_root_window = g.NavWindow->RootWindow)
if (focused_root_window->WasActive && focused_root_window != window->RootWindow)
{
// For the purpose of those flags we differentiate "standard popup" from "modal popup"
// NB: The order of those two tests is important because Modal windows are also Popups.
if (focused_root_window->Flags & ImGuiWindowFlags_Modal)
return false;
if ((focused_root_window->Flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiHoveredFlags_AllowWhenBlockedByPopup))
return false;
}
return true;
}
// This is roughly matching the behavior of internal-facing ItemHoverable()
// - we allow hovering to be true when ActiveId==window->MoveID, so that clicking on non-interactive items such as a Text() item still returns true with IsItemHovered()
// - this should work even for non-interactive items that have no ID, so we cannot use LastItemId
bool ImGui::IsItemHovered(ImGuiHoveredFlags flags)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (g.NavDisableMouseHover && !g.NavDisableHighlight)
return IsItemFocused();
// Test for bounding box overlap, as updated as ItemAdd()
if (!(window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_HoveredRect))
return false;
IM_ASSERT((flags & (ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows)) == 0); // Flags not supported by this function
// Test if we are hovering the right window (our window could be behind another window)
// [2017/10/16] Reverted commit 344d48be3 and testing RootWindow instead. I believe it is correct to NOT test for RootWindow but this leaves us unable to use IsItemHovered() after EndChild() itself.
// Until a solution is found I believe reverting to the test from 2017/09/27 is safe since this was the test that has been running for a long while.
//if (g.HoveredWindow != window)
// return false;
if (g.HoveredRootWindow != window->RootWindow && !(flags & ImGuiHoveredFlags_AllowWhenOverlapped))
return false;
// Test if another item is active (e.g. being dragged)
if (!(flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem))
if (g.ActiveId != 0 && g.ActiveId != window->DC.LastItemId && !g.ActiveIdAllowOverlap && g.ActiveId != window->MoveId)
return false;
// Test if interactions on this window are blocked by an active popup or modal.
// The ImGuiHoveredFlags_AllowWhenBlockedByPopup flag will be tested here.
if (!IsWindowContentHoverable(window, flags))
return false;
// Test if the item is disabled
if ((window->DC.ItemFlags & ImGuiItemFlags_Disabled) && !(flags & ImGuiHoveredFlags_AllowWhenDisabled))
return false;
// Special handling for calling after Begin() which represent the title bar or tab.
// When the window is collapsed (SkipItems==true) that last item will never be overwritten so we need to detect the case.
if (window->DC.LastItemId == window->MoveId && window->WriteAccessed)
return false;
return true;
}
// Internal facing ItemHoverable() used when submitting widgets. Differs slightly from IsItemHovered().
bool ImGui::ItemHoverable(const ImRect& bb, ImGuiID id)
{
ImGuiContext& g = *GImGui;
if (g.HoveredId != 0 && g.HoveredId != id && !g.HoveredIdAllowOverlap)
return false;
ImGuiWindow* window = g.CurrentWindow;
if (g.HoveredWindow != window)
return false;
if (g.ActiveId != 0 && g.ActiveId != id && !g.ActiveIdAllowOverlap)
return false;
if (!IsMouseHoveringRect(bb.Min, bb.Max))
return false;
if (g.NavDisableMouseHover)
return false;
if (!IsWindowContentHoverable(window, ImGuiHoveredFlags_None) || (window->DC.ItemFlags & ImGuiItemFlags_Disabled))
{
g.HoveredIdDisabled = true;
return false;
}
// We exceptionally allow this function to be called with id==0 to allow using it for easy high-level
// hover test in widgets code. We could also decide to split this function is two.
if (id != 0)
{
SetHoveredID(id);
// [DEBUG] Item Picker tool!
// We perform the check here because SetHoveredID() is not frequently called (1~ time a frame), making
// the cost of this tool near-zero. We can get slightly better call-stack and support picking non-hovered
// items if we perform the test in ItemAdd(), but that would incur a small runtime cost.
// #define IMGUI_DEBUG_TOOL_ITEM_PICKER_EX in imconfig.h if you want this check to also be performed in ItemAdd().
if (g.DebugItemPickerActive && g.HoveredIdPreviousFrame == id)
GetForegroundDrawList()->AddRect(bb.Min, bb.Max, IM_COL32(255, 255, 0, 255));
if (g.DebugItemPickerBreakId == id)
IM_DEBUG_BREAK();
}
return true;
}
bool ImGui::IsClippedEx(const ImRect& bb, ImGuiID id, bool clip_even_when_logged)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (!bb.Overlaps(window->ClipRect))
if (id == 0 || (id != g.ActiveId && id != g.NavId))
if (clip_even_when_logged || !g.LogEnabled)
return true;
return false;
}
// This is also inlined in ItemAdd()
// Note: if ImGuiItemStatusFlags_HasDisplayRect is set, user needs to set window->DC.LastItemDisplayRect!
void ImGui::SetLastItemData(ImGuiWindow* window, ImGuiID item_id, ImGuiItemStatusFlags item_flags, const ImRect& item_rect)
{
window->DC.LastItemId = item_id;
window->DC.LastItemStatusFlags = item_flags;
window->DC.LastItemRect = item_rect;
}
// Process TAB/Shift+TAB. Be mindful that this function may _clear_ the ActiveID when tabbing out.
bool ImGui::FocusableItemRegister(ImGuiWindow* window, ImGuiID id)
{
ImGuiContext& g = *GImGui;
// Increment counters
const bool is_tab_stop = (window->DC.ItemFlags & (ImGuiItemFlags_NoTabStop | ImGuiItemFlags_Disabled)) == 0;
window->DC.FocusCounterRegular++;
if (is_tab_stop)
window->DC.FocusCounterTabStop++;
// Process TAB/Shift-TAB to tab *OUT* of the currently focused item.
// (Note that we can always TAB out of a widget that doesn't allow tabbing in)
if (g.ActiveId == id && g.FocusTabPressed && !IsActiveIdUsingKey(ImGuiKey_Tab) && g.FocusRequestNextWindow == NULL)
{
g.FocusRequestNextWindow = window;
g.FocusRequestNextCounterTabStop = window->DC.FocusCounterTabStop + (g.IO.KeyShift ? (is_tab_stop ? -1 : 0) : +1); // Modulo on index will be applied at the end of frame once we've got the total counter of items.
}
// Handle focus requests
if (g.FocusRequestCurrWindow == window)
{
if (window->DC.FocusCounterRegular == g.FocusRequestCurrCounterRegular)
return true;
if (is_tab_stop && window->DC.FocusCounterTabStop == g.FocusRequestCurrCounterTabStop)
{
g.NavJustTabbedId = id;
return true;
}
// If another item is about to be focused, we clear our own active id
if (g.ActiveId == id)
ClearActiveID();
}
return false;
}
void ImGui::FocusableItemUnregister(ImGuiWindow* window)
{
window->DC.FocusCounterRegular--;
window->DC.FocusCounterTabStop--;
}
float ImGui::CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x)
{
if (wrap_pos_x < 0.0f)
return 0.0f;
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (wrap_pos_x == 0.0f)
{
// We could decide to setup a default wrapping max point for auto-resizing windows,
// or have auto-wrap (with unspecified wrapping pos) behave as a ContentSize extending function?
//if (window->Hidden && (window->Flags & ImGuiWindowFlags_AlwaysAutoResize))
// wrap_pos_x = ImMax(window->WorkRect.Min.x + g.FontSize * 10.0f, window->WorkRect.Max.x);
//else
wrap_pos_x = window->WorkRect.Max.x;
}
else if (wrap_pos_x > 0.0f)
{
wrap_pos_x += window->Pos.x - window->Scroll.x; // wrap_pos_x is provided is window local space
}
return ImMax(wrap_pos_x - pos.x, 1.0f);
}
// IM_ALLOC() == ImGui::MemAlloc()
void* ImGui::MemAlloc(size_t size)
{
if (ImGuiContext* ctx = GImGui)
ctx->IO.MetricsActiveAllocations++;
return GImAllocatorAllocFunc(size, GImAllocatorUserData);
}
// IM_FREE() == ImGui::MemFree()
void ImGui::MemFree(void* ptr)
{
if (ptr)
if (ImGuiContext* ctx = GImGui)
ctx->IO.MetricsActiveAllocations--;
return GImAllocatorFreeFunc(ptr, GImAllocatorUserData);
}
const char* ImGui::GetClipboardText()
{
ImGuiContext& g = *GImGui;
return g.IO.GetClipboardTextFn ? g.IO.GetClipboardTextFn(g.IO.ClipboardUserData) : "";
}
void ImGui::SetClipboardText(const char* text)
{
ImGuiContext& g = *GImGui;
if (g.IO.SetClipboardTextFn)
g.IO.SetClipboardTextFn(g.IO.ClipboardUserData, text);
}
const char* ImGui::GetVersion()
{
return IMGUI_VERSION;
}
// Internal state access - if you want to share Dear ImGui state between modules (e.g. DLL) or allocate it yourself
// Note that we still point to some static data and members (such as GFontAtlas), so the state instance you end up using will point to the static data within its module
ImGuiContext* ImGui::GetCurrentContext()
{
return GImGui;
}
void ImGui::SetCurrentContext(ImGuiContext* ctx)
{
#ifdef IMGUI_SET_CURRENT_CONTEXT_FUNC
IMGUI_SET_CURRENT_CONTEXT_FUNC(ctx); // For custom thread-based hackery you may want to have control over this.
#else
GImGui = ctx;
#endif
}
void ImGui::SetAllocatorFunctions(void* (*alloc_func)(size_t sz, void* user_data), void (*free_func)(void* ptr, void* user_data), void* user_data)
{
GImAllocatorAllocFunc = alloc_func;
GImAllocatorFreeFunc = free_func;
GImAllocatorUserData = user_data;
}
ImGuiContext* ImGui::CreateContext(ImFontAtlas* shared_font_atlas)
{
ImGuiContext* ctx = IM_NEW(ImGuiContext)(shared_font_atlas);
if (GImGui == NULL)
SetCurrentContext(ctx);
Initialize(ctx);
return ctx;
}
void ImGui::DestroyContext(ImGuiContext* ctx)
{
if (ctx == NULL)
ctx = GImGui;
Shutdown(ctx);
if (GImGui == ctx)
SetCurrentContext(NULL);
IM_DELETE(ctx);
}
ImGuiIO& ImGui::GetIO()
{
IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
return GImGui->IO;
}
// Same value as passed to the old io.RenderDrawListsFn function. Valid after Render() and until the next call to NewFrame()
ImDrawData* ImGui::GetDrawData()
{
ImGuiContext& g = *GImGui;
return g.DrawData.Valid ? &g.DrawData : NULL;
}
double ImGui::GetTime()
{
return GImGui->Time;
}
int ImGui::GetFrameCount()
{
return GImGui->FrameCount;
}
ImDrawList* ImGui::GetBackgroundDrawList()
{
return &GImGui->BackgroundDrawList;
}
ImDrawList* ImGui::GetForegroundDrawList()
{
return &GImGui->ForegroundDrawList;
}
ImDrawListSharedData* ImGui::GetDrawListSharedData()
{
return &GImGui->DrawListSharedData;
}
void ImGui::StartMouseMovingWindow(ImGuiWindow* window)
{
// Set ActiveId even if the _NoMove flag is set. Without it, dragging away from a window with _NoMove would activate hover on other windows.
// We _also_ call this when clicking in a window empty space when io.ConfigWindowsMoveFromTitleBarOnly is set, but clear g.MovingWindow afterward.
// This is because we want ActiveId to be set even when the window is not permitted to move.
ImGuiContext& g = *GImGui;
FocusWindow(window);
SetActiveID(window->MoveId, window);
g.NavDisableHighlight = true;
g.ActiveIdNoClearOnFocusLoss = true;
g.ActiveIdClickOffset = g.IO.MousePos - window->RootWindow->Pos;
bool can_move_window = true;
if ((window->Flags & ImGuiWindowFlags_NoMove) || (window->RootWindow->Flags & ImGuiWindowFlags_NoMove))
can_move_window = false;
if (can_move_window)
g.MovingWindow = window;
}
// Handle mouse moving window
// Note: moving window with the navigation keys (Square + d-pad / CTRL+TAB + Arrows) are processed in NavUpdateWindowing()
// FIXME: We don't have strong guarantee that g.MovingWindow stay synched with g.ActiveId == g.MovingWindow->MoveId.
// This is currently enforced by the fact that BeginDragDropSource() is setting all g.ActiveIdUsingXXXX flags to inhibit navigation inputs,
// but if we should more thoroughly test cases where g.ActiveId or g.MovingWindow gets changed and not the other.
void ImGui::UpdateMouseMovingWindowNewFrame()
{
ImGuiContext& g = *GImGui;
if (g.MovingWindow != NULL)
{
// We actually want to move the root window. g.MovingWindow == window we clicked on (could be a child window).
// We track it to preserve Focus and so that generally ActiveIdWindow == MovingWindow and ActiveId == MovingWindow->MoveId for consistency.
KeepAliveID(g.ActiveId);
IM_ASSERT(g.MovingWindow && g.MovingWindow->RootWindow);
ImGuiWindow* moving_window = g.MovingWindow->RootWindow;
if (g.IO.MouseDown[0] && IsMousePosValid(&g.IO.MousePos))
{
ImVec2 pos = g.IO.MousePos - g.ActiveIdClickOffset;
if (moving_window->Pos.x != pos.x || moving_window->Pos.y != pos.y)
{
MarkIniSettingsDirty(moving_window);
SetWindowPos(moving_window, pos, ImGuiCond_Always);
}
FocusWindow(g.MovingWindow);
}
else
{
ClearActiveID();
g.MovingWindow = NULL;
}
}
else
{
// When clicking/dragging from a window that has the _NoMove flag, we still set the ActiveId in order to prevent hovering others.
if (g.ActiveIdWindow && g.ActiveIdWindow->MoveId == g.ActiveId)
{
KeepAliveID(g.ActiveId);
if (!g.IO.MouseDown[0])
ClearActiveID();
}
}
}
// Initiate moving window when clicking on empty space or title bar.
// Handle left-click and right-click focus.
void ImGui::UpdateMouseMovingWindowEndFrame()
{
ImGuiContext& g = *GImGui;
if (g.ActiveId != 0 || g.HoveredId != 0)
return;
// Unless we just made a window/popup appear
if (g.NavWindow && g.NavWindow->Appearing)
return;
// Click on empty space to focus window and start moving (after we're done with all our widgets)
if (g.IO.MouseClicked[0])
{
// Handle the edge case of a popup being closed while clicking in its empty space.
// If we try to focus it, FocusWindow() > ClosePopupsOverWindow() will accidentally close any parent popups because they are not linked together any more.
ImGuiWindow* root_window = g.HoveredRootWindow;
const bool is_closed_popup = root_window && (root_window->Flags & ImGuiWindowFlags_Popup) && !IsPopupOpen(root_window->PopupId, ImGuiPopupFlags_AnyPopupLevel);
if (root_window != NULL && !is_closed_popup)
{
StartMouseMovingWindow(g.HoveredWindow);
// Cancel moving if clicked outside of title bar
if (g.IO.ConfigWindowsMoveFromTitleBarOnly && !(root_window->Flags & ImGuiWindowFlags_NoTitleBar))
if (!root_window->TitleBarRect().Contains(g.IO.MouseClickedPos[0]))
g.MovingWindow = NULL;
// Cancel moving if clicked over an item which was disabled or inhibited by popups (note that we know HoveredId == 0 already)
if (g.HoveredIdDisabled)
g.MovingWindow = NULL;
}
else if (root_window == NULL && g.NavWindow != NULL && GetTopMostPopupModal() == NULL)
{
// Clicking on void disable focus
FocusWindow(NULL);
}
}
// With right mouse button we close popups without changing focus based on where the mouse is aimed
// Instead, focus will be restored to the window under the bottom-most closed popup.
// (The left mouse button path calls FocusWindow on the hovered window, which will lead NewFrame->ClosePopupsOverWindow to trigger)
if (g.IO.MouseClicked[1])
{
// Find the top-most window between HoveredWindow and the top-most Modal Window.
// This is where we can trim the popup stack.
ImGuiWindow* modal = GetTopMostPopupModal();
bool hovered_window_above_modal = false;
if (modal == NULL)
hovered_window_above_modal = true;
for (int i = g.Windows.Size - 1; i >= 0 && hovered_window_above_modal == false; i--)
{
ImGuiWindow* window = g.Windows[i];
if (window == modal)
break;
if (window == g.HoveredWindow)
hovered_window_above_modal = true;
}
ClosePopupsOverWindow(hovered_window_above_modal ? g.HoveredWindow : modal, true);
}
}
static bool IsWindowActiveAndVisible(ImGuiWindow* window)
{
return (window->Active) && (!window->Hidden);
}
static void ImGui::UpdateMouseInputs()
{
ImGuiContext& g = *GImGui;
// Round mouse position to avoid spreading non-rounded position (e.g. UpdateManualResize doesn't support them well)
if (IsMousePosValid(&g.IO.MousePos))
g.IO.MousePos = g.LastValidMousePos = ImFloor(g.IO.MousePos);
// If mouse just appeared or disappeared (usually denoted by -FLT_MAX components) we cancel out movement in MouseDelta
if (IsMousePosValid(&g.IO.MousePos) && IsMousePosValid(&g.IO.MousePosPrev))
g.IO.MouseDelta = g.IO.MousePos - g.IO.MousePosPrev;
else
g.IO.MouseDelta = ImVec2(0.0f, 0.0f);
if (g.IO.MouseDelta.x != 0.0f || g.IO.MouseDelta.y != 0.0f)
g.NavDisableMouseHover = false;
g.IO.MousePosPrev = g.IO.MousePos;
for (int i = 0; i < IM_ARRAYSIZE(g.IO.MouseDown); i++)
{
g.IO.MouseClicked[i] = g.IO.MouseDown[i] && g.IO.MouseDownDuration[i] < 0.0f;
g.IO.MouseReleased[i] = !g.IO.MouseDown[i] && g.IO.MouseDownDuration[i] >= 0.0f;
g.IO.MouseDownDurationPrev[i] = g.IO.MouseDownDuration[i];
g.IO.MouseDownDuration[i] = g.IO.MouseDown[i] ? (g.IO.MouseDownDuration[i] < 0.0f ? 0.0f : g.IO.MouseDownDuration[i] + g.IO.DeltaTime) : -1.0f;
g.IO.MouseDoubleClicked[i] = false;
if (g.IO.MouseClicked[i])
{
if ((float)(g.Time - g.IO.MouseClickedTime[i]) < g.IO.MouseDoubleClickTime)
{
ImVec2 delta_from_click_pos = IsMousePosValid(&g.IO.MousePos) ? (g.IO.MousePos - g.IO.MouseClickedPos[i]) : ImVec2(0.0f, 0.0f);
if (ImLengthSqr(delta_from_click_pos) < g.IO.MouseDoubleClickMaxDist * g.IO.MouseDoubleClickMaxDist)
g.IO.MouseDoubleClicked[i] = true;
g.IO.MouseClickedTime[i] = -g.IO.MouseDoubleClickTime * 2.0f; // Mark as "old enough" so the third click isn't turned into a double-click
}
else
{
g.IO.MouseClickedTime[i] = g.Time;
}
g.IO.MouseClickedPos[i] = g.IO.MousePos;
g.IO.MouseDownWasDoubleClick[i] = g.IO.MouseDoubleClicked[i];
g.IO.MouseDragMaxDistanceAbs[i] = ImVec2(0.0f, 0.0f);
g.IO.MouseDragMaxDistanceSqr[i] = 0.0f;
}
else if (g.IO.MouseDown[i])
{
// Maintain the maximum distance we reaching from the initial click position, which is used with dragging threshold
ImVec2 delta_from_click_pos = IsMousePosValid(&g.IO.MousePos) ? (g.IO.MousePos - g.IO.MouseClickedPos[i]) : ImVec2(0.0f, 0.0f);
g.IO.MouseDragMaxDistanceSqr[i] = ImMax(g.IO.MouseDragMaxDistanceSqr[i], ImLengthSqr(delta_from_click_pos));
g.IO.MouseDragMaxDistanceAbs[i].x = ImMax(g.IO.MouseDragMaxDistanceAbs[i].x, delta_from_click_pos.x < 0.0f ? -delta_from_click_pos.x : delta_from_click_pos.x);
g.IO.MouseDragMaxDistanceAbs[i].y = ImMax(g.IO.MouseDragMaxDistanceAbs[i].y, delta_from_click_pos.y < 0.0f ? -delta_from_click_pos.y : delta_from_click_pos.y);
}
if (!g.IO.MouseDown[i] && !g.IO.MouseReleased[i])
g.IO.MouseDownWasDoubleClick[i] = false;
if (g.IO.MouseClicked[i]) // Clicking any mouse button reactivate mouse hovering which may have been deactivated by gamepad/keyboard navigation
g.NavDisableMouseHover = false;
}
}
static void StartLockWheelingWindow(ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
if (g.WheelingWindow == window)
return;
g.WheelingWindow = window;
g.WheelingWindowRefMousePos = g.IO.MousePos;
g.WheelingWindowTimer = WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER;
}
void ImGui::UpdateMouseWheel()
{
ImGuiContext& g = *GImGui;
// Reset the locked window if we move the mouse or after the timer elapses
if (g.WheelingWindow != NULL)
{
g.WheelingWindowTimer -= g.IO.DeltaTime;
if (IsMousePosValid() && ImLengthSqr(g.IO.MousePos - g.WheelingWindowRefMousePos) > g.IO.MouseDragThreshold * g.IO.MouseDragThreshold)
g.WheelingWindowTimer = 0.0f;
if (g.WheelingWindowTimer <= 0.0f)
{
g.WheelingWindow = NULL;
g.WheelingWindowTimer = 0.0f;
}
}
if (g.IO.MouseWheel == 0.0f && g.IO.MouseWheelH == 0.0f)
return;
ImGuiWindow* window = g.WheelingWindow ? g.WheelingWindow : g.HoveredWindow;
if (!window || window->Collapsed)
return;
// Zoom / Scale window
// FIXME-OBSOLETE: This is an old feature, it still works but pretty much nobody is using it and may be best redesigned.
if (g.IO.MouseWheel != 0.0f && g.IO.KeyCtrl && g.IO.FontAllowUserScaling)
{
StartLockWheelingWindow(window);
const float new_font_scale = ImClamp(window->FontWindowScale + g.IO.MouseWheel * 0.10f, 0.50f, 2.50f);
const float scale = new_font_scale / window->FontWindowScale;
window->FontWindowScale = new_font_scale;
if (!(window->Flags & ImGuiWindowFlags_ChildWindow))
{
const ImVec2 offset = window->Size * (1.0f - scale) * (g.IO.MousePos - window->Pos) / window->Size;
SetWindowPos(window, window->Pos + offset, 0);
window->Size = ImFloor(window->Size * scale);
window->SizeFull = ImFloor(window->SizeFull * scale);
}
return;
}
// Mouse wheel scrolling
// If a child window has the ImGuiWindowFlags_NoScrollWithMouse flag, we give a chance to scroll its parent
// Vertical Mouse Wheel scrolling
const float wheel_y = (g.IO.MouseWheel != 0.0f && !g.IO.KeyShift) ? g.IO.MouseWheel : 0.0f;
if (wheel_y != 0.0f && !g.IO.KeyCtrl)
{
StartLockWheelingWindow(window);
while ((window->Flags & ImGuiWindowFlags_ChildWindow) && ((window->ScrollMax.y == 0.0f) || ((window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs))))
window = window->ParentWindow;
if (!(window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs))
{
float max_step = window->InnerRect.GetHeight() * 0.67f;
float scroll_step = ImFloor(ImMin(5 * window->CalcFontSize(), max_step));
SetScrollY(window, window->Scroll.y - wheel_y * scroll_step);
}
}
// Horizontal Mouse Wheel scrolling, or Vertical Mouse Wheel w/ Shift held
const float wheel_x = (g.IO.MouseWheelH != 0.0f && !g.IO.KeyShift) ? g.IO.MouseWheelH : (g.IO.MouseWheel != 0.0f && g.IO.KeyShift) ? g.IO.MouseWheel : 0.0f;
if (wheel_x != 0.0f && !g.IO.KeyCtrl)
{
StartLockWheelingWindow(window);
while ((window->Flags & ImGuiWindowFlags_ChildWindow) && ((window->ScrollMax.x == 0.0f) || ((window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs))))
window = window->ParentWindow;
if (!(window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs))
{
float max_step = window->InnerRect.GetWidth() * 0.67f;
float scroll_step = ImFloor(ImMin(2 * window->CalcFontSize(), max_step));
SetScrollX(window, window->Scroll.x - wheel_x * scroll_step);
}
}
}
void ImGui::UpdateTabFocus()
{
ImGuiContext& g = *GImGui;
// Pressing TAB activate widget focus
g.FocusTabPressed = (g.NavWindow && g.NavWindow->Active && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs) && !g.IO.KeyCtrl && IsKeyPressedMap(ImGuiKey_Tab));
if (g.ActiveId == 0 && g.FocusTabPressed)
{
// Note that SetKeyboardFocusHere() sets the Next fields mid-frame. To be consistent we also
// manipulate the Next fields even, even though they will be turned into Curr fields by the code below.
g.FocusRequestNextWindow = g.NavWindow;
g.FocusRequestNextCounterRegular = INT_MAX;
if (g.NavId != 0 && g.NavIdTabCounter != INT_MAX)
g.FocusRequestNextCounterTabStop = g.NavIdTabCounter + 1 + (g.IO.KeyShift ? -1 : 1);
else
g.FocusRequestNextCounterTabStop = g.IO.KeyShift ? -1 : 0;
}
// Turn queued focus request into current one
g.FocusRequestCurrWindow = NULL;
g.FocusRequestCurrCounterRegular = g.FocusRequestCurrCounterTabStop = INT_MAX;
if (g.FocusRequestNextWindow != NULL)
{
ImGuiWindow* window = g.FocusRequestNextWindow;
g.FocusRequestCurrWindow = window;
if (g.FocusRequestNextCounterRegular != INT_MAX && window->DC.FocusCounterRegular != -1)
g.FocusRequestCurrCounterRegular = ImModPositive(g.FocusRequestNextCounterRegular, window->DC.FocusCounterRegular + 1);
if (g.FocusRequestNextCounterTabStop != INT_MAX && window->DC.FocusCounterTabStop != -1)
g.FocusRequestCurrCounterTabStop = ImModPositive(g.FocusRequestNextCounterTabStop, window->DC.FocusCounterTabStop + 1);
g.FocusRequestNextWindow = NULL;
g.FocusRequestNextCounterRegular = g.FocusRequestNextCounterTabStop = INT_MAX;
}
g.NavIdTabCounter = INT_MAX;
}
// The reason this is exposed in imgui_internal.h is: on touch-based system that don't have hovering, we want to dispatch inputs to the right target (imgui vs imgui+app)
void ImGui::UpdateHoveredWindowAndCaptureFlags()
{
ImGuiContext& g = *GImGui;
// Find the window hovered by mouse:
// - Child windows can extend beyond the limit of their parent so we need to derive HoveredRootWindow from HoveredWindow.
// - When moving a window we can skip the search, which also conveniently bypasses the fact that window->WindowRectClipped is lagging as this point of the frame.
// - We also support the moved window toggling the NoInputs flag after moving has started in order to be able to detect windows below it, which is useful for e.g. docking mechanisms.
bool clear_hovered_windows = false;
FindHoveredWindow();
// Modal windows prevents mouse from hovering behind them.
ImGuiWindow* modal_window = GetTopMostPopupModal();
if (modal_window && g.HoveredRootWindow && !IsWindowChildOf(g.HoveredRootWindow, modal_window))
clear_hovered_windows = true;
// Disabled mouse?
if (g.IO.ConfigFlags & ImGuiConfigFlags_NoMouse)
clear_hovered_windows = true;
// We track click ownership. When clicked outside of a window the click is owned by the application and won't report hovering nor request capture even while dragging over our windows afterward.
int mouse_earliest_button_down = -1;
bool mouse_any_down = false;
for (int i = 0; i < IM_ARRAYSIZE(g.IO.MouseDown); i++)
{
if (g.IO.MouseClicked[i])
g.IO.MouseDownOwned[i] = (g.HoveredWindow != NULL) || (g.OpenPopupStack.Size > 0);
mouse_any_down |= g.IO.MouseDown[i];
if (g.IO.MouseDown[i])
if (mouse_earliest_button_down == -1 || g.IO.MouseClickedTime[i] < g.IO.MouseClickedTime[mouse_earliest_button_down])
mouse_earliest_button_down = i;
}
const bool mouse_avail_to_imgui = (mouse_earliest_button_down == -1) || g.IO.MouseDownOwned[mouse_earliest_button_down];
// If mouse was first clicked outside of ImGui bounds we also cancel out hovering.
// FIXME: For patterns of drag and drop across OS windows, we may need to rework/remove this test (first committed 311c0ca9 on 2015/02)
const bool mouse_dragging_extern_payload = g.DragDropActive && (g.DragDropSourceFlags & ImGuiDragDropFlags_SourceExtern) != 0;
if (!mouse_avail_to_imgui && !mouse_dragging_extern_payload)
clear_hovered_windows = true;
if (clear_hovered_windows)
g.HoveredWindow = g.HoveredRootWindow = g.HoveredWindowUnderMovingWindow = NULL;
// Update io.WantCaptureMouse for the user application (true = dispatch mouse info to imgui, false = dispatch mouse info to Dear ImGui + app)
if (g.WantCaptureMouseNextFrame != -1)
g.IO.WantCaptureMouse = (g.WantCaptureMouseNextFrame != 0);
else
g.IO.WantCaptureMouse = (mouse_avail_to_imgui && (g.HoveredWindow != NULL || mouse_any_down)) || (g.OpenPopupStack.Size > 0);
// Update io.WantCaptureKeyboard for the user application (true = dispatch keyboard info to imgui, false = dispatch keyboard info to Dear ImGui + app)
if (g.WantCaptureKeyboardNextFrame != -1)
g.IO.WantCaptureKeyboard = (g.WantCaptureKeyboardNextFrame != 0);
else
g.IO.WantCaptureKeyboard = (g.ActiveId != 0) || (modal_window != NULL);
if (g.IO.NavActive && (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) && !(g.IO.ConfigFlags & ImGuiConfigFlags_NavNoCaptureKeyboard))
g.IO.WantCaptureKeyboard = true;
// Update io.WantTextInput flag, this is to allow systems without a keyboard (e.g. mobile, hand-held) to show a software keyboard if possible
g.IO.WantTextInput = (g.WantTextInputNextFrame != -1) ? (g.WantTextInputNextFrame != 0) : false;
}
ImGuiKeyModFlags ImGui::GetMergedKeyModFlags()
{
ImGuiContext& g = *GImGui;
ImGuiKeyModFlags key_mod_flags = ImGuiKeyModFlags_None;
if (g.IO.KeyCtrl) { key_mod_flags |= ImGuiKeyModFlags_Ctrl; }
if (g.IO.KeyShift) { key_mod_flags |= ImGuiKeyModFlags_Shift; }
if (g.IO.KeyAlt) { key_mod_flags |= ImGuiKeyModFlags_Alt; }
if (g.IO.KeySuper) { key_mod_flags |= ImGuiKeyModFlags_Super; }
return key_mod_flags;
}
void ImGui::NewFrame()
{
IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
ImGuiContext& g = *GImGui;
#ifdef IMGUI_ENABLE_TEST_ENGINE
ImGuiTestEngineHook_PreNewFrame(&g);
#endif
// Check and assert for various common IO and Configuration mistakes
ErrorCheckNewFrameSanityChecks();
// Load settings on first frame, save settings when modified (after a delay)
UpdateSettings();
g.Time += g.IO.DeltaTime;
g.WithinFrameScope = true;
g.FrameCount += 1;
g.TooltipOverrideCount = 0;
g.WindowsActiveCount = 0;
g.MenusIdSubmittedThisFrame.resize(0);
// Calculate frame-rate for the user, as a purely luxurious feature
g.FramerateSecPerFrameAccum += g.IO.DeltaTime - g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx];
g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx] = g.IO.DeltaTime;
g.FramerateSecPerFrameIdx = (g.FramerateSecPerFrameIdx + 1) % IM_ARRAYSIZE(g.FramerateSecPerFrame);
g.IO.Framerate = (g.FramerateSecPerFrameAccum > 0.0f) ? (1.0f / (g.FramerateSecPerFrameAccum / (float)IM_ARRAYSIZE(g.FramerateSecPerFrame))) : FLT_MAX;
// Setup current font and draw list shared data
g.IO.Fonts->Locked = true;
SetCurrentFont(GetDefaultFont());
IM_ASSERT(g.Font->IsLoaded());
g.DrawListSharedData.ClipRectFullscreen = ImVec4(0.0f, 0.0f, g.IO.DisplaySize.x, g.IO.DisplaySize.y);
g.DrawListSharedData.CurveTessellationTol = g.Style.CurveTessellationTol;
g.DrawListSharedData.SetCircleSegmentMaxError(g.Style.CircleSegmentMaxError);
g.DrawListSharedData.InitialFlags = ImDrawListFlags_None;
if (g.Style.AntiAliasedLines)
g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedLines;
if (g.Style.AntiAliasedLinesUseTex && !(g.Font->ContainerAtlas->Flags & ImFontAtlasFlags_NoBakedLines))
g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedLinesUseTex;
if (g.Style.AntiAliasedFill)
g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedFill;
if (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasVtxOffset)
g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AllowVtxOffset;
g.BackgroundDrawList._ResetForNewFrame();
g.BackgroundDrawList.PushTextureID(g.IO.Fonts->TexID);
g.BackgroundDrawList.PushClipRectFullScreen();
g.ForegroundDrawList._ResetForNewFrame();
g.ForegroundDrawList.PushTextureID(g.IO.Fonts->TexID);
g.ForegroundDrawList.PushClipRectFullScreen();
// Mark rendering data as invalid to prevent user who may have a handle on it to use it.
g.DrawData.Clear();
// Drag and drop keep the source ID alive so even if the source disappear our state is consistent
if (g.DragDropActive && g.DragDropPayload.SourceId == g.ActiveId)
KeepAliveID(g.DragDropPayload.SourceId);
// Update HoveredId data
if (!g.HoveredIdPreviousFrame)
g.HoveredIdTimer = 0.0f;
if (!g.HoveredIdPreviousFrame || (g.HoveredId && g.ActiveId == g.HoveredId))
g.HoveredIdNotActiveTimer = 0.0f;
if (g.HoveredId)
g.HoveredIdTimer += g.IO.DeltaTime;
if (g.HoveredId && g.ActiveId != g.HoveredId)
g.HoveredIdNotActiveTimer += g.IO.DeltaTime;
g.HoveredIdPreviousFrame = g.HoveredId;
g.HoveredId = 0;
g.HoveredIdAllowOverlap = false;
g.HoveredIdDisabled = false;
// Update ActiveId data (clear reference to active widget if the widget isn't alive anymore)
if (g.ActiveIdIsAlive != g.ActiveId && g.ActiveIdPreviousFrame == g.ActiveId && g.ActiveId != 0)
ClearActiveID();
if (g.ActiveId)
g.ActiveIdTimer += g.IO.DeltaTime;
g.LastActiveIdTimer += g.IO.DeltaTime;
g.ActiveIdPreviousFrame = g.ActiveId;
g.ActiveIdPreviousFrameWindow = g.ActiveIdWindow;
g.ActiveIdPreviousFrameHasBeenEditedBefore = g.ActiveIdHasBeenEditedBefore;
g.ActiveIdIsAlive = 0;
g.ActiveIdHasBeenEditedThisFrame = false;
g.ActiveIdPreviousFrameIsAlive = false;
g.ActiveIdIsJustActivated = false;
if (g.TempInputId != 0 && g.ActiveId != g.TempInputId)
g.TempInputId = 0;
if (g.ActiveId == 0)
{
g.ActiveIdUsingNavDirMask = 0x00;
g.ActiveIdUsingNavInputMask = 0x00;
g.ActiveIdUsingKeyInputMask = 0x00;
}
// Drag and drop
g.DragDropAcceptIdPrev = g.DragDropAcceptIdCurr;
g.DragDropAcceptIdCurr = 0;
g.DragDropAcceptIdCurrRectSurface = FLT_MAX;
g.DragDropWithinSource = false;
g.DragDropWithinTarget = false;
g.DragDropHoldJustPressedId = 0;
// Update keyboard input state
// Synchronize io.KeyMods with individual modifiers io.KeyXXX bools
g.IO.KeyMods = GetMergedKeyModFlags();
memcpy(g.IO.KeysDownDurationPrev, g.IO.KeysDownDuration, sizeof(g.IO.KeysDownDuration));
for (int i = 0; i < IM_ARRAYSIZE(g.IO.KeysDown); i++)
g.IO.KeysDownDuration[i] = g.IO.KeysDown[i] ? (g.IO.KeysDownDuration[i] < 0.0f ? 0.0f : g.IO.KeysDownDuration[i] + g.IO.DeltaTime) : -1.0f;
// Update gamepad/keyboard navigation
NavUpdate();
// Update mouse input state
UpdateMouseInputs();
// Find hovered window
// (needs to be before UpdateMouseMovingWindowNewFrame so we fill g.HoveredWindowUnderMovingWindow on the mouse release frame)
UpdateHoveredWindowAndCaptureFlags();
// Handle user moving window with mouse (at the beginning of the frame to avoid input lag or sheering)
UpdateMouseMovingWindowNewFrame();
// Background darkening/whitening
if (GetTopMostPopupModal() != NULL || (g.NavWindowingTarget != NULL && g.NavWindowingHighlightAlpha > 0.0f))
g.DimBgRatio = ImMin(g.DimBgRatio + g.IO.DeltaTime * 6.0f, 1.0f);
else
g.DimBgRatio = ImMax(g.DimBgRatio - g.IO.DeltaTime * 10.0f, 0.0f);
g.MouseCursor = ImGuiMouseCursor_Arrow;
g.WantCaptureMouseNextFrame = g.WantCaptureKeyboardNextFrame = g.WantTextInputNextFrame = -1;
g.PlatformImePos = ImVec2(1.0f, 1.0f); // OS Input Method Editor showing on top-left of our window by default
// Mouse wheel scrolling, scale
UpdateMouseWheel();
// Update legacy TAB focus
UpdateTabFocus();
// Mark all windows as not visible and compact unused memory.
IM_ASSERT(g.WindowsFocusOrder.Size == g.Windows.Size);
const float memory_compact_start_time = (g.IO.ConfigWindowsMemoryCompactTimer >= 0.0f) ? (float)g.Time - g.IO.ConfigWindowsMemoryCompactTimer : FLT_MAX;
for (int i = 0; i != g.Windows.Size; i++)
{
ImGuiWindow* window = g.Windows[i];
window->WasActive = window->Active;
window->BeginCount = 0;
window->Active = false;
window->WriteAccessed = false;
// Garbage collect transient buffers of recently unused windows
if (!window->WasActive && !window->MemoryCompacted && window->LastTimeActive < memory_compact_start_time)
GcCompactTransientWindowBuffers(window);
}
// Closing the focused window restore focus to the first active root window in descending z-order
if (g.NavWindow && !g.NavWindow->WasActive)
FocusTopMostWindowUnderOne(NULL, NULL);
// No window should be open at the beginning of the frame.
// But in order to allow the user to call NewFrame() multiple times without calling Render(), we are doing an explicit clear.
g.CurrentWindowStack.resize(0);
g.BeginPopupStack.resize(0);
ClosePopupsOverWindow(g.NavWindow, false);
// [DEBUG] Item picker tool - start with DebugStartItemPicker() - useful to visually select an item and break into its call-stack.
UpdateDebugToolItemPicker();
// Create implicit/fallback window - which we will only render it if the user has added something to it.
// We don't use "Debug" to avoid colliding with user trying to create a "Debug" window with custom flags.
// This fallback is particularly important as it avoid ImGui:: calls from crashing.
g.WithinFrameScopeWithImplicitWindow = true;
SetNextWindowSize(ImVec2(400, 400), ImGuiCond_FirstUseEver);
Begin("Debug##Default");
IM_ASSERT(g.CurrentWindow->IsFallbackWindow == true);
#ifdef IMGUI_ENABLE_TEST_ENGINE
ImGuiTestEngineHook_PostNewFrame(&g);
#endif
}
// [DEBUG] Item picker tool - start with DebugStartItemPicker() - useful to visually select an item and break into its call-stack.
void ImGui::UpdateDebugToolItemPicker()
{
ImGuiContext& g = *GImGui;
g.DebugItemPickerBreakId = 0;
if (g.DebugItemPickerActive)
{
const ImGuiID hovered_id = g.HoveredIdPreviousFrame;
ImGui::SetMouseCursor(ImGuiMouseCursor_Hand);
if (ImGui::IsKeyPressedMap(ImGuiKey_Escape))
g.DebugItemPickerActive = false;
if (ImGui::IsMouseClicked(0) && hovered_id)
{
g.DebugItemPickerBreakId = hovered_id;
g.DebugItemPickerActive = false;
}
ImGui::SetNextWindowBgAlpha(0.60f);
ImGui::BeginTooltip();
ImGui::Text("HoveredId: 0x%08X", hovered_id);
ImGui::Text("Press ESC to abort picking.");
ImGui::TextColored(GetStyleColorVec4(hovered_id ? ImGuiCol_Text : ImGuiCol_TextDisabled), "Click to break in debugger!");
ImGui::EndTooltip();
}
}
void ImGui::Initialize(ImGuiContext* context)
{
ImGuiContext& g = *context;
IM_ASSERT(!g.Initialized && !g.SettingsLoaded);
// Add .ini handle for ImGuiWindow type
{
ImGuiSettingsHandler ini_handler;
ini_handler.TypeName = "Window";
ini_handler.TypeHash = ImHashStr("Window");
ini_handler.ClearAllFn = WindowSettingsHandler_ClearAll;
ini_handler.ReadOpenFn = WindowSettingsHandler_ReadOpen;
ini_handler.ReadLineFn = WindowSettingsHandler_ReadLine;
ini_handler.ApplyAllFn = WindowSettingsHandler_ApplyAll;
ini_handler.WriteAllFn = WindowSettingsHandler_WriteAll;
g.SettingsHandlers.push_back(ini_handler);
}
#ifdef IMGUI_HAS_TABLE
// Add .ini handle for ImGuiTable type
{
ImGuiSettingsHandler ini_handler;
ini_handler.TypeName = "Table";
ini_handler.TypeHash = ImHashStr("Table");
ini_handler.ReadOpenFn = TableSettingsHandler_ReadOpen;
ini_handler.ReadLineFn = TableSettingsHandler_ReadLine;
ini_handler.WriteAllFn = TableSettingsHandler_WriteAll;
g.SettingsHandlers.push_back(ini_handler);
}
#endif // #ifdef IMGUI_HAS_TABLE
#ifdef IMGUI_HAS_DOCK
#endif // #ifdef IMGUI_HAS_DOCK
g.Initialized = true;
}
// This function is merely here to free heap allocations.
void ImGui::Shutdown(ImGuiContext* context)
{
// The fonts atlas can be used prior to calling NewFrame(), so we clear it even if g.Initialized is FALSE (which would happen if we never called NewFrame)
ImGuiContext& g = *context;
if (g.IO.Fonts && g.FontAtlasOwnedByContext)
{
g.IO.Fonts->Locked = false;
IM_DELETE(g.IO.Fonts);
}
g.IO.Fonts = NULL;
// Cleanup of other data are conditional on actually having initialized Dear ImGui.
if (!g.Initialized)
return;
// Save settings (unless we haven't attempted to load them: CreateContext/DestroyContext without a call to NewFrame shouldn't save an empty file)
if (g.SettingsLoaded && g.IO.IniFilename != NULL)
{
ImGuiContext* backup_context = GImGui;
SetCurrentContext(context);
SaveIniSettingsToDisk(g.IO.IniFilename);
SetCurrentContext(backup_context);
}
// Notify hooked test engine, if any
#ifdef IMGUI_ENABLE_TEST_ENGINE
ImGuiTestEngineHook_Shutdown(context);
#endif
// Clear everything else
for (int i = 0; i < g.Windows.Size; i++)
IM_DELETE(g.Windows[i]);
g.Windows.clear();
g.WindowsFocusOrder.clear();
g.WindowsTempSortBuffer.clear();
g.CurrentWindow = NULL;
g.CurrentWindowStack.clear();
g.WindowsById.Clear();
g.NavWindow = NULL;
g.HoveredWindow = g.HoveredRootWindow = g.HoveredWindowUnderMovingWindow = NULL;
g.ActiveIdWindow = g.ActiveIdPreviousFrameWindow = NULL;
g.MovingWindow = NULL;
g.ColorModifiers.clear();
g.StyleModifiers.clear();
g.FontStack.clear();
g.OpenPopupStack.clear();
g.BeginPopupStack.clear();
g.DrawDataBuilder.ClearFreeMemory();
g.BackgroundDrawList._ClearFreeMemory();
g.ForegroundDrawList._ClearFreeMemory();
g.TabBars.Clear();
g.CurrentTabBarStack.clear();
g.ShrinkWidthBuffer.clear();
g.ClipboardHandlerData.clear();
g.MenusIdSubmittedThisFrame.clear();
g.InputTextState.ClearFreeMemory();
g.SettingsWindows.clear();
g.SettingsHandlers.clear();
if (g.LogFile)
{
#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
if (g.LogFile != stdout)
#endif
ImFileClose(g.LogFile);
g.LogFile = NULL;
}
g.LogBuffer.clear();
g.Initialized = false;
}
// FIXME: Add a more explicit sort order in the window structure.
static int IMGUI_CDECL ChildWindowComparer(const void* lhs, const void* rhs)
{
const ImGuiWindow* const a = *(const ImGuiWindow* const *)lhs;
const ImGuiWindow* const b = *(const ImGuiWindow* const *)rhs;
if (int d = (a->Flags & ImGuiWindowFlags_Popup) - (b->Flags & ImGuiWindowFlags_Popup))
return d;
if (int d = (a->Flags & ImGuiWindowFlags_Tooltip) - (b->Flags & ImGuiWindowFlags_Tooltip))
return d;
return (a->BeginOrderWithinParent - b->BeginOrderWithinParent);
}
static void AddWindowToSortBuffer(ImVector<ImGuiWindow*>* out_sorted_windows, ImGuiWindow* window)
{
out_sorted_windows->push_back(window);
if (window->Active)
{
int count = window->DC.ChildWindows.Size;
if (count > 1)
ImQsort(window->DC.ChildWindows.Data, (size_t)count, sizeof(ImGuiWindow*), ChildWindowComparer);
for (int i = 0; i < count; i++)
{
ImGuiWindow* child = window->DC.ChildWindows[i];
if (child->Active)
AddWindowToSortBuffer(out_sorted_windows, child);
}
}
}
static void AddDrawListToDrawData(ImVector<ImDrawList*>* out_list, ImDrawList* draw_list)
{
// Remove trailing command if unused.
// Technically we could return directly instead of popping, but this make things looks neat in Metrics window as well.
draw_list->_PopUnusedDrawCmd();
if (draw_list->CmdBuffer.Size == 0)
return;
// Draw list sanity check. Detect mismatch between PrimReserve() calls and incrementing _VtxCurrentIdx, _VtxWritePtr etc.
// May trigger for you if you are using PrimXXX functions incorrectly.
IM_ASSERT(draw_list->VtxBuffer.Size == 0 || draw_list->_VtxWritePtr == draw_list->VtxBuffer.Data + draw_list->VtxBuffer.Size);
IM_ASSERT(draw_list->IdxBuffer.Size == 0 || draw_list->_IdxWritePtr == draw_list->IdxBuffer.Data + draw_list->IdxBuffer.Size);
if (!(draw_list->Flags & ImDrawListFlags_AllowVtxOffset))
IM_ASSERT((int)draw_list->_VtxCurrentIdx == draw_list->VtxBuffer.Size);
// Check that draw_list doesn't use more vertices than indexable (default ImDrawIdx = unsigned short = 2 bytes = 64K vertices per ImDrawList = per window)
// If this assert triggers because you are drawing lots of stuff manually:
// - First, make sure you are coarse clipping yourself and not trying to draw many things outside visible bounds.
// Be mindful that the ImDrawList API doesn't filter vertices. Use the Metrics window to inspect draw list contents.
// - If you want large meshes with more than 64K vertices, you can either:
// (A) Handle the ImDrawCmd::VtxOffset value in your renderer back-end, and set 'io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset'.
// Most example back-ends already support this from 1.71. Pre-1.71 back-ends won't.
// Some graphics API such as GL ES 1/2 don't have a way to offset the starting vertex so it is not supported for them.
// (B) Or handle 32-bit indices in your renderer back-end, and uncomment '#define ImDrawIdx unsigned int' line in imconfig.h.
// Most example back-ends already support this. For example, the OpenGL example code detect index size at compile-time:
// glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer_offset);
// Your own engine or render API may use different parameters or function calls to specify index sizes.
// 2 and 4 bytes indices are generally supported by most graphics API.
// - If for some reason neither of those solutions works for you, a workaround is to call BeginChild()/EndChild() before reaching
// the 64K limit to split your draw commands in multiple draw lists.
if (sizeof(ImDrawIdx) == 2)
IM_ASSERT(draw_list->_VtxCurrentIdx < (1 << 16) && "Too many vertices in ImDrawList using 16-bit indices. Read comment above");
out_list->push_back(draw_list);
}
static void AddWindowToDrawData(ImVector<ImDrawList*>* out_render_list, ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
g.IO.MetricsRenderWindows++;
AddDrawListToDrawData(out_render_list, window->DrawList);
for (int i = 0; i < window->DC.ChildWindows.Size; i++)
{
ImGuiWindow* child = window->DC.ChildWindows[i];
if (IsWindowActiveAndVisible(child)) // clipped children may have been marked not active
AddWindowToDrawData(out_render_list, child);
}
}
// Layer is locked for the root window, however child windows may use a different viewport (e.g. extruding menu)
static void AddRootWindowToDrawData(ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
int layer = (window->Flags & ImGuiWindowFlags_Tooltip) ? 1 : 0;
AddWindowToDrawData(&g.DrawDataBuilder.Layers[layer], window);
}
void ImDrawDataBuilder::FlattenIntoSingleLayer()
{
int n = Layers[0].Size;
int size = n;
for (int i = 1; i < IM_ARRAYSIZE(Layers); i++)
size += Layers[i].Size;
Layers[0].resize(size);
for (int layer_n = 1; layer_n < IM_ARRAYSIZE(Layers); layer_n++)
{
ImVector<ImDrawList*>& layer = Layers[layer_n];
if (layer.empty())
continue;
memcpy(&Layers[0][n], &layer[0], layer.Size * sizeof(ImDrawList*));
n += layer.Size;
layer.resize(0);
}
}
static void SetupDrawData(ImVector<ImDrawList*>* draw_lists, ImDrawData* draw_data)
{
ImGuiIO& io = ImGui::GetIO();
draw_data->Valid = true;
draw_data->CmdLists = (draw_lists->Size > 0) ? draw_lists->Data : NULL;
draw_data->CmdListsCount = draw_lists->Size;
draw_data->TotalVtxCount = draw_data->TotalIdxCount = 0;
draw_data->DisplayPos = ImVec2(0.0f, 0.0f);
draw_data->DisplaySize = io.DisplaySize;
draw_data->FramebufferScale = io.DisplayFramebufferScale;
for (int n = 0; n < draw_lists->Size; n++)
{
draw_data->TotalVtxCount += draw_lists->Data[n]->VtxBuffer.Size;
draw_data->TotalIdxCount += draw_lists->Data[n]->IdxBuffer.Size;
}
}
// Push a clipping rectangle for both ImGui logic (hit-testing etc.) and low-level ImDrawList rendering.
// - When using this function it is sane to ensure that float are perfectly rounded to integer values,
// so that e.g. (int)(max.x-min.x) in user's render produce correct result.
// - If the code here changes, may need to update code of functions like NextColumn() and PushColumnClipRect():
// some frequently called functions which to modify both channels and clipping simultaneously tend to use the
// more specialized SetWindowClipRectBeforeSetChannel() to avoid extraneous updates of underlying ImDrawCmds.
void ImGui::PushClipRect(const ImVec2& clip_rect_min, const ImVec2& clip_rect_max, bool intersect_with_current_clip_rect)
{
ImGuiWindow* window = GetCurrentWindow();
window->DrawList->PushClipRect(clip_rect_min, clip_rect_max, intersect_with_current_clip_rect);
window->ClipRect = window->DrawList->_ClipRectStack.back();
}
void ImGui::PopClipRect()
{
ImGuiWindow* window = GetCurrentWindow();
window->DrawList->PopClipRect();
window->ClipRect = window->DrawList->_ClipRectStack.back();
}
// This is normally called by Render(). You may want to call it directly if you want to avoid calling Render() but the gain will be very minimal.
void ImGui::EndFrame()
{
ImGuiContext& g = *GImGui;
IM_ASSERT(g.Initialized);
// Don't process EndFrame() multiple times.
if (g.FrameCountEnded == g.FrameCount)
return;
IM_ASSERT(g.WithinFrameScope && "Forgot to call ImGui::NewFrame()?");
ErrorCheckEndFrameSanityChecks();
// Notify OS when our Input Method Editor cursor has moved (e.g. CJK inputs using Microsoft IME)
if (g.IO.ImeSetInputScreenPosFn && (g.PlatformImeLastPos.x == FLT_MAX || ImLengthSqr(g.PlatformImeLastPos - g.PlatformImePos) > 0.0001f))
{
g.IO.ImeSetInputScreenPosFn((int)g.PlatformImePos.x, (int)g.PlatformImePos.y);
g.PlatformImeLastPos = g.PlatformImePos;
}
// Hide implicit/fallback "Debug" window if it hasn't been used
g.WithinFrameScopeWithImplicitWindow = false;
if (g.CurrentWindow && !g.CurrentWindow->WriteAccessed)
g.CurrentWindow->Active = false;
End();
// Update navigation: CTRL+Tab, wrap-around requests
NavEndFrame();
// Drag and Drop: Elapse payload (if delivered, or if source stops being submitted)
if (g.DragDropActive)
{
bool is_delivered = g.DragDropPayload.Delivery;
bool is_elapsed = (g.DragDropPayload.DataFrameCount + 1 < g.FrameCount) && ((g.DragDropSourceFlags & ImGuiDragDropFlags_SourceAutoExpirePayload) || !IsMouseDown(g.DragDropMouseButton));
if (is_delivered || is_elapsed)
ClearDragDrop();
}
// Drag and Drop: Fallback for source tooltip. This is not ideal but better than nothing.
if (g.DragDropActive && g.DragDropSourceFrameCount < g.FrameCount && !(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
{
g.DragDropWithinSource = true;
SetTooltip("...");
g.DragDropWithinSource = false;
}
// End frame
g.WithinFrameScope = false;
g.FrameCountEnded = g.FrameCount;
// Initiate moving window + handle left-click and right-click focus
UpdateMouseMovingWindowEndFrame();
// Sort the window list so that all child windows are after their parent
// We cannot do that on FocusWindow() because children may not exist yet
g.WindowsTempSortBuffer.resize(0);
g.WindowsTempSortBuffer.reserve(g.Windows.Size);
for (int i = 0; i != g.Windows.Size; i++)
{
ImGuiWindow* window = g.Windows[i];
if (window->Active && (window->Flags & ImGuiWindowFlags_ChildWindow)) // if a child is active its parent will add it
continue;
AddWindowToSortBuffer(&g.WindowsTempSortBuffer, window);
}
// This usually assert if there is a mismatch between the ImGuiWindowFlags_ChildWindow / ParentWindow values and DC.ChildWindows[] in parents, aka we've done something wrong.
IM_ASSERT(g.Windows.Size == g.WindowsTempSortBuffer.Size);
g.Windows.swap(g.WindowsTempSortBuffer);
g.IO.MetricsActiveWindows = g.WindowsActiveCount;
// Unlock font atlas
g.IO.Fonts->Locked = false;
// Clear Input data for next frame
g.IO.MouseWheel = g.IO.MouseWheelH = 0.0f;
g.IO.InputQueueCharacters.resize(0);
memset(g.IO.NavInputs, 0, sizeof(g.IO.NavInputs));
}
void ImGui::Render()
{
ImGuiContext& g = *GImGui;
IM_ASSERT(g.Initialized);
if (g.FrameCountEnded != g.FrameCount)
EndFrame();
g.FrameCountRendered = g.FrameCount;
g.IO.MetricsRenderWindows = 0;
g.DrawDataBuilder.Clear();
// Add background ImDrawList
if (!g.BackgroundDrawList.VtxBuffer.empty())
AddDrawListToDrawData(&g.DrawDataBuilder.Layers[0], &g.BackgroundDrawList);
// Add ImDrawList to render
ImGuiWindow* windows_to_render_top_most[2];
windows_to_render_top_most[0] = (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus)) ? g.NavWindowingTarget->RootWindow : NULL;
windows_to_render_top_most[1] = (g.NavWindowingTarget ? g.NavWindowingListWindow : NULL);
for (int n = 0; n != g.Windows.Size; n++)
{
ImGuiWindow* window = g.Windows[n];
if (IsWindowActiveAndVisible(window) && (window->Flags & ImGuiWindowFlags_ChildWindow) == 0 && window != windows_to_render_top_most[0] && window != windows_to_render_top_most[1])
AddRootWindowToDrawData(window);
}
for (int n = 0; n < IM_ARRAYSIZE(windows_to_render_top_most); n++)
if (windows_to_render_top_most[n] && IsWindowActiveAndVisible(windows_to_render_top_most[n])) // NavWindowingTarget is always temporarily displayed as the top-most window
AddRootWindowToDrawData(windows_to_render_top_most[n]);
g.DrawDataBuilder.FlattenIntoSingleLayer();
// Draw software mouse cursor if requested
if (g.IO.MouseDrawCursor)
RenderMouseCursor(&g.ForegroundDrawList, g.IO.MousePos, g.Style.MouseCursorScale, g.MouseCursor, IM_COL32_WHITE, IM_COL32_BLACK, IM_COL32(0, 0, 0, 48));
// Add foreground ImDrawList
if (!g.ForegroundDrawList.VtxBuffer.empty())
AddDrawListToDrawData(&g.DrawDataBuilder.Layers[0], &g.ForegroundDrawList);
// Setup ImDrawData structure for end-user
SetupDrawData(&g.DrawDataBuilder.Layers[0], &g.DrawData);
g.IO.MetricsRenderVertices = g.DrawData.TotalVtxCount;
g.IO.MetricsRenderIndices = g.DrawData.TotalIdxCount;
// (Legacy) Call the Render callback function. The current prefer way is to let the user retrieve GetDrawData() and call the render function themselves.
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
if (g.DrawData.CmdListsCount > 0 && g.IO.RenderDrawListsFn != NULL)
g.IO.RenderDrawListsFn(&g.DrawData);
#endif
}
// Calculate text size. Text can be multi-line. Optionally ignore text after a ## marker.
// CalcTextSize("") should return ImVec2(0.0f, g.FontSize)
ImVec2 ImGui::CalcTextSize(const char* text, const char* text_end, bool hide_text_after_double_hash, float wrap_width)
{
ImGuiContext& g = *GImGui;
const char* text_display_end;
if (hide_text_after_double_hash)
text_display_end = FindRenderedTextEnd(text, text_end); // Hide anything after a '##' string
else
text_display_end = text_end;
ImFont* font = g.Font;
const float font_size = g.FontSize;
if (text == text_display_end)
return ImVec2(0.0f, font_size);
ImVec2 text_size = font->CalcTextSizeA(font_size, FLT_MAX, wrap_width, text, text_display_end, NULL);
// Round
text_size.x = IM_FLOOR(text_size.x + 0.95f);
return text_size;
}
// Find window given position, search front-to-back
// FIXME: Note that we have an inconsequential lag here: OuterRectClipped is updated in Begin(), so windows moved programmatically
// with SetWindowPos() and not SetNextWindowPos() will have that rectangle lagging by a frame at the time FindHoveredWindow() is
// called, aka before the next Begin(). Moving window isn't affected.
static void FindHoveredWindow()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* hovered_window = NULL;
ImGuiWindow* hovered_window_ignoring_moving_window = NULL;
if (g.MovingWindow && !(g.MovingWindow->Flags & ImGuiWindowFlags_NoMouseInputs))
hovered_window = g.MovingWindow;
ImVec2 padding_regular = g.Style.TouchExtraPadding;
ImVec2 padding_for_resize_from_edges = g.IO.ConfigWindowsResizeFromEdges ? ImMax(g.Style.TouchExtraPadding, ImVec2(WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS, WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS)) : padding_regular;
for (int i = g.Windows.Size - 1; i >= 0; i--)
{
ImGuiWindow* window = g.Windows[i];
if (!window->Active || window->Hidden)
continue;
if (window->Flags & ImGuiWindowFlags_NoMouseInputs)
continue;
// Using the clipped AABB, a child window will typically be clipped by its parent (not always)
ImRect bb(window->OuterRectClipped);
if (window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_AlwaysAutoResize))
bb.Expand(padding_regular);
else
bb.Expand(padding_for_resize_from_edges);
if (!bb.Contains(g.IO.MousePos))
continue;
// Support for one rectangular hole in any given window
// FIXME: Consider generalizing hit-testing override (with more generic data, callback, etc.) (#1512)
if (window->HitTestHoleSize.x != 0)
{
ImVec2 hole_pos(window->Pos.x + (float)window->HitTestHoleOffset.x, window->Pos.y + (float)window->HitTestHoleOffset.y);
ImVec2 hole_size((float)window->HitTestHoleSize.x, (float)window->HitTestHoleSize.y);
if (ImRect(hole_pos, hole_pos + hole_size).Contains(g.IO.MousePos))
continue;
}
if (hovered_window == NULL)
hovered_window = window;
if (hovered_window_ignoring_moving_window == NULL && (!g.MovingWindow || window->RootWindow != g.MovingWindow->RootWindow))
hovered_window_ignoring_moving_window = window;
if (hovered_window && hovered_window_ignoring_moving_window)
break;
}
g.HoveredWindow = hovered_window;
g.HoveredRootWindow = g.HoveredWindow ? g.HoveredWindow->RootWindow : NULL;
g.HoveredWindowUnderMovingWindow = hovered_window_ignoring_moving_window;
}
// Test if mouse cursor is hovering given rectangle
// NB- Rectangle is clipped by our current clip setting
// NB- Expand the rectangle to be generous on imprecise inputs systems (g.Style.TouchExtraPadding)
bool ImGui::IsMouseHoveringRect(const ImVec2& r_min, const ImVec2& r_max, bool clip)
{
ImGuiContext& g = *GImGui;
// Clip
ImRect rect_clipped(r_min, r_max);
if (clip)
rect_clipped.ClipWith(g.CurrentWindow->ClipRect);
// Expand for touch input
const ImRect rect_for_touch(rect_clipped.Min - g.Style.TouchExtraPadding, rect_clipped.Max + g.Style.TouchExtraPadding);
if (!rect_for_touch.Contains(g.IO.MousePos))
return false;
return true;
}
int ImGui::GetKeyIndex(ImGuiKey imgui_key)
{
IM_ASSERT(imgui_key >= 0 && imgui_key < ImGuiKey_COUNT);
ImGuiContext& g = *GImGui;
return g.IO.KeyMap[imgui_key];
}
// Note that dear imgui doesn't know the semantic of each entry of io.KeysDown[]!
// Use your own indices/enums according to how your back-end/engine stored them into io.KeysDown[]!
bool ImGui::IsKeyDown(int user_key_index)
{
if (user_key_index < 0)
return false;
ImGuiContext& g = *GImGui;
IM_ASSERT(user_key_index >= 0 && user_key_index < IM_ARRAYSIZE(g.IO.KeysDown));
return g.IO.KeysDown[user_key_index];
}
// t0 = previous time (e.g.: g.Time - g.IO.DeltaTime)
// t1 = current time (e.g.: g.Time)
// An event is triggered at:
// t = 0.0f t = repeat_delay, t = repeat_delay + repeat_rate*N
int ImGui::CalcTypematicRepeatAmount(float t0, float t1, float repeat_delay, float repeat_rate)
{
if (t1 == 0.0f)
return 1;
if (t0 >= t1)
return 0;
if (repeat_rate <= 0.0f)
return (t0 < repeat_delay) && (t1 >= repeat_delay);
const int count_t0 = (t0 < repeat_delay) ? -1 : (int)((t0 - repeat_delay) / repeat_rate);
const int count_t1 = (t1 < repeat_delay) ? -1 : (int)((t1 - repeat_delay) / repeat_rate);
const int count = count_t1 - count_t0;
return count;
}
int ImGui::GetKeyPressedAmount(int key_index, float repeat_delay, float repeat_rate)
{
ImGuiContext& g = *GImGui;
if (key_index < 0)
return 0;
IM_ASSERT(key_index >= 0 && key_index < IM_ARRAYSIZE(g.IO.KeysDown));
const float t = g.IO.KeysDownDuration[key_index];
return CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, repeat_delay, repeat_rate);
}
bool ImGui::IsKeyPressed(int user_key_index, bool repeat)
{
ImGuiContext& g = *GImGui;
if (user_key_index < 0)
return false;
IM_ASSERT(user_key_index >= 0 && user_key_index < IM_ARRAYSIZE(g.IO.KeysDown));
const float t = g.IO.KeysDownDuration[user_key_index];
if (t == 0.0f)
return true;
if (repeat && t > g.IO.KeyRepeatDelay)
return GetKeyPressedAmount(user_key_index, g.IO.KeyRepeatDelay, g.IO.KeyRepeatRate) > 0;
return false;
}
bool ImGui::IsKeyReleased(int user_key_index)
{
ImGuiContext& g = *GImGui;
if (user_key_index < 0) return false;
IM_ASSERT(user_key_index >= 0 && user_key_index < IM_ARRAYSIZE(g.IO.KeysDown));
return g.IO.KeysDownDurationPrev[user_key_index] >= 0.0f && !g.IO.KeysDown[user_key_index];
}
bool ImGui::IsMouseDown(ImGuiMouseButton button)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
return g.IO.MouseDown[button];
}
bool ImGui::IsMouseClicked(ImGuiMouseButton button, bool repeat)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
const float t = g.IO.MouseDownDuration[button];
if (t == 0.0f)
return true;
if (repeat && t > g.IO.KeyRepeatDelay)
{
// FIXME: 2019/05/03: Our old repeat code was wrong here and led to doubling the repeat rate, which made it an ok rate for repeat on mouse hold.
int amount = CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, g.IO.KeyRepeatDelay, g.IO.KeyRepeatRate * 0.50f);
if (amount > 0)
return true;
}
return false;
}
bool ImGui::IsMouseReleased(ImGuiMouseButton button)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
return g.IO.MouseReleased[button];
}
bool ImGui::IsMouseDoubleClicked(ImGuiMouseButton button)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
return g.IO.MouseDoubleClicked[button];
}
// Return if a mouse click/drag went past the given threshold. Valid to call during the MouseReleased frame.
// [Internal] This doesn't test if the button is pressed
bool ImGui::IsMouseDragPastThreshold(ImGuiMouseButton button, float lock_threshold)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
if (lock_threshold < 0.0f)
lock_threshold = g.IO.MouseDragThreshold;
return g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold;
}
bool ImGui::IsMouseDragging(ImGuiMouseButton button, float lock_threshold)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
if (!g.IO.MouseDown[button])
return false;
return IsMouseDragPastThreshold(button, lock_threshold);
}
ImVec2 ImGui::GetMousePos()
{
ImGuiContext& g = *GImGui;
return g.IO.MousePos;
}
// NB: prefer to call right after BeginPopup(). At the time Selectable/MenuItem is activated, the popup is already closed!
ImVec2 ImGui::GetMousePosOnOpeningCurrentPopup()
{
ImGuiContext& g = *GImGui;
if (g.BeginPopupStack.Size > 0)
return g.OpenPopupStack[g.BeginPopupStack.Size - 1].OpenMousePos;
return g.IO.MousePos;
}
// We typically use ImVec2(-FLT_MAX,-FLT_MAX) to denote an invalid mouse position.
bool ImGui::IsMousePosValid(const ImVec2* mouse_pos)
{
// The assert is only to silence a false-positive in XCode Static Analysis.
// Because GImGui is not dereferenced in every code path, the static analyzer assume that it may be NULL (which it doesn't for other functions).
IM_ASSERT(GImGui != NULL);
const float MOUSE_INVALID = -256000.0f;
ImVec2 p = mouse_pos ? *mouse_pos : GImGui->IO.MousePos;
return p.x >= MOUSE_INVALID && p.y >= MOUSE_INVALID;
}
bool ImGui::IsAnyMouseDown()
{
ImGuiContext& g = *GImGui;
for (int n = 0; n < IM_ARRAYSIZE(g.IO.MouseDown); n++)
if (g.IO.MouseDown[n])
return true;
return false;
}
// Return the delta from the initial clicking position while the mouse button is clicked or was just released.
// This is locked and return 0.0f until the mouse moves past a distance threshold at least once.
// NB: This is only valid if IsMousePosValid(). Back-ends in theory should always keep mouse position valid when dragging even outside the client window.
ImVec2 ImGui::GetMouseDragDelta(ImGuiMouseButton button, float lock_threshold)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
if (lock_threshold < 0.0f)
lock_threshold = g.IO.MouseDragThreshold;
if (g.IO.MouseDown[button] || g.IO.MouseReleased[button])
if (g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold)
if (IsMousePosValid(&g.IO.MousePos) && IsMousePosValid(&g.IO.MouseClickedPos[button]))
return g.IO.MousePos - g.IO.MouseClickedPos[button];
return ImVec2(0.0f, 0.0f);
}
void ImGui::ResetMouseDragDelta(ImGuiMouseButton button)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
// NB: We don't need to reset g.IO.MouseDragMaxDistanceSqr
g.IO.MouseClickedPos[button] = g.IO.MousePos;
}
ImGuiMouseCursor ImGui::GetMouseCursor()
{
return GImGui->MouseCursor;
}
void ImGui::SetMouseCursor(ImGuiMouseCursor cursor_type)
{
GImGui->MouseCursor = cursor_type;
}
void ImGui::CaptureKeyboardFromApp(bool capture)
{
GImGui->WantCaptureKeyboardNextFrame = capture ? 1 : 0;
}
void ImGui::CaptureMouseFromApp(bool capture)
{
GImGui->WantCaptureMouseNextFrame = capture ? 1 : 0;
}
bool ImGui::IsItemActive()
{
ImGuiContext& g = *GImGui;
if (g.ActiveId)
{
ImGuiWindow* window = g.CurrentWindow;
return g.ActiveId == window->DC.LastItemId;
}
return false;
}
bool ImGui::IsItemActivated()
{
ImGuiContext& g = *GImGui;
if (g.ActiveId)
{
ImGuiWindow* window = g.CurrentWindow;
if (g.ActiveId == window->DC.LastItemId && g.ActiveIdPreviousFrame != window->DC.LastItemId)
return true;
}
return false;
}
bool ImGui::IsItemDeactivated()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_HasDeactivated)
return (window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_Deactivated) != 0;
return (g.ActiveIdPreviousFrame == window->DC.LastItemId && g.ActiveIdPreviousFrame != 0 && g.ActiveId != window->DC.LastItemId);
}
bool ImGui::IsItemDeactivatedAfterEdit()
{
ImGuiContext& g = *GImGui;
return IsItemDeactivated() && (g.ActiveIdPreviousFrameHasBeenEditedBefore || (g.ActiveId == 0 && g.ActiveIdHasBeenEditedBefore));
}
bool ImGui::IsItemFocused()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (g.NavId == 0 || g.NavDisableHighlight || g.NavId != window->DC.LastItemId)
return false;
return true;
}
bool ImGui::IsItemClicked(ImGuiMouseButton mouse_button)
{
return IsMouseClicked(mouse_button) && IsItemHovered(ImGuiHoveredFlags_None);
}
bool ImGui::IsItemToggledOpen()
{
ImGuiContext& g = *GImGui;
return (g.CurrentWindow->DC.LastItemStatusFlags & ImGuiItemStatusFlags_ToggledOpen) ? true : false;
}
bool ImGui::IsItemToggledSelection()
{
ImGuiContext& g = *GImGui;
return (g.CurrentWindow->DC.LastItemStatusFlags & ImGuiItemStatusFlags_ToggledSelection) ? true : false;
}
bool ImGui::IsAnyItemHovered()
{
ImGuiContext& g = *GImGui;
return g.HoveredId != 0 || g.HoveredIdPreviousFrame != 0;
}
bool ImGui::IsAnyItemActive()
{
ImGuiContext& g = *GImGui;
return g.ActiveId != 0;
}
bool ImGui::IsAnyItemFocused()
{
ImGuiContext& g = *GImGui;
return g.NavId != 0 && !g.NavDisableHighlight;
}
bool ImGui::IsItemVisible()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->ClipRect.Overlaps(window->DC.LastItemRect);
}
bool ImGui::IsItemEdited()
{
ImGuiWindow* window = GetCurrentWindowRead();
return (window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_Edited) != 0;
}
// Allow last item to be overlapped by a subsequent item. Both may be activated during the same frame before the later one takes priority.
void ImGui::SetItemAllowOverlap()
{
ImGuiContext& g = *GImGui;
if (g.HoveredId == g.CurrentWindow->DC.LastItemId)
g.HoveredIdAllowOverlap = true;
if (g.ActiveId == g.CurrentWindow->DC.LastItemId)
g.ActiveIdAllowOverlap = true;
}
ImVec2 ImGui::GetItemRectMin()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->DC.LastItemRect.Min;
}
ImVec2 ImGui::GetItemRectMax()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->DC.LastItemRect.Max;
}
ImVec2 ImGui::GetItemRectSize()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->DC.LastItemRect.GetSize();
}
static ImRect GetViewportRect()
{
ImGuiContext& g = *GImGui;
return ImRect(0.0f, 0.0f, g.IO.DisplaySize.x, g.IO.DisplaySize.y);
}
bool ImGui::BeginChildEx(const char* name, ImGuiID id, const ImVec2& size_arg, bool border, ImGuiWindowFlags flags)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* parent_window = g.CurrentWindow;
flags |= ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_ChildWindow;
flags |= (parent_window->Flags & ImGuiWindowFlags_NoMove); // Inherit the NoMove flag
// Size
const ImVec2 content_avail = GetContentRegionAvail();
ImVec2 size = ImFloor(size_arg);
const int auto_fit_axises = ((size.x == 0.0f) ? (1 << ImGuiAxis_X) : 0x00) | ((size.y == 0.0f) ? (1 << ImGuiAxis_Y) : 0x00);
if (size.x <= 0.0f)
size.x = ImMax(content_avail.x + size.x, 4.0f); // Arbitrary minimum child size (0.0f causing too much issues)
if (size.y <= 0.0f)
size.y = ImMax(content_avail.y + size.y, 4.0f);
SetNextWindowSize(size);
// Build up name. If you need to append to a same child from multiple location in the ID stack, use BeginChild(ImGuiID id) with a stable value.
char title[256];
if (name)
ImFormatString(title, IM_ARRAYSIZE(title), "%s/%s_%08X", parent_window->Name, name, id);
else
ImFormatString(title, IM_ARRAYSIZE(title), "%s/%08X", parent_window->Name, id);
const float backup_border_size = g.Style.ChildBorderSize;
if (!border)
g.Style.ChildBorderSize = 0.0f;
bool ret = Begin(title, NULL, flags);
g.Style.ChildBorderSize = backup_border_size;
ImGuiWindow* child_window = g.CurrentWindow;
child_window->ChildId = id;
child_window->AutoFitChildAxises = (ImS8)auto_fit_axises;
// Set the cursor to handle case where the user called SetNextWindowPos()+BeginChild() manually.
// While this is not really documented/defined, it seems that the expected thing to do.
if (child_window->BeginCount == 1)
parent_window->DC.CursorPos = child_window->Pos;
// Process navigation-in immediately so NavInit can run on first frame
if (g.NavActivateId == id && !(flags & ImGuiWindowFlags_NavFlattened) && (child_window->DC.NavLayerActiveMask != 0 || child_window->DC.NavHasScroll))
{
FocusWindow(child_window);
NavInitWindow(child_window, false);
SetActiveID(id + 1, child_window); // Steal ActiveId with another arbitrary id so that key-press won't activate child item
g.ActiveIdSource = ImGuiInputSource_Nav;
}
return ret;
}
bool ImGui::BeginChild(const char* str_id, const ImVec2& size_arg, bool border, ImGuiWindowFlags extra_flags)
{
ImGuiWindow* window = GetCurrentWindow();
return BeginChildEx(str_id, window->GetID(str_id), size_arg, border, extra_flags);
}
bool ImGui::BeginChild(ImGuiID id, const ImVec2& size_arg, bool border, ImGuiWindowFlags extra_flags)
{
IM_ASSERT(id != 0);
return BeginChildEx(NULL, id, size_arg, border, extra_flags);
}
void ImGui::EndChild()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
IM_ASSERT(g.WithinEndChild == false);
IM_ASSERT(window->Flags & ImGuiWindowFlags_ChildWindow); // Mismatched BeginChild()/EndChild() calls
g.WithinEndChild = true;
if (window->BeginCount > 1)
{
End();
}
else
{
ImVec2 sz = window->Size;
if (window->AutoFitChildAxises & (1 << ImGuiAxis_X)) // Arbitrary minimum zero-ish child size of 4.0f causes less trouble than a 0.0f
sz.x = ImMax(4.0f, sz.x);
if (window->AutoFitChildAxises & (1 << ImGuiAxis_Y))
sz.y = ImMax(4.0f, sz.y);
End();
ImGuiWindow* parent_window = g.CurrentWindow;
ImRect bb(parent_window->DC.CursorPos, parent_window->DC.CursorPos + sz);
ItemSize(sz);
if ((window->DC.NavLayerActiveMask != 0 || window->DC.NavHasScroll) && !(window->Flags & ImGuiWindowFlags_NavFlattened))
{
ItemAdd(bb, window->ChildId);
RenderNavHighlight(bb, window->ChildId);
// When browsing a window that has no activable items (scroll only) we keep a highlight on the child
if (window->DC.NavLayerActiveMask == 0 && window == g.NavWindow)
RenderNavHighlight(ImRect(bb.Min - ImVec2(2, 2), bb.Max + ImVec2(2, 2)), g.NavId, ImGuiNavHighlightFlags_TypeThin);
}
else
{
// Not navigable into
ItemAdd(bb, 0);
}
}
g.WithinEndChild = false;
}
// Helper to create a child window / scrolling region that looks like a normal widget frame.
bool ImGui::BeginChildFrame(ImGuiID id, const ImVec2& size, ImGuiWindowFlags extra_flags)
{
ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
PushStyleColor(ImGuiCol_ChildBg, style.Colors[ImGuiCol_FrameBg]);
PushStyleVar(ImGuiStyleVar_ChildRounding, style.FrameRounding);
PushStyleVar(ImGuiStyleVar_ChildBorderSize, style.FrameBorderSize);
PushStyleVar(ImGuiStyleVar_WindowPadding, style.FramePadding);
bool ret = BeginChild(id, size, true, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_AlwaysUseWindowPadding | extra_flags);
PopStyleVar(3);
PopStyleColor();
return ret;
}
void ImGui::EndChildFrame()
{
EndChild();
}
static void SetWindowConditionAllowFlags(ImGuiWindow* window, ImGuiCond flags, bool enabled)
{
window->SetWindowPosAllowFlags = enabled ? (window->SetWindowPosAllowFlags | flags) : (window->SetWindowPosAllowFlags & ~flags);
window->SetWindowSizeAllowFlags = enabled ? (window->SetWindowSizeAllowFlags | flags) : (window->SetWindowSizeAllowFlags & ~flags);
window->SetWindowCollapsedAllowFlags = enabled ? (window->SetWindowCollapsedAllowFlags | flags) : (window->SetWindowCollapsedAllowFlags & ~flags);
}
ImGuiWindow* ImGui::FindWindowByID(ImGuiID id)
{
ImGuiContext& g = *GImGui;
return (ImGuiWindow*)g.WindowsById.GetVoidPtr(id);
}
ImGuiWindow* ImGui::FindWindowByName(const char* name)
{
ImGuiID id = ImHashStr(name);
return FindWindowByID(id);
}
static void ApplyWindowSettings(ImGuiWindow* window, ImGuiWindowSettings* settings)
{
window->Pos = ImFloor(ImVec2(settings->Pos.x, settings->Pos.y));
if (settings->Size.x > 0 && settings->Size.y > 0)
window->Size = window->SizeFull = ImFloor(ImVec2(settings->Size.x, settings->Size.y));
window->Collapsed = settings->Collapsed;
}
static ImGuiWindow* CreateNewWindow(const char* name, ImGuiWindowFlags flags)
{
ImGuiContext& g = *GImGui;
//IMGUI_DEBUG_LOG("CreateNewWindow '%s', flags = 0x%08X\n", name, flags);
// Create window the first time
ImGuiWindow* window = IM_NEW(ImGuiWindow)(&g, name);
window->Flags = flags;
g.WindowsById.SetVoidPtr(window->ID, window);
// Default/arbitrary window position. Use SetNextWindowPos() with the appropriate condition flag to change the initial position of a window.
window->Pos = ImVec2(60, 60);
// User can disable loading and saving of settings. Tooltip and child windows also don't store settings.
if (!(flags & ImGuiWindowFlags_NoSavedSettings))
if (ImGuiWindowSettings* settings = ImGui::FindWindowSettings(window->ID))
{
// Retrieve settings from .ini file
window->SettingsOffset = g.SettingsWindows.offset_from_ptr(settings);
SetWindowConditionAllowFlags(window, ImGuiCond_FirstUseEver, false);
ApplyWindowSettings(window, settings);
}
window->DC.CursorStartPos = window->DC.CursorMaxPos = window->Pos; // So first call to CalcContentSize() doesn't return crazy values
if ((flags & ImGuiWindowFlags_AlwaysAutoResize) != 0)
{
window->AutoFitFramesX = window->AutoFitFramesY = 2;
window->AutoFitOnlyGrows = false;
}
else
{
if (window->Size.x <= 0.0f)
window->AutoFitFramesX = 2;
if (window->Size.y <= 0.0f)
window->AutoFitFramesY = 2;
window->AutoFitOnlyGrows = (window->AutoFitFramesX > 0) || (window->AutoFitFramesY > 0);
}
g.WindowsFocusOrder.push_back(window);
if (flags & ImGuiWindowFlags_NoBringToFrontOnFocus)
g.Windows.push_front(window); // Quite slow but rare and only once
else
g.Windows.push_back(window);
return window;
}
static ImVec2 CalcWindowSizeAfterConstraint(ImGuiWindow* window, ImVec2 new_size)
{
ImGuiContext& g = *GImGui;
if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSizeConstraint)
{
// Using -1,-1 on either X/Y axis to preserve the current size.
ImRect cr = g.NextWindowData.SizeConstraintRect;
new_size.x = (cr.Min.x >= 0 && cr.Max.x >= 0) ? ImClamp(new_size.x, cr.Min.x, cr.Max.x) : window->SizeFull.x;
new_size.y = (cr.Min.y >= 0 && cr.Max.y >= 0) ? ImClamp(new_size.y, cr.Min.y, cr.Max.y) : window->SizeFull.y;
if (g.NextWindowData.SizeCallback)
{
ImGuiSizeCallbackData data;
data.UserData = g.NextWindowData.SizeCallbackUserData;
data.Pos = window->Pos;
data.CurrentSize = window->SizeFull;
data.DesiredSize = new_size;
g.NextWindowData.SizeCallback(&data);
new_size = data.DesiredSize;
}
new_size.x = IM_FLOOR(new_size.x);
new_size.y = IM_FLOOR(new_size.y);
}
// Minimum size
if (!(window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_AlwaysAutoResize)))
{
ImGuiWindow* window_for_height = window;
new_size = ImMax(new_size, g.Style.WindowMinSize);
new_size.y = ImMax(new_size.y, window_for_height->TitleBarHeight() + window_for_height->MenuBarHeight() + ImMax(0.0f, g.Style.WindowRounding - 1.0f)); // Reduce artifacts with very small windows
}
return new_size;
}
static ImVec2 CalcWindowContentSize(ImGuiWindow* window)
{
if (window->Collapsed)
if (window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0)
return window->ContentSize;
if (window->Hidden && window->HiddenFramesCannotSkipItems == 0 && window->HiddenFramesCanSkipItems > 0)
return window->ContentSize;
ImVec2 sz;
sz.x = IM_FLOOR((window->ContentSizeExplicit.x != 0.0f) ? window->ContentSizeExplicit.x : window->DC.CursorMaxPos.x - window->DC.CursorStartPos.x);
sz.y = IM_FLOOR((window->ContentSizeExplicit.y != 0.0f) ? window->ContentSizeExplicit.y : window->DC.CursorMaxPos.y - window->DC.CursorStartPos.y);
return sz;
}
static ImVec2 CalcWindowAutoFitSize(ImGuiWindow* window, const ImVec2& size_contents)
{
ImGuiContext& g = *GImGui;
ImGuiStyle& style = g.Style;
ImVec2 size_decorations = ImVec2(0.0f, window->TitleBarHeight() + window->MenuBarHeight());
ImVec2 size_pad = window->WindowPadding * 2.0f;
ImVec2 size_desired = size_contents + size_pad + size_decorations;
if (window->Flags & ImGuiWindowFlags_Tooltip)
{
// Tooltip always resize
return size_desired;
}
else
{
// Maximum window size is determined by the viewport size or monitor size
const bool is_popup = (window->Flags & ImGuiWindowFlags_Popup) != 0;
const bool is_menu = (window->Flags & ImGuiWindowFlags_ChildMenu) != 0;
ImVec2 size_min = style.WindowMinSize;
if (is_popup || is_menu) // Popups and menus bypass style.WindowMinSize by default, but we give then a non-zero minimum size to facilitate understanding problematic cases (e.g. empty popups)
size_min = ImMin(size_min, ImVec2(4.0f, 4.0f));
ImVec2 size_auto_fit = ImClamp(size_desired, size_min, ImMax(size_min, g.IO.DisplaySize - style.DisplaySafeAreaPadding * 2.0f));
// When the window cannot fit all contents (either because of constraints, either because screen is too small),
// we are growing the size on the other axis to compensate for expected scrollbar. FIXME: Might turn bigger than ViewportSize-WindowPadding.
ImVec2 size_auto_fit_after_constraint = CalcWindowSizeAfterConstraint(window, size_auto_fit);
bool will_have_scrollbar_x = (size_auto_fit_after_constraint.x - size_pad.x - size_decorations.x < size_contents.x && !(window->Flags & ImGuiWindowFlags_NoScrollbar) && (window->Flags & ImGuiWindowFlags_HorizontalScrollbar)) || (window->Flags & ImGuiWindowFlags_AlwaysHorizontalScrollbar);
bool will_have_scrollbar_y = (size_auto_fit_after_constraint.y - size_pad.y - size_decorations.y < size_contents.y && !(window->Flags & ImGuiWindowFlags_NoScrollbar)) || (window->Flags & ImGuiWindowFlags_AlwaysVerticalScrollbar);
if (will_have_scrollbar_x)
size_auto_fit.y += style.ScrollbarSize;
if (will_have_scrollbar_y)
size_auto_fit.x += style.ScrollbarSize;
return size_auto_fit;
}
}
ImVec2 ImGui::CalcWindowExpectedSize(ImGuiWindow* window)
{
ImVec2 size_contents = CalcWindowContentSize(window);
ImVec2 size_auto_fit = CalcWindowAutoFitSize(window, size_contents);
ImVec2 size_final = CalcWindowSizeAfterConstraint(window, size_auto_fit);
return size_final;
}
static ImGuiCol GetWindowBgColorIdxFromFlags(ImGuiWindowFlags flags)
{
if (flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup))
return ImGuiCol_PopupBg;
if (flags & ImGuiWindowFlags_ChildWindow)
return ImGuiCol_ChildBg;
return ImGuiCol_WindowBg;
}
static void CalcResizePosSizeFromAnyCorner(ImGuiWindow* window, const ImVec2& corner_target, const ImVec2& corner_norm, ImVec2* out_pos, ImVec2* out_size)
{
ImVec2 pos_min = ImLerp(corner_target, window->Pos, corner_norm); // Expected window upper-left
ImVec2 pos_max = ImLerp(window->Pos + window->Size, corner_target, corner_norm); // Expected window lower-right
ImVec2 size_expected = pos_max - pos_min;
ImVec2 size_constrained = CalcWindowSizeAfterConstraint(window, size_expected);
*out_pos = pos_min;
if (corner_norm.x == 0.0f)
out_pos->x -= (size_constrained.x - size_expected.x);
if (corner_norm.y == 0.0f)
out_pos->y -= (size_constrained.y - size_expected.y);
*out_size = size_constrained;
}
struct ImGuiResizeGripDef
{
ImVec2 CornerPosN;
ImVec2 InnerDir;
int AngleMin12, AngleMax12;
};
static const ImGuiResizeGripDef resize_grip_def[4] =
{
{ ImVec2(1, 1), ImVec2(-1, -1), 0, 3 }, // Lower-right
{ ImVec2(0, 1), ImVec2(+1, -1), 3, 6 }, // Lower-left
{ ImVec2(0, 0), ImVec2(+1, +1), 6, 9 }, // Upper-left (Unused)
{ ImVec2(1, 0), ImVec2(-1, +1), 9, 12 }, // Upper-right (Unused)
};
struct ImGuiResizeBorderDef
{
ImVec2 InnerDir;
ImVec2 CornerPosN1, CornerPosN2;
float OuterAngle;
};
static const ImGuiResizeBorderDef resize_border_def[4] =
{
{ ImVec2(0, +1), ImVec2(0, 0), ImVec2(1, 0), IM_PI * 1.50f }, // Top
{ ImVec2(-1, 0), ImVec2(1, 0), ImVec2(1, 1), IM_PI * 0.00f }, // Right
{ ImVec2(0, -1), ImVec2(1, 1), ImVec2(0, 1), IM_PI * 0.50f }, // Bottom
{ ImVec2(+1, 0), ImVec2(0, 1), ImVec2(0, 0), IM_PI * 1.00f } // Left
};
static ImRect GetResizeBorderRect(ImGuiWindow* window, int border_n, float perp_padding, float thickness)
{
ImRect rect = window->Rect();
if (thickness == 0.0f) rect.Max -= ImVec2(1, 1);
if (border_n == 0) { return ImRect(rect.Min.x + perp_padding, rect.Min.y - thickness, rect.Max.x - perp_padding, rect.Min.y + thickness); } // Top
if (border_n == 1) { return ImRect(rect.Max.x - thickness, rect.Min.y + perp_padding, rect.Max.x + thickness, rect.Max.y - perp_padding); } // Right
if (border_n == 2) { return ImRect(rect.Min.x + perp_padding, rect.Max.y - thickness, rect.Max.x - perp_padding, rect.Max.y + thickness); } // Bottom
if (border_n == 3) { return ImRect(rect.Min.x - thickness, rect.Min.y + perp_padding, rect.Min.x + thickness, rect.Max.y - perp_padding); } // Left
IM_ASSERT(0);
return ImRect();
}
// 0..3: corners (Lower-right, Lower-left, Unused, Unused)
// 4..7: borders (Top, Right, Bottom, Left)
ImGuiID ImGui::GetWindowResizeID(ImGuiWindow* window, int n)
{
IM_ASSERT(n >= 0 && n <= 7);
ImGuiID id = window->ID;
id = ImHashStr("#RESIZE", 0, id);
id = ImHashData(&n, sizeof(int), id);
return id;
}
// Handle resize for: Resize Grips, Borders, Gamepad
// Return true when using auto-fit (double click on resize grip)
static bool ImGui::UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4], const ImRect& visibility_rect)
{
ImGuiContext& g = *GImGui;
ImGuiWindowFlags flags = window->Flags;
if ((flags & ImGuiWindowFlags_NoResize) || (flags & ImGuiWindowFlags_AlwaysAutoResize) || window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
return false;
if (window->WasActive == false) // Early out to avoid running this code for e.g. an hidden implicit/fallback Debug window.
return false;
bool ret_auto_fit = false;
const int resize_border_count = g.IO.ConfigWindowsResizeFromEdges ? 4 : 0;
const float grip_draw_size = IM_FLOOR(ImMax(g.FontSize * 1.35f, window->WindowRounding + 1.0f + g.FontSize * 0.2f));
const float grip_hover_inner_size = IM_FLOOR(grip_draw_size * 0.75f);
const float grip_hover_outer_size = g.IO.ConfigWindowsResizeFromEdges ? WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS : 0.0f;
ImVec2 pos_target(FLT_MAX, FLT_MAX);
ImVec2 size_target(FLT_MAX, FLT_MAX);
// Resize grips and borders are on layer 1
window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
window->DC.NavLayerCurrentMask = (1 << ImGuiNavLayer_Menu);
// Manual resize grips
PushID("#RESIZE");
for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++)
{
const ImGuiResizeGripDef& grip = resize_grip_def[resize_grip_n];
const ImVec2 corner = ImLerp(window->Pos, window->Pos + window->Size, grip.CornerPosN);
// Using the FlattenChilds button flag we make the resize button accessible even if we are hovering over a child window
ImRect resize_rect(corner - grip.InnerDir * grip_hover_outer_size, corner + grip.InnerDir * grip_hover_inner_size);
if (resize_rect.Min.x > resize_rect.Max.x) ImSwap(resize_rect.Min.x, resize_rect.Max.x);
if (resize_rect.Min.y > resize_rect.Max.y) ImSwap(resize_rect.Min.y, resize_rect.Max.y);
bool hovered, held;
ButtonBehavior(resize_rect, window->GetID(resize_grip_n), &hovered, &held, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_NoNavFocus);
//GetForegroundDrawList(window)->AddRect(resize_rect.Min, resize_rect.Max, IM_COL32(255, 255, 0, 255));
if (hovered || held)
g.MouseCursor = (resize_grip_n & 1) ? ImGuiMouseCursor_ResizeNESW : ImGuiMouseCursor_ResizeNWSE;
if (held && g.IO.MouseDoubleClicked[0] && resize_grip_n == 0)
{
// Manual auto-fit when double-clicking
size_target = CalcWindowSizeAfterConstraint(window, size_auto_fit);
ret_auto_fit = true;
ClearActiveID();
}
else if (held)
{
// Resize from any of the four corners
// We don't use an incremental MouseDelta but rather compute an absolute target size based on mouse position
ImVec2 corner_target = g.IO.MousePos - g.ActiveIdClickOffset + ImLerp(grip.InnerDir * grip_hover_outer_size, grip.InnerDir * -grip_hover_inner_size, grip.CornerPosN); // Corner of the window corresponding to our corner grip
ImVec2 clamp_min = ImVec2(grip.CornerPosN.x == 1.0f ? visibility_rect.Min.x : -FLT_MAX, grip.CornerPosN.y == 1.0f ? visibility_rect.Min.y : -FLT_MAX);
ImVec2 clamp_max = ImVec2(grip.CornerPosN.x == 0.0f ? visibility_rect.Max.x : +FLT_MAX, grip.CornerPosN.y == 0.0f ? visibility_rect.Max.y : +FLT_MAX);
corner_target = ImClamp(corner_target, clamp_min, clamp_max);
CalcResizePosSizeFromAnyCorner(window, corner_target, grip.CornerPosN, &pos_target, &size_target);
}
if (resize_grip_n == 0 || held || hovered)
resize_grip_col[resize_grip_n] = GetColorU32(held ? ImGuiCol_ResizeGripActive : hovered ? ImGuiCol_ResizeGripHovered : ImGuiCol_ResizeGrip);
}
for (int border_n = 0; border_n < resize_border_count; border_n++)
{
bool hovered, held;
ImRect border_rect = GetResizeBorderRect(window, border_n, grip_hover_inner_size, WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS);
ButtonBehavior(border_rect, window->GetID(border_n + 4), &hovered, &held, ImGuiButtonFlags_FlattenChildren);
//GetForegroundDrawLists(window)->AddRect(border_rect.Min, border_rect.Max, IM_COL32(255, 255, 0, 255));
if ((hovered && g.HoveredIdTimer > WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER) || held)
{
g.MouseCursor = (border_n & 1) ? ImGuiMouseCursor_ResizeEW : ImGuiMouseCursor_ResizeNS;
if (held)
*border_held = border_n;
}
if (held)
{
ImVec2 border_target = window->Pos;
ImVec2 border_posn;
if (border_n == 0) { border_posn = ImVec2(0, 0); border_target.y = (g.IO.MousePos.y - g.ActiveIdClickOffset.y + WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS); } // Top
if (border_n == 1) { border_posn = ImVec2(1, 0); border_target.x = (g.IO.MousePos.x - g.ActiveIdClickOffset.x + WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS); } // Right
if (border_n == 2) { border_posn = ImVec2(0, 1); border_target.y = (g.IO.MousePos.y - g.ActiveIdClickOffset.y + WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS); } // Bottom
if (border_n == 3) { border_posn = ImVec2(0, 0); border_target.x = (g.IO.MousePos.x - g.ActiveIdClickOffset.x + WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS); } // Left
ImVec2 clamp_min = ImVec2(border_n == 1 ? visibility_rect.Min.x : -FLT_MAX, border_n == 2 ? visibility_rect.Min.y : -FLT_MAX);
ImVec2 clamp_max = ImVec2(border_n == 3 ? visibility_rect.Max.x : +FLT_MAX, border_n == 0 ? visibility_rect.Max.y : +FLT_MAX);
border_target = ImClamp(border_target, clamp_min, clamp_max);
CalcResizePosSizeFromAnyCorner(window, border_target, border_posn, &pos_target, &size_target);
}
}
PopID();
// Restore nav layer
window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
window->DC.NavLayerCurrentMask = (1 << ImGuiNavLayer_Main);
// Navigation resize (keyboard/gamepad)
if (g.NavWindowingTarget && g.NavWindowingTarget->RootWindow == window)
{
ImVec2 nav_resize_delta;
if (g.NavInputSource == ImGuiInputSource_NavKeyboard && g.IO.KeyShift)
nav_resize_delta = GetNavInputAmount2d(ImGuiNavDirSourceFlags_Keyboard, ImGuiInputReadMode_Down);
if (g.NavInputSource == ImGuiInputSource_NavGamepad)
nav_resize_delta = GetNavInputAmount2d(ImGuiNavDirSourceFlags_PadDPad, ImGuiInputReadMode_Down);
if (nav_resize_delta.x != 0.0f || nav_resize_delta.y != 0.0f)
{
const float NAV_RESIZE_SPEED = 600.0f;
nav_resize_delta *= ImFloor(NAV_RESIZE_SPEED * g.IO.DeltaTime * ImMin(g.IO.DisplayFramebufferScale.x, g.IO.DisplayFramebufferScale.y));
nav_resize_delta = ImMax(nav_resize_delta, visibility_rect.Min - window->Pos - window->Size);
g.NavWindowingToggleLayer = false;
g.NavDisableMouseHover = true;
resize_grip_col[0] = GetColorU32(ImGuiCol_ResizeGripActive);
// FIXME-NAV: Should store and accumulate into a separate size buffer to handle sizing constraints properly, right now a constraint will make us stuck.
size_target = CalcWindowSizeAfterConstraint(window, window->SizeFull + nav_resize_delta);
}
}
// Apply back modified position/size to window
if (size_target.x != FLT_MAX)
{
window->SizeFull = size_target;
MarkIniSettingsDirty(window);
}
if (pos_target.x != FLT_MAX)
{
window->Pos = ImFloor(pos_target);
MarkIniSettingsDirty(window);
}
window->Size = window->SizeFull;
return ret_auto_fit;
}
static inline void ClampWindowRect(ImGuiWindow* window, const ImRect& visibility_rect)
{
ImGuiContext& g = *GImGui;
ImVec2 size_for_clamping = window->Size;
if (g.IO.ConfigWindowsMoveFromTitleBarOnly && !(window->Flags & ImGuiWindowFlags_NoTitleBar))
size_for_clamping.y = window->TitleBarHeight();
window->Pos = ImClamp(window->Pos, visibility_rect.Min - size_for_clamping, visibility_rect.Max);
}
static void ImGui::RenderWindowOuterBorders(ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
float rounding = window->WindowRounding;
float border_size = window->WindowBorderSize;
if (border_size > 0.0f && !(window->Flags & ImGuiWindowFlags_NoBackground))
window->DrawList->AddRect(window->Pos, window->Pos + window->Size, GetColorU32(ImGuiCol_Border), rounding, ImDrawCornerFlags_All, border_size);
int border_held = window->ResizeBorderHeld;
if (border_held != -1)
{
const ImGuiResizeBorderDef& def = resize_border_def[border_held];
ImRect border_r = GetResizeBorderRect(window, border_held, rounding, 0.0f);
window->DrawList->PathArcTo(ImLerp(border_r.Min, border_r.Max, def.CornerPosN1) + ImVec2(0.5f, 0.5f) + def.InnerDir * rounding, rounding, def.OuterAngle - IM_PI * 0.25f, def.OuterAngle);
window->DrawList->PathArcTo(ImLerp(border_r.Min, border_r.Max, def.CornerPosN2) + ImVec2(0.5f, 0.5f) + def.InnerDir * rounding, rounding, def.OuterAngle, def.OuterAngle + IM_PI * 0.25f);
window->DrawList->PathStroke(GetColorU32(ImGuiCol_SeparatorActive), false, ImMax(2.0f, border_size)); // Thicker than usual
}
if (g.Style.FrameBorderSize > 0 && !(window->Flags & ImGuiWindowFlags_NoTitleBar))
{
float y = window->Pos.y + window->TitleBarHeight() - 1;
window->DrawList->AddLine(ImVec2(window->Pos.x + border_size, y), ImVec2(window->Pos.x + window->Size.x - border_size, y), GetColorU32(ImGuiCol_Border), g.Style.FrameBorderSize);
}
}
// Draw background and borders
// Draw and handle scrollbars
void ImGui::RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar_rect, bool title_bar_is_highlight, int resize_grip_count, const ImU32 resize_grip_col[4], float resize_grip_draw_size)
{
ImGuiContext& g = *GImGui;
ImGuiStyle& style = g.Style;
ImGuiWindowFlags flags = window->Flags;
// Ensure that ScrollBar doesn't read last frame's SkipItems
IM_ASSERT(window->BeginCount == 0);
window->SkipItems = false;
// Draw window + handle manual resize
// As we highlight the title bar when want_focus is set, multiple reappearing windows will have have their title bar highlighted on their reappearing frame.
const float window_rounding = window->WindowRounding;
const float window_border_size = window->WindowBorderSize;
if (window->Collapsed)
{
// Title bar only
float backup_border_size = style.FrameBorderSize;
g.Style.FrameBorderSize = window->WindowBorderSize;
ImU32 title_bar_col = GetColorU32((title_bar_is_highlight && !g.NavDisableHighlight) ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBgCollapsed);
RenderFrame(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, true, window_rounding);
g.Style.FrameBorderSize = backup_border_size;
}
else
{
// Window background
if (!(flags & ImGuiWindowFlags_NoBackground))
{
ImU32 bg_col = GetColorU32(GetWindowBgColorIdxFromFlags(flags));
bool override_alpha = false;
float alpha = 1.0f;
if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasBgAlpha)
{
alpha = g.NextWindowData.BgAlphaVal;
override_alpha = true;
}
if (override_alpha)
bg_col = (bg_col & ~IM_COL32_A_MASK) | (IM_F32_TO_INT8_SAT(alpha) << IM_COL32_A_SHIFT);
window->DrawList->AddRectFilled(window->Pos + ImVec2(0, window->TitleBarHeight()), window->Pos + window->Size, bg_col, window_rounding, (flags & ImGuiWindowFlags_NoTitleBar) ? ImDrawCornerFlags_All : ImDrawCornerFlags_Bot);
}
// Title bar
if (!(flags & ImGuiWindowFlags_NoTitleBar))
{
ImU32 title_bar_col = GetColorU32(title_bar_is_highlight ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg);
window->DrawList->AddRectFilled(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, window_rounding, ImDrawCornerFlags_Top);
}
// Menu bar
if (flags & ImGuiWindowFlags_MenuBar)
{
ImRect menu_bar_rect = window->MenuBarRect();
menu_bar_rect.ClipWith(window->Rect()); // Soft clipping, in particular child window don't have minimum size covering the menu bar so this is useful for them.
window->DrawList->AddRectFilled(menu_bar_rect.Min + ImVec2(window_border_size, 0), menu_bar_rect.Max - ImVec2(window_border_size, 0), GetColorU32(ImGuiCol_MenuBarBg), (flags & ImGuiWindowFlags_NoTitleBar) ? window_rounding : 0.0f, ImDrawCornerFlags_Top);
if (style.FrameBorderSize > 0.0f && menu_bar_rect.Max.y < window->Pos.y + window->Size.y)
window->DrawList->AddLine(menu_bar_rect.GetBL(), menu_bar_rect.GetBR(), GetColorU32(ImGuiCol_Border), style.FrameBorderSize);
}
// Scrollbars
if (window->ScrollbarX)
Scrollbar(ImGuiAxis_X);
if (window->ScrollbarY)
Scrollbar(ImGuiAxis_Y);
// Render resize grips (after their input handling so we don't have a frame of latency)
if (!(flags & ImGuiWindowFlags_NoResize))
{
for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++)
{
const ImGuiResizeGripDef& grip = resize_grip_def[resize_grip_n];
const ImVec2 corner = ImLerp(window->Pos, window->Pos + window->Size, grip.CornerPosN);
window->DrawList->PathLineTo(corner + grip.InnerDir * ((resize_grip_n & 1) ? ImVec2(window_border_size, resize_grip_draw_size) : ImVec2(resize_grip_draw_size, window_border_size)));
window->DrawList->PathLineTo(corner + grip.InnerDir * ((resize_grip_n & 1) ? ImVec2(resize_grip_draw_size, window_border_size) : ImVec2(window_border_size, resize_grip_draw_size)));
window->DrawList->PathArcToFast(ImVec2(corner.x + grip.InnerDir.x * (window_rounding + window_border_size), corner.y + grip.InnerDir.y * (window_rounding + window_border_size)), window_rounding, grip.AngleMin12, grip.AngleMax12);
window->DrawList->PathFillConvex(resize_grip_col[resize_grip_n]);
}
}
// Borders
RenderWindowOuterBorders(window);
}
}
// Render title text, collapse button, close button
void ImGui::RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& title_bar_rect, const char* name, bool* p_open)
{
ImGuiContext& g = *GImGui;
ImGuiStyle& style = g.Style;
ImGuiWindowFlags flags = window->Flags;
const bool has_close_button = (p_open != NULL);
const bool has_collapse_button = !(flags & ImGuiWindowFlags_NoCollapse) && (style.WindowMenuButtonPosition != ImGuiDir_None);
// Close & Collapse button are on the Menu NavLayer and don't default focus (unless there's nothing else on that layer)
const ImGuiItemFlags item_flags_backup = window->DC.ItemFlags;
window->DC.ItemFlags |= ImGuiItemFlags_NoNavDefaultFocus;
window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
window->DC.NavLayerCurrentMask = (1 << ImGuiNavLayer_Menu);
// Layout buttons
// FIXME: Would be nice to generalize the subtleties expressed here into reusable code.
float pad_l = style.FramePadding.x;
float pad_r = style.FramePadding.x;
float button_sz = g.FontSize;
ImVec2 close_button_pos;
ImVec2 collapse_button_pos;
if (has_close_button)
{
pad_r += button_sz;
close_button_pos = ImVec2(title_bar_rect.Max.x - pad_r - style.FramePadding.x, title_bar_rect.Min.y);
}
if (has_collapse_button && style.WindowMenuButtonPosition == ImGuiDir_Right)
{
pad_r += button_sz;
collapse_button_pos = ImVec2(title_bar_rect.Max.x - pad_r - style.FramePadding.x, title_bar_rect.Min.y);
}
if (has_collapse_button && style.WindowMenuButtonPosition == ImGuiDir_Left)
{
collapse_button_pos = ImVec2(title_bar_rect.Min.x + pad_l - style.FramePadding.x, title_bar_rect.Min.y);
pad_l += button_sz;
}
// Collapse button (submitting first so it gets priority when choosing a navigation init fallback)
if (has_collapse_button)
if (CollapseButton(window->GetID("#COLLAPSE"), collapse_button_pos))
window->WantCollapseToggle = true; // Defer actual collapsing to next frame as we are too far in the Begin() function
// Close button
if (has_close_button)
if (CloseButton(window->GetID("#CLOSE"), close_button_pos))
*p_open = false;
window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
window->DC.NavLayerCurrentMask = (1 << ImGuiNavLayer_Main);
window->DC.ItemFlags = item_flags_backup;
// Title bar text (with: horizontal alignment, avoiding collapse/close button, optional "unsaved document" marker)
// FIXME: Refactor text alignment facilities along with RenderText helpers, this is WAY too much messy code..
const char* UNSAVED_DOCUMENT_MARKER = "*";
const float marker_size_x = (flags & ImGuiWindowFlags_UnsavedDocument) ? CalcTextSize(UNSAVED_DOCUMENT_MARKER, NULL, false).x : 0.0f;
const ImVec2 text_size = CalcTextSize(name, NULL, true) + ImVec2(marker_size_x, 0.0f);
// As a nice touch we try to ensure that centered title text doesn't get affected by visibility of Close/Collapse button,
// while uncentered title text will still reach edges correct.
if (pad_l > style.FramePadding.x)
pad_l += g.Style.ItemInnerSpacing.x;
if (pad_r > style.FramePadding.x)
pad_r += g.Style.ItemInnerSpacing.x;
if (style.WindowTitleAlign.x > 0.0f && style.WindowTitleAlign.x < 1.0f)
{
float centerness = ImSaturate(1.0f - ImFabs(style.WindowTitleAlign.x - 0.5f) * 2.0f); // 0.0f on either edges, 1.0f on center
float pad_extend = ImMin(ImMax(pad_l, pad_r), title_bar_rect.GetWidth() - pad_l - pad_r - text_size.x);
pad_l = ImMax(pad_l, pad_extend * centerness);
pad_r = ImMax(pad_r, pad_extend * centerness);
}
ImRect layout_r(title_bar_rect.Min.x + pad_l, title_bar_rect.Min.y, title_bar_rect.Max.x - pad_r, title_bar_rect.Max.y);
ImRect clip_r(layout_r.Min.x, layout_r.Min.y, layout_r.Max.x + g.Style.ItemInnerSpacing.x, layout_r.Max.y);
//if (g.IO.KeyCtrl) window->DrawList->AddRect(layout_r.Min, layout_r.Max, IM_COL32(255, 128, 0, 255)); // [DEBUG]
RenderTextClipped(layout_r.Min, layout_r.Max, name, NULL, &text_size, style.WindowTitleAlign, &clip_r);
if (flags & ImGuiWindowFlags_UnsavedDocument)
{
ImVec2 marker_pos = ImVec2(ImMax(layout_r.Min.x, layout_r.Min.x + (layout_r.GetWidth() - text_size.x) * style.WindowTitleAlign.x) + text_size.x, layout_r.Min.y) + ImVec2(2 - marker_size_x, 0.0f);
ImVec2 off = ImVec2(0.0f, IM_FLOOR(-g.FontSize * 0.25f));
RenderTextClipped(marker_pos + off, layout_r.Max + off, UNSAVED_DOCUMENT_MARKER, NULL, NULL, ImVec2(0, style.WindowTitleAlign.y), &clip_r);
}
}
void ImGui::UpdateWindowParentAndRootLinks(ImGuiWindow* window, ImGuiWindowFlags flags, ImGuiWindow* parent_window)
{
window->ParentWindow = parent_window;
window->RootWindow = window->RootWindowForTitleBarHighlight = window->RootWindowForNav = window;
if (parent_window && (flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Tooltip))
window->RootWindow = parent_window->RootWindow;
if (parent_window && !(flags & ImGuiWindowFlags_Modal) && (flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup)))
window->RootWindowForTitleBarHighlight = parent_window->RootWindowForTitleBarHighlight;
while (window->RootWindowForNav->Flags & ImGuiWindowFlags_NavFlattened)
{
IM_ASSERT(window->RootWindowForNav->ParentWindow != NULL);
window->RootWindowForNav = window->RootWindowForNav->ParentWindow;
}
}
// Push a new Dear ImGui window to add widgets to.
// - A default window called "Debug" is automatically stacked at the beginning of every frame so you can use widgets without explicitly calling a Begin/End pair.
// - Begin/End can be called multiple times during the frame with the same window name to append content.
// - The window name is used as a unique identifier to preserve window information across frames (and save rudimentary information to the .ini file).
// You can use the "##" or "###" markers to use the same label with different id, or same id with different label. See documentation at the top of this file.
// - Return false when window is collapsed, so you can early out in your code. You always need to call ImGui::End() even if false is returned.
// - Passing 'bool* p_open' displays a Close button on the upper-right corner of the window, the pointed value will be set to false when the button is pressed.
bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
{
ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
IM_ASSERT(name != NULL && name[0] != '\0'); // Window name required
IM_ASSERT(g.WithinFrameScope); // Forgot to call ImGui::NewFrame()
IM_ASSERT(g.FrameCountEnded != g.FrameCount); // Called ImGui::Render() or ImGui::EndFrame() and haven't called ImGui::NewFrame() again yet
// Find or create
ImGuiWindow* window = FindWindowByName(name);
const bool window_just_created = (window == NULL);
if (window_just_created)
window = CreateNewWindow(name, flags);
// Automatically disable manual moving/resizing when NoInputs is set
if ((flags & ImGuiWindowFlags_NoInputs) == ImGuiWindowFlags_NoInputs)
flags |= ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize;
if (flags & ImGuiWindowFlags_NavFlattened)
IM_ASSERT(flags & ImGuiWindowFlags_ChildWindow);
const int current_frame = g.FrameCount;
const bool first_begin_of_the_frame = (window->LastFrameActive != current_frame);
window->IsFallbackWindow = (g.CurrentWindowStack.Size == 0 && g.WithinFrameScopeWithImplicitWindow);
// Update the Appearing flag
bool window_just_activated_by_user = (window->LastFrameActive < current_frame - 1); // Not using !WasActive because the implicit "Debug" window would always toggle off->on
const bool window_just_appearing_after_hidden_for_resize = (window->HiddenFramesCannotSkipItems > 0);
if (flags & ImGuiWindowFlags_Popup)
{
ImGuiPopupData& popup_ref = g.OpenPopupStack[g.BeginPopupStack.Size];
window_just_activated_by_user |= (window->PopupId != popup_ref.PopupId); // We recycle popups so treat window as activated if popup id changed
window_just_activated_by_user |= (window != popup_ref.Window);
}
window->Appearing = (window_just_activated_by_user || window_just_appearing_after_hidden_for_resize);
if (window->Appearing)
SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, true);
// Update Flags, LastFrameActive, BeginOrderXXX fields
if (first_begin_of_the_frame)
{
window->Flags = (ImGuiWindowFlags)flags;
window->LastFrameActive = current_frame;
window->LastTimeActive = (float)g.Time;
window->BeginOrderWithinParent = 0;
window->BeginOrderWithinContext = (short)(g.WindowsActiveCount++);
}
else
{
flags = window->Flags;
}
// Parent window is latched only on the first call to Begin() of the frame, so further append-calls can be done from a different window stack
ImGuiWindow* parent_window_in_stack = g.CurrentWindowStack.empty() ? NULL : g.CurrentWindowStack.back();
ImGuiWindow* parent_window = first_begin_of_the_frame ? ((flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup)) ? parent_window_in_stack : NULL) : window->ParentWindow;
IM_ASSERT(parent_window != NULL || !(flags & ImGuiWindowFlags_ChildWindow));
// We allow window memory to be compacted so recreate the base stack when needed.
if (window->IDStack.Size == 0)
window->IDStack.push_back(window->ID);
// Add to stack
// We intentionally set g.CurrentWindow to NULL to prevent usage until when the viewport is set, then will call SetCurrentWindow()
g.CurrentWindowStack.push_back(window);
g.CurrentWindow = NULL;
ErrorCheckBeginEndCompareStacksSize(window, true);
if (flags & ImGuiWindowFlags_Popup)
{
ImGuiPopupData& popup_ref = g.OpenPopupStack[g.BeginPopupStack.Size];
popup_ref.Window = window;
g.BeginPopupStack.push_back(popup_ref);
window->PopupId = popup_ref.PopupId;
}
if (window_just_appearing_after_hidden_for_resize && !(flags & ImGuiWindowFlags_ChildWindow))
window->NavLastIds[0] = 0;
// Update ->RootWindow and others pointers (before any possible call to FocusWindow)
if (first_begin_of_the_frame)
UpdateWindowParentAndRootLinks(window, flags, parent_window);
// Process SetNextWindow***() calls
// (FIXME: Consider splitting the HasXXX flags into X/Y components
bool window_pos_set_by_api = false;
bool window_size_x_set_by_api = false, window_size_y_set_by_api = false;
if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos)
{
window_pos_set_by_api = (window->SetWindowPosAllowFlags & g.NextWindowData.PosCond) != 0;
if (window_pos_set_by_api && ImLengthSqr(g.NextWindowData.PosPivotVal) > 0.00001f)
{
// May be processed on the next frame if this is our first frame and we are measuring size
// FIXME: Look into removing the branch so everything can go through this same code path for consistency.
window->SetWindowPosVal = g.NextWindowData.PosVal;
window->SetWindowPosPivot = g.NextWindowData.PosPivotVal;
window->SetWindowPosAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
}
else
{
SetWindowPos(window, g.NextWindowData.PosVal, g.NextWindowData.PosCond);
}
}
if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize)
{
window_size_x_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.x > 0.0f);
window_size_y_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.y > 0.0f);
SetWindowSize(window, g.NextWindowData.SizeVal, g.NextWindowData.SizeCond);
}
if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasScroll)
{
if (g.NextWindowData.ScrollVal.x >= 0.0f)
{
window->ScrollTarget.x = g.NextWindowData.ScrollVal.x;
window->ScrollTargetCenterRatio.x = 0.0f;
}
if (g.NextWindowData.ScrollVal.y >= 0.0f)
{
window->ScrollTarget.y = g.NextWindowData.ScrollVal.y;
window->ScrollTargetCenterRatio.y = 0.0f;
}
}
if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasContentSize)
window->ContentSizeExplicit = g.NextWindowData.ContentSizeVal;
else if (first_begin_of_the_frame)
window->ContentSizeExplicit = ImVec2(0.0f, 0.0f);
if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasCollapsed)
SetWindowCollapsed(window, g.NextWindowData.CollapsedVal, g.NextWindowData.CollapsedCond);
if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasFocus)
FocusWindow(window);
if (window->Appearing)
SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, false);
// When reusing window again multiple times a frame, just append content (don't need to setup again)
if (first_begin_of_the_frame)
{
// Initialize
const bool window_is_child_tooltip = (flags & ImGuiWindowFlags_ChildWindow) && (flags & ImGuiWindowFlags_Tooltip); // FIXME-WIP: Undocumented behavior of Child+Tooltip for pinned tooltip (#1345)
window->Active = true;
window->HasCloseButton = (p_open != NULL);
window->ClipRect = ImVec4(-FLT_MAX, -FLT_MAX, +FLT_MAX, +FLT_MAX);
window->IDStack.resize(1);
window->DrawList->_ResetForNewFrame();
// Restore buffer capacity when woken from a compacted state, to avoid
if (window->MemoryCompacted)
GcAwakeTransientWindowBuffers(window);
// Update stored window name when it changes (which can _only_ happen with the "###" operator, so the ID would stay unchanged).
// The title bar always display the 'name' parameter, so we only update the string storage if it needs to be visible to the end-user elsewhere.
bool window_title_visible_elsewhere = false;
if (g.NavWindowingListWindow != NULL && (window->Flags & ImGuiWindowFlags_NoNavFocus) == 0) // Window titles visible when using CTRL+TAB
window_title_visible_elsewhere = true;
if (window_title_visible_elsewhere && !window_just_created && strcmp(name, window->Name) != 0)
{
size_t buf_len = (size_t)window->NameBufLen;
window->Name = ImStrdupcpy(window->Name, &buf_len, name);
window->NameBufLen = (int)buf_len;
}
// UPDATE CONTENTS SIZE, UPDATE HIDDEN STATUS
// Update contents size from last frame for auto-fitting (or use explicit size)
window->ContentSize = CalcWindowContentSize(window);
if (window->HiddenFramesCanSkipItems > 0)
window->HiddenFramesCanSkipItems--;
if (window->HiddenFramesCannotSkipItems > 0)
window->HiddenFramesCannotSkipItems--;
// Hide new windows for one frame until they calculate their size
if (window_just_created && (!window_size_x_set_by_api || !window_size_y_set_by_api))
window->HiddenFramesCannotSkipItems = 1;
// Hide popup/tooltip window when re-opening while we measure size (because we recycle the windows)
// We reset Size/ContentSize for reappearing popups/tooltips early in this function, so further code won't be tempted to use the old size.
if (window_just_activated_by_user && (flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) != 0)
{
window->HiddenFramesCannotSkipItems = 1;
if (flags & ImGuiWindowFlags_AlwaysAutoResize)
{
if (!window_size_x_set_by_api)
window->Size.x = window->SizeFull.x = 0.f;
if (!window_size_y_set_by_api)
window->Size.y = window->SizeFull.y = 0.f;
window->ContentSize = ImVec2(0.f, 0.f);
}
}
// SELECT VIEWPORT
// FIXME-VIEWPORT: In the docking/viewport branch, this is the point where we select the current viewport (which may affect the style)
SetCurrentWindow(window);
// LOCK BORDER SIZE AND PADDING FOR THE FRAME (so that altering them doesn't cause inconsistencies)
if (flags & ImGuiWindowFlags_ChildWindow)
window->WindowBorderSize = style.ChildBorderSize;
else
window->WindowBorderSize = ((flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupBorderSize : style.WindowBorderSize;
window->WindowPadding = style.WindowPadding;
if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & (ImGuiWindowFlags_AlwaysUseWindowPadding | ImGuiWindowFlags_Popup)) && window->WindowBorderSize == 0.0f)
window->WindowPadding = ImVec2(0.0f, (flags & ImGuiWindowFlags_MenuBar) ? style.WindowPadding.y : 0.0f);
// Lock menu offset so size calculation can use it as menu-bar windows need a minimum size.
window->DC.MenuBarOffset.x = ImMax(ImMax(window->WindowPadding.x, style.ItemSpacing.x), g.NextWindowData.MenuBarOffsetMinVal.x);
window->DC.MenuBarOffset.y = g.NextWindowData.MenuBarOffsetMinVal.y;
// Collapse window by double-clicking on title bar
// At this point we don't have a clipping rectangle setup yet, so we can use the title bar area for hit detection and drawing
if (!(flags & ImGuiWindowFlags_NoTitleBar) && !(flags & ImGuiWindowFlags_NoCollapse))
{
// We don't use a regular button+id to test for double-click on title bar (mostly due to legacy reason, could be fixed), so verify that we don't have items over the title bar.
ImRect title_bar_rect = window->TitleBarRect();
if (g.HoveredWindow == window && g.HoveredId == 0 && g.HoveredIdPreviousFrame == 0 && IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max) && g.IO.MouseDoubleClicked[0])
window->WantCollapseToggle = true;
if (window->WantCollapseToggle)
{
window->Collapsed = !window->Collapsed;
MarkIniSettingsDirty(window);
FocusWindow(window);
}
}
else
{
window->Collapsed = false;
}
window->WantCollapseToggle = false;
// SIZE
// Calculate auto-fit size, handle automatic resize
const ImVec2 size_auto_fit = CalcWindowAutoFitSize(window, window->ContentSize);
bool use_current_size_for_scrollbar_x = window_just_created;
bool use_current_size_for_scrollbar_y = window_just_created;
if ((flags & ImGuiWindowFlags_AlwaysAutoResize) && !window->Collapsed)
{
// Using SetNextWindowSize() overrides ImGuiWindowFlags_AlwaysAutoResize, so it can be used on tooltips/popups, etc.
if (!window_size_x_set_by_api)
{
window->SizeFull.x = size_auto_fit.x;
use_current_size_for_scrollbar_x = true;
}
if (!window_size_y_set_by_api)
{
window->SizeFull.y = size_auto_fit.y;
use_current_size_for_scrollbar_y = true;
}
}
else if (window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
{
// Auto-fit may only grow window during the first few frames
// We still process initial auto-fit on collapsed windows to get a window width, but otherwise don't honor ImGuiWindowFlags_AlwaysAutoResize when collapsed.
if (!window_size_x_set_by_api && window->AutoFitFramesX > 0)
{
window->SizeFull.x = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.x, size_auto_fit.x) : size_auto_fit.x;
use_current_size_for_scrollbar_x = true;
}
if (!window_size_y_set_by_api && window->AutoFitFramesY > 0)
{
window->SizeFull.y = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.y, size_auto_fit.y) : size_auto_fit.y;
use_current_size_for_scrollbar_y = true;
}
if (!window->Collapsed)
MarkIniSettingsDirty(window);
}
// Apply minimum/maximum window size constraints and final size
window->SizeFull = CalcWindowSizeAfterConstraint(window, window->SizeFull);
window->Size = window->Collapsed && !(flags & ImGuiWindowFlags_ChildWindow) ? window->TitleBarRect().GetSize() : window->SizeFull;
// Decoration size
const float decoration_up_height = window->TitleBarHeight() + window->MenuBarHeight();
// POSITION
// Popup latch its initial position, will position itself when it appears next frame
if (window_just_activated_by_user)
{
window->AutoPosLastDirection = ImGuiDir_None;
if ((flags & ImGuiWindowFlags_Popup) != 0 && !(flags & ImGuiWindowFlags_Modal) && !window_pos_set_by_api) // FIXME: BeginPopup() could use SetNextWindowPos()
window->Pos = g.BeginPopupStack.back().OpenPopupPos;
}
// Position child window
if (flags & ImGuiWindowFlags_ChildWindow)
{
IM_ASSERT(parent_window && parent_window->Active);
window->BeginOrderWithinParent = (short)parent_window->DC.ChildWindows.Size;
parent_window->DC.ChildWindows.push_back(window);
if (!(flags & ImGuiWindowFlags_Popup) && !window_pos_set_by_api && !window_is_child_tooltip)
window->Pos = parent_window->DC.CursorPos;
}
const bool window_pos_with_pivot = (window->SetWindowPosVal.x != FLT_MAX && window->HiddenFramesCannotSkipItems == 0);
if (window_pos_with_pivot)
SetWindowPos(window, window->SetWindowPosVal - window->Size * window->SetWindowPosPivot, 0); // Position given a pivot (e.g. for centering)
else if ((flags & ImGuiWindowFlags_ChildMenu) != 0)
window->Pos = FindBestWindowPosForPopup(window);
else if ((flags & ImGuiWindowFlags_Popup) != 0 && !window_pos_set_by_api && window_just_appearing_after_hidden_for_resize)
window->Pos = FindBestWindowPosForPopup(window);
else if ((flags & ImGuiWindowFlags_Tooltip) != 0 && !window_pos_set_by_api && !window_is_child_tooltip)
window->Pos = FindBestWindowPosForPopup(window);
// Calculate the range of allowed position for that window (to be movable and visible past safe area padding)
// When clamping to stay visible, we will enforce that window->Pos stays inside of visibility_rect.
ImRect viewport_rect(GetViewportRect());
ImVec2 visibility_padding = ImMax(style.DisplayWindowPadding, style.DisplaySafeAreaPadding);
ImRect visibility_rect(viewport_rect.Min + visibility_padding, viewport_rect.Max - visibility_padding);
// Clamp position/size so window stays visible within its viewport or monitor
// Ignore zero-sized display explicitly to avoid losing positions if a window manager reports zero-sized window when initializing or minimizing.
if (!window_pos_set_by_api && !(flags & ImGuiWindowFlags_ChildWindow) && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0)
if (viewport_rect.GetWidth() > 0.0f && viewport_rect.GetHeight() > 0.0f)
ClampWindowRect(window, visibility_rect);
window->Pos = ImFloor(window->Pos);
// Lock window rounding for the frame (so that altering them doesn't cause inconsistencies)
// Large values tend to lead to variety of artifacts and are not recommended.
window->WindowRounding = (flags & ImGuiWindowFlags_ChildWindow) ? style.ChildRounding : ((flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupRounding : style.WindowRounding;
// For windows with title bar or menu bar, we clamp to FrameHeight(FontSize + FramePadding.y * 2.0f) to completely hide artifacts.
//if ((window->Flags & ImGuiWindowFlags_MenuBar) || !(window->Flags & ImGuiWindowFlags_NoTitleBar))
// window->WindowRounding = ImMin(window->WindowRounding, g.FontSize + style.FramePadding.y * 2.0f);
// Apply window focus (new and reactivated windows are moved to front)
bool want_focus = false;
if (window_just_activated_by_user && !(flags & ImGuiWindowFlags_NoFocusOnAppearing))
{
if (flags & ImGuiWindowFlags_Popup)
want_focus = true;
else if ((flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Tooltip)) == 0)
want_focus = true;
}
// Handle manual resize: Resize Grips, Borders, Gamepad
int border_held = -1;
ImU32 resize_grip_col[4] = {};
const int resize_grip_count = g.IO.ConfigWindowsResizeFromEdges ? 2 : 1; // Allow resize from lower-left if we have the mouse cursor feedback for it.
const float resize_grip_draw_size = IM_FLOOR(ImMax(g.FontSize * 1.35f, window->WindowRounding + 1.0f + g.FontSize * 0.2f));
if (!window->Collapsed)
if (UpdateWindowManualResize(window, size_auto_fit, &border_held, resize_grip_count, &resize_grip_col[0], visibility_rect))
use_current_size_for_scrollbar_x = use_current_size_for_scrollbar_y = true;
window->ResizeBorderHeld = (signed char)border_held;
// SCROLLBAR VISIBILITY
// Update scrollbar visibility (based on the Size that was effective during last frame or the auto-resized Size).
if (!window->Collapsed)
{
// When reading the current size we need to read it after size constraints have been applied.
// When we use InnerRect here we are intentionally reading last frame size, same for ScrollbarSizes values before we set them again.
ImVec2 avail_size_from_current_frame = ImVec2(window->SizeFull.x, window->SizeFull.y - decoration_up_height);
ImVec2 avail_size_from_last_frame = window->InnerRect.GetSize() + window->ScrollbarSizes;
ImVec2 needed_size_from_last_frame = window_just_created ? ImVec2(0, 0) : window->ContentSize + window->WindowPadding * 2.0f;
float size_x_for_scrollbars = use_current_size_for_scrollbar_x ? avail_size_from_current_frame.x : avail_size_from_last_frame.x;
float size_y_for_scrollbars = use_current_size_for_scrollbar_y ? avail_size_from_current_frame.y : avail_size_from_last_frame.y;
//bool scrollbar_y_from_last_frame = window->ScrollbarY; // FIXME: May want to use that in the ScrollbarX expression? How many pros vs cons?
window->ScrollbarY = (flags & ImGuiWindowFlags_AlwaysVerticalScrollbar) || ((needed_size_from_last_frame.y > size_y_for_scrollbars) && !(flags & ImGuiWindowFlags_NoScrollbar));
window->ScrollbarX = (flags & ImGuiWindowFlags_AlwaysHorizontalScrollbar) || ((needed_size_from_last_frame.x > size_x_for_scrollbars - (window->ScrollbarY ? style.ScrollbarSize : 0.0f)) && !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar));
if (window->ScrollbarX && !window->ScrollbarY)
window->ScrollbarY = (needed_size_from_last_frame.y > size_y_for_scrollbars) && !(flags & ImGuiWindowFlags_NoScrollbar);
window->ScrollbarSizes = ImVec2(window->ScrollbarY ? style.ScrollbarSize : 0.0f, window->ScrollbarX ? style.ScrollbarSize : 0.0f);
}
// UPDATE RECTANGLES (1- THOSE NOT AFFECTED BY SCROLLING)
// Update various regions. Variables they depends on should be set above in this function.
// We set this up after processing the resize grip so that our rectangles doesn't lag by a frame.
// Outer rectangle
// Not affected by window border size. Used by:
// - FindHoveredWindow() (w/ extra padding when border resize is enabled)
// - Begin() initial clipping rect for drawing window background and borders.
// - Begin() clipping whole child
const ImRect host_rect = ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip) ? parent_window->ClipRect : viewport_rect;
const ImRect outer_rect = window->Rect();
const ImRect title_bar_rect = window->TitleBarRect();
window->OuterRectClipped = outer_rect;
window->OuterRectClipped.ClipWith(host_rect);
// Inner rectangle
// Not affected by window border size. Used by:
// - InnerClipRect
// - ScrollToBringRectIntoView()
// - NavUpdatePageUpPageDown()
// - Scrollbar()
window->InnerRect.Min.x = window->Pos.x;
window->InnerRect.Min.y = window->Pos.y + decoration_up_height;
window->InnerRect.Max.x = window->Pos.x + window->Size.x - window->ScrollbarSizes.x;
window->InnerRect.Max.y = window->Pos.y + window->Size.y - window->ScrollbarSizes.y;
// Inner clipping rectangle.
// Will extend a little bit outside the normal work region.
// This is to allow e.g. Selectable or CollapsingHeader or some separators to cover that space.
// Force round operator last to ensure that e.g. (int)(max.x-min.x) in user's render code produce correct result.
// Note that if our window is collapsed we will end up with an inverted (~null) clipping rectangle which is the correct behavior.
// Affected by window/frame border size. Used by:
// - Begin() initial clip rect
float top_border_size = (((flags & ImGuiWindowFlags_MenuBar) || !(flags & ImGuiWindowFlags_NoTitleBar)) ? style.FrameBorderSize : window->WindowBorderSize);
window->InnerClipRect.Min.x = ImFloor(0.5f + window->InnerRect.Min.x + ImMax(ImFloor(window->WindowPadding.x * 0.5f), window->WindowBorderSize));
window->InnerClipRect.Min.y = ImFloor(0.5f + window->InnerRect.Min.y + top_border_size);
window->InnerClipRect.Max.x = ImFloor(0.5f + window->InnerRect.Max.x - ImMax(ImFloor(window->WindowPadding.x * 0.5f), window->WindowBorderSize));
window->InnerClipRect.Max.y = ImFloor(0.5f + window->InnerRect.Max.y - window->WindowBorderSize);
window->InnerClipRect.ClipWithFull(host_rect);
// Default item width. Make it proportional to window size if window manually resizes
if (window->Size.x > 0.0f && !(flags & ImGuiWindowFlags_Tooltip) && !(flags & ImGuiWindowFlags_AlwaysAutoResize))
window->ItemWidthDefault = ImFloor(window->Size.x * 0.65f);
else
window->ItemWidthDefault = ImFloor(g.FontSize * 16.0f);
// SCROLLING
// Lock down maximum scrolling
// The value of ScrollMax are ahead from ScrollbarX/ScrollbarY which is intentionally using InnerRect from previous rect in order to accommodate
// for right/bottom aligned items without creating a scrollbar.
window->ScrollMax.x = ImMax(0.0f, window->ContentSize.x + window->WindowPadding.x * 2.0f - window->InnerRect.GetWidth());
window->ScrollMax.y = ImMax(0.0f, window->ContentSize.y + window->WindowPadding.y * 2.0f - window->InnerRect.GetHeight());
// Apply scrolling
window->Scroll = CalcNextScrollFromScrollTargetAndClamp(window);
window->ScrollTarget = ImVec2(FLT_MAX, FLT_MAX);
// DRAWING
// Setup draw list and outer clipping rectangle
IM_ASSERT(window->DrawList->CmdBuffer.Size == 1 && window->DrawList->CmdBuffer[0].ElemCount == 0);
window->DrawList->PushTextureID(g.Font->ContainerAtlas->TexID);
PushClipRect(host_rect.Min, host_rect.Max, false);
// Draw modal window background (darkens what is behind them, all viewports)
const bool dim_bg_for_modal = (flags & ImGuiWindowFlags_Modal) && window == GetTopMostPopupModal() && window->HiddenFramesCannotSkipItems <= 0;
const bool dim_bg_for_window_list = g.NavWindowingTargetAnim && (window == g.NavWindowingTargetAnim->RootWindow);
if (dim_bg_for_modal || dim_bg_for_window_list)
{
const ImU32 dim_bg_col = GetColorU32(dim_bg_for_modal ? ImGuiCol_ModalWindowDimBg : ImGuiCol_NavWindowingDimBg, g.DimBgRatio);
window->DrawList->AddRectFilled(viewport_rect.Min, viewport_rect.Max, dim_bg_col);
}
// Draw navigation selection/windowing rectangle background
if (dim_bg_for_window_list && window == g.NavWindowingTargetAnim)
{
ImRect bb = window->Rect();
bb.Expand(g.FontSize);
if (!bb.Contains(viewport_rect)) // Avoid drawing if the window covers all the viewport anyway
window->DrawList->AddRectFilled(bb.Min, bb.Max, GetColorU32(ImGuiCol_NavWindowingHighlight, g.NavWindowingHighlightAlpha * 0.25f), g.Style.WindowRounding);
}
// Since 1.71, child window can render their decoration (bg color, border, scrollbars, etc.) within their parent to save a draw call.
// When using overlapping child windows, this will break the assumption that child z-order is mapped to submission order.
// We disable this when the parent window has zero vertices, which is a common pattern leading to laying out multiple overlapping child.
// We also disabled this when we have dimming overlay behind this specific one child.
// FIXME: More code may rely on explicit sorting of overlapping child window and would need to disable this somehow. Please get in contact if you are affected.
{
bool render_decorations_in_parent = false;
if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip)
if (window->DrawList->CmdBuffer.back().ElemCount == 0 && parent_window->DrawList->VtxBuffer.Size > 0)
render_decorations_in_parent = true;
if (render_decorations_in_parent)
window->DrawList = parent_window->DrawList;
// Handle title bar, scrollbar, resize grips and resize borders
const ImGuiWindow* window_to_highlight = g.NavWindowingTarget ? g.NavWindowingTarget : g.NavWindow;
const bool title_bar_is_highlight = want_focus || (window_to_highlight && window->RootWindowForTitleBarHighlight == window_to_highlight->RootWindowForTitleBarHighlight);
RenderWindowDecorations(window, title_bar_rect, title_bar_is_highlight, resize_grip_count, resize_grip_col, resize_grip_draw_size);
if (render_decorations_in_parent)
window->DrawList = &window->DrawListInst;
}
// Draw navigation selection/windowing rectangle border
if (g.NavWindowingTargetAnim == window)
{
float rounding = ImMax(window->WindowRounding, g.Style.WindowRounding);
ImRect bb = window->Rect();
bb.Expand(g.FontSize);
if (bb.Contains(viewport_rect)) // If a window fits the entire viewport, adjust its highlight inward
{
bb.Expand(-g.FontSize - 1.0f);
rounding = window->WindowRounding;
}
window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_NavWindowingHighlight, g.NavWindowingHighlightAlpha), rounding, ~0, 3.0f);
}
// UPDATE RECTANGLES (2- THOSE AFFECTED BY SCROLLING)
// Work rectangle.
// Affected by window padding and border size. Used by:
// - Columns() for right-most edge
// - TreeNode(), CollapsingHeader() for right-most edge
// - BeginTabBar() for right-most edge
const bool allow_scrollbar_x = !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar);
const bool allow_scrollbar_y = !(flags & ImGuiWindowFlags_NoScrollbar);
const float work_rect_size_x = (window->ContentSizeExplicit.x != 0.0f ? window->ContentSizeExplicit.x : ImMax(allow_scrollbar_x ? window->ContentSize.x : 0.0f, window->Size.x - window->WindowPadding.x * 2.0f - window->ScrollbarSizes.x));
const float work_rect_size_y = (window->ContentSizeExplicit.y != 0.0f ? window->ContentSizeExplicit.y : ImMax(allow_scrollbar_y ? window->ContentSize.y : 0.0f, window->Size.y - window->WindowPadding.y * 2.0f - decoration_up_height - window->ScrollbarSizes.y));
window->WorkRect.Min.x = ImFloor(window->InnerRect.Min.x - window->Scroll.x + ImMax(window->WindowPadding.x, window->WindowBorderSize));
window->WorkRect.Min.y = ImFloor(window->InnerRect.Min.y - window->Scroll.y + ImMax(window->WindowPadding.y, window->WindowBorderSize));
window->WorkRect.Max.x = window->WorkRect.Min.x + work_rect_size_x;
window->WorkRect.Max.y = window->WorkRect.Min.y + work_rect_size_y;
window->ParentWorkRect = window->WorkRect;
// [LEGACY] Content Region
// FIXME-OBSOLETE: window->ContentRegionRect.Max is currently very misleading / partly faulty, but some BeginChild() patterns relies on it.
// Used by:
// - Mouse wheel scrolling + many other things
window->ContentRegionRect.Min.x = window->Pos.x - window->Scroll.x + window->WindowPadding.x;
window->ContentRegionRect.Min.y = window->Pos.y - window->Scroll.y + window->WindowPadding.y + decoration_up_height;
window->ContentRegionRect.Max.x = window->ContentRegionRect.Min.x + (window->ContentSizeExplicit.x != 0.0f ? window->ContentSizeExplicit.x : (window->Size.x - window->WindowPadding.x * 2.0f - window->ScrollbarSizes.x));
window->ContentRegionRect.Max.y = window->ContentRegionRect.Min.y + (window->ContentSizeExplicit.y != 0.0f ? window->ContentSizeExplicit.y : (window->Size.y - window->WindowPadding.y * 2.0f - decoration_up_height - window->ScrollbarSizes.y));
// Setup drawing context
// (NB: That term "drawing context / DC" lost its meaning a long time ago. Initially was meant to hold transient data only. Nowadays difference between window-> and window->DC-> is dubious.)
window->DC.Indent.x = 0.0f + window->WindowPadding.x - window->Scroll.x;
window->DC.GroupOffset.x = 0.0f;
window->DC.ColumnsOffset.x = 0.0f;
window->DC.CursorStartPos = window->Pos + ImVec2(window->DC.Indent.x + window->DC.ColumnsOffset.x, decoration_up_height + window->WindowPadding.y - window->Scroll.y);
window->DC.CursorPos = window->DC.CursorStartPos;
window->DC.CursorPosPrevLine = window->DC.CursorPos;
window->DC.CursorMaxPos = window->DC.CursorStartPos;
window->DC.CurrLineSize = window->DC.PrevLineSize = ImVec2(0.0f, 0.0f);
window->DC.CurrLineTextBaseOffset = window->DC.PrevLineTextBaseOffset = 0.0f;
window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
window->DC.NavLayerCurrentMask = (1 << ImGuiNavLayer_Main);
window->DC.NavLayerActiveMask = window->DC.NavLayerActiveMaskNext;
window->DC.NavLayerActiveMaskNext = 0x00;
window->DC.NavFocusScopeIdCurrent = (flags & ImGuiWindowFlags_ChildWindow) ? parent_window->DC.NavFocusScopeIdCurrent : 0; // -V595
window->DC.NavHideHighlightOneFrame = false;
window->DC.NavHasScroll = (window->ScrollMax.y > 0.0f);
window->DC.MenuBarAppending = false;
window->DC.MenuColumns.Update(3, style.ItemSpacing.x, window_just_activated_by_user);
window->DC.TreeDepth = 0;
window->DC.TreeJumpToParentOnPopMask = 0x00;
window->DC.ChildWindows.resize(0);
window->DC.StateStorage = &window->StateStorage;
window->DC.CurrentColumns = NULL;
window->DC.LayoutType = ImGuiLayoutType_Vertical;
window->DC.ParentLayoutType = parent_window ? parent_window->DC.LayoutType : ImGuiLayoutType_Vertical;
window->DC.FocusCounterRegular = window->DC.FocusCounterTabStop = -1;
window->DC.ItemWidth = window->ItemWidthDefault;
window->DC.TextWrapPos = -1.0f; // disabled
window->DC.ItemFlagsStack.resize(0);
window->DC.ItemWidthStack.resize(0);
window->DC.TextWrapPosStack.resize(0);
window->DC.GroupStack.resize(0);
window->DC.ItemFlags = parent_window ? parent_window->DC.ItemFlags : ImGuiItemFlags_Default_;
if (parent_window)
window->DC.ItemFlagsStack.push_back(window->DC.ItemFlags);
if (window->AutoFitFramesX > 0)
window->AutoFitFramesX--;
if (window->AutoFitFramesY > 0)
window->AutoFitFramesY--;
// Apply focus (we need to call FocusWindow() AFTER setting DC.CursorStartPos so our initial navigation reference rectangle can start around there)
if (want_focus)
{
FocusWindow(window);
NavInitWindow(window, false);
}
// Title bar
if (!(flags & ImGuiWindowFlags_NoTitleBar))
RenderWindowTitleBarContents(window, title_bar_rect, name, p_open);
// Clear hit test shape every frame
window->HitTestHoleSize.x = window->HitTestHoleSize.y = 0;
// Pressing CTRL+C while holding on a window copy its content to the clipboard
// This works but 1. doesn't handle multiple Begin/End pairs, 2. recursing into another Begin/End pair - so we need to work that out and add better logging scope.
// Maybe we can support CTRL+C on every element?
/*
if (g.ActiveId == move_id)
if (g.IO.KeyCtrl && IsKeyPressedMap(ImGuiKey_C))
LogToClipboard();
*/
// We fill last item data based on Title Bar/Tab, in order for IsItemHovered() and IsItemActive() to be usable after Begin().
// This is useful to allow creating context menus on title bar only, etc.
SetLastItemData(window, window->MoveId, IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max, false) ? ImGuiItemStatusFlags_HoveredRect : 0, title_bar_rect);
#ifdef IMGUI_ENABLE_TEST_ENGINE
if (!(window->Flags & ImGuiWindowFlags_NoTitleBar))
IMGUI_TEST_ENGINE_ITEM_ADD(window->DC.LastItemRect, window->DC.LastItemId);
#endif
}
else
{
// Append
SetCurrentWindow(window);
}
PushClipRect(window->InnerClipRect.Min, window->InnerClipRect.Max, true);
// Clear 'accessed' flag last thing (After PushClipRect which will set the flag. We want the flag to stay false when the default "Debug" window is unused)
if (first_begin_of_the_frame)
window->WriteAccessed = false;
window->BeginCount++;
g.NextWindowData.ClearFlags();
// Update visibility
if (first_begin_of_the_frame)
{
if (flags & ImGuiWindowFlags_ChildWindow)
{
// Child window can be out of sight and have "negative" clip windows.
// Mark them as collapsed so commands are skipped earlier (we can't manually collapse them because they have no title bar).
IM_ASSERT((flags & ImGuiWindowFlags_NoTitleBar) != 0);
if (!(flags & ImGuiWindowFlags_AlwaysAutoResize) && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0)
if (window->OuterRectClipped.Min.x >= window->OuterRectClipped.Max.x || window->OuterRectClipped.Min.y >= window->OuterRectClipped.Max.y)
window->HiddenFramesCanSkipItems = 1;
// Hide along with parent or if parent is collapsed
if (parent_window && (parent_window->Collapsed || parent_window->HiddenFramesCanSkipItems > 0))
window->HiddenFramesCanSkipItems = 1;
if (parent_window && (parent_window->Collapsed || parent_window->HiddenFramesCannotSkipItems > 0))
window->HiddenFramesCannotSkipItems = 1;
}
// Don't render if style alpha is 0.0 at the time of Begin(). This is arbitrary and inconsistent but has been there for a long while (may remove at some point)
if (style.Alpha <= 0.0f)
window->HiddenFramesCanSkipItems = 1;
// Update the Hidden flag
window->Hidden = (window->HiddenFramesCanSkipItems > 0) || (window->HiddenFramesCannotSkipItems > 0);
// Update the SkipItems flag, used to early out of all items functions (no layout required)
bool skip_items = false;
if (window->Collapsed || !window->Active || window->Hidden)
if (window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0 && window->HiddenFramesCannotSkipItems <= 0)
skip_items = true;
window->SkipItems = skip_items;
}
return !window->SkipItems;
}
void ImGui::End()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
// Error checking: verify that user hasn't called End() too many times!
if (g.CurrentWindowStack.Size <= 1 && g.WithinFrameScopeWithImplicitWindow)
{
IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size > 1, "Calling End() too many times!");
return;
}
IM_ASSERT(g.CurrentWindowStack.Size > 0);
// Error checking: verify that user doesn't directly call End() on a child window.
if (window->Flags & ImGuiWindowFlags_ChildWindow)
IM_ASSERT_USER_ERROR(g.WithinEndChild, "Must call EndChild() and not End()!");
// Close anything that is open
if (window->DC.CurrentColumns)
EndColumns();
PopClipRect(); // Inner window clip rectangle
// Stop logging
if (!(window->Flags & ImGuiWindowFlags_ChildWindow)) // FIXME: add more options for scope of logging
LogFinish();
// Pop from window stack
g.CurrentWindowStack.pop_back();
if (window->Flags & ImGuiWindowFlags_Popup)
g.BeginPopupStack.pop_back();
ErrorCheckBeginEndCompareStacksSize(window, false);
SetCurrentWindow(g.CurrentWindowStack.empty() ? NULL : g.CurrentWindowStack.back());
}
void ImGui::BringWindowToFocusFront(ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
if (g.WindowsFocusOrder.back() == window)
return;
for (int i = g.WindowsFocusOrder.Size - 2; i >= 0; i--) // We can ignore the top-most window
if (g.WindowsFocusOrder[i] == window)
{
memmove(&g.WindowsFocusOrder[i], &g.WindowsFocusOrder[i + 1], (size_t)(g.WindowsFocusOrder.Size - i - 1) * sizeof(ImGuiWindow*));
g.WindowsFocusOrder[g.WindowsFocusOrder.Size - 1] = window;
break;
}
}
void ImGui::BringWindowToDisplayFront(ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* current_front_window = g.Windows.back();
if (current_front_window == window || current_front_window->RootWindow == window) // Cheap early out (could be better)
return;
for (int i = g.Windows.Size - 2; i >= 0; i--) // We can ignore the top-most window
if (g.Windows[i] == window)
{
memmove(&g.Windows[i], &g.Windows[i + 1], (size_t)(g.Windows.Size - i - 1) * sizeof(ImGuiWindow*));
g.Windows[g.Windows.Size - 1] = window;
break;
}
}
void ImGui::BringWindowToDisplayBack(ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
if (g.Windows[0] == window)
return;
for (int i = 0; i < g.Windows.Size; i++)
if (g.Windows[i] == window)
{
memmove(&g.Windows[1], &g.Windows[0], (size_t)i * sizeof(ImGuiWindow*));
g.Windows[0] = window;
break;
}
}
// Moving window to front of display and set focus (which happens to be back of our sorted list)
void ImGui::FocusWindow(ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
if (g.NavWindow != window)
{
g.NavWindow = window;
if (window && g.NavDisableMouseHover)
g.NavMousePosDirty = true;
g.NavInitRequest = false;
g.NavId = window ? window->NavLastIds[0] : 0; // Restore NavId
g.NavFocusScopeId = 0;
g.NavIdIsAlive = false;
g.NavLayer = ImGuiNavLayer_Main;
//IMGUI_DEBUG_LOG("FocusWindow(\"%s\")\n", window ? window->Name : NULL);
}
// Close popups if any
ClosePopupsOverWindow(window, false);
// Move the root window to the top of the pile
IM_ASSERT(window == NULL || window->RootWindow != NULL);
ImGuiWindow* focus_front_window = window ? window->RootWindow : NULL; // NB: In docking branch this is window->RootWindowDockStop
ImGuiWindow* display_front_window = window ? window->RootWindow : NULL;
// Steal active widgets. Some of the cases it triggers includes:
// - Focus a window while an InputText in another window is active, if focus happens before the old InputText can run.
// - When using Nav to activate menu items (due to timing of activating on press->new window appears->losing ActiveId)
if (g.ActiveId != 0 && g.ActiveIdWindow && g.ActiveIdWindow->RootWindow != focus_front_window)
if (!g.ActiveIdNoClearOnFocusLoss)
ClearActiveID();
// Passing NULL allow to disable keyboard focus
if (!window)
return;
// Bring to front
BringWindowToFocusFront(focus_front_window);
if (((window->Flags | display_front_window->Flags) & ImGuiWindowFlags_NoBringToFrontOnFocus) == 0)
BringWindowToDisplayFront(display_front_window);
}
void ImGui::FocusTopMostWindowUnderOne(ImGuiWindow* under_this_window, ImGuiWindow* ignore_window)
{
ImGuiContext& g = *GImGui;
int start_idx = g.WindowsFocusOrder.Size - 1;
if (under_this_window != NULL)
{
int under_this_window_idx = FindWindowFocusIndex(under_this_window);
if (under_this_window_idx != -1)
start_idx = under_this_window_idx - 1;
}
for (int i = start_idx; i >= 0; i--)
{
// We may later decide to test for different NoXXXInputs based on the active navigation input (mouse vs nav) but that may feel more confusing to the user.
ImGuiWindow* window = g.WindowsFocusOrder[i];
if (window != ignore_window && window->WasActive && !(window->Flags & ImGuiWindowFlags_ChildWindow))
if ((window->Flags & (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs)) != (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs))
{
ImGuiWindow* focus_window = NavRestoreLastChildNavWindow(window);
FocusWindow(focus_window);
return;
}
}
FocusWindow(NULL);
}
void ImGui::SetCurrentFont(ImFont* font)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(font && font->IsLoaded()); // Font Atlas not created. Did you call io.Fonts->GetTexDataAsRGBA32 / GetTexDataAsAlpha8 ?
IM_ASSERT(font->Scale > 0.0f);
g.Font = font;
g.FontBaseSize = ImMax(1.0f, g.IO.FontGlobalScale * g.Font->FontSize * g.Font->Scale);
g.FontSize = g.CurrentWindow ? g.CurrentWindow->CalcFontSize() : 0.0f;
ImFontAtlas* atlas = g.Font->ContainerAtlas;
g.DrawListSharedData.TexUvWhitePixel = atlas->TexUvWhitePixel;
g.DrawListSharedData.TexUvLines = atlas->TexUvLines;
g.DrawListSharedData.Font = g.Font;
g.DrawListSharedData.FontSize = g.FontSize;
}
void ImGui::PushFont(ImFont* font)
{
ImGuiContext& g = *GImGui;
if (!font)
font = GetDefaultFont();
SetCurrentFont(font);
g.FontStack.push_back(font);
g.CurrentWindow->DrawList->PushTextureID(font->ContainerAtlas->TexID);
}
void ImGui::PopFont()
{
ImGuiContext& g = *GImGui;
g.CurrentWindow->DrawList->PopTextureID();
g.FontStack.pop_back();
SetCurrentFont(g.FontStack.empty() ? GetDefaultFont() : g.FontStack.back());
}
void ImGui::PushItemFlag(ImGuiItemFlags option, bool enabled)
{
ImGuiWindow* window = GetCurrentWindow();
if (enabled)
window->DC.ItemFlags |= option;
else
window->DC.ItemFlags &= ~option;
window->DC.ItemFlagsStack.push_back(window->DC.ItemFlags);
}
void ImGui::PopItemFlag()
{
ImGuiWindow* window = GetCurrentWindow();
window->DC.ItemFlagsStack.pop_back();
window->DC.ItemFlags = window->DC.ItemFlagsStack.empty() ? ImGuiItemFlags_Default_ : window->DC.ItemFlagsStack.back();
}
// FIXME: Look into renaming this once we have settled the new Focus/Activation/TabStop system.
void ImGui::PushAllowKeyboardFocus(bool allow_keyboard_focus)
{
PushItemFlag(ImGuiItemFlags_NoTabStop, !allow_keyboard_focus);
}
void ImGui::PopAllowKeyboardFocus()
{
PopItemFlag();
}
void ImGui::PushButtonRepeat(bool repeat)
{
PushItemFlag(ImGuiItemFlags_ButtonRepeat, repeat);
}
void ImGui::PopButtonRepeat()
{
PopItemFlag();
}
void ImGui::PushTextWrapPos(float wrap_pos_x)
{
ImGuiWindow* window = GetCurrentWindow();
window->DC.TextWrapPos = wrap_pos_x;
window->DC.TextWrapPosStack.push_back(wrap_pos_x);
}
void ImGui::PopTextWrapPos()
{
ImGuiWindow* window = GetCurrentWindow();
window->DC.TextWrapPosStack.pop_back();
window->DC.TextWrapPos = window->DC.TextWrapPosStack.empty() ? -1.0f : window->DC.TextWrapPosStack.back();
}
bool ImGui::IsWindowChildOf(ImGuiWindow* window, ImGuiWindow* potential_parent)
{
if (window->RootWindow == potential_parent)
return true;
while (window != NULL)
{
if (window == potential_parent)
return true;
window = window->ParentWindow;
}
return false;
}
bool ImGui::IsWindowHovered(ImGuiHoveredFlags flags)
{
IM_ASSERT((flags & ImGuiHoveredFlags_AllowWhenOverlapped) == 0); // Flags not supported by this function
ImGuiContext& g = *GImGui;
if (flags & ImGuiHoveredFlags_AnyWindow)
{
if (g.HoveredWindow == NULL)
return false;
}
else
{
switch (flags & (ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows))
{
case ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows:
if (g.HoveredRootWindow != g.CurrentWindow->RootWindow)
return false;
break;
case ImGuiHoveredFlags_RootWindow:
if (g.HoveredWindow != g.CurrentWindow->RootWindow)
return false;
break;
case ImGuiHoveredFlags_ChildWindows:
if (g.HoveredWindow == NULL || !IsWindowChildOf(g.HoveredWindow, g.CurrentWindow))
return false;
break;
default:
if (g.HoveredWindow != g.CurrentWindow)
return false;
break;
}
}
if (!IsWindowContentHoverable(g.HoveredWindow, flags))
return false;
if (!(flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem))
if (g.ActiveId != 0 && !g.ActiveIdAllowOverlap && g.ActiveId != g.HoveredWindow->MoveId)
return false;
return true;
}
bool ImGui::IsWindowFocused(ImGuiFocusedFlags flags)
{
ImGuiContext& g = *GImGui;
if (flags & ImGuiFocusedFlags_AnyWindow)
return g.NavWindow != NULL;
IM_ASSERT(g.CurrentWindow); // Not inside a Begin()/End()
switch (flags & (ImGuiFocusedFlags_RootWindow | ImGuiFocusedFlags_ChildWindows))
{
case ImGuiFocusedFlags_RootWindow | ImGuiFocusedFlags_ChildWindows:
return g.NavWindow && g.NavWindow->RootWindow == g.CurrentWindow->RootWindow;
case ImGuiFocusedFlags_RootWindow:
return g.NavWindow == g.CurrentWindow->RootWindow;
case ImGuiFocusedFlags_ChildWindows:
return g.NavWindow && IsWindowChildOf(g.NavWindow, g.CurrentWindow);
default:
return g.NavWindow == g.CurrentWindow;
}
}
// Can we focus this window with CTRL+TAB (or PadMenu + PadFocusPrev/PadFocusNext)
// Note that NoNavFocus makes the window not reachable with CTRL+TAB but it can still be focused with mouse or programmatically.
// If you want a window to never be focused, you may use the e.g. NoInputs flag.
bool ImGui::IsWindowNavFocusable(ImGuiWindow* window)
{
return window->Active && window == window->RootWindow && !(window->Flags & ImGuiWindowFlags_NoNavFocus);
}
float ImGui::GetWindowWidth()
{
ImGuiWindow* window = GImGui->CurrentWindow;
return window->Size.x;
}
float ImGui::GetWindowHeight()
{
ImGuiWindow* window = GImGui->CurrentWindow;
return window->Size.y;
}
ImVec2 ImGui::GetWindowPos()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
return window->Pos;
}
void ImGui::SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiCond cond)
{
// Test condition (NB: bit 0 is always true) and clear flags for next time
if (cond && (window->SetWindowPosAllowFlags & cond) == 0)
return;
IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
window->SetWindowPosAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
window->SetWindowPosVal = ImVec2(FLT_MAX, FLT_MAX);
// Set
const ImVec2 old_pos = window->Pos;
window->Pos = ImFloor(pos);
ImVec2 offset = window->Pos - old_pos;
window->DC.CursorPos += offset; // As we happen to move the window while it is being appended to (which is a bad idea - will smear) let's at least offset the cursor
window->DC.CursorMaxPos += offset; // And more importantly we need to offset CursorMaxPos/CursorStartPos this so ContentSize calculation doesn't get affected.
window->DC.CursorStartPos += offset;
}
void ImGui::SetWindowPos(const ImVec2& pos, ImGuiCond cond)
{
ImGuiWindow* window = GetCurrentWindowRead();
SetWindowPos(window, pos, cond);
}
void ImGui::SetWindowPos(const char* name, const ImVec2& pos, ImGuiCond cond)
{
if (ImGuiWindow* window = FindWindowByName(name))
SetWindowPos(window, pos, cond);
}
ImVec2 ImGui::GetWindowSize()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->Size;
}
void ImGui::SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiCond cond)
{
// Test condition (NB: bit 0 is always true) and clear flags for next time
if (cond && (window->SetWindowSizeAllowFlags & cond) == 0)
return;
IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
window->SetWindowSizeAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
// Set
if (size.x > 0.0f)
{
window->AutoFitFramesX = 0;
window->SizeFull.x = IM_FLOOR(size.x);
}
else
{
window->AutoFitFramesX = 2;
window->AutoFitOnlyGrows = false;
}
if (size.y > 0.0f)
{
window->AutoFitFramesY = 0;
window->SizeFull.y = IM_FLOOR(size.y);
}
else
{
window->AutoFitFramesY = 2;
window->AutoFitOnlyGrows = false;
}
}
void ImGui::SetWindowSize(const ImVec2& size, ImGuiCond cond)
{
SetWindowSize(GImGui->CurrentWindow, size, cond);
}
void ImGui::SetWindowSize(const char* name, const ImVec2& size, ImGuiCond cond)
{
if (ImGuiWindow* window = FindWindowByName(name))
SetWindowSize(window, size, cond);
}
void ImGui::SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiCond cond)
{
// Test condition (NB: bit 0 is always true) and clear flags for next time
if (cond && (window->SetWindowCollapsedAllowFlags & cond) == 0)
return;
window->SetWindowCollapsedAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
// Set
window->Collapsed = collapsed;
}
void ImGui::SetWindowHitTestHole(ImGuiWindow* window, const ImVec2& pos, const ImVec2& size)
{
IM_ASSERT(window->HitTestHoleSize.x == 0); // We don't support multiple holes/hit test filters
window->HitTestHoleSize = ImVec2ih(size);
window->HitTestHoleOffset = ImVec2ih(pos - window->Pos);
}
void ImGui::SetWindowCollapsed(bool collapsed, ImGuiCond cond)
{
SetWindowCollapsed(GImGui->CurrentWindow, collapsed, cond);
}
bool ImGui::IsWindowCollapsed()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->Collapsed;
}
bool ImGui::IsWindowAppearing()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->Appearing;
}
void ImGui::SetWindowCollapsed(const char* name, bool collapsed, ImGuiCond cond)
{
if (ImGuiWindow* window = FindWindowByName(name))
SetWindowCollapsed(window, collapsed, cond);
}
void ImGui::SetWindowFocus()
{
FocusWindow(GImGui->CurrentWindow);
}
void ImGui::SetWindowFocus(const char* name)
{
if (name)
{
if (ImGuiWindow* window = FindWindowByName(name))
FocusWindow(window);
}
else
{
FocusWindow(NULL);
}
}
void ImGui::SetNextWindowPos(const ImVec2& pos, ImGuiCond cond, const ImVec2& pivot)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasPos;
g.NextWindowData.PosVal = pos;
g.NextWindowData.PosPivotVal = pivot;
g.NextWindowData.PosCond = cond ? cond : ImGuiCond_Always;
}
void ImGui::SetNextWindowSize(const ImVec2& size, ImGuiCond cond)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasSize;
g.NextWindowData.SizeVal = size;
g.NextWindowData.SizeCond = cond ? cond : ImGuiCond_Always;
}
void ImGui::SetNextWindowSizeConstraints(const ImVec2& size_min, const ImVec2& size_max, ImGuiSizeCallback custom_callback, void* custom_callback_user_data)
{
ImGuiContext& g = *GImGui;
g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasSizeConstraint;
g.NextWindowData.SizeConstraintRect = ImRect(size_min, size_max);
g.NextWindowData.SizeCallback = custom_callback;
g.NextWindowData.SizeCallbackUserData = custom_callback_user_data;
}
// Content size = inner scrollable rectangle, padded with WindowPadding.
// SetNextWindowContentSize(ImVec2(100,100) + ImGuiWindowFlags_AlwaysAutoResize will always allow submitting a 100x100 item.
void ImGui::SetNextWindowContentSize(const ImVec2& size)
{
ImGuiContext& g = *GImGui;
g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasContentSize;
g.NextWindowData.ContentSizeVal = size;
}
void ImGui::SetNextWindowScroll(const ImVec2& scroll)
{
ImGuiContext& g = *GImGui;
g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasScroll;
g.NextWindowData.ScrollVal = scroll;
}
void ImGui::SetNextWindowCollapsed(bool collapsed, ImGuiCond cond)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasCollapsed;
g.NextWindowData.CollapsedVal = collapsed;
g.NextWindowData.CollapsedCond = cond ? cond : ImGuiCond_Always;
}
void ImGui::SetNextWindowFocus()
{
ImGuiContext& g = *GImGui;
g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasFocus;
}
void ImGui::SetNextWindowBgAlpha(float alpha)
{
ImGuiContext& g = *GImGui;
g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasBgAlpha;
g.NextWindowData.BgAlphaVal = alpha;
}
ImDrawList* ImGui::GetWindowDrawList()
{
ImGuiWindow* window = GetCurrentWindow();
return window->DrawList;
}
ImFont* ImGui::GetFont()
{
return GImGui->Font;
}
float ImGui::GetFontSize()
{
return GImGui->FontSize;
}
ImVec2 ImGui::GetFontTexUvWhitePixel()
{
return GImGui->DrawListSharedData.TexUvWhitePixel;
}
void ImGui::SetWindowFontScale(float scale)
{
IM_ASSERT(scale > 0.0f);
ImGuiContext& g = *GImGui;
ImGuiWindow* window = GetCurrentWindow();
window->FontWindowScale = scale;
g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize();
}
void ImGui::ActivateItem(ImGuiID id)
{
ImGuiContext& g = *GImGui;
g.NavNextActivateId = id;
}
// Note: this is storing in same stack as IDStack, so Push/Pop mismatch will be reported there.
void ImGui::PushFocusScope(ImGuiID id)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
window->IDStack.push_back(window->DC.NavFocusScopeIdCurrent);
window->DC.NavFocusScopeIdCurrent = id;
}
void ImGui::PopFocusScope()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
window->DC.NavFocusScopeIdCurrent = window->IDStack.back();
window->IDStack.pop_back();
}
void ImGui::SetKeyboardFocusHere(int offset)
{
IM_ASSERT(offset >= -1); // -1 is allowed but not below
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
g.FocusRequestNextWindow = window;
g.FocusRequestNextCounterRegular = window->DC.FocusCounterRegular + 1 + offset;
g.FocusRequestNextCounterTabStop = INT_MAX;
}
void ImGui::SetItemDefaultFocus()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (!window->Appearing)
return;
if (g.NavWindow == window->RootWindowForNav && (g.NavInitRequest || g.NavInitResultId != 0) && g.NavLayer == g.NavWindow->DC.NavLayerCurrent)
{
g.NavInitRequest = false;
g.NavInitResultId = g.NavWindow->DC.LastItemId;
g.NavInitResultRectRel = ImRect(g.NavWindow->DC.LastItemRect.Min - g.NavWindow->Pos, g.NavWindow->DC.LastItemRect.Max - g.NavWindow->Pos);
NavUpdateAnyRequestFlag();
if (!IsItemVisible())
SetScrollHereY();
}
}
void ImGui::SetStateStorage(ImGuiStorage* tree)
{
ImGuiWindow* window = GImGui->CurrentWindow;
window->DC.StateStorage = tree ? tree : &window->StateStorage;
}
ImGuiStorage* ImGui::GetStateStorage()
{
ImGuiWindow* window = GImGui->CurrentWindow;
return window->DC.StateStorage;
}
void ImGui::PushID(const char* str_id)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
ImGuiID id = window->GetIDNoKeepAlive(str_id);
window->IDStack.push_back(id);
}
void ImGui::PushID(const char* str_id_begin, const char* str_id_end)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
ImGuiID id = window->GetIDNoKeepAlive(str_id_begin, str_id_end);
window->IDStack.push_back(id);
}
void ImGui::PushID(const void* ptr_id)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
ImGuiID id = window->GetIDNoKeepAlive(ptr_id);
window->IDStack.push_back(id);
}
void ImGui::PushID(int int_id)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
ImGuiID id = window->GetIDNoKeepAlive(int_id);
window->IDStack.push_back(id);
}
// Push a given id value ignoring the ID stack as a seed.
void ImGui::PushOverrideID(ImGuiID id)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
window->IDStack.push_back(id);
}
void ImGui::PopID()
{
ImGuiWindow* window = GImGui->CurrentWindow;
window->IDStack.pop_back();
}
ImGuiID ImGui::GetID(const char* str_id)
{
ImGuiWindow* window = GImGui->CurrentWindow;
return window->GetID(str_id);
}
ImGuiID ImGui::GetID(const char* str_id_begin, const char* str_id_end)
{
ImGuiWindow* window = GImGui->CurrentWindow;
return window->GetID(str_id_begin, str_id_end);
}
ImGuiID ImGui::GetID(const void* ptr_id)
{
ImGuiWindow* window = GImGui->CurrentWindow;
return window->GetID(ptr_id);
}
bool ImGui::IsRectVisible(const ImVec2& size)
{
ImGuiWindow* window = GImGui->CurrentWindow;
return window->ClipRect.Overlaps(ImRect(window->DC.CursorPos, window->DC.CursorPos + size));
}
bool ImGui::IsRectVisible(const ImVec2& rect_min, const ImVec2& rect_max)
{
ImGuiWindow* window = GImGui->CurrentWindow;
return window->ClipRect.Overlaps(ImRect(rect_min, rect_max));
}
//-----------------------------------------------------------------------------
// [SECTION] ERROR CHECKING
//-----------------------------------------------------------------------------
// Helper function to verify ABI compatibility between caller code and compiled version of Dear ImGui.
// Verify that the type sizes are matching between the calling file's compilation unit and imgui.cpp's compilation unit
// If the user has inconsistent compilation settings, imgui configuration #define, packing pragma, etc. your user code
// may see different structures than what imgui.cpp sees, which is problematic.
// We usually require settings to be in imconfig.h to make sure that they are accessible to all compilation units involved with Dear ImGui.
bool ImGui::DebugCheckVersionAndDataLayout(const char* version, size_t sz_io, size_t sz_style, size_t sz_vec2, size_t sz_vec4, size_t sz_vert, size_t sz_idx)
{
bool error = false;
if (strcmp(version, IMGUI_VERSION) != 0) { error = true; IM_ASSERT(strcmp(version, IMGUI_VERSION) == 0 && "Mismatched version string!"); }
if (sz_io != sizeof(ImGuiIO)) { error = true; IM_ASSERT(sz_io == sizeof(ImGuiIO) && "Mismatched struct layout!"); }
if (sz_style != sizeof(ImGuiStyle)) { error = true; IM_ASSERT(sz_style == sizeof(ImGuiStyle) && "Mismatched struct layout!"); }
if (sz_vec2 != sizeof(ImVec2)) { error = true; IM_ASSERT(sz_vec2 == sizeof(ImVec2) && "Mismatched struct layout!"); }
if (sz_vec4 != sizeof(ImVec4)) { error = true; IM_ASSERT(sz_vec4 == sizeof(ImVec4) && "Mismatched struct layout!"); }
if (sz_vert != sizeof(ImDrawVert)) { error = true; IM_ASSERT(sz_vert == sizeof(ImDrawVert) && "Mismatched struct layout!"); }
if (sz_idx != sizeof(ImDrawIdx)) { error = true; IM_ASSERT(sz_idx == sizeof(ImDrawIdx) && "Mismatched struct layout!"); }
return !error;
}
static void ImGui::ErrorCheckNewFrameSanityChecks()
{
ImGuiContext& g = *GImGui;
// Check user IM_ASSERT macro
// (IF YOU GET A WARNING OR COMPILE ERROR HERE: it means you assert macro is incorrectly defined!
// If your macro uses multiple statements, it NEEDS to be surrounded by a 'do { ... } while (0)' block.
// This is a common C/C++ idiom to allow multiple statements macros to be used in control flow blocks.)
// #define IM_ASSERT(EXPR) SomeCode(EXPR); SomeMoreCode(); // Wrong!
// #define IM_ASSERT(EXPR) do { SomeCode(EXPR); SomeMoreCode(); } while (0) // Correct!
if (true) IM_ASSERT(1); else IM_ASSERT(0);
// Check user data
// (We pass an error message in the assert expression to make it visible to programmers who are not using a debugger, as most assert handlers display their argument)
IM_ASSERT(g.Initialized);
IM_ASSERT((g.IO.DeltaTime > 0.0f || g.FrameCount == 0) && "Need a positive DeltaTime!");
IM_ASSERT((g.FrameCount == 0 || g.FrameCountEnded == g.FrameCount) && "Forgot to call Render() or EndFrame() at the end of the previous frame?");
IM_ASSERT(g.IO.DisplaySize.x >= 0.0f && g.IO.DisplaySize.y >= 0.0f && "Invalid DisplaySize value!");
IM_ASSERT(g.IO.Fonts->Fonts.Size > 0 && "Font Atlas not built. Did you call io.Fonts->GetTexDataAsRGBA32() / GetTexDataAsAlpha8() ?");
IM_ASSERT(g.IO.Fonts->Fonts[0]->IsLoaded() && "Font Atlas not built. Did you call io.Fonts->GetTexDataAsRGBA32() / GetTexDataAsAlpha8() ?");
IM_ASSERT(g.Style.CurveTessellationTol > 0.0f && "Invalid style setting!");
IM_ASSERT(g.Style.CircleSegmentMaxError > 0.0f && "Invalid style setting!");
IM_ASSERT(g.Style.Alpha >= 0.0f && g.Style.Alpha <= 1.0f && "Invalid style setting. Alpha cannot be negative (allows us to avoid a few clamps in color computations)!");
IM_ASSERT(g.Style.WindowMinSize.x >= 1.0f && g.Style.WindowMinSize.y >= 1.0f && "Invalid style setting.");
IM_ASSERT(g.Style.WindowMenuButtonPosition == ImGuiDir_None || g.Style.WindowMenuButtonPosition == ImGuiDir_Left || g.Style.WindowMenuButtonPosition == ImGuiDir_Right);
for (int n = 0; n < ImGuiKey_COUNT; n++)
IM_ASSERT(g.IO.KeyMap[n] >= -1 && g.IO.KeyMap[n] < IM_ARRAYSIZE(g.IO.KeysDown) && "io.KeyMap[] contains an out of bound value (need to be 0..512, or -1 for unmapped key)");
// Perform simple check: required key mapping (we intentionally do NOT check all keys to not pressure user into setting up everything, but Space is required and was only recently added in 1.60 WIP)
if (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard)
IM_ASSERT(g.IO.KeyMap[ImGuiKey_Space] != -1 && "ImGuiKey_Space is not mapped, required for keyboard navigation.");
// Perform simple check: the beta io.ConfigWindowsResizeFromEdges option requires back-end to honor mouse cursor changes and set the ImGuiBackendFlags_HasMouseCursors flag accordingly.
if (g.IO.ConfigWindowsResizeFromEdges && !(g.IO.BackendFlags & ImGuiBackendFlags_HasMouseCursors))
g.IO.ConfigWindowsResizeFromEdges = false;
}
static void ImGui::ErrorCheckEndFrameSanityChecks()
{
ImGuiContext& g = *GImGui;
// Verify that io.KeyXXX fields haven't been tampered with. Key mods should not be modified between NewFrame() and EndFrame()
// One possible reason leading to this assert is that your back-ends update inputs _AFTER_ NewFrame().
const ImGuiKeyModFlags expected_key_mod_flags = GetMergedKeyModFlags();
IM_ASSERT(g.IO.KeyMods == expected_key_mod_flags && "Mismatching io.KeyCtrl/io.KeyShift/io.KeyAlt/io.KeySuper vs io.KeyMods");
IM_UNUSED(expected_key_mod_flags);
// Report when there is a mismatch of Begin/BeginChild vs End/EndChild calls. Important: Remember that the Begin/BeginChild API requires you
// to always call End/EndChild even if Begin/BeginChild returns false! (this is unfortunately inconsistent with most other Begin* API).
if (g.CurrentWindowStack.Size != 1)
{
if (g.CurrentWindowStack.Size > 1)
{
IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size == 1, "Mismatched Begin/BeginChild vs End/EndChild calls: did you forget to call End/EndChild?");
while (g.CurrentWindowStack.Size > 1)
End();
}
else
{
IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size == 1, "Mismatched Begin/BeginChild vs End/EndChild calls: did you call End/EndChild too much?");
}
}
}
// Save and compare stack sizes on Begin()/End() to detect usage errors
// Begin() calls this with write=true
// End() calls this with write=false
static void ImGui::ErrorCheckBeginEndCompareStacksSize(ImGuiWindow* window, bool write)
{
ImGuiContext& g = *GImGui;
short* p = &window->DC.StackSizesBackup[0];
// Window stacks
// NOT checking: DC.ItemWidth, DC.AllowKeyboardFocus, DC.ButtonRepeat, DC.TextWrapPos (per window) to allow user to conveniently push once and not pop (they are cleared on Begin)
{ int n = window->IDStack.Size; if (write) *p = (short)n; else IM_ASSERT(*p == n && "PushID/PopID or TreeNode/TreePop Mismatch!"); p++; } // Too few or too many PopID()/TreePop()
{ int n = window->DC.GroupStack.Size; if (write) *p = (short)n; else IM_ASSERT(*p == n && "BeginGroup/EndGroup Mismatch!"); p++; } // Too few or too many EndGroup()
// Global stacks
// For color, style and font stacks there is an incentive to use Push/Begin/Pop/.../End patterns, so we relax our checks a little to allow them.
{ int n = g.BeginPopupStack.Size; if (write) *p = (short)n; else IM_ASSERT(*p == n && "BeginMenu/EndMenu or BeginPopup/EndPopup Mismatch!"); p++; }// Too few or too many EndMenu()/EndPopup()
{ int n = g.ColorModifiers.Size; if (write) *p = (short)n; else IM_ASSERT(*p >= n && "PushStyleColor/PopStyleColor Mismatch!"); p++; } // Too few or too many PopStyleColor()
{ int n = g.StyleModifiers.Size; if (write) *p = (short)n; else IM_ASSERT(*p >= n && "PushStyleVar/PopStyleVar Mismatch!"); p++; } // Too few or too many PopStyleVar()
{ int n = g.FontStack.Size; if (write) *p = (short)n; else IM_ASSERT(*p >= n && "PushFont/PopFont Mismatch!"); p++; } // Too few or too many PopFont()
IM_ASSERT(p == window->DC.StackSizesBackup + IM_ARRAYSIZE(window->DC.StackSizesBackup));
}
//-----------------------------------------------------------------------------
// [SECTION] LAYOUT
//-----------------------------------------------------------------------------
// - ItemSize()
// - ItemAdd()
// - SameLine()
// - GetCursorScreenPos()
// - SetCursorScreenPos()
// - GetCursorPos(), GetCursorPosX(), GetCursorPosY()
// - SetCursorPos(), SetCursorPosX(), SetCursorPosY()
// - GetCursorStartPos()
// - Indent()
// - Unindent()
// - SetNextItemWidth()
// - PushItemWidth()
// - PushMultiItemsWidths()
// - PopItemWidth()
// - CalcItemWidth()
// - CalcItemSize()
// - GetTextLineHeight()
// - GetTextLineHeightWithSpacing()
// - GetFrameHeight()
// - GetFrameHeightWithSpacing()
// - GetContentRegionMax()
// - GetContentRegionMaxAbs() [Internal]
// - GetContentRegionAvail(),
// - GetWindowContentRegionMin(), GetWindowContentRegionMax()
// - GetWindowContentRegionWidth()
// - BeginGroup()
// - EndGroup()
// Also see in imgui_widgets: tab bars, columns.
//-----------------------------------------------------------------------------
// Advance cursor given item size for layout.
// Register minimum needed size so it can extend the bounding box used for auto-fit calculation.
// See comments in ItemAdd() about how/why the size provided to ItemSize() vs ItemAdd() may often different.
void ImGui::ItemSize(const ImVec2& size, float text_baseline_y)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (window->SkipItems)
return;
// We increase the height in this function to accommodate for baseline offset.
// In theory we should be offsetting the starting position (window->DC.CursorPos), that will be the topic of a larger refactor,
// but since ItemSize() is not yet an API that moves the cursor (to handle e.g. wrapping) enlarging the height has the same effect.
const float offset_to_match_baseline_y = (text_baseline_y >= 0) ? ImMax(0.0f, window->DC.CurrLineTextBaseOffset - text_baseline_y) : 0.0f;
const float line_height = ImMax(window->DC.CurrLineSize.y, size.y + offset_to_match_baseline_y);
// Always align ourselves on pixel boundaries
//if (g.IO.KeyAlt) window->DrawList->AddRect(window->DC.CursorPos, window->DC.CursorPos + ImVec2(size.x, line_height), IM_COL32(255,0,0,200)); // [DEBUG]
window->DC.CursorPosPrevLine.x = window->DC.CursorPos.x + size.x;
window->DC.CursorPosPrevLine.y = window->DC.CursorPos.y;
window->DC.CursorPos.x = IM_FLOOR(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x); // Next line
window->DC.CursorPos.y = IM_FLOOR(window->DC.CursorPos.y + line_height + g.Style.ItemSpacing.y); // Next line
window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPosPrevLine.x);
window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y - g.Style.ItemSpacing.y);
//if (g.IO.KeyAlt) window->DrawList->AddCircle(window->DC.CursorMaxPos, 3.0f, IM_COL32(255,0,0,255), 4); // [DEBUG]
window->DC.PrevLineSize.y = line_height;
window->DC.CurrLineSize.y = 0.0f;
window->DC.PrevLineTextBaseOffset = ImMax(window->DC.CurrLineTextBaseOffset, text_baseline_y);
window->DC.CurrLineTextBaseOffset = 0.0f;
// Horizontal layout mode
if (window->DC.LayoutType == ImGuiLayoutType_Horizontal)
SameLine();
}
void ImGui::ItemSize(const ImRect& bb, float text_baseline_y)
{
ItemSize(bb.GetSize(), text_baseline_y);
}
// Declare item bounding box for clipping and interaction.
// Note that the size can be different than the one provided to ItemSize(). Typically, widgets that spread over available surface
// declare their minimum size requirement to ItemSize() and provide a larger region to ItemAdd() which is used drawing/interaction.
bool ImGui::ItemAdd(const ImRect& bb, ImGuiID id, const ImRect* nav_bb_arg)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (id != 0)
{
// Navigation processing runs prior to clipping early-out
// (a) So that NavInitRequest can be honored, for newly opened windows to select a default widget
// (b) So that we can scroll up/down past clipped items. This adds a small O(N) cost to regular navigation requests
// unfortunately, but it is still limited to one window. It may not scale very well for windows with ten of
// thousands of item, but at least NavMoveRequest is only set on user interaction, aka maximum once a frame.
// We could early out with "if (is_clipped && !g.NavInitRequest) return false;" but when we wouldn't be able
// to reach unclipped widgets. This would work if user had explicit scrolling control (e.g. mapped on a stick).
// We intentionally don't check if g.NavWindow != NULL because g.NavAnyRequest should only be set when it is non null.
// If we crash on a NULL g.NavWindow we need to fix the bug elsewhere.
window->DC.NavLayerActiveMaskNext |= window->DC.NavLayerCurrentMask;
if (g.NavId == id || g.NavAnyRequest)
if (g.NavWindow->RootWindowForNav == window->RootWindowForNav)
if (window == g.NavWindow || ((window->Flags | g.NavWindow->Flags) & ImGuiWindowFlags_NavFlattened))
NavProcessItem(window, nav_bb_arg ? *nav_bb_arg : bb, id);
// [DEBUG] Item Picker tool, when enabling the "extended" version we perform the check in ItemAdd()
#ifdef IMGUI_DEBUG_TOOL_ITEM_PICKER_EX
if (id == g.DebugItemPickerBreakId)
{
IM_DEBUG_BREAK();
g.DebugItemPickerBreakId = 0;
}
#endif
}
// Equivalent to calling SetLastItemData()
window->DC.LastItemId = id;
window->DC.LastItemRect = bb;
window->DC.LastItemStatusFlags = ImGuiItemStatusFlags_None;
g.NextItemData.Flags = ImGuiNextItemDataFlags_None;
#ifdef IMGUI_ENABLE_TEST_ENGINE
if (id != 0)
IMGUI_TEST_ENGINE_ITEM_ADD(nav_bb_arg ? *nav_bb_arg : bb, id);
#endif
// Clipping test
const bool is_clipped = IsClippedEx(bb, id, false);
if (is_clipped)
return false;
//if (g.IO.KeyAlt) window->DrawList->AddRect(bb.Min, bb.Max, IM_COL32(255,255,0,120)); // [DEBUG]
// We need to calculate this now to take account of the current clipping rectangle (as items like Selectable may change them)
if (IsMouseHoveringRect(bb.Min, bb.Max))
window->DC.LastItemStatusFlags |= ImGuiItemStatusFlags_HoveredRect;
return true;
}
// Gets back to previous line and continue with horizontal layout
// offset_from_start_x == 0 : follow right after previous item
// offset_from_start_x != 0 : align to specified x position (relative to window/group left)
// spacing_w < 0 : use default spacing if pos_x == 0, no spacing if pos_x != 0
// spacing_w >= 0 : enforce spacing amount
void ImGui::SameLine(float offset_from_start_x, float spacing_w)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return;
ImGuiContext& g = *GImGui;
if (offset_from_start_x != 0.0f)
{
if (spacing_w < 0.0f) spacing_w = 0.0f;
window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + offset_from_start_x + spacing_w + window->DC.GroupOffset.x + window->DC.ColumnsOffset.x;
window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y;
}
else
{
if (spacing_w < 0.0f) spacing_w = g.Style.ItemSpacing.x;
window->DC.CursorPos.x = window->DC.CursorPosPrevLine.x + spacing_w;
window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y;
}
window->DC.CurrLineSize = window->DC.PrevLineSize;
window->DC.CurrLineTextBaseOffset = window->DC.PrevLineTextBaseOffset;
}
ImVec2 ImGui::GetCursorScreenPos()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->DC.CursorPos;
}
void ImGui::SetCursorScreenPos(const ImVec2& pos)
{
ImGuiWindow* window = GetCurrentWindow();
window->DC.CursorPos = pos;
window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
}
// User generally sees positions in window coordinates. Internally we store CursorPos in absolute screen coordinates because it is more convenient.
// Conversion happens as we pass the value to user, but it makes our naming convention confusing because GetCursorPos() == (DC.CursorPos - window.Pos). May want to rename 'DC.CursorPos'.
ImVec2 ImGui::GetCursorPos()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->DC.CursorPos - window->Pos + window->Scroll;
}
float ImGui::GetCursorPosX()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->DC.CursorPos.x - window->Pos.x + window->Scroll.x;
}
float ImGui::GetCursorPosY()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->DC.CursorPos.y - window->Pos.y + window->Scroll.y;
}
void ImGui::SetCursorPos(const ImVec2& local_pos)
{
ImGuiWindow* window = GetCurrentWindow();
window->DC.CursorPos = window->Pos - window->Scroll + local_pos;
window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
}
void ImGui::SetCursorPosX(float x)
{
ImGuiWindow* window = GetCurrentWindow();
window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + x;
window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPos.x);
}
void ImGui::SetCursorPosY(float y)
{
ImGuiWindow* window = GetCurrentWindow();
window->DC.CursorPos.y = window->Pos.y - window->Scroll.y + y;
window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y);
}
ImVec2 ImGui::GetCursorStartPos()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->DC.CursorStartPos - window->Pos;
}
void ImGui::Indent(float indent_w)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = GetCurrentWindow();
window->DC.Indent.x += (indent_w != 0.0f) ? indent_w : g.Style.IndentSpacing;
window->DC.CursorPos.x = window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x;
}
void ImGui::Unindent(float indent_w)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = GetCurrentWindow();
window->DC.Indent.x -= (indent_w != 0.0f) ? indent_w : g.Style.IndentSpacing;
window->DC.CursorPos.x = window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x;
}
// Affect large frame+labels widgets only.
void ImGui::SetNextItemWidth(float item_width)
{
ImGuiContext& g = *GImGui;
g.NextItemData.Flags |= ImGuiNextItemDataFlags_HasWidth;
g.NextItemData.Width = item_width;
}
void ImGui::PushItemWidth(float item_width)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
window->DC.ItemWidth = (item_width == 0.0f ? window->ItemWidthDefault : item_width);
window->DC.ItemWidthStack.push_back(window->DC.ItemWidth);
g.NextItemData.Flags &= ~ImGuiNextItemDataFlags_HasWidth;
}
void ImGui::PushMultiItemsWidths(int components, float w_full)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
const ImGuiStyle& style = g.Style;
const float w_item_one = ImMax(1.0f, IM_FLOOR((w_full - (style.ItemInnerSpacing.x) * (components - 1)) / (float)components));
const float w_item_last = ImMax(1.0f, IM_FLOOR(w_full - (w_item_one + style.ItemInnerSpacing.x) * (components - 1)));
window->DC.ItemWidthStack.push_back(w_item_last);
for (int i = 0; i < components - 1; i++)
window->DC.ItemWidthStack.push_back(w_item_one);
window->DC.ItemWidth = window->DC.ItemWidthStack.back();
g.NextItemData.Flags &= ~ImGuiNextItemDataFlags_HasWidth;
}
void ImGui::PopItemWidth()
{
ImGuiWindow* window = GetCurrentWindow();
window->DC.ItemWidthStack.pop_back();
window->DC.ItemWidth = window->DC.ItemWidthStack.empty() ? window->ItemWidthDefault : window->DC.ItemWidthStack.back();
}
// Calculate default item width given value passed to PushItemWidth() or SetNextItemWidth().
// The SetNextItemWidth() data is generally cleared/consumed by ItemAdd() or NextItemData.ClearFlags()
float ImGui::CalcItemWidth()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
float w;
if (g.NextItemData.Flags & ImGuiNextItemDataFlags_HasWidth)
w = g.NextItemData.Width;
else
w = window->DC.ItemWidth;
if (w < 0.0f)
{
float region_max_x = GetContentRegionMaxAbs().x;
w = ImMax(1.0f, region_max_x - window->DC.CursorPos.x + w);
}
w = IM_FLOOR(w);
return w;
}
// [Internal] Calculate full item size given user provided 'size' parameter and default width/height. Default width is often == CalcItemWidth().
// Those two functions CalcItemWidth vs CalcItemSize are awkwardly named because they are not fully symmetrical.
// Note that only CalcItemWidth() is publicly exposed.
// The 4.0f here may be changed to match CalcItemWidth() and/or BeginChild() (right now we have a mismatch which is harmless but undesirable)
ImVec2 ImGui::CalcItemSize(ImVec2 size, float default_w, float default_h)
{
ImGuiWindow* window = GImGui->CurrentWindow;
ImVec2 region_max;
if (size.x < 0.0f || size.y < 0.0f)
region_max = GetContentRegionMaxAbs();
if (size.x == 0.0f)
size.x = default_w;
else if (size.x < 0.0f)
size.x = ImMax(4.0f, region_max.x - window->DC.CursorPos.x + size.x);
if (size.y == 0.0f)
size.y = default_h;
else if (size.y < 0.0f)
size.y = ImMax(4.0f, region_max.y - window->DC.CursorPos.y + size.y);
return size;
}
float ImGui::GetTextLineHeight()
{
ImGuiContext& g = *GImGui;
return g.FontSize;
}
float ImGui::GetTextLineHeightWithSpacing()
{
ImGuiContext& g = *GImGui;
return g.FontSize + g.Style.ItemSpacing.y;
}
float ImGui::GetFrameHeight()
{
ImGuiContext& g = *GImGui;
return g.FontSize + g.Style.FramePadding.y * 2.0f;
}
float ImGui::GetFrameHeightWithSpacing()
{
ImGuiContext& g = *GImGui;
return g.FontSize + g.Style.FramePadding.y * 2.0f + g.Style.ItemSpacing.y;
}
// FIXME: All the Contents Region function are messy or misleading. WE WILL AIM TO OBSOLETE ALL OF THEM WITH A NEW "WORK RECT" API. Thanks for your patience!
// FIXME: This is in window space (not screen space!).
ImVec2 ImGui::GetContentRegionMax()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
ImVec2 mx = window->ContentRegionRect.Max - window->Pos;
if (window->DC.CurrentColumns)
mx.x = window->WorkRect.Max.x - window->Pos.x;
return mx;
}
// [Internal] Absolute coordinate. Saner. This is not exposed until we finishing refactoring work rect features.
ImVec2 ImGui::GetContentRegionMaxAbs()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
ImVec2 mx = window->ContentRegionRect.Max;
if (window->DC.CurrentColumns)
mx.x = window->WorkRect.Max.x;
return mx;
}
ImVec2 ImGui::GetContentRegionAvail()
{
ImGuiWindow* window = GImGui->CurrentWindow;
return GetContentRegionMaxAbs() - window->DC.CursorPos;
}
// In window space (not screen space!)
ImVec2 ImGui::GetWindowContentRegionMin()
{
ImGuiWindow* window = GImGui->CurrentWindow;
return window->ContentRegionRect.Min - window->Pos;
}
ImVec2 ImGui::GetWindowContentRegionMax()
{
ImGuiWindow* window = GImGui->CurrentWindow;
return window->ContentRegionRect.Max - window->Pos;
}
float ImGui::GetWindowContentRegionWidth()
{
ImGuiWindow* window = GImGui->CurrentWindow;
return window->ContentRegionRect.GetWidth();
}
// Lock horizontal starting position + capture group bounding box into one "item" (so you can use IsItemHovered() or layout primitives such as SameLine() on whole group, etc.)
// Groups are currently a mishmash of functionalities which should perhaps be clarified and separated.
void ImGui::BeginGroup()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
window->DC.GroupStack.resize(window->DC.GroupStack.Size + 1);
ImGuiGroupData& group_data = window->DC.GroupStack.back();
group_data.BackupCursorPos = window->DC.CursorPos;
group_data.BackupCursorMaxPos = window->DC.CursorMaxPos;
group_data.BackupIndent = window->DC.Indent;
group_data.BackupGroupOffset = window->DC.GroupOffset;
group_data.BackupCurrLineSize = window->DC.CurrLineSize;
group_data.BackupCurrLineTextBaseOffset = window->DC.CurrLineTextBaseOffset;
group_data.BackupActiveIdIsAlive = g.ActiveIdIsAlive;
group_data.BackupActiveIdPreviousFrameIsAlive = g.ActiveIdPreviousFrameIsAlive;
group_data.EmitItem = true;
window->DC.GroupOffset.x = window->DC.CursorPos.x - window->Pos.x - window->DC.ColumnsOffset.x;
window->DC.Indent = window->DC.GroupOffset;
window->DC.CursorMaxPos = window->DC.CursorPos;
window->DC.CurrLineSize = ImVec2(0.0f, 0.0f);
if (g.LogEnabled)
g.LogLinePosY = -FLT_MAX; // To enforce Log carriage return
}
void ImGui::EndGroup()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
IM_ASSERT(window->DC.GroupStack.Size > 0); // Mismatched BeginGroup()/EndGroup() calls
ImGuiGroupData& group_data = window->DC.GroupStack.back();
ImRect group_bb(group_data.BackupCursorPos, ImMax(window->DC.CursorMaxPos, group_data.BackupCursorPos));
window->DC.CursorPos = group_data.BackupCursorPos;
window->DC.CursorMaxPos = ImMax(group_data.BackupCursorMaxPos, window->DC.CursorMaxPos);
window->DC.Indent = group_data.BackupIndent;
window->DC.GroupOffset = group_data.BackupGroupOffset;
window->DC.CurrLineSize = group_data.BackupCurrLineSize;
window->DC.CurrLineTextBaseOffset = group_data.BackupCurrLineTextBaseOffset;
if (g.LogEnabled)
g.LogLinePosY = -FLT_MAX; // To enforce Log carriage return
if (!group_data.EmitItem)
{
window->DC.GroupStack.pop_back();
return;
}
window->DC.CurrLineTextBaseOffset = ImMax(window->DC.PrevLineTextBaseOffset, group_data.BackupCurrLineTextBaseOffset); // FIXME: Incorrect, we should grab the base offset from the *first line* of the group but it is hard to obtain now.
ItemSize(group_bb.GetSize());
ItemAdd(group_bb, 0);
// If the current ActiveId was declared within the boundary of our group, we copy it to LastItemId so IsItemActive(), IsItemDeactivated() etc. will be functional on the entire group.
// It would be be neater if we replaced window.DC.LastItemId by e.g. 'bool LastItemIsActive', but would put a little more burden on individual widgets.
// Also if you grep for LastItemId you'll notice it is only used in that context.
// (The two tests not the same because ActiveIdIsAlive is an ID itself, in order to be able to handle ActiveId being overwritten during the frame.)
const bool group_contains_curr_active_id = (group_data.BackupActiveIdIsAlive != g.ActiveId) && (g.ActiveIdIsAlive == g.ActiveId) && g.ActiveId;
const bool group_contains_prev_active_id = (group_data.BackupActiveIdPreviousFrameIsAlive == false) && (g.ActiveIdPreviousFrameIsAlive == true);
if (group_contains_curr_active_id)
window->DC.LastItemId = g.ActiveId;
else if (group_contains_prev_active_id)
window->DC.LastItemId = g.ActiveIdPreviousFrame;
window->DC.LastItemRect = group_bb;
// Forward Edited flag
if (group_contains_curr_active_id && g.ActiveIdHasBeenEditedThisFrame)
window->DC.LastItemStatusFlags |= ImGuiItemStatusFlags_Edited;
// Forward Deactivated flag
window->DC.LastItemStatusFlags |= ImGuiItemStatusFlags_HasDeactivated;
if (group_contains_prev_active_id && g.ActiveId != g.ActiveIdPreviousFrame)
window->DC.LastItemStatusFlags |= ImGuiItemStatusFlags_Deactivated;
window->DC.GroupStack.pop_back();
//window->DrawList->AddRect(group_bb.Min, group_bb.Max, IM_COL32(255,0,255,255)); // [Debug]
}
//-----------------------------------------------------------------------------
// [SECTION] SCROLLING
//-----------------------------------------------------------------------------
static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window)
{
ImVec2 scroll = window->Scroll;
if (window->ScrollTarget.x < FLT_MAX)
{
float cr_x = window->ScrollTargetCenterRatio.x;
float target_x = window->ScrollTarget.x;
scroll.x = target_x - cr_x * (window->SizeFull.x - window->ScrollbarSizes.x);
}
if (window->ScrollTarget.y < FLT_MAX)
{
float decoration_up_height = window->TitleBarHeight() + window->MenuBarHeight();
float cr_y = window->ScrollTargetCenterRatio.y;
float target_y = window->ScrollTarget.y;
scroll.y = target_y - cr_y * (window->SizeFull.y - window->ScrollbarSizes.y - decoration_up_height);
}
scroll.x = IM_FLOOR(ImMax(scroll.x, 0.0f));
scroll.y = IM_FLOOR(ImMax(scroll.y, 0.0f));
if (!window->Collapsed && !window->SkipItems)
{
scroll.x = ImMin(scroll.x, window->ScrollMax.x);
scroll.y = ImMin(scroll.y, window->ScrollMax.y);
}
return scroll;
}
// Scroll to keep newly navigated item fully into view
ImVec2 ImGui::ScrollToBringRectIntoView(ImGuiWindow* window, const ImRect& item_rect)
{
ImGuiContext& g = *GImGui;
ImRect window_rect(window->InnerRect.Min - ImVec2(1, 1), window->InnerRect.Max + ImVec2(1, 1));
//GetForegroundDrawList(window)->AddRect(window_rect.Min, window_rect.Max, IM_COL32_WHITE); // [DEBUG]
ImVec2 delta_scroll;
if (!window_rect.Contains(item_rect))
{
if (window->ScrollbarX && item_rect.Min.x < window_rect.Min.x)
SetScrollFromPosX(window, item_rect.Min.x - window->Pos.x - g.Style.ItemSpacing.x, 0.0f);
else if (window->ScrollbarX && item_rect.Max.x >= window_rect.Max.x)
SetScrollFromPosX(window, item_rect.Max.x - window->Pos.x + g.Style.ItemSpacing.x, 1.0f);
if (item_rect.Min.y < window_rect.Min.y)
SetScrollFromPosY(window, item_rect.Min.y - window->Pos.y - g.Style.ItemSpacing.y, 0.0f);
else if (item_rect.Max.y >= window_rect.Max.y)
SetScrollFromPosY(window, item_rect.Max.y - window->Pos.y + g.Style.ItemSpacing.y, 1.0f);
ImVec2 next_scroll = CalcNextScrollFromScrollTargetAndClamp(window);
delta_scroll = next_scroll - window->Scroll;
}
// Also scroll parent window to keep us into view if necessary
if (window->Flags & ImGuiWindowFlags_ChildWindow)
delta_scroll += ScrollToBringRectIntoView(window->ParentWindow, ImRect(item_rect.Min - delta_scroll, item_rect.Max - delta_scroll));
return delta_scroll;
}
float ImGui::GetScrollX()
{
ImGuiWindow* window = GImGui->CurrentWindow;
return window->Scroll.x;
}
float ImGui::GetScrollY()
{
ImGuiWindow* window = GImGui->CurrentWindow;
return window->Scroll.y;
}
float ImGui::GetScrollMaxX()
{
ImGuiWindow* window = GImGui->CurrentWindow;
return window->ScrollMax.x;
}
float ImGui::GetScrollMaxY()
{
ImGuiWindow* window = GImGui->CurrentWindow;
return window->ScrollMax.y;
}
void ImGui::SetScrollX(float scroll_x)
{
ImGuiWindow* window = GetCurrentWindow();
window->ScrollTarget.x = scroll_x;
window->ScrollTargetCenterRatio.x = 0.0f;
}
void ImGui::SetScrollY(float scroll_y)
{
ImGuiWindow* window = GetCurrentWindow();
window->ScrollTarget.y = scroll_y;
window->ScrollTargetCenterRatio.y = 0.0f;
}
void ImGui::SetScrollX(ImGuiWindow* window, float new_scroll_x)
{
window->ScrollTarget.x = new_scroll_x;
window->ScrollTargetCenterRatio.x = 0.0f;
}
void ImGui::SetScrollY(ImGuiWindow* window, float new_scroll_y)
{
window->ScrollTarget.y = new_scroll_y;
window->ScrollTargetCenterRatio.y = 0.0f;
}
// Note that a local position will vary depending on initial scroll value
// We store a target position so centering can occur on the next frame when we are guaranteed to have a known window size
void ImGui::SetScrollFromPosX(ImGuiWindow* window, float local_x, float center_x_ratio)
{
IM_ASSERT(center_x_ratio >= 0.0f && center_x_ratio <= 1.0f);
window->ScrollTarget.x = IM_FLOOR(local_x + window->Scroll.x);
window->ScrollTargetCenterRatio.x = center_x_ratio;
}
void ImGui::SetScrollFromPosY(ImGuiWindow* window, float local_y, float center_y_ratio)
{
IM_ASSERT(center_y_ratio >= 0.0f && center_y_ratio <= 1.0f);
local_y -= window->TitleBarHeight() + window->MenuBarHeight(); // FIXME: Would be nice to have a more standardized access to our scrollable/client rect
window->ScrollTarget.y = IM_FLOOR(local_y + window->Scroll.y);
window->ScrollTargetCenterRatio.y = center_y_ratio;
}
void ImGui::SetScrollFromPosX(float local_x, float center_x_ratio)
{
ImGuiContext& g = *GImGui;
SetScrollFromPosX(g.CurrentWindow, local_x, center_x_ratio);
}
void ImGui::SetScrollFromPosY(float local_y, float center_y_ratio)
{
ImGuiContext& g = *GImGui;
SetScrollFromPosY(g.CurrentWindow, local_y, center_y_ratio);
}
// Tweak: snap on edges when aiming at an item very close to the edge,
// So the difference between WindowPadding and ItemSpacing will be in the visible area after scrolling.
// When we refactor the scrolling API this may be configurable with a flag?
// Note that the effect for this won't be visible on X axis with default Style settings as WindowPadding.x == ItemSpacing.x by default.
static float CalcScrollSnap(float target, float snap_min, float snap_max, float snap_threshold, float center_ratio)
{
if (target <= snap_min + snap_threshold)
return ImLerp(snap_min, target, center_ratio);
if (target >= snap_max - snap_threshold)
return ImLerp(target, snap_max, center_ratio);
return target;
}
// center_x_ratio: 0.0f left of last item, 0.5f horizontal center of last item, 1.0f right of last item.
void ImGui::SetScrollHereX(float center_x_ratio)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
float spacing_x = g.Style.ItemSpacing.x;
float target_x = ImLerp(window->DC.LastItemRect.Min.x - spacing_x, window->DC.LastItemRect.Max.x + spacing_x, center_x_ratio);
// Tweak: snap on edges when aiming at an item very close to the edge
const float snap_x_threshold = ImMax(0.0f, window->WindowPadding.x - spacing_x);
const float snap_x_min = window->DC.CursorStartPos.x - window->WindowPadding.x;
const float snap_x_max = window->DC.CursorStartPos.x + window->ContentSize.x + window->WindowPadding.x;
target_x = CalcScrollSnap(target_x, snap_x_min, snap_x_max, snap_x_threshold, center_x_ratio);
SetScrollFromPosX(window, target_x - window->Pos.x, center_x_ratio);
}
// center_y_ratio: 0.0f top of last item, 0.5f vertical center of last item, 1.0f bottom of last item.
void ImGui::SetScrollHereY(float center_y_ratio)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
float spacing_y = g.Style.ItemSpacing.y;
float target_y = ImLerp(window->DC.CursorPosPrevLine.y - spacing_y, window->DC.CursorPosPrevLine.y + window->DC.PrevLineSize.y + spacing_y, center_y_ratio);
// Tweak: snap on edges when aiming at an item very close to the edge
const float snap_y_threshold = ImMax(0.0f, window->WindowPadding.y - spacing_y);
const float snap_y_min = window->DC.CursorStartPos.y - window->WindowPadding.y;
const float snap_y_max = window->DC.CursorStartPos.y + window->ContentSize.y + window->WindowPadding.y;
target_y = CalcScrollSnap(target_y, snap_y_min, snap_y_max, snap_y_threshold, center_y_ratio);
SetScrollFromPosY(window, target_y - window->Pos.y, center_y_ratio);
}
//-----------------------------------------------------------------------------
// [SECTION] TOOLTIPS
//-----------------------------------------------------------------------------
void ImGui::BeginTooltip()
{
BeginTooltipEx(ImGuiWindowFlags_None, ImGuiTooltipFlags_None);
}
void ImGui::BeginTooltipEx(ImGuiWindowFlags extra_flags, ImGuiTooltipFlags tooltip_flags)
{
ImGuiContext& g = *GImGui;
if (g.DragDropWithinSource || g.DragDropWithinTarget)
{
// The default tooltip position is a little offset to give space to see the context menu (it's also clamped within the current viewport/monitor)
// In the context of a dragging tooltip we try to reduce that offset and we enforce following the cursor.
// Whatever we do we want to call SetNextWindowPos() to enforce a tooltip position and disable clipping the tooltip without our display area, like regular tooltip do.
//ImVec2 tooltip_pos = g.IO.MousePos - g.ActiveIdClickOffset - g.Style.WindowPadding;
ImVec2 tooltip_pos = g.IO.MousePos + ImVec2(16 * g.Style.MouseCursorScale, 8 * g.Style.MouseCursorScale);
SetNextWindowPos(tooltip_pos);
SetNextWindowBgAlpha(g.Style.Colors[ImGuiCol_PopupBg].w * 0.60f);
//PushStyleVar(ImGuiStyleVar_Alpha, g.Style.Alpha * 0.60f); // This would be nice but e.g ColorButton with checkboard has issue with transparent colors :(
tooltip_flags |= ImGuiTooltipFlags_OverridePreviousTooltip;
}
char window_name[16];
ImFormatString(window_name, IM_ARRAYSIZE(window_name), "##Tooltip_%02d", g.TooltipOverrideCount);
if (tooltip_flags & ImGuiTooltipFlags_OverridePreviousTooltip)
if (ImGuiWindow* window = FindWindowByName(window_name))
if (window->Active)
{
// Hide previous tooltip from being displayed. We can't easily "reset" the content of a window so we create a new one.
window->Hidden = true;
window->HiddenFramesCanSkipItems = 1;
ImFormatString(window_name, IM_ARRAYSIZE(window_name), "##Tooltip_%02d", ++g.TooltipOverrideCount);
}
ImGuiWindowFlags flags = ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_AlwaysAutoResize;
Begin(window_name, NULL, flags | extra_flags);
}
void ImGui::EndTooltip()
{
IM_ASSERT(GetCurrentWindowRead()->Flags & ImGuiWindowFlags_Tooltip); // Mismatched BeginTooltip()/EndTooltip() calls
End();
}
void ImGui::SetTooltipV(const char* fmt, va_list args)
{
BeginTooltipEx(0, ImGuiTooltipFlags_OverridePreviousTooltip);
TextV(fmt, args);
EndTooltip();
}
void ImGui::SetTooltip(const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
SetTooltipV(fmt, args);
va_end(args);
}
//-----------------------------------------------------------------------------
// [SECTION] POPUPS
//-----------------------------------------------------------------------------
// Supported flags: ImGuiPopupFlags_AnyPopupId, ImGuiPopupFlags_AnyPopupLevel
bool ImGui::IsPopupOpen(ImGuiID id, ImGuiPopupFlags popup_flags)
{
ImGuiContext& g = *GImGui;
if (popup_flags & ImGuiPopupFlags_AnyPopupId)
{
// Return true if any popup is open at the current BeginPopup() level of the popup stack
// This may be used to e.g. test for another popups already opened to handle popups priorities at the same level.
IM_ASSERT(id == 0);
if (popup_flags & ImGuiPopupFlags_AnyPopupLevel)
return g.OpenPopupStack.Size > 0;
else
return g.OpenPopupStack.Size > g.BeginPopupStack.Size;
}
else
{
if (popup_flags & ImGuiPopupFlags_AnyPopupLevel)
{
// Return true if the popup is open anywhere in the popup stack
for (int n = 0; n < g.OpenPopupStack.Size; n++)
if (g.OpenPopupStack[n].PopupId == id)
return true;
return false;
}
else
{
// Return true if the popup is open at the current BeginPopup() level of the popup stack (this is the most-common query)
return g.OpenPopupStack.Size > g.BeginPopupStack.Size && g.OpenPopupStack[g.BeginPopupStack.Size].PopupId == id;
}
}
}
bool ImGui::IsPopupOpen(const char* str_id, ImGuiPopupFlags popup_flags)
{
ImGuiContext& g = *GImGui;
ImGuiID id = (popup_flags & ImGuiPopupFlags_AnyPopupId) ? 0 : g.CurrentWindow->GetID(str_id);
if ((popup_flags & ImGuiPopupFlags_AnyPopupLevel) && id != 0)
IM_ASSERT(0 && "Cannot use IsPopupOpen() with a string id and ImGuiPopupFlags_AnyPopupLevel."); // But non-string version is legal and used internally
return IsPopupOpen(id, popup_flags);
}
ImGuiWindow* ImGui::GetTopMostPopupModal()
{
ImGuiContext& g = *GImGui;
for (int n = g.OpenPopupStack.Size - 1; n >= 0; n--)
if (ImGuiWindow* popup = g.OpenPopupStack.Data[n].Window)
if (popup->Flags & ImGuiWindowFlags_Modal)
return popup;
return NULL;
}
void ImGui::OpenPopup(const char* str_id, ImGuiPopupFlags popup_flags)
{
ImGuiContext& g = *GImGui;
OpenPopupEx(g.CurrentWindow->GetID(str_id), popup_flags);
}
// Mark popup as open (toggle toward open state).
// Popups are closed when user click outside, or activate a pressable item, or CloseCurrentPopup() is called within a BeginPopup()/EndPopup() block.
// Popup identifiers are relative to the current ID-stack (so OpenPopup and BeginPopup needs to be at the same level).
// One open popup per level of the popup hierarchy (NB: when assigning we reset the Window member of ImGuiPopupRef to NULL)
void ImGui::OpenPopupEx(ImGuiID id, ImGuiPopupFlags popup_flags)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* parent_window = g.CurrentWindow;
const int current_stack_size = g.BeginPopupStack.Size;
if (popup_flags & ImGuiPopupFlags_NoOpenOverExistingPopup)
if (IsPopupOpen(0u, ImGuiPopupFlags_AnyPopupId))
return;
ImGuiPopupData popup_ref; // Tagged as new ref as Window will be set back to NULL if we write this into OpenPopupStack.
popup_ref.PopupId = id;
popup_ref.Window = NULL;
popup_ref.SourceWindow = g.NavWindow;
popup_ref.OpenFrameCount = g.FrameCount;
popup_ref.OpenParentId = parent_window->IDStack.back();
popup_ref.OpenPopupPos = NavCalcPreferredRefPos();
popup_ref.OpenMousePos = IsMousePosValid(&g.IO.MousePos) ? g.IO.MousePos : popup_ref.OpenPopupPos;
IMGUI_DEBUG_LOG_POPUP("OpenPopupEx(0x%08X)\n", id);
if (g.OpenPopupStack.Size < current_stack_size + 1)
{
g.OpenPopupStack.push_back(popup_ref);
}
else
{
// Gently handle the user mistakenly calling OpenPopup() every frame. It is a programming mistake! However, if we were to run the regular code path, the ui
// would become completely unusable because the popup will always be in hidden-while-calculating-size state _while_ claiming focus. Which would be a very confusing
// situation for the programmer. Instead, we silently allow the popup to proceed, it will keep reappearing and the programming error will be more obvious to understand.
if (g.OpenPopupStack[current_stack_size].PopupId == id && g.OpenPopupStack[current_stack_size].OpenFrameCount == g.FrameCount - 1)
{
g.OpenPopupStack[current_stack_size].OpenFrameCount = popup_ref.OpenFrameCount;
}
else
{
// Close child popups if any, then flag popup for open/reopen
ClosePopupToLevel(current_stack_size, false);
g.OpenPopupStack.push_back(popup_ref);
}
// When reopening a popup we first refocus its parent, otherwise if its parent is itself a popup it would get closed by ClosePopupsOverWindow().
// This is equivalent to what ClosePopupToLevel() does.
//if (g.OpenPopupStack[current_stack_size].PopupId == id)
// FocusWindow(parent_window);
}
}
// When popups are stacked, clicking on a lower level popups puts focus back to it and close popups above it.
// This function closes any popups that are over 'ref_window'.
void ImGui::ClosePopupsOverWindow(ImGuiWindow* ref_window, bool restore_focus_to_window_under_popup)
{
ImGuiContext& g = *GImGui;
if (g.OpenPopupStack.Size == 0)
return;
// Don't close our own child popup windows.
int popup_count_to_keep = 0;
if (ref_window)
{
// Find the highest popup which is a descendant of the reference window (generally reference window = NavWindow)
for (; popup_count_to_keep < g.OpenPopupStack.Size; popup_count_to_keep++)
{
ImGuiPopupData& popup = g.OpenPopupStack[popup_count_to_keep];
if (!popup.Window)
continue;
IM_ASSERT((popup.Window->Flags & ImGuiWindowFlags_Popup) != 0);
if (popup.Window->Flags & ImGuiWindowFlags_ChildWindow)
continue;
// Trim the stack unless the popup is a direct parent of the reference window (the reference window is often the NavWindow)
// - With this stack of window, clicking/focusing Popup1 will close Popup2 and Popup3:
// Window -> Popup1 -> Popup2 -> Popup3
// - Each popups may contain child windows, which is why we compare ->RootWindow!
// Window -> Popup1 -> Popup1_Child -> Popup2 -> Popup2_Child
bool ref_window_is_descendent_of_popup = false;
for (int n = popup_count_to_keep; n < g.OpenPopupStack.Size; n++)
if (ImGuiWindow* popup_window = g.OpenPopupStack[n].Window)
if (popup_window->RootWindow == ref_window->RootWindow)
{
ref_window_is_descendent_of_popup = true;
break;
}
if (!ref_window_is_descendent_of_popup)
break;
}
}
if (popup_count_to_keep < g.OpenPopupStack.Size) // This test is not required but it allows to set a convenient breakpoint on the statement below
{
IMGUI_DEBUG_LOG_POPUP("ClosePopupsOverWindow(\"%s\") -> ClosePopupToLevel(%d)\n", ref_window->Name, popup_count_to_keep);
ClosePopupToLevel(popup_count_to_keep, restore_focus_to_window_under_popup);
}
}
void ImGui::ClosePopupToLevel(int remaining, bool restore_focus_to_window_under_popup)
{
ImGuiContext& g = *GImGui;
IMGUI_DEBUG_LOG_POPUP("ClosePopupToLevel(%d), restore_focus_to_window_under_popup=%d\n", remaining, restore_focus_to_window_under_popup);
IM_ASSERT(remaining >= 0 && remaining < g.OpenPopupStack.Size);
// Trim open popup stack
ImGuiWindow* focus_window = g.OpenPopupStack[remaining].SourceWindow;
ImGuiWindow* popup_window = g.OpenPopupStack[remaining].Window;
g.OpenPopupStack.resize(remaining);
if (restore_focus_to_window_under_popup)
{
if (focus_window && !focus_window->WasActive && popup_window)
{
// Fallback
FocusTopMostWindowUnderOne(popup_window, NULL);
}
else
{
if (g.NavLayer == ImGuiNavLayer_Main && focus_window)
focus_window = NavRestoreLastChildNavWindow(focus_window);
FocusWindow(focus_window);
}
}
}
// Close the popup we have begin-ed into.
void ImGui::CloseCurrentPopup()
{
ImGuiContext& g = *GImGui;
int popup_idx = g.BeginPopupStack.Size - 1;
if (popup_idx < 0 || popup_idx >= g.OpenPopupStack.Size || g.BeginPopupStack[popup_idx].PopupId != g.OpenPopupStack[popup_idx].PopupId)
return;
// Closing a menu closes its top-most parent popup (unless a modal)
while (popup_idx > 0)
{
ImGuiWindow* popup_window = g.OpenPopupStack[popup_idx].Window;
ImGuiWindow* parent_popup_window = g.OpenPopupStack[popup_idx - 1].Window;
bool close_parent = false;
if (popup_window && (popup_window->Flags & ImGuiWindowFlags_ChildMenu))
if (parent_popup_window == NULL || !(parent_popup_window->Flags & ImGuiWindowFlags_Modal))
close_parent = true;
if (!close_parent)
break;
popup_idx--;
}
IMGUI_DEBUG_LOG_POPUP("CloseCurrentPopup %d -> %d\n", g.BeginPopupStack.Size - 1, popup_idx);
ClosePopupToLevel(popup_idx, true);
// A common pattern is to close a popup when selecting a menu item/selectable that will open another window.
// To improve this usage pattern, we avoid nav highlight for a single frame in the parent window.
// Similarly, we could avoid mouse hover highlight in this window but it is less visually problematic.
if (ImGuiWindow* window = g.NavWindow)
window->DC.NavHideHighlightOneFrame = true;
}
// Attention! BeginPopup() adds default flags which BeginPopupEx()!
bool ImGui::BeginPopupEx(ImGuiID id, ImGuiWindowFlags flags)
{
ImGuiContext& g = *GImGui;
if (!IsPopupOpen(id, ImGuiPopupFlags_None))
{
g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
return false;
}
char name[20];
if (flags & ImGuiWindowFlags_ChildMenu)
ImFormatString(name, IM_ARRAYSIZE(name), "##Menu_%02d", g.BeginPopupStack.Size); // Recycle windows based on depth
else
ImFormatString(name, IM_ARRAYSIZE(name), "##Popup_%08x", id); // Not recycling, so we can close/open during the same frame
flags |= ImGuiWindowFlags_Popup;
bool is_open = Begin(name, NULL, flags);
if (!is_open) // NB: Begin can return false when the popup is completely clipped (e.g. zero size display)
EndPopup();
return is_open;
}
bool ImGui::BeginPopup(const char* str_id, ImGuiWindowFlags flags)
{
ImGuiContext& g = *GImGui;
if (g.OpenPopupStack.Size <= g.BeginPopupStack.Size) // Early out for performance
{
g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
return false;
}
flags |= ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings;
return BeginPopupEx(g.CurrentWindow->GetID(str_id), flags);
}
// If 'p_open' is specified for a modal popup window, the popup will have a regular close button which will close the popup.
// Note that popup visibility status is owned by Dear ImGui (and manipulated with e.g. OpenPopup) so the actual value of *p_open is meaningless here.
bool ImGui::BeginPopupModal(const char* name, bool* p_open, ImGuiWindowFlags flags)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
const ImGuiID id = window->GetID(name);
if (!IsPopupOpen(id, ImGuiPopupFlags_None))
{
g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
return false;
}
// Center modal windows by default for increased visibility
// (this won't really last as settings will kick in, and is mostly for backward compatibility. user may do the same themselves)
// FIXME: Should test for (PosCond & window->SetWindowPosAllowFlags) with the upcoming window.
if ((g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos) == 0)
SetNextWindowPos(g.IO.DisplaySize * 0.5f, ImGuiCond_FirstUseEver, ImVec2(0.5f, 0.5f));
flags |= ImGuiWindowFlags_Popup | ImGuiWindowFlags_Modal | ImGuiWindowFlags_NoCollapse;
const bool is_open = Begin(name, p_open, flags);
if (!is_open || (p_open && !*p_open)) // NB: is_open can be 'false' when the popup is completely clipped (e.g. zero size display)
{
EndPopup();
if (is_open)
ClosePopupToLevel(g.BeginPopupStack.Size, true);
return false;
}
return is_open;
}
void ImGui::EndPopup()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
IM_ASSERT(window->Flags & ImGuiWindowFlags_Popup); // Mismatched BeginPopup()/EndPopup() calls
IM_ASSERT(g.BeginPopupStack.Size > 0);
// Make all menus and popups wrap around for now, may need to expose that policy.
if (g.NavWindow == window)
NavMoveRequestTryWrapping(window, ImGuiNavMoveFlags_LoopY);
// Child-popups don't need to be laid out
IM_ASSERT(g.WithinEndChild == false);
if (window->Flags & ImGuiWindowFlags_ChildWindow)
g.WithinEndChild = true;
End();
g.WithinEndChild = false;
}
// Open a popup if mouse button is released over the item
bool ImGui::OpenPopupContextItem(const char* str_id, ImGuiPopupFlags popup_flags)
{
ImGuiWindow* window = GImGui->CurrentWindow;
int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
{
ImGuiID id = str_id ? window->GetID(str_id) : window->DC.LastItemId; // If user hasn't passed an ID, we can use the LastItemID. Using LastItemID as a Popup ID won't conflict!
IM_ASSERT(id != 0); // You cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item)
OpenPopupEx(id, popup_flags);
return true;
}
return false;
}
// This is a helper to handle the simplest case of associating one named popup to one given widget.
// - You can pass a NULL str_id to use the identifier of the last item.
// - You may want to handle this on user side if you have specific needs (e.g. tweaking IsItemHovered() parameters).
// - This is essentially the same as calling OpenPopupContextItem() + BeginPopup() but written to avoid
// computing the ID twice because BeginPopupContextXXX functions are called very frequently.
bool ImGui::BeginPopupContextItem(const char* str_id, ImGuiPopupFlags popup_flags)
{
ImGuiWindow* window = GImGui->CurrentWindow;
if (window->SkipItems)
return false;
ImGuiID id = str_id ? window->GetID(str_id) : window->DC.LastItemId; // If user hasn't passed an ID, we can use the LastItemID. Using LastItemID as a Popup ID won't conflict!
IM_ASSERT(id != 0); // You cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item)
int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
OpenPopupEx(id, popup_flags);
return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings);
}
bool ImGui::BeginPopupContextWindow(const char* str_id, ImGuiPopupFlags popup_flags)
{
ImGuiWindow* window = GImGui->CurrentWindow;
if (!str_id)
str_id = "window_context";
ImGuiID id = window->GetID(str_id);
int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
if (IsMouseReleased(mouse_button) && IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
if (!(popup_flags & ImGuiPopupFlags_NoOpenOverItems) || !IsAnyItemHovered())
OpenPopupEx(id, popup_flags);
return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings);
}
bool ImGui::BeginPopupContextVoid(const char* str_id, ImGuiPopupFlags popup_flags)
{
ImGuiWindow* window = GImGui->CurrentWindow;
if (!str_id)
str_id = "void_context";
ImGuiID id = window->GetID(str_id);
int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
if (IsMouseReleased(mouse_button) && !IsWindowHovered(ImGuiHoveredFlags_AnyWindow))
if (GetTopMostPopupModal() == NULL)
OpenPopupEx(id, popup_flags);
return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings);
}
// r_avoid = the rectangle to avoid (e.g. for tooltip it is a rectangle around the mouse cursor which we want to avoid. for popups it's a small point around the cursor.)
// r_outer = the visible area rectangle, minus safe area padding. If our popup size won't fit because of safe area padding we ignore it.
ImVec2 ImGui::FindBestWindowPosForPopupEx(const ImVec2& ref_pos, const ImVec2& size, ImGuiDir* last_dir, const ImRect& r_outer, const ImRect& r_avoid, ImGuiPopupPositionPolicy policy)
{
ImVec2 base_pos_clamped = ImClamp(ref_pos, r_outer.Min, r_outer.Max - size);
//GetForegroundDrawList()->AddRect(r_avoid.Min, r_avoid.Max, IM_COL32(255,0,0,255));
//GetForegroundDrawList()->AddRect(r_outer.Min, r_outer.Max, IM_COL32(0,255,0,255));
// Combo Box policy (we want a connecting edge)
if (policy == ImGuiPopupPositionPolicy_ComboBox)
{
const ImGuiDir dir_prefered_order[ImGuiDir_COUNT] = { ImGuiDir_Down, ImGuiDir_Right, ImGuiDir_Left, ImGuiDir_Up };
for (int n = (*last_dir != ImGuiDir_None) ? -1 : 0; n < ImGuiDir_COUNT; n++)
{
const ImGuiDir dir = (n == -1) ? *last_dir : dir_prefered_order[n];
if (n != -1 && dir == *last_dir) // Already tried this direction?
continue;
ImVec2 pos;
if (dir == ImGuiDir_Down) pos = ImVec2(r_avoid.Min.x, r_avoid.Max.y); // Below, Toward Right (default)
if (dir == ImGuiDir_Right) pos = ImVec2(r_avoid.Min.x, r_avoid.Min.y - size.y); // Above, Toward Right
if (dir == ImGuiDir_Left) pos = ImVec2(r_avoid.Max.x - size.x, r_avoid.Max.y); // Below, Toward Left
if (dir == ImGuiDir_Up) pos = ImVec2(r_avoid.Max.x - size.x, r_avoid.Min.y - size.y); // Above, Toward Left
if (!r_outer.Contains(ImRect(pos, pos + size)))
continue;
*last_dir = dir;
return pos;
}
}
// Default popup policy
const ImGuiDir dir_prefered_order[ImGuiDir_COUNT] = { ImGuiDir_Right, ImGuiDir_Down, ImGuiDir_Up, ImGuiDir_Left };
for (int n = (*last_dir != ImGuiDir_None) ? -1 : 0; n < ImGuiDir_COUNT; n++)
{
const ImGuiDir dir = (n == -1) ? *last_dir : dir_prefered_order[n];
if (n != -1 && dir == *last_dir) // Already tried this direction?
continue;
float avail_w = (dir == ImGuiDir_Left ? r_avoid.Min.x : r_outer.Max.x) - (dir == ImGuiDir_Right ? r_avoid.Max.x : r_outer.Min.x);
float avail_h = (dir == ImGuiDir_Up ? r_avoid.Min.y : r_outer.Max.y) - (dir == ImGuiDir_Down ? r_avoid.Max.y : r_outer.Min.y);
if (avail_w < size.x || avail_h < size.y)
continue;
ImVec2 pos;
pos.x = (dir == ImGuiDir_Left) ? r_avoid.Min.x - size.x : (dir == ImGuiDir_Right) ? r_avoid.Max.x : base_pos_clamped.x;
pos.y = (dir == ImGuiDir_Up) ? r_avoid.Min.y - size.y : (dir == ImGuiDir_Down) ? r_avoid.Max.y : base_pos_clamped.y;
*last_dir = dir;
return pos;
}
// Fallback, try to keep within display
*last_dir = ImGuiDir_None;
ImVec2 pos = ref_pos;
pos.x = ImMax(ImMin(pos.x + size.x, r_outer.Max.x) - size.x, r_outer.Min.x);
pos.y = ImMax(ImMin(pos.y + size.y, r_outer.Max.y) - size.y, r_outer.Min.y);
return pos;
}
ImRect ImGui::GetWindowAllowedExtentRect(ImGuiWindow* window)
{
IM_UNUSED(window);
ImVec2 padding = GImGui->Style.DisplaySafeAreaPadding;
ImRect r_screen = GetViewportRect();
r_screen.Expand(ImVec2((r_screen.GetWidth() > padding.x * 2) ? -padding.x : 0.0f, (r_screen.GetHeight() > padding.y * 2) ? -padding.y : 0.0f));
return r_screen;
}
ImVec2 ImGui::FindBestWindowPosForPopup(ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
ImRect r_outer = GetWindowAllowedExtentRect(window);
if (window->Flags & ImGuiWindowFlags_ChildMenu)
{
// Child menus typically request _any_ position within the parent menu item, and then we move the new menu outside the parent bounds.
// This is how we end up with child menus appearing (most-commonly) on the right of the parent menu.
IM_ASSERT(g.CurrentWindow == window);
ImGuiWindow* parent_window = g.CurrentWindowStack[g.CurrentWindowStack.Size - 2];
float horizontal_overlap = g.Style.ItemInnerSpacing.x; // We want some overlap to convey the relative depth of each menu (currently the amount of overlap is hard-coded to style.ItemSpacing.x).
ImRect r_avoid;
if (parent_window->DC.MenuBarAppending)
r_avoid = ImRect(-FLT_MAX, parent_window->ClipRect.Min.y, FLT_MAX, parent_window->ClipRect.Max.y); // Avoid parent menu-bar. If we wanted multi-line menu-bar, we may instead want to have the calling window setup e.g. a NextWindowData.PosConstraintAvoidRect field
else
r_avoid = ImRect(parent_window->Pos.x + horizontal_overlap, -FLT_MAX, parent_window->Pos.x + parent_window->Size.x - horizontal_overlap - parent_window->ScrollbarSizes.x, FLT_MAX);
return FindBestWindowPosForPopupEx(window->Pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid);
}
if (window->Flags & ImGuiWindowFlags_Popup)
{
ImRect r_avoid = ImRect(window->Pos.x - 1, window->Pos.y - 1, window->Pos.x + 1, window->Pos.y + 1);
return FindBestWindowPosForPopupEx(window->Pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid);
}
if (window->Flags & ImGuiWindowFlags_Tooltip)
{
// Position tooltip (always follows mouse)
float sc = g.Style.MouseCursorScale;
ImVec2 ref_pos = NavCalcPreferredRefPos();
ImRect r_avoid;
if (!g.NavDisableHighlight && g.NavDisableMouseHover && !(g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos))
r_avoid = ImRect(ref_pos.x - 16, ref_pos.y - 8, ref_pos.x + 16, ref_pos.y + 8);
else
r_avoid = ImRect(ref_pos.x - 16, ref_pos.y - 8, ref_pos.x + 24 * sc, ref_pos.y + 24 * sc); // FIXME: Hard-coded based on mouse cursor shape expectation. Exact dimension not very important.
ImVec2 pos = FindBestWindowPosForPopupEx(ref_pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid);
if (window->AutoPosLastDirection == ImGuiDir_None)
pos = ref_pos + ImVec2(2, 2); // If there's not enough room, for tooltip we prefer avoiding the cursor at all cost even if it means that part of the tooltip won't be visible.
return pos;
}
IM_ASSERT(0);
return window->Pos;
}
//-----------------------------------------------------------------------------
// [SECTION] KEYBOARD/GAMEPAD NAVIGATION
//-----------------------------------------------------------------------------
// FIXME-NAV: The existence of SetNavID vs SetNavIDWithRectRel vs SetFocusID is incredibly messy and confusing,
// and needs some explanation or serious refactoring.
void ImGui::SetNavID(ImGuiID id, int nav_layer, ImGuiID focus_scope_id)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(g.NavWindow);
IM_ASSERT(nav_layer == 0 || nav_layer == 1);
g.NavId = id;
g.NavFocusScopeId = focus_scope_id;
g.NavWindow->NavLastIds[nav_layer] = id;
}
void ImGui::SetNavIDWithRectRel(ImGuiID id, int nav_layer, ImGuiID focus_scope_id, const ImRect& rect_rel)
{
ImGuiContext& g = *GImGui;
SetNavID(id, nav_layer, focus_scope_id);
g.NavWindow->NavRectRel[nav_layer] = rect_rel;
g.NavMousePosDirty = true;
g.NavDisableHighlight = false;
g.NavDisableMouseHover = true;
}
void ImGui::SetFocusID(ImGuiID id, ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(id != 0);
// Assume that SetFocusID() is called in the context where its window->DC.NavLayerCurrent and window->DC.NavFocusScopeIdCurrent are valid.
// Note that window may be != g.CurrentWindow (e.g. SetFocusID call in InputTextEx for multi-line text)
const ImGuiNavLayer nav_layer = window->DC.NavLayerCurrent;
if (g.NavWindow != window)
g.NavInitRequest = false;
g.NavWindow = window;
g.NavId = id;
g.NavLayer = nav_layer;
g.NavFocusScopeId = window->DC.NavFocusScopeIdCurrent;
window->NavLastIds[nav_layer] = id;
if (window->DC.LastItemId == id)
window->NavRectRel[nav_layer] = ImRect(window->DC.LastItemRect.Min - window->Pos, window->DC.LastItemRect.Max - window->Pos);
if (g.ActiveIdSource == ImGuiInputSource_Nav)
g.NavDisableMouseHover = true;
else
g.NavDisableHighlight = true;
}
ImGuiDir ImGetDirQuadrantFromDelta(float dx, float dy)
{
if (ImFabs(dx) > ImFabs(dy))
return (dx > 0.0f) ? ImGuiDir_Right : ImGuiDir_Left;
return (dy > 0.0f) ? ImGuiDir_Down : ImGuiDir_Up;
}
static float inline NavScoreItemDistInterval(float a0, float a1, float b0, float b1)
{
if (a1 < b0)
return a1 - b0;
if (b1 < a0)
return a0 - b1;
return 0.0f;
}
static void inline NavClampRectToVisibleAreaForMoveDir(ImGuiDir move_dir, ImRect& r, const ImRect& clip_rect)
{
if (move_dir == ImGuiDir_Left || move_dir == ImGuiDir_Right)
{
r.Min.y = ImClamp(r.Min.y, clip_rect.Min.y, clip_rect.Max.y);
r.Max.y = ImClamp(r.Max.y, clip_rect.Min.y, clip_rect.Max.y);
}
else
{
r.Min.x = ImClamp(r.Min.x, clip_rect.Min.x, clip_rect.Max.x);
r.Max.x = ImClamp(r.Max.x, clip_rect.Min.x, clip_rect.Max.x);
}
}
// Scoring function for gamepad/keyboard directional navigation. Based on https://gist.github.com/rygorous/6981057
static bool ImGui::NavScoreItem(ImGuiNavMoveResult* result, ImRect cand)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (g.NavLayer != window->DC.NavLayerCurrent)
return false;
const ImRect& curr = g.NavScoringRect; // Current modified source rect (NB: we've applied Max.x = Min.x in NavUpdate() to inhibit the effect of having varied item width)
g.NavScoringCount++;
// When entering through a NavFlattened border, we consider child window items as fully clipped for scoring
if (window->ParentWindow == g.NavWindow)
{
IM_ASSERT((window->Flags | g.NavWindow->Flags) & ImGuiWindowFlags_NavFlattened);
if (!window->ClipRect.Overlaps(cand))
return false;
cand.ClipWithFull(window->ClipRect); // This allows the scored item to not overlap other candidates in the parent window
}
// We perform scoring on items bounding box clipped by the current clipping rectangle on the other axis (clipping on our movement axis would give us equal scores for all clipped items)
// For example, this ensure that items in one column are not reached when moving vertically from items in another column.
NavClampRectToVisibleAreaForMoveDir(g.NavMoveClipDir, cand, window->ClipRect);
// Compute distance between boxes
// FIXME-NAV: Introducing biases for vertical navigation, needs to be removed.
float dbx = NavScoreItemDistInterval(cand.Min.x, cand.Max.x, curr.Min.x, curr.Max.x);
float dby = NavScoreItemDistInterval(ImLerp(cand.Min.y, cand.Max.y, 0.2f), ImLerp(cand.Min.y, cand.Max.y, 0.8f), ImLerp(curr.Min.y, curr.Max.y, 0.2f), ImLerp(curr.Min.y, curr.Max.y, 0.8f)); // Scale down on Y to keep using box-distance for vertically touching items
if (dby != 0.0f && dbx != 0.0f)
dbx = (dbx / 1000.0f) + ((dbx > 0.0f) ? +1.0f : -1.0f);
float dist_box = ImFabs(dbx) + ImFabs(dby);
// Compute distance between centers (this is off by a factor of 2, but we only compare center distances with each other so it doesn't matter)
float dcx = (cand.Min.x + cand.Max.x) - (curr.Min.x + curr.Max.x);
float dcy = (cand.Min.y + cand.Max.y) - (curr.Min.y + curr.Max.y);
float dist_center = ImFabs(dcx) + ImFabs(dcy); // L1 metric (need this for our connectedness guarantee)
// Determine which quadrant of 'curr' our candidate item 'cand' lies in based on distance
ImGuiDir quadrant;
float dax = 0.0f, day = 0.0f, dist_axial = 0.0f;
if (dbx != 0.0f || dby != 0.0f)
{
// For non-overlapping boxes, use distance between boxes
dax = dbx;
day = dby;
dist_axial = dist_box;
quadrant = ImGetDirQuadrantFromDelta(dbx, dby);
}
else if (dcx != 0.0f || dcy != 0.0f)
{
// For overlapping boxes with different centers, use distance between centers
dax = dcx;
day = dcy;
dist_axial = dist_center;
quadrant = ImGetDirQuadrantFromDelta(dcx, dcy);
}
else
{
// Degenerate case: two overlapping buttons with same center, break ties arbitrarily (note that LastItemId here is really the _previous_ item order, but it doesn't matter)
quadrant = (window->DC.LastItemId < g.NavId) ? ImGuiDir_Left : ImGuiDir_Right;
}
#if IMGUI_DEBUG_NAV_SCORING
char buf[128];
if (IsMouseHoveringRect(cand.Min, cand.Max))
{
ImFormatString(buf, IM_ARRAYSIZE(buf), "dbox (%.2f,%.2f->%.4f)\ndcen (%.2f,%.2f->%.4f)\nd (%.2f,%.2f->%.4f)\nnav %c, quadrant %c", dbx, dby, dist_box, dcx, dcy, dist_center, dax, day, dist_axial, "WENS"[g.NavMoveDir], "WENS"[quadrant]);
ImDrawList* draw_list = GetForegroundDrawList(window);
draw_list->AddRect(curr.Min, curr.Max, IM_COL32(255,200,0,100));
draw_list->AddRect(cand.Min, cand.Max, IM_COL32(255,255,0,200));
draw_list->AddRectFilled(cand.Max - ImVec2(4, 4), cand.Max + CalcTextSize(buf) + ImVec2(4, 4), IM_COL32(40,0,0,150));
draw_list->AddText(g.IO.FontDefault, 13.0f, cand.Max, ~0U, buf);
}
else if (g.IO.KeyCtrl) // Hold to preview score in matching quadrant. Press C to rotate.
{
if (IsKeyPressedMap(ImGuiKey_C)) { g.NavMoveDirLast = (ImGuiDir)((g.NavMoveDirLast + 1) & 3); g.IO.KeysDownDuration[g.IO.KeyMap[ImGuiKey_C]] = 0.01f; }
if (quadrant == g.NavMoveDir)
{
ImFormatString(buf, IM_ARRAYSIZE(buf), "%.0f/%.0f", dist_box, dist_center);
ImDrawList* draw_list = GetForegroundDrawList(window);
draw_list->AddRectFilled(cand.Min, cand.Max, IM_COL32(255, 0, 0, 200));
draw_list->AddText(g.IO.FontDefault, 13.0f, cand.Min, IM_COL32(255, 255, 255, 255), buf);
}
}
#endif
// Is it in the quadrant we're interesting in moving to?
bool new_best = false;
if (quadrant == g.NavMoveDir)
{
// Does it beat the current best candidate?
if (dist_box < result->DistBox)
{
result->DistBox = dist_box;
result->DistCenter = dist_center;
return true;
}
if (dist_box == result->DistBox)
{
// Try using distance between center points to break ties
if (dist_center < result->DistCenter)
{
result->DistCenter = dist_center;
new_best = true;
}
else if (dist_center == result->DistCenter)
{
// Still tied! we need to be extra-careful to make sure everything gets linked properly. We consistently break ties by symbolically moving "later" items
// (with higher index) to the right/downwards by an infinitesimal amount since we the current "best" button already (so it must have a lower index),
// this is fairly easy. This rule ensures that all buttons with dx==dy==0 will end up being linked in order of appearance along the x axis.
if (((g.NavMoveDir == ImGuiDir_Up || g.NavMoveDir == ImGuiDir_Down) ? dby : dbx) < 0.0f) // moving bj to the right/down decreases distance
new_best = true;
}
}
}
// Axial check: if 'curr' has no link at all in some direction and 'cand' lies roughly in that direction, add a tentative link. This will only be kept if no "real" matches
// are found, so it only augments the graph produced by the above method using extra links. (important, since it doesn't guarantee strong connectedness)
// This is just to avoid buttons having no links in a particular direction when there's a suitable neighbor. you get good graphs without this too.
// 2017/09/29: FIXME: This now currently only enabled inside menu bars, ideally we'd disable it everywhere. Menus in particular need to catch failure. For general navigation it feels awkward.
// Disabling it may lead to disconnected graphs when nodes are very spaced out on different axis. Perhaps consider offering this as an option?
if (result->DistBox == FLT_MAX && dist_axial < result->DistAxial) // Check axial match
if (g.NavLayer == ImGuiNavLayer_Menu && !(g.NavWindow->Flags & ImGuiWindowFlags_ChildMenu))
if ((g.NavMoveDir == ImGuiDir_Left && dax < 0.0f) || (g.NavMoveDir == ImGuiDir_Right && dax > 0.0f) || (g.NavMoveDir == ImGuiDir_Up && day < 0.0f) || (g.NavMoveDir == ImGuiDir_Down && day > 0.0f))
{
result->DistAxial = dist_axial;
new_best = true;
}
return new_best;
}
// We get there when either NavId == id, or when g.NavAnyRequest is set (which is updated by NavUpdateAnyRequestFlag above)
static void ImGui::NavProcessItem(ImGuiWindow* window, const ImRect& nav_bb, const ImGuiID id)
{
ImGuiContext& g = *GImGui;
//if (!g.IO.NavActive) // [2017/10/06] Removed this possibly redundant test but I am not sure of all the side-effects yet. Some of the feature here will need to work regardless of using a _NoNavInputs flag.
// return;
const ImGuiItemFlags item_flags = window->DC.ItemFlags;
const ImRect nav_bb_rel(nav_bb.Min - window->Pos, nav_bb.Max - window->Pos);
// Process Init Request
if (g.NavInitRequest && g.NavLayer == window->DC.NavLayerCurrent)
{
// Even if 'ImGuiItemFlags_NoNavDefaultFocus' is on (typically collapse/close button) we record the first ResultId so they can be used as a fallback
if (!(item_flags & ImGuiItemFlags_NoNavDefaultFocus) || g.NavInitResultId == 0)
{
g.NavInitResultId = id;
g.NavInitResultRectRel = nav_bb_rel;
}
if (!(item_flags & ImGuiItemFlags_NoNavDefaultFocus))
{
g.NavInitRequest = false; // Found a match, clear request
NavUpdateAnyRequestFlag();
}
}
// Process Move Request (scoring for navigation)
// FIXME-NAV: Consider policy for double scoring (scoring from NavScoringRectScreen + scoring from a rect wrapped according to current wrapping policy)
if ((g.NavId != id || (g.NavMoveRequestFlags & ImGuiNavMoveFlags_AllowCurrentNavId)) && !(item_flags & (ImGuiItemFlags_Disabled | ImGuiItemFlags_NoNav)))
{
ImGuiNavMoveResult* result = (window == g.NavWindow) ? &g.NavMoveResultLocal : &g.NavMoveResultOther;
#if IMGUI_DEBUG_NAV_SCORING
// [DEBUG] Score all items in NavWindow at all times
if (!g.NavMoveRequest)
g.NavMoveDir = g.NavMoveDirLast;
bool new_best = NavScoreItem(result, nav_bb) && g.NavMoveRequest;
#else
bool new_best = g.NavMoveRequest && NavScoreItem(result, nav_bb);
#endif
if (new_best)
{
result->Window = window;
result->ID = id;
result->FocusScopeId = window->DC.NavFocusScopeIdCurrent;
result->RectRel = nav_bb_rel;
}
// Features like PageUp/PageDown need to maintain a separate score for the visible set of items.
const float VISIBLE_RATIO = 0.70f;
if ((g.NavMoveRequestFlags & ImGuiNavMoveFlags_AlsoScoreVisibleSet) && window->ClipRect.Overlaps(nav_bb))
if (ImClamp(nav_bb.Max.y, window->ClipRect.Min.y, window->ClipRect.Max.y) - ImClamp(nav_bb.Min.y, window->ClipRect.Min.y, window->ClipRect.Max.y) >= (nav_bb.Max.y - nav_bb.Min.y) * VISIBLE_RATIO)
if (NavScoreItem(&g.NavMoveResultLocalVisibleSet, nav_bb))
{
result = &g.NavMoveResultLocalVisibleSet;
result->Window = window;
result->ID = id;
result->FocusScopeId = window->DC.NavFocusScopeIdCurrent;
result->RectRel = nav_bb_rel;
}
}
// Update window-relative bounding box of navigated item
if (g.NavId == id)
{
g.NavWindow = window; // Always refresh g.NavWindow, because some operations such as FocusItem() don't have a window.
g.NavLayer = window->DC.NavLayerCurrent;
g.NavFocusScopeId = window->DC.NavFocusScopeIdCurrent;
g.NavIdIsAlive = true;
g.NavIdTabCounter = window->DC.FocusCounterTabStop;
window->NavRectRel[window->DC.NavLayerCurrent] = nav_bb_rel; // Store item bounding box (relative to window position)
}
}
bool ImGui::NavMoveRequestButNoResultYet()
{
ImGuiContext& g = *GImGui;
return g.NavMoveRequest && g.NavMoveResultLocal.ID == 0 && g.NavMoveResultOther.ID == 0;
}
void ImGui::NavMoveRequestCancel()
{
ImGuiContext& g = *GImGui;
g.NavMoveRequest = false;
NavUpdateAnyRequestFlag();
}
void ImGui::NavMoveRequestForward(ImGuiDir move_dir, ImGuiDir clip_dir, const ImRect& bb_rel, ImGuiNavMoveFlags move_flags)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(g.NavMoveRequestForward == ImGuiNavForward_None);
NavMoveRequestCancel();
g.NavMoveDir = move_dir;
g.NavMoveClipDir = clip_dir;
g.NavMoveRequestForward = ImGuiNavForward_ForwardQueued;
g.NavMoveRequestFlags = move_flags;
g.NavWindow->NavRectRel[g.NavLayer] = bb_rel;
}
void ImGui::NavMoveRequestTryWrapping(ImGuiWindow* window, ImGuiNavMoveFlags move_flags)
{
ImGuiContext& g = *GImGui;
// Navigation wrap-around logic is delayed to the end of the frame because this operation is only valid after entire
// popup is assembled and in case of appended popups it is not clear which EndPopup() call is final.
g.NavWrapRequestWindow = window;
g.NavWrapRequestFlags = move_flags;
}
// FIXME: This could be replaced by updating a frame number in each window when (window == NavWindow) and (NavLayer == 0).
// This way we could find the last focused window among our children. It would be much less confusing this way?
static void ImGui::NavSaveLastChildNavWindowIntoParent(ImGuiWindow* nav_window)
{
ImGuiWindow* parent = nav_window;
while (parent && (parent->Flags & ImGuiWindowFlags_ChildWindow) != 0 && (parent->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == 0)
parent = parent->ParentWindow;
if (parent && parent != nav_window)
parent->NavLastChildNavWindow = nav_window;
}
// Restore the last focused child.
// Call when we are expected to land on the Main Layer (0) after FocusWindow()
static ImGuiWindow* ImGui::NavRestoreLastChildNavWindow(ImGuiWindow* window)
{
if (window->NavLastChildNavWindow && window->NavLastChildNavWindow->WasActive)
return window->NavLastChildNavWindow;
return window;
}
static void NavRestoreLayer(ImGuiNavLayer layer)
{
ImGuiContext& g = *GImGui;
g.NavLayer = layer;
if (layer == 0)
g.NavWindow = ImGui::NavRestoreLastChildNavWindow(g.NavWindow);
ImGuiWindow* window = g.NavWindow;
if (layer == 0 && window->NavLastIds[0] != 0)
ImGui::SetNavIDWithRectRel(window->NavLastIds[0], layer, 0, window->NavRectRel[0]);
else
ImGui::NavInitWindow(window, true);
}
static inline void ImGui::NavUpdateAnyRequestFlag()
{
ImGuiContext& g = *GImGui;
g.NavAnyRequest = g.NavMoveRequest || g.NavInitRequest || (IMGUI_DEBUG_NAV_SCORING && g.NavWindow != NULL);
if (g.NavAnyRequest)
IM_ASSERT(g.NavWindow != NULL);
}
// This needs to be called before we submit any widget (aka in or before Begin)
void ImGui::NavInitWindow(ImGuiWindow* window, bool force_reinit)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(window == g.NavWindow);
bool init_for_nav = false;
if (!(window->Flags & ImGuiWindowFlags_NoNavInputs))
if (!(window->Flags & ImGuiWindowFlags_ChildWindow) || (window->Flags & ImGuiWindowFlags_Popup) || (window->NavLastIds[0] == 0) || force_reinit)
init_for_nav = true;
//IMGUI_DEBUG_LOG("[Nav] NavInitWindow() init_for_nav=%d, window=\"%s\", layer=%d\n", init_for_nav, window->Name, g.NavLayer);
if (init_for_nav)
{
SetNavID(0, g.NavLayer, 0);
g.NavInitRequest = true;
g.NavInitRequestFromMove = false;
g.NavInitResultId = 0;
g.NavInitResultRectRel = ImRect();
NavUpdateAnyRequestFlag();
}
else
{
g.NavId = window->NavLastIds[0];
g.NavFocusScopeId = 0;
}
}
static ImVec2 ImGui::NavCalcPreferredRefPos()
{
ImGuiContext& g = *GImGui;
if (g.NavDisableHighlight || !g.NavDisableMouseHover || !g.NavWindow)
{
// Mouse (we need a fallback in case the mouse becomes invalid after being used)
if (IsMousePosValid(&g.IO.MousePos))
return g.IO.MousePos;
return g.LastValidMousePos;
}
else
{
// When navigation is active and mouse is disabled, decide on an arbitrary position around the bottom left of the currently navigated item.
const ImRect& rect_rel = g.NavWindow->NavRectRel[g.NavLayer];
ImVec2 pos = g.NavWindow->Pos + ImVec2(rect_rel.Min.x + ImMin(g.Style.FramePadding.x * 4, rect_rel.GetWidth()), rect_rel.Max.y - ImMin(g.Style.FramePadding.y, rect_rel.GetHeight()));
ImRect visible_rect = GetViewportRect();
return ImFloor(ImClamp(pos, visible_rect.Min, visible_rect.Max)); // ImFloor() is important because non-integer mouse position application in back-end might be lossy and result in undesirable non-zero delta.
}
}
float ImGui::GetNavInputAmount(ImGuiNavInput n, ImGuiInputReadMode mode)
{
ImGuiContext& g = *GImGui;
if (mode == ImGuiInputReadMode_Down)
return g.IO.NavInputs[n]; // Instant, read analog input (0.0f..1.0f, as provided by user)
const float t = g.IO.NavInputsDownDuration[n];
if (t < 0.0f && mode == ImGuiInputReadMode_Released) // Return 1.0f when just released, no repeat, ignore analog input.
return (g.IO.NavInputsDownDurationPrev[n] >= 0.0f ? 1.0f : 0.0f);
if (t < 0.0f)
return 0.0f;
if (mode == ImGuiInputReadMode_Pressed) // Return 1.0f when just pressed, no repeat, ignore analog input.
return (t == 0.0f) ? 1.0f : 0.0f;
if (mode == ImGuiInputReadMode_Repeat)
return (float)CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, g.IO.KeyRepeatDelay * 0.72f, g.IO.KeyRepeatRate * 0.80f);
if (mode == ImGuiInputReadMode_RepeatSlow)
return (float)CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, g.IO.KeyRepeatDelay * 1.25f, g.IO.KeyRepeatRate * 2.00f);
if (mode == ImGuiInputReadMode_RepeatFast)
return (float)CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, g.IO.KeyRepeatDelay * 0.72f, g.IO.KeyRepeatRate * 0.30f);
return 0.0f;
}
ImVec2 ImGui::GetNavInputAmount2d(ImGuiNavDirSourceFlags dir_sources, ImGuiInputReadMode mode, float slow_factor, float fast_factor)
{
ImVec2 delta(0.0f, 0.0f);
if (dir_sources & ImGuiNavDirSourceFlags_Keyboard)
delta += ImVec2(GetNavInputAmount(ImGuiNavInput_KeyRight_, mode) - GetNavInputAmount(ImGuiNavInput_KeyLeft_, mode), GetNavInputAmount(ImGuiNavInput_KeyDown_, mode) - GetNavInputAmount(ImGuiNavInput_KeyUp_, mode));
if (dir_sources & ImGuiNavDirSourceFlags_PadDPad)
delta += ImVec2(GetNavInputAmount(ImGuiNavInput_DpadRight, mode) - GetNavInputAmount(ImGuiNavInput_DpadLeft, mode), GetNavInputAmount(ImGuiNavInput_DpadDown, mode) - GetNavInputAmount(ImGuiNavInput_DpadUp, mode));
if (dir_sources & ImGuiNavDirSourceFlags_PadLStick)
delta += ImVec2(GetNavInputAmount(ImGuiNavInput_LStickRight, mode) - GetNavInputAmount(ImGuiNavInput_LStickLeft, mode), GetNavInputAmount(ImGuiNavInput_LStickDown, mode) - GetNavInputAmount(ImGuiNavInput_LStickUp, mode));
if (slow_factor != 0.0f && IsNavInputDown(ImGuiNavInput_TweakSlow))
delta *= slow_factor;
if (fast_factor != 0.0f && IsNavInputDown(ImGuiNavInput_TweakFast))
delta *= fast_factor;
return delta;
}
static void ImGui::NavUpdate()
{
ImGuiContext& g = *GImGui;
ImGuiIO& io = g.IO;
io.WantSetMousePos = false;
g.NavWrapRequestWindow = NULL;
g.NavWrapRequestFlags = ImGuiNavMoveFlags_None;
#if 0
if (g.NavScoringCount > 0) IMGUI_DEBUG_LOG("NavScoringCount %d for '%s' layer %d (Init:%d, Move:%d)\n", g.FrameCount, g.NavScoringCount, g.NavWindow ? g.NavWindow->Name : "NULL", g.NavLayer, g.NavInitRequest || g.NavInitResultId != 0, g.NavMoveRequest);
#endif
// Set input source as Gamepad when buttons are pressed (as some features differs when used with Gamepad vs Keyboard)
// (do it before we map Keyboard input!)
bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
if (nav_gamepad_active && g.NavInputSource != ImGuiInputSource_NavGamepad)
{
if (io.NavInputs[ImGuiNavInput_Activate] > 0.0f || io.NavInputs[ImGuiNavInput_Input] > 0.0f || io.NavInputs[ImGuiNavInput_Cancel] > 0.0f || io.NavInputs[ImGuiNavInput_Menu] > 0.0f
|| io.NavInputs[ImGuiNavInput_DpadLeft] > 0.0f || io.NavInputs[ImGuiNavInput_DpadRight] > 0.0f || io.NavInputs[ImGuiNavInput_DpadUp] > 0.0f || io.NavInputs[ImGuiNavInput_DpadDown] > 0.0f)
g.NavInputSource = ImGuiInputSource_NavGamepad;
}
// Update Keyboard->Nav inputs mapping
if (nav_keyboard_active)
{
#define NAV_MAP_KEY(_KEY, _NAV_INPUT) do { if (IsKeyDown(io.KeyMap[_KEY])) { io.NavInputs[_NAV_INPUT] = 1.0f; g.NavInputSource = ImGuiInputSource_NavKeyboard; } } while (0)
NAV_MAP_KEY(ImGuiKey_Space, ImGuiNavInput_Activate );
NAV_MAP_KEY(ImGuiKey_Enter, ImGuiNavInput_Input );
NAV_MAP_KEY(ImGuiKey_Escape, ImGuiNavInput_Cancel );
NAV_MAP_KEY(ImGuiKey_LeftArrow, ImGuiNavInput_KeyLeft_ );
NAV_MAP_KEY(ImGuiKey_RightArrow,ImGuiNavInput_KeyRight_);
NAV_MAP_KEY(ImGuiKey_UpArrow, ImGuiNavInput_KeyUp_ );
NAV_MAP_KEY(ImGuiKey_DownArrow, ImGuiNavInput_KeyDown_ );
if (io.KeyCtrl)
io.NavInputs[ImGuiNavInput_TweakSlow] = 1.0f;
if (io.KeyShift)
io.NavInputs[ImGuiNavInput_TweakFast] = 1.0f;
if (io.KeyAlt && !io.KeyCtrl) // AltGR is Alt+Ctrl, also even on keyboards without AltGR we don't want Alt+Ctrl to open menu.
io.NavInputs[ImGuiNavInput_KeyMenu_] = 1.0f;
#undef NAV_MAP_KEY
}
memcpy(io.NavInputsDownDurationPrev, io.NavInputsDownDuration, sizeof(io.NavInputsDownDuration));
for (int i = 0; i < IM_ARRAYSIZE(io.NavInputs); i++)
io.NavInputsDownDuration[i] = (io.NavInputs[i] > 0.0f) ? (io.NavInputsDownDuration[i] < 0.0f ? 0.0f : io.NavInputsDownDuration[i] + io.DeltaTime) : -1.0f;
// Process navigation init request (select first/default focus)
// In very rare cases g.NavWindow may be null (e.g. clearing focus after requesting an init request, which does happen when releasing Alt while clicking on void)
if (g.NavInitResultId != 0 && (!g.NavDisableHighlight || g.NavInitRequestFromMove) && g.NavWindow)
{
// Apply result from previous navigation init request (will typically select the first item, unless SetItemDefaultFocus() has been called)
//IMGUI_DEBUG_LOG("[Nav] Apply NavInitRequest result: 0x%08X Layer %d in \"%s\"\n", g.NavInitResultId, g.NavLayer, g.NavWindow->Name);
if (g.NavInitRequestFromMove)
SetNavIDWithRectRel(g.NavInitResultId, g.NavLayer, 0, g.NavInitResultRectRel);
else
SetNavID(g.NavInitResultId, g.NavLayer, 0);
g.NavWindow->NavRectRel[g.NavLayer] = g.NavInitResultRectRel;
}
g.NavInitRequest = false;
g.NavInitRequestFromMove = false;
g.NavInitResultId = 0;
g.NavJustMovedToId = 0;
// Process navigation move request
if (g.NavMoveRequest)
NavUpdateMoveResult();
// When a forwarded move request failed, we restore the highlight that we disabled during the forward frame
if (g.NavMoveRequestForward == ImGuiNavForward_ForwardActive)
{
IM_ASSERT(g.NavMoveRequest);
if (g.NavMoveResultLocal.ID == 0 && g.NavMoveResultOther.ID == 0)
g.NavDisableHighlight = false;
g.NavMoveRequestForward = ImGuiNavForward_None;
}
// Apply application mouse position movement, after we had a chance to process move request result.
if (g.NavMousePosDirty && g.NavIdIsAlive)
{
// Set mouse position given our knowledge of the navigated item position from last frame
if ((io.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos) && (io.BackendFlags & ImGuiBackendFlags_HasSetMousePos))
{
if (!g.NavDisableHighlight && g.NavDisableMouseHover && g.NavWindow)
{
io.MousePos = io.MousePosPrev = NavCalcPreferredRefPos();
io.WantSetMousePos = true;
}
}
g.NavMousePosDirty = false;
}
g.NavIdIsAlive = false;
g.NavJustTabbedId = 0;
IM_ASSERT(g.NavLayer == 0 || g.NavLayer == 1);
// Store our return window (for returning from Layer 1 to Layer 0) and clear it as soon as we step back in our own Layer 0
if (g.NavWindow)
NavSaveLastChildNavWindowIntoParent(g.NavWindow);
if (g.NavWindow && g.NavWindow->NavLastChildNavWindow != NULL && g.NavLayer == ImGuiNavLayer_Main)
g.NavWindow->NavLastChildNavWindow = NULL;
// Update CTRL+TAB and Windowing features (hold Square to move/resize/etc.)
NavUpdateWindowing();
// Set output flags for user application
io.NavActive = (nav_keyboard_active || nav_gamepad_active) && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs);
io.NavVisible = (io.NavActive && g.NavId != 0 && !g.NavDisableHighlight) || (g.NavWindowingTarget != NULL);
// Process NavCancel input (to close a popup, get back to parent, clear focus)
if (IsNavInputTest(ImGuiNavInput_Cancel, ImGuiInputReadMode_Pressed))
{
if (g.ActiveId != 0)
{
if (!IsActiveIdUsingNavInput(ImGuiNavInput_Cancel))
ClearActiveID();
}
else if (g.NavWindow && (g.NavWindow->Flags & ImGuiWindowFlags_ChildWindow) && !(g.NavWindow->Flags & ImGuiWindowFlags_Popup) && g.NavWindow->ParentWindow)
{
// Exit child window
ImGuiWindow* child_window = g.NavWindow;
ImGuiWindow* parent_window = g.NavWindow->ParentWindow;
IM_ASSERT(child_window->ChildId != 0);
FocusWindow(parent_window);
SetNavID(child_window->ChildId, 0, 0);
// Reassigning with same value, we're being explicit here.
g.NavIdIsAlive = false; // -V1048
if (g.NavDisableMouseHover)
g.NavMousePosDirty = true;
}
else if (g.OpenPopupStack.Size > 0)
{
// Close open popup/menu
if (!(g.OpenPopupStack.back().Window->Flags & ImGuiWindowFlags_Modal))
ClosePopupToLevel(g.OpenPopupStack.Size - 1, true);
}
else if (g.NavLayer != ImGuiNavLayer_Main)
{
// Leave the "menu" layer
NavRestoreLayer(ImGuiNavLayer_Main);
}
else
{
// Clear NavLastId for popups but keep it for regular child window so we can leave one and come back where we were
if (g.NavWindow && ((g.NavWindow->Flags & ImGuiWindowFlags_Popup) || !(g.NavWindow->Flags & ImGuiWindowFlags_ChildWindow)))
g.NavWindow->NavLastIds[0] = 0;
g.NavId = g.NavFocusScopeId = 0;
}
}
// Process manual activation request
g.NavActivateId = g.NavActivateDownId = g.NavActivatePressedId = g.NavInputId = 0;
if (g.NavId != 0 && !g.NavDisableHighlight && !g.NavWindowingTarget && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
{
bool activate_down = IsNavInputDown(ImGuiNavInput_Activate);
bool activate_pressed = activate_down && IsNavInputTest(ImGuiNavInput_Activate, ImGuiInputReadMode_Pressed);
if (g.ActiveId == 0 && activate_pressed)
g.NavActivateId = g.NavId;
if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && activate_down)
g.NavActivateDownId = g.NavId;
if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && activate_pressed)
g.NavActivatePressedId = g.NavId;
if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && IsNavInputTest(ImGuiNavInput_Input, ImGuiInputReadMode_Pressed))
g.NavInputId = g.NavId;
}
if (g.NavWindow && (g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
g.NavDisableHighlight = true;
if (g.NavActivateId != 0)
IM_ASSERT(g.NavActivateDownId == g.NavActivateId);
g.NavMoveRequest = false;
// Process programmatic activation request
if (g.NavNextActivateId != 0)
g.NavActivateId = g.NavActivateDownId = g.NavActivatePressedId = g.NavInputId = g.NavNextActivateId;
g.NavNextActivateId = 0;
// Initiate directional inputs request
if (g.NavMoveRequestForward == ImGuiNavForward_None)
{
g.NavMoveDir = ImGuiDir_None;
g.NavMoveRequestFlags = ImGuiNavMoveFlags_None;
if (g.NavWindow && !g.NavWindowingTarget && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
{
const ImGuiInputReadMode read_mode = ImGuiInputReadMode_Repeat;
if (!IsActiveIdUsingNavDir(ImGuiDir_Left) && (IsNavInputTest(ImGuiNavInput_DpadLeft, read_mode) || IsNavInputTest(ImGuiNavInput_KeyLeft_, read_mode))) { g.NavMoveDir = ImGuiDir_Left; }
if (!IsActiveIdUsingNavDir(ImGuiDir_Right) && (IsNavInputTest(ImGuiNavInput_DpadRight, read_mode) || IsNavInputTest(ImGuiNavInput_KeyRight_, read_mode))) { g.NavMoveDir = ImGuiDir_Right; }
if (!IsActiveIdUsingNavDir(ImGuiDir_Up) && (IsNavInputTest(ImGuiNavInput_DpadUp, read_mode) || IsNavInputTest(ImGuiNavInput_KeyUp_, read_mode))) { g.NavMoveDir = ImGuiDir_Up; }
if (!IsActiveIdUsingNavDir(ImGuiDir_Down) && (IsNavInputTest(ImGuiNavInput_DpadDown, read_mode) || IsNavInputTest(ImGuiNavInput_KeyDown_, read_mode))) { g.NavMoveDir = ImGuiDir_Down; }
}
g.NavMoveClipDir = g.NavMoveDir;
}
else
{
// Forwarding previous request (which has been modified, e.g. wrap around menus rewrite the requests with a starting rectangle at the other side of the window)
// (Preserve g.NavMoveRequestFlags, g.NavMoveClipDir which were set by the NavMoveRequestForward() function)
IM_ASSERT(g.NavMoveDir != ImGuiDir_None && g.NavMoveClipDir != ImGuiDir_None);
IM_ASSERT(g.NavMoveRequestForward == ImGuiNavForward_ForwardQueued);
g.NavMoveRequestForward = ImGuiNavForward_ForwardActive;
}
// Update PageUp/PageDown/Home/End scroll
// FIXME-NAV: Consider enabling those keys even without the master ImGuiConfigFlags_NavEnableKeyboard flag?
float nav_scoring_rect_offset_y = 0.0f;
if (nav_keyboard_active)
nav_scoring_rect_offset_y = NavUpdatePageUpPageDown();
// If we initiate a movement request and have no current NavId, we initiate a InitDefautRequest that will be used as a fallback if the direction fails to find a match
if (g.NavMoveDir != ImGuiDir_None)
{
g.NavMoveRequest = true;
g.NavMoveRequestKeyMods = io.KeyMods;
g.NavMoveDirLast = g.NavMoveDir;
}
if (g.NavMoveRequest && g.NavId == 0)
{
//IMGUI_DEBUG_LOG("[Nav] NavInitRequest from move, window \"%s\", layer=%d\n", g.NavWindow->Name, g.NavLayer);
g.NavInitRequest = g.NavInitRequestFromMove = true;
// Reassigning with same value, we're being explicit here.
g.NavInitResultId = 0; // -V1048
g.NavDisableHighlight = false;
}
NavUpdateAnyRequestFlag();
// Scrolling
if (g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs) && !g.NavWindowingTarget)
{
// *Fallback* manual-scroll with Nav directional keys when window has no navigable item
ImGuiWindow* window = g.NavWindow;
const float scroll_speed = IM_ROUND(window->CalcFontSize() * 100 * io.DeltaTime); // We need round the scrolling speed because sub-pixel scroll isn't reliably supported.
if (window->DC.NavLayerActiveMask == 0x00 && window->DC.NavHasScroll && g.NavMoveRequest)
{
if (g.NavMoveDir == ImGuiDir_Left || g.NavMoveDir == ImGuiDir_Right)
SetScrollX(window, ImFloor(window->Scroll.x + ((g.NavMoveDir == ImGuiDir_Left) ? -1.0f : +1.0f) * scroll_speed));
if (g.NavMoveDir == ImGuiDir_Up || g.NavMoveDir == ImGuiDir_Down)
SetScrollY(window, ImFloor(window->Scroll.y + ((g.NavMoveDir == ImGuiDir_Up) ? -1.0f : +1.0f) * scroll_speed));
}
// *Normal* Manual scroll with NavScrollXXX keys
// Next movement request will clamp the NavId reference rectangle to the visible area, so navigation will resume within those bounds.
ImVec2 scroll_dir = GetNavInputAmount2d(ImGuiNavDirSourceFlags_PadLStick, ImGuiInputReadMode_Down, 1.0f / 10.0f, 10.0f);
if (scroll_dir.x != 0.0f && window->ScrollbarX)
SetScrollX(window, ImFloor(window->Scroll.x + scroll_dir.x * scroll_speed));
if (scroll_dir.y != 0.0f)
SetScrollY(window, ImFloor(window->Scroll.y + scroll_dir.y * scroll_speed));
}
// Reset search results
g.NavMoveResultLocal.Clear();
g.NavMoveResultLocalVisibleSet.Clear();
g.NavMoveResultOther.Clear();
// When using gamepad, we project the reference nav bounding box into window visible area.
// This is to allow resuming navigation inside the visible area after doing a large amount of scrolling, since with gamepad every movements are relative
// (can't focus a visible object like we can with the mouse).
if (g.NavMoveRequest && g.NavInputSource == ImGuiInputSource_NavGamepad && g.NavLayer == ImGuiNavLayer_Main)
{
ImGuiWindow* window = g.NavWindow;
ImRect window_rect_rel(window->InnerRect.Min - window->Pos - ImVec2(1, 1), window->InnerRect.Max - window->Pos + ImVec2(1, 1));
if (!window_rect_rel.Contains(window->NavRectRel[g.NavLayer]))
{
float pad = window->CalcFontSize() * 0.5f;
window_rect_rel.Expand(ImVec2(-ImMin(window_rect_rel.GetWidth(), pad), -ImMin(window_rect_rel.GetHeight(), pad))); // Terrible approximation for the intent of starting navigation from first fully visible item
window->NavRectRel[g.NavLayer].ClipWithFull(window_rect_rel);
g.NavId = g.NavFocusScopeId = 0;
}
}
// For scoring we use a single segment on the left side our current item bounding box (not touching the edge to avoid box overlap with zero-spaced items)
ImRect nav_rect_rel = g.NavWindow ? g.NavWindow->NavRectRel[g.NavLayer] : ImRect(0, 0, 0, 0);
g.NavScoringRect = g.NavWindow ? ImRect(g.NavWindow->Pos + nav_rect_rel.Min, g.NavWindow->Pos + nav_rect_rel.Max) : GetViewportRect();
g.NavScoringRect.TranslateY(nav_scoring_rect_offset_y);
g.NavScoringRect.Min.x = ImMin(g.NavScoringRect.Min.x + 1.0f, g.NavScoringRect.Max.x);
g.NavScoringRect.Max.x = g.NavScoringRect.Min.x;
IM_ASSERT(!g.NavScoringRect.IsInverted()); // Ensure if we have a finite, non-inverted bounding box here will allows us to remove extraneous ImFabs() calls in NavScoreItem().
//GetForegroundDrawList()->AddRect(g.NavScoringRectScreen.Min, g.NavScoringRectScreen.Max, IM_COL32(255,200,0,255)); // [DEBUG]
g.NavScoringCount = 0;
#if IMGUI_DEBUG_NAV_RECTS
if (g.NavWindow)
{
ImDrawList* draw_list = GetForegroundDrawList(g.NavWindow);
if (1) { for (int layer = 0; layer < 2; layer++) draw_list->AddRect(g.NavWindow->Pos + g.NavWindow->NavRectRel[layer].Min, g.NavWindow->Pos + g.NavWindow->NavRectRel[layer].Max, IM_COL32(255,200,0,255)); } // [DEBUG]
if (1) { ImU32 col = (!g.NavWindow->Hidden) ? IM_COL32(255,0,255,255) : IM_COL32(255,0,0,255); ImVec2 p = NavCalcPreferredRefPos(); char buf[32]; ImFormatString(buf, 32, "%d", g.NavLayer); draw_list->AddCircleFilled(p, 3.0f, col); draw_list->AddText(NULL, 13.0f, p + ImVec2(8,-4), col, buf); }
}
#endif
}
// Apply result from previous frame navigation directional move request
static void ImGui::NavUpdateMoveResult()
{
ImGuiContext& g = *GImGui;
if (g.NavMoveResultLocal.ID == 0 && g.NavMoveResultOther.ID == 0)
{
// In a situation when there is no results but NavId != 0, re-enable the Navigation highlight (because g.NavId is not considered as a possible result)
if (g.NavId != 0)
{
g.NavDisableHighlight = false;
g.NavDisableMouseHover = true;
}
return;
}
// Select which result to use
ImGuiNavMoveResult* result = (g.NavMoveResultLocal.ID != 0) ? &g.NavMoveResultLocal : &g.NavMoveResultOther;
// PageUp/PageDown behavior first jumps to the bottom/top mostly visible item, _otherwise_ use the result from the previous/next page.
if (g.NavMoveRequestFlags & ImGuiNavMoveFlags_AlsoScoreVisibleSet)
if (g.NavMoveResultLocalVisibleSet.ID != 0 && g.NavMoveResultLocalVisibleSet.ID != g.NavId)
result = &g.NavMoveResultLocalVisibleSet;
// Maybe entering a flattened child from the outside? In this case solve the tie using the regular scoring rules.
if (result != &g.NavMoveResultOther && g.NavMoveResultOther.ID != 0 && g.NavMoveResultOther.Window->ParentWindow == g.NavWindow)
if ((g.NavMoveResultOther.DistBox < result->DistBox) || (g.NavMoveResultOther.DistBox == result->DistBox && g.NavMoveResultOther.DistCenter < result->DistCenter))
result = &g.NavMoveResultOther;
IM_ASSERT(g.NavWindow && result->Window);
// Scroll to keep newly navigated item fully into view.
if (g.NavLayer == ImGuiNavLayer_Main)
{
ImVec2 delta_scroll;
if (g.NavMoveRequestFlags & ImGuiNavMoveFlags_ScrollToEdge)
{
float scroll_target = (g.NavMoveDir == ImGuiDir_Up) ? result->Window->ScrollMax.y : 0.0f;
delta_scroll.y = result->Window->Scroll.y - scroll_target;
SetScrollY(result->Window, scroll_target);
}
else
{
ImRect rect_abs = ImRect(result->RectRel.Min + result->Window->Pos, result->RectRel.Max + result->Window->Pos);
delta_scroll = ScrollToBringRectIntoView(result->Window, rect_abs);
}
// Offset our result position so mouse position can be applied immediately after in NavUpdate()
result->RectRel.TranslateX(-delta_scroll.x);
result->RectRel.TranslateY(-delta_scroll.y);
}
ClearActiveID();
g.NavWindow = result->Window;
if (g.NavId != result->ID)
{
// Don't set NavJustMovedToId if just landed on the same spot (which may happen with ImGuiNavMoveFlags_AllowCurrentNavId)
g.NavJustMovedToId = result->ID;
g.NavJustMovedToFocusScopeId = result->FocusScopeId;
g.NavJustMovedToKeyMods = g.NavMoveRequestKeyMods;
}
SetNavIDWithRectRel(result->ID, g.NavLayer, result->FocusScopeId, result->RectRel);
}
// Handle PageUp/PageDown/Home/End keys
static float ImGui::NavUpdatePageUpPageDown()
{
ImGuiContext& g = *GImGui;
ImGuiIO& io = g.IO;
if (g.NavMoveDir != ImGuiDir_None || g.NavWindow == NULL)
return 0.0f;
if ((g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs) || g.NavWindowingTarget != NULL || g.NavLayer != ImGuiNavLayer_Main)
return 0.0f;
ImGuiWindow* window = g.NavWindow;
const bool page_up_held = IsKeyDown(io.KeyMap[ImGuiKey_PageUp]) && !IsActiveIdUsingKey(ImGuiKey_PageUp);
const bool page_down_held = IsKeyDown(io.KeyMap[ImGuiKey_PageDown]) && !IsActiveIdUsingKey(ImGuiKey_PageDown);
const bool home_pressed = IsKeyPressed(io.KeyMap[ImGuiKey_Home]) && !IsActiveIdUsingKey(ImGuiKey_Home);
const bool end_pressed = IsKeyPressed(io.KeyMap[ImGuiKey_End]) && !IsActiveIdUsingKey(ImGuiKey_End);
if (page_up_held != page_down_held || home_pressed != end_pressed) // If either (not both) are pressed
{
if (window->DC.NavLayerActiveMask == 0x00 && window->DC.NavHasScroll)
{
// Fallback manual-scroll when window has no navigable item
if (IsKeyPressed(io.KeyMap[ImGuiKey_PageUp], true))
SetScrollY(window, window->Scroll.y - window->InnerRect.GetHeight());
else if (IsKeyPressed(io.KeyMap[ImGuiKey_PageDown], true))
SetScrollY(window, window->Scroll.y + window->InnerRect.GetHeight());
else if (home_pressed)
SetScrollY(window, 0.0f);
else if (end_pressed)
SetScrollY(window, window->ScrollMax.y);
}
else
{
ImRect& nav_rect_rel = window->NavRectRel[g.NavLayer];
const float page_offset_y = ImMax(0.0f, window->InnerRect.GetHeight() - window->CalcFontSize() * 1.0f + nav_rect_rel.GetHeight());
float nav_scoring_rect_offset_y = 0.0f;
if (IsKeyPressed(io.KeyMap[ImGuiKey_PageUp], true))
{
nav_scoring_rect_offset_y = -page_offset_y;
g.NavMoveDir = ImGuiDir_Down; // Because our scoring rect is offset up, we request the down direction (so we can always land on the last item)
g.NavMoveClipDir = ImGuiDir_Up;
g.NavMoveRequestFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_AlsoScoreVisibleSet;
}
else if (IsKeyPressed(io.KeyMap[ImGuiKey_PageDown], true))
{
nav_scoring_rect_offset_y = +page_offset_y;
g.NavMoveDir = ImGuiDir_Up; // Because our scoring rect is offset down, we request the up direction (so we can always land on the last item)
g.NavMoveClipDir = ImGuiDir_Down;
g.NavMoveRequestFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_AlsoScoreVisibleSet;
}
else if (home_pressed)
{
// FIXME-NAV: handling of Home/End is assuming that the top/bottom most item will be visible with Scroll.y == 0/ScrollMax.y
// Scrolling will be handled via the ImGuiNavMoveFlags_ScrollToEdge flag, we don't scroll immediately to avoid scrolling happening before nav result.
// Preserve current horizontal position if we have any.
nav_rect_rel.Min.y = nav_rect_rel.Max.y = -window->Scroll.y;
if (nav_rect_rel.IsInverted())
nav_rect_rel.Min.x = nav_rect_rel.Max.x = 0.0f;
g.NavMoveDir = ImGuiDir_Down;
g.NavMoveRequestFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_ScrollToEdge;
}
else if (end_pressed)
{
nav_rect_rel.Min.y = nav_rect_rel.Max.y = window->ScrollMax.y + window->SizeFull.y - window->Scroll.y;
if (nav_rect_rel.IsInverted())
nav_rect_rel.Min.x = nav_rect_rel.Max.x = 0.0f;
g.NavMoveDir = ImGuiDir_Up;
g.NavMoveRequestFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_ScrollToEdge;
}
return nav_scoring_rect_offset_y;
}
}
return 0.0f;
}
static void ImGui::NavEndFrame()
{
ImGuiContext& g = *GImGui;
// Show CTRL+TAB list window
if (g.NavWindowingTarget != NULL)
NavUpdateWindowingOverlay();
// Perform wrap-around in menus
ImGuiWindow* window = g.NavWrapRequestWindow;
ImGuiNavMoveFlags move_flags = g.NavWrapRequestFlags;
if (window != NULL && g.NavWindow == window && NavMoveRequestButNoResultYet() && g.NavMoveRequestForward == ImGuiNavForward_None && g.NavLayer == ImGuiNavLayer_Main)
{
IM_ASSERT(move_flags != 0); // No points calling this with no wrapping
ImRect bb_rel = window->NavRectRel[0];
ImGuiDir clip_dir = g.NavMoveDir;
if (g.NavMoveDir == ImGuiDir_Left && (move_flags & (ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX)))
{
bb_rel.Min.x = bb_rel.Max.x =
ImMax(window->SizeFull.x, window->ContentSize.x + window->WindowPadding.x * 2.0f) - window->Scroll.x;
if (move_flags & ImGuiNavMoveFlags_WrapX)
{
bb_rel.TranslateY(-bb_rel.GetHeight());
clip_dir = ImGuiDir_Up;
}
NavMoveRequestForward(g.NavMoveDir, clip_dir, bb_rel, move_flags);
}
if (g.NavMoveDir == ImGuiDir_Right && (move_flags & (ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX)))
{
bb_rel.Min.x = bb_rel.Max.x = -window->Scroll.x;
if (move_flags & ImGuiNavMoveFlags_WrapX)
{
bb_rel.TranslateY(+bb_rel.GetHeight());
clip_dir = ImGuiDir_Down;
}
NavMoveRequestForward(g.NavMoveDir, clip_dir, bb_rel, move_flags);
}
if (g.NavMoveDir == ImGuiDir_Up && (move_flags & (ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY)))
{
bb_rel.Min.y = bb_rel.Max.y =
ImMax(window->SizeFull.y, window->ContentSize.y + window->WindowPadding.y * 2.0f) - window->Scroll.y;
if (move_flags & ImGuiNavMoveFlags_WrapY)
{
bb_rel.TranslateX(-bb_rel.GetWidth());
clip_dir = ImGuiDir_Left;
}
NavMoveRequestForward(g.NavMoveDir, clip_dir, bb_rel, move_flags);
}
if (g.NavMoveDir == ImGuiDir_Down && (move_flags & (ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY)))
{
bb_rel.Min.y = bb_rel.Max.y = -window->Scroll.y;
if (move_flags & ImGuiNavMoveFlags_WrapY)
{
bb_rel.TranslateX(+bb_rel.GetWidth());
clip_dir = ImGuiDir_Right;
}
NavMoveRequestForward(g.NavMoveDir, clip_dir, bb_rel, move_flags);
}
}
}
static int ImGui::FindWindowFocusIndex(ImGuiWindow* window) // FIXME-OPT O(N)
{
ImGuiContext& g = *GImGui;
for (int i = g.WindowsFocusOrder.Size - 1; i >= 0; i--)
if (g.WindowsFocusOrder[i] == window)
return i;
return -1;
}
static ImGuiWindow* FindWindowNavFocusable(int i_start, int i_stop, int dir) // FIXME-OPT O(N)
{
ImGuiContext& g = *GImGui;
for (int i = i_start; i >= 0 && i < g.WindowsFocusOrder.Size && i != i_stop; i += dir)
if (ImGui::IsWindowNavFocusable(g.WindowsFocusOrder[i]))
return g.WindowsFocusOrder[i];
return NULL;
}
static void NavUpdateWindowingHighlightWindow(int focus_change_dir)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(g.NavWindowingTarget);
if (g.NavWindowingTarget->Flags & ImGuiWindowFlags_Modal)
return;
const int i_current = ImGui::FindWindowFocusIndex(g.NavWindowingTarget);
ImGuiWindow* window_target = FindWindowNavFocusable(i_current + focus_change_dir, -INT_MAX, focus_change_dir);
if (!window_target)
window_target = FindWindowNavFocusable((focus_change_dir < 0) ? (g.WindowsFocusOrder.Size - 1) : 0, i_current, focus_change_dir);
if (window_target) // Don't reset windowing target if there's a single window in the list
g.NavWindowingTarget = g.NavWindowingTargetAnim = window_target;
g.NavWindowingToggleLayer = false;
}
// Windowing management mode
// Keyboard: CTRL+Tab (change focus/move/resize), Alt (toggle menu layer)
// Gamepad: Hold Menu/Square (change focus/move/resize), Tap Menu/Square (toggle menu layer)
static void ImGui::NavUpdateWindowing()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* apply_focus_window = NULL;
bool apply_toggle_layer = false;
ImGuiWindow* modal_window = GetTopMostPopupModal();
bool allow_windowing = (modal_window == NULL);
if (!allow_windowing)
g.NavWindowingTarget = NULL;
// Fade out
if (g.NavWindowingTargetAnim && g.NavWindowingTarget == NULL)
{
g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha - g.IO.DeltaTime * 10.0f, 0.0f);
if (g.DimBgRatio <= 0.0f && g.NavWindowingHighlightAlpha <= 0.0f)
g.NavWindowingTargetAnim = NULL;
}
// Start CTRL-TAB or Square+L/R window selection
bool start_windowing_with_gamepad = allow_windowing && !g.NavWindowingTarget && IsNavInputTest(ImGuiNavInput_Menu, ImGuiInputReadMode_Pressed);
bool start_windowing_with_keyboard = allow_windowing && !g.NavWindowingTarget && g.IO.KeyCtrl && IsKeyPressedMap(ImGuiKey_Tab) && (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard);
if (start_windowing_with_gamepad || start_windowing_with_keyboard)
if (ImGuiWindow* window = g.NavWindow ? g.NavWindow : FindWindowNavFocusable(g.WindowsFocusOrder.Size - 1, -INT_MAX, -1))
{
g.NavWindowingTarget = g.NavWindowingTargetAnim = window->RootWindow; // FIXME-DOCK: Will need to use RootWindowDockStop
g.NavWindowingTimer = g.NavWindowingHighlightAlpha = 0.0f;
g.NavWindowingToggleLayer = start_windowing_with_keyboard ? false : true;
g.NavInputSource = start_windowing_with_keyboard ? ImGuiInputSource_NavKeyboard : ImGuiInputSource_NavGamepad;
}
// Gamepad update
g.NavWindowingTimer += g.IO.DeltaTime;
if (g.NavWindowingTarget && g.NavInputSource == ImGuiInputSource_NavGamepad)
{
// Highlight only appears after a brief time holding the button, so that a fast tap on PadMenu (to toggle NavLayer) doesn't add visual noise
g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05f));
// Select window to focus
const int focus_change_dir = (int)IsNavInputTest(ImGuiNavInput_FocusPrev, ImGuiInputReadMode_RepeatSlow) - (int)IsNavInputTest(ImGuiNavInput_FocusNext, ImGuiInputReadMode_RepeatSlow);
if (focus_change_dir != 0)
{
NavUpdateWindowingHighlightWindow(focus_change_dir);
g.NavWindowingHighlightAlpha = 1.0f;
}
// Single press toggles NavLayer, long press with L/R apply actual focus on release (until then the window was merely rendered top-most)
if (!IsNavInputDown(ImGuiNavInput_Menu))
{
g.NavWindowingToggleLayer &= (g.NavWindowingHighlightAlpha < 1.0f); // Once button was held long enough we don't consider it a tap-to-toggle-layer press anymore.
if (g.NavWindowingToggleLayer && g.NavWindow)
apply_toggle_layer = true;
else if (!g.NavWindowingToggleLayer)
apply_focus_window = g.NavWindowingTarget;
g.NavWindowingTarget = NULL;
}
}
// Keyboard: Focus
if (g.NavWindowingTarget && g.NavInputSource == ImGuiInputSource_NavKeyboard)
{
// Visuals only appears after a brief time after pressing TAB the first time, so that a fast CTRL+TAB doesn't add visual noise
g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05f)); // 1.0f
if (IsKeyPressedMap(ImGuiKey_Tab, true))
NavUpdateWindowingHighlightWindow(g.IO.KeyShift ? +1 : -1);
if (!g.IO.KeyCtrl)
apply_focus_window = g.NavWindowingTarget;
}
// Keyboard: Press and Release ALT to toggle menu layer
// FIXME: We lack an explicit IO variable for "is the imgui window focused", so compare mouse validity to detect the common case of back-end clearing releases all keys on ALT-TAB
if (IsNavInputTest(ImGuiNavInput_KeyMenu_, ImGuiInputReadMode_Pressed))
g.NavWindowingToggleLayer = true;
if ((g.ActiveId == 0 || g.ActiveIdAllowOverlap) && g.NavWindowingToggleLayer && IsNavInputTest(ImGuiNavInput_KeyMenu_, ImGuiInputReadMode_Released))
if (IsMousePosValid(&g.IO.MousePos) == IsMousePosValid(&g.IO.MousePosPrev))
apply_toggle_layer = true;
// Move window
if (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoMove))
{
ImVec2 move_delta;
if (g.NavInputSource == ImGuiInputSource_NavKeyboard && !g.IO.KeyShift)
move_delta = GetNavInputAmount2d(ImGuiNavDirSourceFlags_Keyboard, ImGuiInputReadMode_Down);
if (g.NavInputSource == ImGuiInputSource_NavGamepad)
move_delta = GetNavInputAmount2d(ImGuiNavDirSourceFlags_PadLStick, ImGuiInputReadMode_Down);
if (move_delta.x != 0.0f || move_delta.y != 0.0f)
{
const float NAV_MOVE_SPEED = 800.0f;
const float move_speed = ImFloor(NAV_MOVE_SPEED * g.IO.DeltaTime * ImMin(g.IO.DisplayFramebufferScale.x, g.IO.DisplayFramebufferScale.y)); // FIXME: Doesn't handle variable framerate very well
ImGuiWindow* moving_window = g.NavWindowingTarget->RootWindow;
SetWindowPos(moving_window, moving_window->Pos + move_delta * move_speed, ImGuiCond_Always);
MarkIniSettingsDirty(moving_window);
g.NavDisableMouseHover = true;
}
}
// Apply final focus
if (apply_focus_window && (g.NavWindow == NULL || apply_focus_window != g.NavWindow->RootWindow))
{
ClearActiveID();
g.NavDisableHighlight = false;
g.NavDisableMouseHover = true;
apply_focus_window = NavRestoreLastChildNavWindow(apply_focus_window);
ClosePopupsOverWindow(apply_focus_window, false);
FocusWindow(apply_focus_window);
if (apply_focus_window->NavLastIds[0] == 0)
NavInitWindow(apply_focus_window, false);
// If the window only has a menu layer, select it directly
if (apply_focus_window->DC.NavLayerActiveMask == (1 << ImGuiNavLayer_Menu))
g.NavLayer = ImGuiNavLayer_Menu;
}
if (apply_focus_window)
g.NavWindowingTarget = NULL;
// Apply menu/layer toggle
if (apply_toggle_layer && g.NavWindow)
{
// Move to parent menu if necessary
ImGuiWindow* new_nav_window = g.NavWindow;
while (new_nav_window->ParentWindow
&& (new_nav_window->DC.NavLayerActiveMask & (1 << ImGuiNavLayer_Menu)) == 0
&& (new_nav_window->Flags & ImGuiWindowFlags_ChildWindow) != 0
&& (new_nav_window->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == 0)
new_nav_window = new_nav_window->ParentWindow;
if (new_nav_window != g.NavWindow)
{
ImGuiWindow* old_nav_window = g.NavWindow;
FocusWindow(new_nav_window);
new_nav_window->NavLastChildNavWindow = old_nav_window;
}
g.NavDisableHighlight = false;
g.NavDisableMouseHover = true;
// When entering a regular menu bar with the Alt key, we always reinitialize the navigation ID.
const ImGuiNavLayer new_nav_layer = (g.NavWindow->DC.NavLayerActiveMask & (1 << ImGuiNavLayer_Menu)) ? (ImGuiNavLayer)((int)g.NavLayer ^ 1) : ImGuiNavLayer_Main;
NavRestoreLayer(new_nav_layer);
}
}
// Window has already passed the IsWindowNavFocusable()
static const char* GetFallbackWindowNameForWindowingList(ImGuiWindow* window)
{
if (window->Flags & ImGuiWindowFlags_Popup)
return "(Popup)";
if ((window->Flags & ImGuiWindowFlags_MenuBar) && strcmp(window->Name, "##MainMenuBar") == 0)
return "(Main menu bar)";
return "(Untitled)";
}
// Overlay displayed when using CTRL+TAB. Called by EndFrame().
void ImGui::NavUpdateWindowingOverlay()
{
ImGuiContext& g = *GImGui;
IM_ASSERT(g.NavWindowingTarget != NULL);
if (g.NavWindowingTimer < NAV_WINDOWING_LIST_APPEAR_DELAY)
return;
if (g.NavWindowingListWindow == NULL)
g.NavWindowingListWindow = FindWindowByName("###NavWindowingList");
SetNextWindowSizeConstraints(ImVec2(g.IO.DisplaySize.x * 0.20f, g.IO.DisplaySize.y * 0.20f), ImVec2(FLT_MAX, FLT_MAX));
SetNextWindowPos(g.IO.DisplaySize * 0.5f, ImGuiCond_Always, ImVec2(0.5f, 0.5f));
PushStyleVar(ImGuiStyleVar_WindowPadding, g.Style.WindowPadding * 2.0f);
Begin("###NavWindowingList", NULL, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings);
for (int n = g.WindowsFocusOrder.Size - 1; n >= 0; n--)
{
ImGuiWindow* window = g.WindowsFocusOrder[n];
if (!IsWindowNavFocusable(window))
continue;
const char* label = window->Name;
if (label == FindRenderedTextEnd(label))
label = GetFallbackWindowNameForWindowingList(window);
Selectable(label, g.NavWindowingTarget == window);
}
End();
PopStyleVar();
}
//-----------------------------------------------------------------------------
// [SECTION] DRAG AND DROP
//-----------------------------------------------------------------------------
void ImGui::ClearDragDrop()
{
ImGuiContext& g = *GImGui;
g.DragDropActive = false;
g.DragDropPayload.Clear();
g.DragDropAcceptFlags = ImGuiDragDropFlags_None;
g.DragDropAcceptIdCurr = g.DragDropAcceptIdPrev = 0;
g.DragDropAcceptIdCurrRectSurface = FLT_MAX;
g.DragDropAcceptFrameCount = -1;
g.DragDropPayloadBufHeap.clear();
memset(&g.DragDropPayloadBufLocal, 0, sizeof(g.DragDropPayloadBufLocal));
}
// Call when current ID is active.
// When this returns true you need to: a) call SetDragDropPayload() exactly once, b) you may render the payload visual/description, c) call EndDragDropSource()
bool ImGui::BeginDragDropSource(ImGuiDragDropFlags flags)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
bool source_drag_active = false;
ImGuiID source_id = 0;
ImGuiID source_parent_id = 0;
ImGuiMouseButton mouse_button = ImGuiMouseButton_Left;
if (!(flags & ImGuiDragDropFlags_SourceExtern))
{
source_id = window->DC.LastItemId;
if (source_id != 0 && g.ActiveId != source_id) // Early out for most common case
return false;
if (g.IO.MouseDown[mouse_button] == false)
return false;
if (source_id == 0)
{
// If you want to use BeginDragDropSource() on an item with no unique identifier for interaction, such as Text() or Image(), you need to:
// A) Read the explanation below, B) Use the ImGuiDragDropFlags_SourceAllowNullID flag, C) Swallow your programmer pride.
if (!(flags & ImGuiDragDropFlags_SourceAllowNullID))
{
IM_ASSERT(0);
return false;
}
// Early out
if ((window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_HoveredRect) == 0 && (g.ActiveId == 0 || g.ActiveIdWindow != window))
return false;
// Magic fallback (=somehow reprehensible) to handle items with no assigned ID, e.g. Text(), Image()
// We build a throwaway ID based on current ID stack + relative AABB of items in window.
// THE IDENTIFIER WON'T SURVIVE ANY REPOSITIONING OF THE WIDGET, so if your widget moves your dragging operation will be canceled.
// We don't need to maintain/call ClearActiveID() as releasing the button will early out this function and trigger !ActiveIdIsAlive.
source_id = window->DC.LastItemId = window->GetIDFromRectangle(window->DC.LastItemRect);
bool is_hovered = ItemHoverable(window->DC.LastItemRect, source_id);
if (is_hovered && g.IO.MouseClicked[mouse_button])
{
SetActiveID(source_id, window);
FocusWindow(window);
}
if (g.ActiveId == source_id) // Allow the underlying widget to display/return hovered during the mouse release frame, else we would get a flicker.
g.ActiveIdAllowOverlap = is_hovered;
}
else
{
g.ActiveIdAllowOverlap = false;
}
if (g.ActiveId != source_id)
return false;
source_parent_id = window->IDStack.back();
source_drag_active = IsMouseDragging(mouse_button);
// Disable navigation and key inputs while dragging
g.ActiveIdUsingNavDirMask = ~(ImU32)0;
g.ActiveIdUsingNavInputMask = ~(ImU32)0;
g.ActiveIdUsingKeyInputMask = ~(ImU64)0;
}
else
{
window = NULL;
source_id = ImHashStr("#SourceExtern");
source_drag_active = true;
}
if (source_drag_active)
{
if (!g.DragDropActive)
{
IM_ASSERT(source_id != 0);
ClearDragDrop();
ImGuiPayload& payload = g.DragDropPayload;
payload.SourceId = source_id;
payload.SourceParentId = source_parent_id;
g.DragDropActive = true;
g.DragDropSourceFlags = flags;
g.DragDropMouseButton = mouse_button;
}
g.DragDropSourceFrameCount = g.FrameCount;
g.DragDropWithinSource = true;
if (!(flags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
{
// Target can request the Source to not display its tooltip (we use a dedicated flag to make this request explicit)
// We unfortunately can't just modify the source flags and skip the call to BeginTooltip, as caller may be emitting contents.
BeginTooltip();
if (g.DragDropAcceptIdPrev && (g.DragDropAcceptFlags & ImGuiDragDropFlags_AcceptNoPreviewTooltip))
{
ImGuiWindow* tooltip_window = g.CurrentWindow;
tooltip_window->SkipItems = true;
tooltip_window->HiddenFramesCanSkipItems = 1;
}
}
if (!(flags & ImGuiDragDropFlags_SourceNoDisableHover) && !(flags & ImGuiDragDropFlags_SourceExtern))
window->DC.LastItemStatusFlags &= ~ImGuiItemStatusFlags_HoveredRect;
return true;
}
return false;
}
void ImGui::EndDragDropSource()
{
ImGuiContext& g = *GImGui;
IM_ASSERT(g.DragDropActive);
IM_ASSERT(g.DragDropWithinSource && "Not after a BeginDragDropSource()?");
if (!(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
EndTooltip();
// Discard the drag if have not called SetDragDropPayload()
if (g.DragDropPayload.DataFrameCount == -1)
ClearDragDrop();
g.DragDropWithinSource = false;
}
// Use 'cond' to choose to submit payload on drag start or every frame
bool ImGui::SetDragDropPayload(const char* type, const void* data, size_t data_size, ImGuiCond cond)
{
ImGuiContext& g = *GImGui;
ImGuiPayload& payload = g.DragDropPayload;
if (cond == 0)
cond = ImGuiCond_Always;
IM_ASSERT(type != NULL);
IM_ASSERT(strlen(type) < IM_ARRAYSIZE(payload.DataType) && "Payload type can be at most 32 characters long");
IM_ASSERT((data != NULL && data_size > 0) || (data == NULL && data_size == 0));
IM_ASSERT(cond == ImGuiCond_Always || cond == ImGuiCond_Once);
IM_ASSERT(payload.SourceId != 0); // Not called between BeginDragDropSource() and EndDragDropSource()
if (cond == ImGuiCond_Always || payload.DataFrameCount == -1)
{
// Copy payload
ImStrncpy(payload.DataType, type, IM_ARRAYSIZE(payload.DataType));
g.DragDropPayloadBufHeap.resize(0);
if (data_size > sizeof(g.DragDropPayloadBufLocal))
{
// Store in heap
g.DragDropPayloadBufHeap.resize((int)data_size);
payload.Data = g.DragDropPayloadBufHeap.Data;
memcpy(payload.Data, data, data_size);
}
else if (data_size > 0)
{
// Store locally
memset(&g.DragDropPayloadBufLocal, 0, sizeof(g.DragDropPayloadBufLocal));
payload.Data = g.DragDropPayloadBufLocal;
memcpy(payload.Data, data, data_size);
}
else
{
payload.Data = NULL;
}
payload.DataSize = (int)data_size;
}
payload.DataFrameCount = g.FrameCount;
return (g.DragDropAcceptFrameCount == g.FrameCount) || (g.DragDropAcceptFrameCount == g.FrameCount - 1);
}
bool ImGui::BeginDragDropTargetCustom(const ImRect& bb, ImGuiID id)
{
ImGuiContext& g = *GImGui;
if (!g.DragDropActive)
return false;
ImGuiWindow* window = g.CurrentWindow;
ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow;
if (hovered_window == NULL || window->RootWindow != hovered_window->RootWindow)
return false;
IM_ASSERT(id != 0);
if (!IsMouseHoveringRect(bb.Min, bb.Max) || (id == g.DragDropPayload.SourceId))
return false;
if (window->SkipItems)
return false;
IM_ASSERT(g.DragDropWithinTarget == false);
g.DragDropTargetRect = bb;
g.DragDropTargetId = id;
g.DragDropWithinTarget = true;
return true;
}
// We don't use BeginDragDropTargetCustom() and duplicate its code because:
// 1) we use LastItemRectHoveredRect which handles items that pushes a temporarily clip rectangle in their code. Calling BeginDragDropTargetCustom(LastItemRect) would not handle them.
// 2) and it's faster. as this code may be very frequently called, we want to early out as fast as we can.
// Also note how the HoveredWindow test is positioned differently in both functions (in both functions we optimize for the cheapest early out case)
bool ImGui::BeginDragDropTarget()
{
ImGuiContext& g = *GImGui;
if (!g.DragDropActive)
return false;
ImGuiWindow* window = g.CurrentWindow;
if (!(window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_HoveredRect))
return false;
ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow;
if (hovered_window == NULL || window->RootWindow != hovered_window->RootWindow)
return false;
const ImRect& display_rect = (window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_HasDisplayRect) ? window->DC.LastItemDisplayRect : window->DC.LastItemRect;
ImGuiID id = window->DC.LastItemId;
if (id == 0)
id = window->GetIDFromRectangle(display_rect);
if (g.DragDropPayload.SourceId == id)
return false;
IM_ASSERT(g.DragDropWithinTarget == false);
g.DragDropTargetRect = display_rect;
g.DragDropTargetId = id;
g.DragDropWithinTarget = true;
return true;
}
bool ImGui::IsDragDropPayloadBeingAccepted()
{
ImGuiContext& g = *GImGui;
return g.DragDropActive && g.DragDropAcceptIdPrev != 0;
}
const ImGuiPayload* ImGui::AcceptDragDropPayload(const char* type, ImGuiDragDropFlags flags)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
ImGuiPayload& payload = g.DragDropPayload;
IM_ASSERT(g.DragDropActive); // Not called between BeginDragDropTarget() and EndDragDropTarget() ?
IM_ASSERT(payload.DataFrameCount != -1); // Forgot to call EndDragDropTarget() ?
if (type != NULL && !payload.IsDataType(type))
return NULL;
// Accept smallest drag target bounding box, this allows us to nest drag targets conveniently without ordering constraints.
// NB: We currently accept NULL id as target. However, overlapping targets requires a unique ID to function!
const bool was_accepted_previously = (g.DragDropAcceptIdPrev == g.DragDropTargetId);
ImRect r = g.DragDropTargetRect;
float r_surface = r.GetWidth() * r.GetHeight();
if (r_surface < g.DragDropAcceptIdCurrRectSurface)
{
g.DragDropAcceptFlags = flags;
g.DragDropAcceptIdCurr = g.DragDropTargetId;
g.DragDropAcceptIdCurrRectSurface = r_surface;
}
// Render default drop visuals
payload.Preview = was_accepted_previously;
flags |= (g.DragDropSourceFlags & ImGuiDragDropFlags_AcceptNoDrawDefaultRect); // Source can also inhibit the preview (useful for external sources that lives for 1 frame)
if (!(flags & ImGuiDragDropFlags_AcceptNoDrawDefaultRect) && payload.Preview)
{
// FIXME-DRAG: Settle on a proper default visuals for drop target.
r.Expand(3.5f);
bool push_clip_rect = !window->ClipRect.Contains(r);
if (push_clip_rect) window->DrawList->PushClipRect(r.Min - ImVec2(1, 1), r.Max + ImVec2(1, 1));
window->DrawList->AddRect(r.Min, r.Max, GetColorU32(ImGuiCol_DragDropTarget), 0.0f, ~0, 2.0f);
if (push_clip_rect) window->DrawList->PopClipRect();
}
g.DragDropAcceptFrameCount = g.FrameCount;
payload.Delivery = was_accepted_previously && !IsMouseDown(g.DragDropMouseButton); // For extern drag sources affecting os window focus, it's easier to just test !IsMouseDown() instead of IsMouseReleased()
if (!payload.Delivery && !(flags & ImGuiDragDropFlags_AcceptBeforeDelivery))
return NULL;
return &payload;
}
const ImGuiPayload* ImGui::GetDragDropPayload()
{
ImGuiContext& g = *GImGui;
return g.DragDropActive ? &g.DragDropPayload : NULL;
}
// We don't really use/need this now, but added it for the sake of consistency and because we might need it later.
void ImGui::EndDragDropTarget()
{
ImGuiContext& g = *GImGui;
IM_ASSERT(g.DragDropActive);
IM_ASSERT(g.DragDropWithinTarget);
g.DragDropWithinTarget = false;
}
//-----------------------------------------------------------------------------
// [SECTION] LOGGING/CAPTURING
//-----------------------------------------------------------------------------
// All text output from the interface can be captured into tty/file/clipboard.
// By default, tree nodes are automatically opened during logging.
//-----------------------------------------------------------------------------
// Pass text data straight to log (without being displayed)
void ImGui::LogText(const char* fmt, ...)
{
ImGuiContext& g = *GImGui;
if (!g.LogEnabled)
return;
va_list args;
va_start(args, fmt);
if (g.LogFile)
{
g.LogBuffer.Buf.resize(0);
g.LogBuffer.appendfv(fmt, args);
ImFileWrite(g.LogBuffer.c_str(), sizeof(char), (ImU64)g.LogBuffer.size(), g.LogFile);
}
else
{
g.LogBuffer.appendfv(fmt, args);
}
va_end(args);
}
// Internal version that takes a position to decide on newline placement and pad items according to their depth.
// We split text into individual lines to add current tree level padding
void ImGui::LogRenderedText(const ImVec2* ref_pos, const char* text, const char* text_end)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (!text_end)
text_end = FindRenderedTextEnd(text, text_end);
const bool log_new_line = ref_pos && (ref_pos->y > g.LogLinePosY + 1);
if (ref_pos)
g.LogLinePosY = ref_pos->y;
if (log_new_line)
g.LogLineFirstItem = true;
const char* text_remaining = text;
if (g.LogDepthRef > window->DC.TreeDepth) // Re-adjust padding if we have popped out of our starting depth
g.LogDepthRef = window->DC.TreeDepth;
const int tree_depth = (window->DC.TreeDepth - g.LogDepthRef);
for (;;)
{
// Split the string. Each new line (after a '\n') is followed by spacing corresponding to the current depth of our log entry.
// We don't add a trailing \n to allow a subsequent item on the same line to be captured.
const char* line_start = text_remaining;
const char* line_end = ImStreolRange(line_start, text_end);
const bool is_first_line = (line_start == text);
const bool is_last_line = (line_end == text_end);
if (!is_last_line || (line_start != line_end))
{
const int char_count = (int)(line_end - line_start);
if (log_new_line || !is_first_line)
LogText(IM_NEWLINE "%*s%.*s", tree_depth * 4, "", char_count, line_start);
else if (g.LogLineFirstItem)
LogText("%*s%.*s", tree_depth * 4, "", char_count, line_start);
else
LogText(" %.*s", char_count, line_start);
g.LogLineFirstItem = false;
}
else if (log_new_line)
{
// An empty "" string at a different Y position should output a carriage return.
LogText(IM_NEWLINE);
break;
}
if (is_last_line)
break;
text_remaining = line_end + 1;
}
}
// Start logging/capturing text output
void ImGui::LogBegin(ImGuiLogType type, int auto_open_depth)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
IM_ASSERT(g.LogEnabled == false);
IM_ASSERT(g.LogFile == NULL);
IM_ASSERT(g.LogBuffer.empty());
g.LogEnabled = true;
g.LogType = type;
g.LogDepthRef = window->DC.TreeDepth;
g.LogDepthToExpand = ((auto_open_depth >= 0) ? auto_open_depth : g.LogDepthToExpandDefault);
g.LogLinePosY = FLT_MAX;
g.LogLineFirstItem = true;
}
void ImGui::LogToTTY(int auto_open_depth)
{
ImGuiContext& g = *GImGui;
if (g.LogEnabled)
return;
IM_UNUSED(auto_open_depth);
#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
LogBegin(ImGuiLogType_TTY, auto_open_depth);
g.LogFile = stdout;
#endif
}
// Start logging/capturing text output to given file
void ImGui::LogToFile(int auto_open_depth, const char* filename)
{
ImGuiContext& g = *GImGui;
if (g.LogEnabled)
return;
// FIXME: We could probably open the file in text mode "at", however note that clipboard/buffer logging will still
// be subject to outputting OS-incompatible carriage return if within strings the user doesn't use IM_NEWLINE.
// By opening the file in binary mode "ab" we have consistent output everywhere.
if (!filename)
filename = g.IO.LogFilename;
if (!filename || !filename[0])
return;
ImFileHandle f = ImFileOpen(filename, "ab");
if (!f)
{
IM_ASSERT(0);
return;
}
LogBegin(ImGuiLogType_File, auto_open_depth);
g.LogFile = f;
}
// Start logging/capturing text output to clipboard
void ImGui::LogToClipboard(int auto_open_depth)
{
ImGuiContext& g = *GImGui;
if (g.LogEnabled)
return;
LogBegin(ImGuiLogType_Clipboard, auto_open_depth);
}
void ImGui::LogToBuffer(int auto_open_depth)
{
ImGuiContext& g = *GImGui;
if (g.LogEnabled)
return;
LogBegin(ImGuiLogType_Buffer, auto_open_depth);
}
void ImGui::LogFinish()
{
ImGuiContext& g = *GImGui;
if (!g.LogEnabled)
return;
LogText(IM_NEWLINE);
switch (g.LogType)
{
case ImGuiLogType_TTY:
#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
fflush(g.LogFile);
#endif
break;
case ImGuiLogType_File:
ImFileClose(g.LogFile);
break;
case ImGuiLogType_Buffer:
break;
case ImGuiLogType_Clipboard:
if (!g.LogBuffer.empty())
SetClipboardText(g.LogBuffer.begin());
break;
case ImGuiLogType_None:
IM_ASSERT(0);
break;
}
g.LogEnabled = false;
g.LogType = ImGuiLogType_None;
g.LogFile = NULL;
g.LogBuffer.clear();
}
// Helper to display logging buttons
// FIXME-OBSOLETE: We should probably obsolete this and let the user have their own helper (this is one of the oldest function alive!)
void ImGui::LogButtons()
{
ImGuiContext& g = *GImGui;
PushID("LogButtons");
#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
const bool log_to_tty = Button("Log To TTY"); SameLine();
#else
const bool log_to_tty = false;
#endif
const bool log_to_file = Button("Log To File"); SameLine();
const bool log_to_clipboard = Button("Log To Clipboard"); SameLine();
PushAllowKeyboardFocus(false);
SetNextItemWidth(80.0f);
SliderInt("Default Depth", &g.LogDepthToExpandDefault, 0, 9, NULL);
PopAllowKeyboardFocus();
PopID();
// Start logging at the end of the function so that the buttons don't appear in the log
if (log_to_tty)
LogToTTY();
if (log_to_file)
LogToFile();
if (log_to_clipboard)
LogToClipboard();
}
//-----------------------------------------------------------------------------
// [SECTION] SETTINGS
//-----------------------------------------------------------------------------
// - UpdateSettings() [Internal]
// - MarkIniSettingsDirty() [Internal]
// - CreateNewWindowSettings() [Internal]
// - FindWindowSettings() [Internal]
// - FindOrCreateWindowSettings() [Internal]
// - FindSettingsHandler() [Internal]
// - ClearIniSettings() [Internal]
// - LoadIniSettingsFromDisk()
// - LoadIniSettingsFromMemory()
// - SaveIniSettingsToDisk()
// - SaveIniSettingsToMemory()
// - WindowSettingsHandler_***() [Internal]
//-----------------------------------------------------------------------------
// Called by NewFrame()
void ImGui::UpdateSettings()
{
// Load settings on first frame (if not explicitly loaded manually before)
ImGuiContext& g = *GImGui;
if (!g.SettingsLoaded)
{
IM_ASSERT(g.SettingsWindows.empty());
if (g.IO.IniFilename)
LoadIniSettingsFromDisk(g.IO.IniFilename);
g.SettingsLoaded = true;
}
// Save settings (with a delay after the last modification, so we don't spam disk too much)
if (g.SettingsDirtyTimer > 0.0f)
{
g.SettingsDirtyTimer -= g.IO.DeltaTime;
if (g.SettingsDirtyTimer <= 0.0f)
{
if (g.IO.IniFilename != NULL)
SaveIniSettingsToDisk(g.IO.IniFilename);
else
g.IO.WantSaveIniSettings = true; // Let user know they can call SaveIniSettingsToMemory(). user will need to clear io.WantSaveIniSettings themselves.
g.SettingsDirtyTimer = 0.0f;
}
}
}
void ImGui::MarkIniSettingsDirty()
{
ImGuiContext& g = *GImGui;
if (g.SettingsDirtyTimer <= 0.0f)
g.SettingsDirtyTimer = g.IO.IniSavingRate;
}
void ImGui::MarkIniSettingsDirty(ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
if (!(window->Flags & ImGuiWindowFlags_NoSavedSettings))
if (g.SettingsDirtyTimer <= 0.0f)
g.SettingsDirtyTimer = g.IO.IniSavingRate;
}
ImGuiWindowSettings* ImGui::CreateNewWindowSettings(const char* name)
{
ImGuiContext& g = *GImGui;
#if !IMGUI_DEBUG_INI_SETTINGS
// Skip to the "###" marker if any. We don't skip past to match the behavior of GetID()
// Preserve the full string when IMGUI_DEBUG_INI_SETTINGS is set to make .ini inspection easier.
if (const char* p = strstr(name, "###"))
name = p;
#endif
const size_t name_len = strlen(name);
// Allocate chunk
const size_t chunk_size = sizeof(ImGuiWindowSettings) + name_len + 1;
ImGuiWindowSettings* settings = g.SettingsWindows.alloc_chunk(chunk_size);
IM_PLACEMENT_NEW(settings) ImGuiWindowSettings();
settings->ID = ImHashStr(name, name_len);
memcpy(settings->GetName(), name, name_len + 1); // Store with zero terminator
return settings;
}
ImGuiWindowSettings* ImGui::FindWindowSettings(ImGuiID id)
{
ImGuiContext& g = *GImGui;
for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
if (settings->ID == id)
return settings;
return NULL;
}
ImGuiWindowSettings* ImGui::FindOrCreateWindowSettings(const char* name)
{
if (ImGuiWindowSettings* settings = FindWindowSettings(ImHashStr(name)))
return settings;
return CreateNewWindowSettings(name);
}
ImGuiSettingsHandler* ImGui::FindSettingsHandler(const char* type_name)
{
ImGuiContext& g = *GImGui;
const ImGuiID type_hash = ImHashStr(type_name);
for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++)
if (g.SettingsHandlers[handler_n].TypeHash == type_hash)
return &g.SettingsHandlers[handler_n];
return NULL;
}
void ImGui::ClearIniSettings()
{
ImGuiContext& g = *GImGui;
g.SettingsIniData.clear();
for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++)
if (g.SettingsHandlers[handler_n].ClearAllFn)
g.SettingsHandlers[handler_n].ClearAllFn(&g, &g.SettingsHandlers[handler_n]);
}
void ImGui::LoadIniSettingsFromDisk(const char* ini_filename)
{
size_t file_data_size = 0;
char* file_data = (char*)ImFileLoadToMemory(ini_filename, "rb", &file_data_size);
if (!file_data)
return;
LoadIniSettingsFromMemory(file_data, (size_t)file_data_size);
IM_FREE(file_data);
}
// Zero-tolerance, no error reporting, cheap .ini parsing
void ImGui::LoadIniSettingsFromMemory(const char* ini_data, size_t ini_size)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(g.Initialized);
//IM_ASSERT(!g.WithinFrameScope && "Cannot be called between NewFrame() and EndFrame()");
//IM_ASSERT(g.SettingsLoaded == false && g.FrameCount == 0);
// For user convenience, we allow passing a non zero-terminated string (hence the ini_size parameter).
// For our convenience and to make the code simpler, we'll also write zero-terminators within the buffer. So let's create a writable copy..
if (ini_size == 0)
ini_size = strlen(ini_data);
g.SettingsIniData.Buf.resize((int)ini_size + 1);
char* const buf = g.SettingsIniData.Buf.Data;
char* const buf_end = buf + ini_size;
memcpy(buf, ini_data, ini_size);
buf_end[0] = 0;
// Call pre-read handlers
// Some types will clear their data (e.g. dock information) some types will allow merge/override (window)
for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++)
if (g.SettingsHandlers[handler_n].ReadInitFn)
g.SettingsHandlers[handler_n].ReadInitFn(&g, &g.SettingsHandlers[handler_n]);
void* entry_data = NULL;
ImGuiSettingsHandler* entry_handler = NULL;
char* line_end = NULL;
for (char* line = buf; line < buf_end; line = line_end + 1)
{
// Skip new lines markers, then find end of the line
while (*line == '\n' || *line == '\r')
line++;
line_end = line;
while (line_end < buf_end && *line_end != '\n' && *line_end != '\r')
line_end++;
line_end[0] = 0;
if (line[0] == ';')
continue;
if (line[0] == '[' && line_end > line && line_end[-1] == ']')
{
// Parse "[Type][Name]". Note that 'Name' can itself contains [] characters, which is acceptable with the current format and parsing code.
line_end[-1] = 0;
const char* name_end = line_end - 1;
const char* type_start = line + 1;
char* type_end = (char*)(void*)ImStrchrRange(type_start, name_end, ']');
const char* name_start = type_end ? ImStrchrRange(type_end + 1, name_end, '[') : NULL;
if (!type_end || !name_start)
continue;
*type_end = 0; // Overwrite first ']'
name_start++; // Skip second '['
entry_handler = FindSettingsHandler(type_start);
entry_data = entry_handler ? entry_handler->ReadOpenFn(&g, entry_handler, name_start) : NULL;
}
else if (entry_handler != NULL && entry_data != NULL)
{
// Let type handler parse the line
entry_handler->ReadLineFn(&g, entry_handler, entry_data, line);
}
}
g.SettingsLoaded = true;
// [DEBUG] Restore untouched copy so it can be browsed in Metrics (not strictly necessary)
memcpy(buf, ini_data, ini_size);
// Call post-read handlers
for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++)
if (g.SettingsHandlers[handler_n].ApplyAllFn)
g.SettingsHandlers[handler_n].ApplyAllFn(&g, &g.SettingsHandlers[handler_n]);
}
void ImGui::SaveIniSettingsToDisk(const char* ini_filename)
{
ImGuiContext& g = *GImGui;
g.SettingsDirtyTimer = 0.0f;
if (!ini_filename)
return;
size_t ini_data_size = 0;
const char* ini_data = SaveIniSettingsToMemory(&ini_data_size);
ImFileHandle f = ImFileOpen(ini_filename, "wt");
if (!f)
return;
ImFileWrite(ini_data, sizeof(char), ini_data_size, f);
ImFileClose(f);
}
// Call registered handlers (e.g. SettingsHandlerWindow_WriteAll() + custom handlers) to write their stuff into a text buffer
const char* ImGui::SaveIniSettingsToMemory(size_t* out_size)
{
ImGuiContext& g = *GImGui;
g.SettingsDirtyTimer = 0.0f;
g.SettingsIniData.Buf.resize(0);
g.SettingsIniData.Buf.push_back(0);
for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++)
{
ImGuiSettingsHandler* handler = &g.SettingsHandlers[handler_n];
handler->WriteAllFn(&g, handler, &g.SettingsIniData);
}
if (out_size)
*out_size = (size_t)g.SettingsIniData.size();
return g.SettingsIniData.c_str();
}
static void WindowSettingsHandler_ClearAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
{
ImGuiContext& g = *ctx;
for (int i = 0; i != g.Windows.Size; i++)
g.Windows[i]->SettingsOffset = -1;
g.SettingsWindows.clear();
}
static void* WindowSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name)
{
ImGuiWindowSettings* settings = ImGui::FindOrCreateWindowSettings(name);
ImGuiID id = settings->ID;
*settings = ImGuiWindowSettings(); // Clear existing if recycling previous entry
settings->ID = id;
settings->WantApply = true;
return (void*)settings;
}
static void WindowSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line)
{
ImGuiWindowSettings* settings = (ImGuiWindowSettings*)entry;
int x, y;
int i;
if (sscanf(line, "Pos=%i,%i", &x, &y) == 2) { settings->Pos = ImVec2ih((short)x, (short)y); }
else if (sscanf(line, "Size=%i,%i", &x, &y) == 2) { settings->Size = ImVec2ih((short)x, (short)y); }
else if (sscanf(line, "Collapsed=%d", &i) == 1) { settings->Collapsed = (i != 0); }
}
// Apply to existing windows (if any)
static void WindowSettingsHandler_ApplyAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
{
ImGuiContext& g = *ctx;
for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
if (settings->WantApply)
{
if (ImGuiWindow* window = ImGui::FindWindowByID(settings->ID))
ApplyWindowSettings(window, settings);
settings->WantApply = false;
}
}
static void WindowSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf)
{
// Gather data from windows that were active during this session
// (if a window wasn't opened in this session we preserve its settings)
ImGuiContext& g = *ctx;
for (int i = 0; i != g.Windows.Size; i++)
{
ImGuiWindow* window = g.Windows[i];
if (window->Flags & ImGuiWindowFlags_NoSavedSettings)
continue;
ImGuiWindowSettings* settings = (window->SettingsOffset != -1) ? g.SettingsWindows.ptr_from_offset(window->SettingsOffset) : ImGui::FindWindowSettings(window->ID);
if (!settings)
{
settings = ImGui::CreateNewWindowSettings(window->Name);
window->SettingsOffset = g.SettingsWindows.offset_from_ptr(settings);
}
IM_ASSERT(settings->ID == window->ID);
settings->Pos = ImVec2ih((short)window->Pos.x, (short)window->Pos.y);
settings->Size = ImVec2ih((short)window->SizeFull.x, (short)window->SizeFull.y);
settings->Collapsed = window->Collapsed;
}
// Write to text buffer
buf->reserve(buf->size() + g.SettingsWindows.size() * 6); // ballpark reserve
for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
{
const char* settings_name = settings->GetName();
buf->appendf("[%s][%s]\n", handler->TypeName, settings_name);
buf->appendf("Pos=%d,%d\n", settings->Pos.x, settings->Pos.y);
buf->appendf("Size=%d,%d\n", settings->Size.x, settings->Size.y);
buf->appendf("Collapsed=%d\n", settings->Collapsed);
buf->append("\n");
}
}
//-----------------------------------------------------------------------------
// [SECTION] VIEWPORTS, PLATFORM WINDOWS
//-----------------------------------------------------------------------------
// (this section is filled in the 'docking' branch)
//-----------------------------------------------------------------------------
// [SECTION] DOCKING
//-----------------------------------------------------------------------------
// (this section is filled in the 'docking' branch)
//-----------------------------------------------------------------------------
// [SECTION] PLATFORM DEPENDENT HELPERS
//-----------------------------------------------------------------------------
#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS)
#ifdef _MSC_VER
#pragma comment(lib, "user32")
#pragma comment(lib, "kernel32")
#endif
// Win32 clipboard implementation
// We use g.ClipboardHandlerData for temporary storage to ensure it is freed on Shutdown()
static const char* GetClipboardTextFn_DefaultImpl(void*)
{
ImGuiContext& g = *GImGui;
g.ClipboardHandlerData.clear();
if (!::OpenClipboard(NULL))
return NULL;
HANDLE wbuf_handle = ::GetClipboardData(CF_UNICODETEXT);
if (wbuf_handle == NULL)
{
::CloseClipboard();
return NULL;
}
if (const WCHAR* wbuf_global = (const WCHAR*)::GlobalLock(wbuf_handle))
{
int buf_len = ::WideCharToMultiByte(CP_UTF8, 0, wbuf_global, -1, NULL, 0, NULL, NULL);
g.ClipboardHandlerData.resize(buf_len);
::WideCharToMultiByte(CP_UTF8, 0, wbuf_global, -1, g.ClipboardHandlerData.Data, buf_len, NULL, NULL);
}
::GlobalUnlock(wbuf_handle);
::CloseClipboard();
return g.ClipboardHandlerData.Data;
}
static void SetClipboardTextFn_DefaultImpl(void*, const char* text)
{
if (!::OpenClipboard(NULL))
return;
const int wbuf_length = ::MultiByteToWideChar(CP_UTF8, 0, text, -1, NULL, 0);
HGLOBAL wbuf_handle = ::GlobalAlloc(GMEM_MOVEABLE, (SIZE_T)wbuf_length * sizeof(WCHAR));
if (wbuf_handle == NULL)
{
::CloseClipboard();
return;
}
WCHAR* wbuf_global = (WCHAR*)::GlobalLock(wbuf_handle);
::MultiByteToWideChar(CP_UTF8, 0, text, -1, wbuf_global, wbuf_length);
::GlobalUnlock(wbuf_handle);
::EmptyClipboard();
if (::SetClipboardData(CF_UNICODETEXT, wbuf_handle) == NULL)
::GlobalFree(wbuf_handle);
::CloseClipboard();
}
#elif defined(__APPLE__) && TARGET_OS_OSX && defined(IMGUI_ENABLE_OSX_DEFAULT_CLIPBOARD_FUNCTIONS)
#include <Carbon/Carbon.h> // Use old API to avoid need for separate .mm file
static PasteboardRef main_clipboard = 0;
// OSX clipboard implementation
// If you enable this you will need to add '-framework ApplicationServices' to your linker command-line!
static void SetClipboardTextFn_DefaultImpl(void*, const char* text)
{
if (!main_clipboard)
PasteboardCreate(kPasteboardClipboard, &main_clipboard);
PasteboardClear(main_clipboard);
CFDataRef cf_data = CFDataCreate(kCFAllocatorDefault, (const UInt8*)text, strlen(text));
if (cf_data)
{
PasteboardPutItemFlavor(main_clipboard, (PasteboardItemID)1, CFSTR("public.utf8-plain-text"), cf_data, 0);
CFRelease(cf_data);
}
}
static const char* GetClipboardTextFn_DefaultImpl(void*)
{
if (!main_clipboard)
PasteboardCreate(kPasteboardClipboard, &main_clipboard);
PasteboardSynchronize(main_clipboard);
ItemCount item_count = 0;
PasteboardGetItemCount(main_clipboard, &item_count);
for (ItemCount i = 0; i < item_count; i++)
{
PasteboardItemID item_id = 0;
PasteboardGetItemIdentifier(main_clipboard, i + 1, &item_id);
CFArrayRef flavor_type_array = 0;
PasteboardCopyItemFlavors(main_clipboard, item_id, &flavor_type_array);
for (CFIndex j = 0, nj = CFArrayGetCount(flavor_type_array); j < nj; j++)
{
CFDataRef cf_data;
if (PasteboardCopyItemFlavorData(main_clipboard, item_id, CFSTR("public.utf8-plain-text"), &cf_data) == noErr)
{
ImGuiContext& g = *GImGui;
g.ClipboardHandlerData.clear();
int length = (int)CFDataGetLength(cf_data);
g.ClipboardHandlerData.resize(length + 1);
CFDataGetBytes(cf_data, CFRangeMake(0, length), (UInt8*)g.ClipboardHandlerData.Data);
g.ClipboardHandlerData[length] = 0;
CFRelease(cf_data);
return g.ClipboardHandlerData.Data;
}
}
}
return NULL;
}
#else
// Local Dear ImGui-only clipboard implementation, if user hasn't defined better clipboard handlers.
static const char* GetClipboardTextFn_DefaultImpl(void*)
{
ImGuiContext& g = *GImGui;
return g.ClipboardHandlerData.empty() ? NULL : g.ClipboardHandlerData.begin();
}
static void SetClipboardTextFn_DefaultImpl(void*, const char* text)
{
ImGuiContext& g = *GImGui;
g.ClipboardHandlerData.clear();
const char* text_end = text + strlen(text);
g.ClipboardHandlerData.resize((int)(text_end - text) + 1);
memcpy(&g.ClipboardHandlerData[0], text, (size_t)(text_end - text));
g.ClipboardHandlerData[(int)(text_end - text)] = 0;
}
#endif
// Win32 API IME support (for Asian languages, etc.)
#if defined(_WIN32) && !defined(__GNUC__) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS)
#include <imm.h>
#ifdef _MSC_VER
#pragma comment(lib, "imm32")
#endif
static void ImeSetInputScreenPosFn_DefaultImpl(int x, int y)
{
// Notify OS Input Method Editor of text input position
ImGuiIO& io = ImGui::GetIO();
if (HWND hwnd = (HWND)io.ImeWindowHandle)
if (HIMC himc = ::ImmGetContext(hwnd))
{
COMPOSITIONFORM cf;
cf.ptCurrentPos.x = x;
cf.ptCurrentPos.y = y;
cf.dwStyle = CFS_FORCE_POSITION;
::ImmSetCompositionWindow(himc, &cf);
::ImmReleaseContext(hwnd, himc);
}
}
#else
static void ImeSetInputScreenPosFn_DefaultImpl(int, int) {}
#endif
//-----------------------------------------------------------------------------
// [SECTION] METRICS/DEBUG WINDOW
//-----------------------------------------------------------------------------
#ifndef IMGUI_DISABLE_METRICS_WINDOW
// Avoid naming collision with imgui_demo.cpp's HelpMarker() for unity builds.
static void MetricsHelpMarker(const char* desc)
{
ImGui::TextDisabled("(?)");
if (ImGui::IsItemHovered())
{
ImGui::BeginTooltip();
ImGui::PushTextWrapPos(ImGui::GetFontSize() * 35.0f);
ImGui::TextUnformatted(desc);
ImGui::PopTextWrapPos();
ImGui::EndTooltip();
}
}
void ImGui::ShowMetricsWindow(bool* p_open)
{
if (!ImGui::Begin("Dear ImGui Metrics", p_open))
{
ImGui::End();
return;
}
// Debugging enums
enum { WRT_OuterRect, WRT_OuterRectClipped, WRT_InnerRect, WRT_InnerClipRect, WRT_WorkRect, WRT_Content, WRT_ContentRegionRect, WRT_Count }; // Windows Rect Type
const char* wrt_rects_names[WRT_Count] = { "OuterRect", "OuterRectClipped", "InnerRect", "InnerClipRect", "WorkRect", "Content", "ContentRegionRect" };
enum { TRT_OuterRect, TRT_WorkRect, TRT_HostClipRect, TRT_InnerClipRect, TRT_BackgroundClipRect, TRT_ColumnsRect, TRT_ColumnsClipRect, TRT_ColumnsContentHeadersUsed, TRT_ColumnsContentHeadersIdeal, TRT_ColumnsContentRowsFrozen, TRT_ColumnsContentRowsUnfrozen, TRT_Count }; // Tables Rect Type
const char* trt_rects_names[TRT_Count] = { "OuterRect", "WorkRect", "HostClipRect", "InnerClipRect", "BackgroundClipRect", "ColumnsRect", "ColumnsClipRect", "ColumnsContentHeadersUsed", "ColumnsContentHeadersIdeal", "ColumnsContentRowsFrozen", "ColumnsContentRowsUnfrozen" };
// State
static bool show_windows_rects = false;
static int show_windows_rect_type = WRT_WorkRect;
static bool show_windows_begin_order = false;
static bool show_tables_rects = false;
static int show_tables_rect_type = TRT_WorkRect;
static bool show_drawcmd_mesh = true;
static bool show_drawcmd_aabb = true;
// Basic info
ImGuiContext& g = *GImGui;
ImGuiIO& io = ImGui::GetIO();
ImGui::Text("Dear ImGui %s", ImGui::GetVersion());
ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate);
ImGui::Text("%d vertices, %d indices (%d triangles)", io.MetricsRenderVertices, io.MetricsRenderIndices, io.MetricsRenderIndices / 3);
ImGui::Text("%d active windows (%d visible)", io.MetricsActiveWindows, io.MetricsRenderWindows);
ImGui::Text("%d active allocations", io.MetricsActiveAllocations);
ImGui::Separator();
// Helper functions to display common structures:
// - NodeDrawList()
// - NodeColumns()
// - NodeWindow()
// - NodeWindows()
// - NodeTabBar()
// - NodeStorage()
struct Funcs
{
static ImRect GetWindowRect(ImGuiWindow* window, int rect_type)
{
if (rect_type == WRT_OuterRect) { return window->Rect(); }
else if (rect_type == WRT_OuterRectClipped) { return window->OuterRectClipped; }
else if (rect_type == WRT_InnerRect) { return window->InnerRect; }
else if (rect_type == WRT_InnerClipRect) { return window->InnerClipRect; }
else if (rect_type == WRT_WorkRect) { return window->WorkRect; }
else if (rect_type == WRT_Content) { ImVec2 min = window->InnerRect.Min - window->Scroll + window->WindowPadding; return ImRect(min, min + window->ContentSize); }
else if (rect_type == WRT_ContentRegionRect) { return window->ContentRegionRect; }
IM_ASSERT(0);
return ImRect();
}
static void NodeDrawCmdShowMeshAndBoundingBox(ImGuiWindow* window, const ImDrawList* draw_list, const ImDrawCmd* draw_cmd, int elem_offset, bool show_mesh, bool show_aabb)
{
IM_ASSERT(show_mesh || show_aabb);
ImDrawList* fg_draw_list = GetForegroundDrawList(window); // Render additional visuals into the top-most draw list
ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL;
// Draw wire-frame version of all triangles
ImRect clip_rect = draw_cmd->ClipRect;
ImRect vtxs_rect(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX);
ImDrawListFlags backup_flags = fg_draw_list->Flags;
fg_draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; // Disable AA on triangle outlines is more readable for very large and thin triangles.
for (unsigned int base_idx = elem_offset; base_idx < (elem_offset + draw_cmd->ElemCount); base_idx += 3)
{
ImVec2 triangle[3];
for (int n = 0; n < 3; n++)
{
ImVec2 p = draw_list->VtxBuffer[idx_buffer ? idx_buffer[base_idx + n] : (base_idx + n)].pos;
triangle[n] = p;
vtxs_rect.Add(p);
}
if (show_mesh)
fg_draw_list->AddPolyline(triangle, 3, IM_COL32(255, 255, 0, 255), true, 1.0f); // In yellow: mesh triangles
}
// Draw bounding boxes
if (show_aabb)
{
fg_draw_list->AddRect(ImFloor(clip_rect.Min), ImFloor(clip_rect.Max), IM_COL32(255, 0, 255, 255)); // In pink: clipping rectangle submitted to GPU
fg_draw_list->AddRect(ImFloor(vtxs_rect.Min), ImFloor(vtxs_rect.Max), IM_COL32(0, 255, 255, 255)); // In cyan: bounding box of triangles
}
fg_draw_list->Flags = backup_flags;
}
static void NodeDrawList(ImGuiWindow* window, ImDrawList* draw_list, const char* label)
{
bool node_open = ImGui::TreeNode(draw_list, "%s: '%s' %d vtx, %d indices, %d cmds", label, draw_list->_OwnerName ? draw_list->_OwnerName : "", draw_list->VtxBuffer.Size, draw_list->IdxBuffer.Size, draw_list->CmdBuffer.Size);
if (draw_list == ImGui::GetWindowDrawList())
{
ImGui::SameLine();
ImGui::TextColored(ImVec4(1.0f, 0.4f, 0.4f, 1.0f), "CURRENTLY APPENDING"); // Can't display stats for active draw list! (we don't have the data double-buffered)
if (node_open) ImGui::TreePop();
return;
}
ImDrawList* fg_draw_list = GetForegroundDrawList(window); // Render additional visuals into the top-most draw list
if (window && IsItemHovered())
fg_draw_list->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
if (!node_open)
return;
if (window && !window->WasActive)
ImGui::TextDisabled("Warning: owning Window is inactive. This DrawList is not being rendered!");
unsigned int elem_offset = 0;
for (const ImDrawCmd* pcmd = draw_list->CmdBuffer.begin(); pcmd < draw_list->CmdBuffer.end(); elem_offset += pcmd->ElemCount, pcmd++)
{
if (pcmd->UserCallback == NULL && pcmd->ElemCount == 0)
continue;
if (pcmd->UserCallback)
{
ImGui::BulletText("Callback %p, user_data %p", pcmd->UserCallback, pcmd->UserCallbackData);
continue;
}
ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL;
char buf[300];
ImFormatString(buf, IM_ARRAYSIZE(buf), "DrawCmd:%5d triangles, Tex 0x%p, ClipRect (%4.0f,%4.0f)-(%4.0f,%4.0f)",
pcmd->ElemCount / 3, (void*)(intptr_t)pcmd->TextureId,
pcmd->ClipRect.x, pcmd->ClipRect.y, pcmd->ClipRect.z, pcmd->ClipRect.w);
bool pcmd_node_open = ImGui::TreeNode((void*)(pcmd - draw_list->CmdBuffer.begin()), "%s", buf);
if (ImGui::IsItemHovered() && (show_drawcmd_mesh || show_drawcmd_aabb) && fg_draw_list)
NodeDrawCmdShowMeshAndBoundingBox(window, draw_list, pcmd, elem_offset, show_drawcmd_mesh, show_drawcmd_aabb);
if (!pcmd_node_open)
continue;
// Calculate approximate coverage area (touched pixel count)
// This will be in pixels squared as long there's no post-scaling happening to the renderer output.
float total_area = 0.0f;
for (unsigned int base_idx = elem_offset; base_idx < (elem_offset + pcmd->ElemCount); base_idx += 3)
{
ImVec2 triangle[3];
for (int n = 0; n < 3; n++)
triangle[n] = draw_list->VtxBuffer[idx_buffer ? idx_buffer[base_idx + n] : (base_idx + n)].pos;
total_area += ImTriangleArea(triangle[0], triangle[1], triangle[2]);
}
// Display vertex information summary. Hover to get all triangles drawn in wire-frame
ImFormatString(buf, IM_ARRAYSIZE(buf), "Mesh: ElemCount: %d, VtxOffset: +%d, IdxOffset: +%d, Area: ~%0.f px", pcmd->ElemCount, pcmd->VtxOffset, pcmd->IdxOffset, total_area);
ImGui::Selectable(buf);
if (ImGui::IsItemHovered() && fg_draw_list)
NodeDrawCmdShowMeshAndBoundingBox(window, draw_list, pcmd, elem_offset, true, false);
// Display individual triangles/vertices. Hover on to get the corresponding triangle highlighted.
ImGuiListClipper clipper(pcmd->ElemCount / 3); // Manually coarse clip our print out of individual vertices to save CPU, only items that may be visible.
while (clipper.Step())
for (int prim = clipper.DisplayStart, idx_i = elem_offset + clipper.DisplayStart * 3; prim < clipper.DisplayEnd; prim++)
{
char* buf_p = buf, *buf_end = buf + IM_ARRAYSIZE(buf);
ImVec2 triangle[3];
for (int n = 0; n < 3; n++, idx_i++)
{
ImDrawVert& v = draw_list->VtxBuffer[idx_buffer ? idx_buffer[idx_i] : idx_i];
triangle[n] = v.pos;
buf_p += ImFormatString(buf_p, buf_end - buf_p, "%s %04d: pos (%8.2f,%8.2f), uv (%.6f,%.6f), col %08X\n",
(n == 0) ? "Vert:" : " ", idx_i, v.pos.x, v.pos.y, v.uv.x, v.uv.y, v.col);
}
ImGui::Selectable(buf, false);
if (fg_draw_list && ImGui::IsItemHovered())
{
ImDrawListFlags backup_flags = fg_draw_list->Flags;
fg_draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; // Disable AA on triangle outlines is more readable for very large and thin triangles.
fg_draw_list->AddPolyline(triangle, 3, IM_COL32(255,255,0,255), true, 1.0f);
fg_draw_list->Flags = backup_flags;
}
}
ImGui::TreePop();
}
ImGui::TreePop();
}
static void NodeColumns(const ImGuiColumns* columns)
{
if (!ImGui::TreeNode((void*)(uintptr_t)columns->ID, "Columns Id: 0x%08X, Count: %d, Flags: 0x%04X", columns->ID, columns->Count, columns->Flags))
return;
ImGui::BulletText("Width: %.1f (MinX: %.1f, MaxX: %.1f)", columns->OffMaxX - columns->OffMinX, columns->OffMinX, columns->OffMaxX);
for (int column_n = 0; column_n < columns->Columns.Size; column_n++)
ImGui::BulletText("Column %02d: OffsetNorm %.3f (= %.1f px)", column_n, columns->Columns[column_n].OffsetNorm, GetColumnOffsetFromNorm(columns, columns->Columns[column_n].OffsetNorm));
ImGui::TreePop();
}
static void NodeWindows(ImVector<ImGuiWindow*>& windows, const char* label)
{
if (!ImGui::TreeNode(label, "%s (%d)", label, windows.Size))
return;
ImGui::Text("(In front-to-back order:)");
for (int i = windows.Size - 1; i >= 0; i--) // Iterate front to back
{
ImGui::PushID(windows[i]);
Funcs::NodeWindow(windows[i], "Window");
ImGui::PopID();
}
ImGui::TreePop();
}
static void NodeWindow(ImGuiWindow* window, const char* label)
{
if (window == NULL)
{
ImGui::BulletText("%s: NULL", label);
return;
}
ImGuiContext& g = *GImGui;
const bool is_active = window->WasActive;
ImGuiTreeNodeFlags tree_node_flags = (window == g.NavWindow) ? ImGuiTreeNodeFlags_Selected : ImGuiTreeNodeFlags_None;
if (!is_active) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); }
const bool open = ImGui::TreeNodeEx(label, tree_node_flags, "%s '%s'%s", label, window->Name, is_active ? "" : " *Inactive*");
if (!is_active) { PopStyleColor(); }
if (ImGui::IsItemHovered() && is_active)
ImGui::GetForegroundDrawList(window)->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
if (!open)
return;
if (window->MemoryCompacted)
ImGui::TextDisabled("Note: some memory buffers have been compacted/freed.");
ImGuiWindowFlags flags = window->Flags;
NodeDrawList(window, window->DrawList, "DrawList");
ImGui::BulletText("Pos: (%.1f,%.1f), Size: (%.1f,%.1f), ContentSize (%.1f,%.1f)", window->Pos.x, window->Pos.y, window->Size.x, window->Size.y, window->ContentSize.x, window->ContentSize.y);
ImGui::BulletText("Flags: 0x%08X (%s%s%s%s%s%s%s%s%s..)", flags,
(flags & ImGuiWindowFlags_ChildWindow) ? "Child " : "", (flags & ImGuiWindowFlags_Tooltip) ? "Tooltip " : "", (flags & ImGuiWindowFlags_Popup) ? "Popup " : "",
(flags & ImGuiWindowFlags_Modal) ? "Modal " : "", (flags & ImGuiWindowFlags_ChildMenu) ? "ChildMenu " : "", (flags & ImGuiWindowFlags_NoSavedSettings) ? "NoSavedSettings " : "",
(flags & ImGuiWindowFlags_NoMouseInputs)? "NoMouseInputs":"", (flags & ImGuiWindowFlags_NoNavInputs) ? "NoNavInputs" : "", (flags & ImGuiWindowFlags_AlwaysAutoResize) ? "AlwaysAutoResize" : "");
ImGui::BulletText("Scroll: (%.2f/%.2f,%.2f/%.2f) Scrollbar:%s%s", window->Scroll.x, window->ScrollMax.x, window->Scroll.y, window->ScrollMax.y, window->ScrollbarX ? "X" : "", window->ScrollbarY ? "Y" : "");
ImGui::BulletText("Active: %d/%d, WriteAccessed: %d, BeginOrderWithinContext: %d", window->Active, window->WasActive, window->WriteAccessed, (window->Active || window->WasActive) ? window->BeginOrderWithinContext : -1);
ImGui::BulletText("Appearing: %d, Hidden: %d (CanSkip %d Cannot %d), SkipItems: %d", window->Appearing, window->Hidden, window->HiddenFramesCanSkipItems, window->HiddenFramesCannotSkipItems, window->SkipItems);
ImGui::BulletText("NavLastIds: 0x%08X,0x%08X, NavLayerActiveMask: %X", window->NavLastIds[0], window->NavLastIds[1], window->DC.NavLayerActiveMask);
ImGui::BulletText("NavLastChildNavWindow: %s", window->NavLastChildNavWindow ? window->NavLastChildNavWindow->Name : "NULL");
if (!window->NavRectRel[0].IsInverted())
ImGui::BulletText("NavRectRel[0]: (%.1f,%.1f)(%.1f,%.1f)", window->NavRectRel[0].Min.x, window->NavRectRel[0].Min.y, window->NavRectRel[0].Max.x, window->NavRectRel[0].Max.y);
else
ImGui::BulletText("NavRectRel[0]: <None>");
if (window->RootWindow != window) NodeWindow(window->RootWindow, "RootWindow");
if (window->ParentWindow != NULL) NodeWindow(window->ParentWindow, "ParentWindow");
if (window->DC.ChildWindows.Size > 0) NodeWindows(window->DC.ChildWindows, "ChildWindows");
if (window->ColumnsStorage.Size > 0 && ImGui::TreeNode("Columns", "Columns sets (%d)", window->ColumnsStorage.Size))
{
for (int n = 0; n < window->ColumnsStorage.Size; n++)
NodeColumns(&window->ColumnsStorage[n]);
ImGui::TreePop();
}
NodeStorage(&window->StateStorage, "Storage");
ImGui::TreePop();
}
static void NodeWindowSettings(ImGuiWindowSettings* settings)
{
ImGui::Text("0x%08X \"%s\" Pos (%d,%d) Size (%d,%d) Collapsed=%d",
settings->ID, settings->GetName(), settings->Pos.x, settings->Pos.y, settings->Size.x, settings->Size.y, settings->Collapsed);
}
static void NodeTabBar(ImGuiTabBar* tab_bar)
{
// Standalone tab bars (not associated to docking/windows functionality) currently hold no discernible strings.
char buf[256];
char* p = buf;
const char* buf_end = buf + IM_ARRAYSIZE(buf);
const bool is_active = (tab_bar->PrevFrameVisible >= ImGui::GetFrameCount() - 2);
p += ImFormatString(p, buf_end - p, "Tab Bar 0x%08X (%d tabs)%s", tab_bar->ID, tab_bar->Tabs.Size, is_active ? "" : " *Inactive*");
IM_UNUSED(p);
if (!is_active) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); }
bool open = ImGui::TreeNode(tab_bar, "%s", buf);
if (!is_active) { PopStyleColor(); }
if (open)
{
for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++)
{
const ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
ImGui::PushID(tab);
if (ImGui::SmallButton("<")) { TabBarQueueReorder(tab_bar, tab, -1); } ImGui::SameLine(0, 2);
if (ImGui::SmallButton(">")) { TabBarQueueReorder(tab_bar, tab, +1); } ImGui::SameLine();
ImGui::Text("%02d%c Tab 0x%08X '%s'", tab_n, (tab->ID == tab_bar->SelectedTabId) ? '*' : ' ', tab->ID, (tab->NameOffset != -1) ? tab_bar->GetTabName(tab) : "");
ImGui::PopID();
}
ImGui::TreePop();
}
}
static void NodeStorage(ImGuiStorage* storage, const char* label)
{
if (!ImGui::TreeNode(label, "%s: %d entries, %d bytes", label, storage->Data.Size, storage->Data.size_in_bytes()))
return;
for (int n = 0; n < storage->Data.Size; n++)
{
const ImGuiStorage::ImGuiStoragePair& p = storage->Data[n];
ImGui::BulletText("Key 0x%08X Value { i: %d }", p.key, p.val_i); // Important: we currently don't store a type, real value may not be integer.
}
ImGui::TreePop();
}
};
// Tools
if (ImGui::TreeNode("Tools"))
{
// The Item Picker tool is super useful to visually select an item and break into the call-stack of where it was submitted.
if (ImGui::Button("Item Picker.."))
ImGui::DebugStartItemPicker();
ImGui::SameLine();
MetricsHelpMarker("Will call the IM_DEBUG_BREAK() macro to break in debugger.\nWarning: If you don't have a debugger attached, this will probably crash.");
ImGui::Checkbox("Show windows begin order", &show_windows_begin_order);
ImGui::Checkbox("Show windows rectangles", &show_windows_rects);
ImGui::SameLine();
ImGui::SetNextItemWidth(ImGui::GetFontSize() * 12);
show_windows_rects |= ImGui::Combo("##show_windows_rect_type", &show_windows_rect_type, wrt_rects_names, WRT_Count, WRT_Count);
if (show_windows_rects && g.NavWindow)
{
ImGui::BulletText("'%s':", g.NavWindow->Name);
ImGui::Indent();
for (int rect_n = 0; rect_n < WRT_Count; rect_n++)
{
ImRect r = Funcs::GetWindowRect(g.NavWindow, rect_n);
ImGui::Text("(%6.1f,%6.1f) (%6.1f,%6.1f) Size (%6.1f,%6.1f) %s", r.Min.x, r.Min.y, r.Max.x, r.Max.y, r.GetWidth(), r.GetHeight(), wrt_rects_names[rect_n]);
}
ImGui::Unindent();
}
ImGui::Checkbox("Show mesh when hovering ImDrawCmd", &show_drawcmd_mesh);
ImGui::Checkbox("Show bounding boxes when hovering ImDrawCmd", &show_drawcmd_aabb);
ImGui::TreePop();
}
// Contents
Funcs::NodeWindows(g.Windows, "Windows");
//Funcs::NodeWindows(g.WindowsFocusOrder, "WindowsFocusOrder");
if (ImGui::TreeNode("DrawLists", "Active DrawLists (%d)", g.DrawDataBuilder.Layers[0].Size))
{
for (int i = 0; i < g.DrawDataBuilder.Layers[0].Size; i++)
Funcs::NodeDrawList(NULL, g.DrawDataBuilder.Layers[0][i], "DrawList");
ImGui::TreePop();
}
// Details for Popups
if (ImGui::TreeNode("Popups", "Popups (%d)", g.OpenPopupStack.Size))
{
for (int i = 0; i < g.OpenPopupStack.Size; i++)
{
ImGuiWindow* window = g.OpenPopupStack[i].Window;
ImGui::BulletText("PopupID: %08x, Window: '%s'%s%s", g.OpenPopupStack[i].PopupId, window ? window->Name : "NULL", window && (window->Flags & ImGuiWindowFlags_ChildWindow) ? " ChildWindow" : "", window && (window->Flags & ImGuiWindowFlags_ChildMenu) ? " ChildMenu" : "");
}
ImGui::TreePop();
}
// Details for TabBars
if (ImGui::TreeNode("TabBars", "Tab Bars (%d)", g.TabBars.GetSize()))
{
for (int n = 0; n < g.TabBars.GetSize(); n++)
Funcs::NodeTabBar(g.TabBars.GetByIndex(n));
ImGui::TreePop();
}
// Details for Tables
IM_UNUSED(trt_rects_names);
IM_UNUSED(show_tables_rects);
IM_UNUSED(show_tables_rect_type);
#ifdef IMGUI_HAS_TABLE
if (ImGui::TreeNode("Tables", "Tables (%d)", g.Tables.GetSize()))
{
for (int n = 0; n < g.Tables.GetSize(); n++)
Funcs::NodeTable(g.Tables.GetByIndex(n));
ImGui::TreePop();
}
#endif // #ifdef IMGUI_HAS_TABLE
// Details for Docking
#ifdef IMGUI_HAS_DOCK
if (ImGui::TreeNode("Dock nodes"))
{
ImGui::TreePop();
}
#endif // #ifdef IMGUI_HAS_DOCK
// Settings
if (ImGui::TreeNode("Settings"))
{
if (ImGui::SmallButton("Clear"))
ImGui::ClearIniSettings();
ImGui::SameLine();
if (ImGui::SmallButton("Save to memory"))
ImGui::SaveIniSettingsToMemory();
ImGui::SameLine();
if (ImGui::SmallButton("Save to disk"))
ImGui::SaveIniSettingsToDisk(g.IO.IniFilename);
ImGui::SameLine();
if (g.IO.IniFilename)
ImGui::Text("\"%s\"", g.IO.IniFilename);
else
ImGui::TextUnformatted("<NULL>");
ImGui::Text("SettingsDirtyTimer %.2f", g.SettingsDirtyTimer);
if (ImGui::TreeNode("SettingsHandlers", "Settings handlers: (%d)", g.SettingsHandlers.Size))
{
for (int n = 0; n < g.SettingsHandlers.Size; n++)
ImGui::BulletText("%s", g.SettingsHandlers[n].TypeName);
ImGui::TreePop();
}
if (ImGui::TreeNode("SettingsWindows", "Settings packed data: Windows: %d bytes", g.SettingsWindows.size()))
{
for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
Funcs::NodeWindowSettings(settings);
ImGui::TreePop();
}
#ifdef IMGUI_HAS_TABLE
if (ImGui::TreeNode("SettingsTables", "Settings packed data: Tables: %d bytes", g.SettingsTables.size()))
{
for (ImGuiTableSettings* settings = g.SettingsTables.begin(); settings != NULL; settings = g.SettingsTables.next_chunk(settings))
Funcs::NodeTableSettings(settings);
ImGui::TreePop();
}
#endif // #ifdef IMGUI_HAS_TABLE
#ifdef IMGUI_HAS_DOCK
#endif // #ifdef IMGUI_HAS_DOCK
if (ImGui::TreeNode("SettingsIniData", "Settings unpacked data (.ini): %d bytes", g.SettingsIniData.size()))
{
ImGui::InputTextMultiline("##Ini", (char*)(void*)g.SettingsIniData.c_str(), g.SettingsIniData.Buf.Size, ImVec2(-FLT_MIN, 0.0f), ImGuiInputTextFlags_ReadOnly);
ImGui::TreePop();
}
ImGui::TreePop();
}
// Misc Details
if (ImGui::TreeNode("Internal state"))
{
const char* input_source_names[] = { "None", "Mouse", "Nav", "NavKeyboard", "NavGamepad" }; IM_ASSERT(IM_ARRAYSIZE(input_source_names) == ImGuiInputSource_COUNT);
ImGui::Text("WINDOWING");
ImGui::Indent();
ImGui::Text("HoveredWindow: '%s'", g.HoveredWindow ? g.HoveredWindow->Name : "NULL");
ImGui::Text("HoveredRootWindow: '%s'", g.HoveredRootWindow ? g.HoveredRootWindow->Name : "NULL");
ImGui::Text("HoveredWindowUnderMovingWindow: '%s'", g.HoveredWindowUnderMovingWindow ? g.HoveredWindowUnderMovingWindow->Name : "NULL");
ImGui::Text("MovingWindow: '%s'", g.MovingWindow ? g.MovingWindow->Name : "NULL");
ImGui::Unindent();
ImGui::Text("ITEMS");
ImGui::Indent();
ImGui::Text("ActiveId: 0x%08X/0x%08X (%.2f sec), AllowOverlap: %d, Source: %s", g.ActiveId, g.ActiveIdPreviousFrame, g.ActiveIdTimer, g.ActiveIdAllowOverlap, input_source_names[g.ActiveIdSource]);
ImGui::Text("ActiveIdWindow: '%s'", g.ActiveIdWindow ? g.ActiveIdWindow->Name : "NULL");
ImGui::Text("HoveredId: 0x%08X/0x%08X (%.2f sec), AllowOverlap: %d", g.HoveredId, g.HoveredIdPreviousFrame, g.HoveredIdTimer, g.HoveredIdAllowOverlap); // Data is "in-flight" so depending on when the Metrics window is called we may see current frame information or not
ImGui::Text("DragDrop: %d, SourceId = 0x%08X, Payload \"%s\" (%d bytes)", g.DragDropActive, g.DragDropPayload.SourceId, g.DragDropPayload.DataType, g.DragDropPayload.DataSize);
ImGui::Unindent();
ImGui::Text("NAV,FOCUS");
ImGui::Indent();
ImGui::Text("NavWindow: '%s'", g.NavWindow ? g.NavWindow->Name : "NULL");
ImGui::Text("NavId: 0x%08X, NavLayer: %d", g.NavId, g.NavLayer);
ImGui::Text("NavInputSource: %s", input_source_names[g.NavInputSource]);
ImGui::Text("NavActive: %d, NavVisible: %d", g.IO.NavActive, g.IO.NavVisible);
ImGui::Text("NavActivateId: 0x%08X, NavInputId: 0x%08X", g.NavActivateId, g.NavInputId);
ImGui::Text("NavDisableHighlight: %d, NavDisableMouseHover: %d", g.NavDisableHighlight, g.NavDisableMouseHover);
ImGui::Text("NavFocusScopeId = 0x%08X", g.NavFocusScopeId);
ImGui::Text("NavWindowingTarget: '%s'", g.NavWindowingTarget ? g.NavWindowingTarget->Name : "NULL");
ImGui::Unindent();
ImGui::TreePop();
}
// Overlay: Display windows Rectangles and Begin Order
if (show_windows_rects || show_windows_begin_order)
{
for (int n = 0; n < g.Windows.Size; n++)
{
ImGuiWindow* window = g.Windows[n];
if (!window->WasActive)
continue;
ImDrawList* draw_list = GetForegroundDrawList(window);
if (show_windows_rects)
{
ImRect r = Funcs::GetWindowRect(window, show_windows_rect_type);
draw_list->AddRect(r.Min, r.Max, IM_COL32(255, 0, 128, 255));
}
if (show_windows_begin_order && !(window->Flags & ImGuiWindowFlags_ChildWindow))
{
char buf[32];
ImFormatString(buf, IM_ARRAYSIZE(buf), "%d", window->BeginOrderWithinContext);
float font_size = ImGui::GetFontSize();
draw_list->AddRectFilled(window->Pos, window->Pos + ImVec2(font_size, font_size), IM_COL32(200, 100, 100, 255));
draw_list->AddText(window->Pos, IM_COL32(255, 255, 255, 255), buf);
}
}
}
#ifdef IMGUI_HAS_TABLE
// Overlay: Display Tables Rectangles
if (show_tables_rects)
{
for (int table_n = 0; table_n < g.Tables.GetSize(); table_n++)
{
ImGuiTable* table = g.Tables.GetByIndex(table_n);
}
}
#endif // #ifdef IMGUI_HAS_TABLE
#ifdef IMGUI_HAS_DOCK
// Overlay: Display Docking info
if (show_docking_nodes && g.IO.KeyCtrl)
{
}
#endif // #ifdef IMGUI_HAS_DOCK
ImGui::End();
}
#else
void ImGui::ShowMetricsWindow(bool*) { }
#endif
//-----------------------------------------------------------------------------
// Include imgui_user.inl at the end of imgui.cpp to access private data/functions that aren't exposed.
// Prefer just including imgui_internal.h from your code rather than using this define. If a declaration is missing from imgui_internal.h add it or request it on the github.
#ifdef IMGUI_INCLUDE_IMGUI_USER_INL
#include "imgui_user.inl"
#endif
//-----------------------------------------------------------------------------
#endif // #ifndef IMGUI_DISABLE
|
/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "QmitkPointListWidget.h"
#include <mitkGlobalInteraction.h>
#include <mitkPointSetReader.h>
#include <mitkPointSetWriter.h>
#include <QHBoxLayout>
#include <QFileDialog>
#include <QMessageBox>
#include <QDir>
#include <QmitkEditPointDialog.h>
#include "btnLoad.xpm"
#include "btnSave.xpm"
#include "btnClear.xpm"
#include "btnSetPoints.xpm"
#include "btnSetPointsManually.xpm"
#include "btnUp.xpm"
#include "btnDown.xpm"
QmitkPointListWidget::QmitkPointListWidget(QWidget *parent, int orientation):
QWidget(parent), m_PointListView(NULL), m_MultiWidget(NULL), m_PointSetNode(NULL), m_Orientation(0), m_MovePointUpBtn(NULL),
m_MovePointDownBtn(NULL), m_RemovePointBtn(NULL), m_SavePointsBtn(NULL), m_LoadPointsBtn(NULL), m_ToggleAddPoint(NULL),
m_AddPoint(NULL),
m_Snc1(NULL),
m_Snc2(NULL),
m_Snc3(NULL),
m_Interactor(NULL),
m_TimeStep(0),
m_EditAllowed(true),
m_NodeObserverTag(0)
{
m_PointListView = new QmitkPointListView();
if(orientation != 0)
m_Orientation = orientation;
SetupUi();
SetupConnections();
ObserveNewNode(NULL);
}
QmitkPointListWidget::~QmitkPointListWidget()
{
if (m_Interactor)
mitk::GlobalInteraction::GetInstance()->RemoveInteractor( m_Interactor );
m_Interactor = NULL;
if(m_PointSetNode && m_NodeObserverTag)
{
m_PointSetNode->RemoveObserver(m_NodeObserverTag);
m_NodeObserverTag = 0;
}
m_MultiWidget = NULL;
delete m_PointListView;
}
void QmitkPointListWidget::SetupConnections()
{
//m_PointListView->setModel(m_PointListModel);
connect(this->m_LoadPointsBtn, SIGNAL(clicked()), this, SLOT(OnBtnLoadPoints()));
connect(this->m_SavePointsBtn, SIGNAL(clicked()), this, SLOT(OnBtnSavePoints()));
connect(this->m_MovePointUpBtn, SIGNAL(clicked()), this, SLOT(MoveSelectedPointUp()));
connect(this->m_MovePointDownBtn, SIGNAL(clicked()), this, SLOT(MoveSelectedPointDown()));
connect(this->m_RemovePointBtn, SIGNAL(clicked()), this, SLOT(RemoveSelectedPoint()));
connect(this->m_ToggleAddPoint, SIGNAL(toggled(bool)), this, SLOT(OnBtnAddPoint(bool)));
connect(this->m_AddPoint, SIGNAL(clicked()), this, SLOT(OnBtnAddPointManually()));
connect(this->m_PointListView, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(OnListDoubleClick()));
connect(this->m_PointListView, SIGNAL(SignalPointSelectionChanged()), this, SLOT(OnPointSelectionChanged()));
}
void QmitkPointListWidget::SetupUi()
{
//Setup the buttons
m_ToggleAddPoint = new QPushButton();//iconSetPoints, "", this);
m_ToggleAddPoint->setMaximumSize(25,25);
m_ToggleAddPoint->setCheckable(true);
m_ToggleAddPoint->setToolTip("Toggle point editing (use SHIFT + Left Mouse Button to add Points)");
QIcon iconAdd(btnSetPoints_xpm);
m_ToggleAddPoint->setIcon(iconAdd);
m_AddPoint = new QPushButton();//iconSetPoints, "", this);
m_AddPoint->setMaximumSize(25,25);
m_AddPoint->setToolTip("Manually add point");
QIcon iconAddManually(btnSetPointsManually_xpm);
m_AddPoint->setIcon(iconAddManually);
m_RemovePointBtn = new QPushButton();
m_RemovePointBtn->setMaximumSize(25, 25);
const QIcon iconDel(btnClear_xpm);
m_RemovePointBtn->setIcon(iconDel);
m_RemovePointBtn->setToolTip("Erase one point from list (Hotkey: DEL)");
m_MovePointUpBtn = new QPushButton();
m_MovePointUpBtn->setMaximumSize(25, 25);
const QIcon iconUp(btnUp_xpm);
m_MovePointUpBtn->setIcon(iconUp);
m_MovePointUpBtn->setToolTip("Swap selected point upwards (Hotkey: F2)");
m_MovePointDownBtn = new QPushButton();
m_MovePointDownBtn->setMaximumSize(25, 25);
const QIcon iconDown(btnDown_xpm);
m_MovePointDownBtn->setIcon(iconDown);
m_MovePointDownBtn->setToolTip("Swap selected point downwards (Hotkey: F3)");
m_SavePointsBtn = new QPushButton();
m_SavePointsBtn->setMaximumSize(25, 25);
QIcon iconSave(btnSave_xpm);
m_SavePointsBtn->setIcon(iconSave);
m_SavePointsBtn->setToolTip("Save points to file");
m_LoadPointsBtn = new QPushButton();
m_LoadPointsBtn->setMaximumSize(25, 25);
QIcon iconLoad(btnLoad_xpm);
m_LoadPointsBtn->setIcon(iconLoad);
m_LoadPointsBtn->setToolTip("Load list of points from file (REPLACES current content)");
int i;
QBoxLayout* lay1;
QBoxLayout* lay2;
switch (m_Orientation)
{
case 0:
lay1 = new QVBoxLayout(this);
lay2 = new QHBoxLayout();
i = 0;
break;
case 1:
lay1 = new QHBoxLayout(this);
lay2 = new QVBoxLayout();
i=-1;
break;
case 2:
lay1 = new QHBoxLayout(this);
lay2 = new QVBoxLayout();
i=0;
break;
default:
lay1 = new QVBoxLayout(this);
lay2 = new QHBoxLayout();
i=-1;
break;
}
//setup Layouts
this->setLayout(lay1);
lay1->addLayout(lay2);
lay2->stretch(true);
lay2->addWidget(m_ToggleAddPoint);
lay2->addWidget(m_AddPoint);
lay2->addWidget(m_RemovePointBtn);
lay2->addWidget(m_MovePointUpBtn);
lay2->addWidget(m_MovePointDownBtn);
lay2->addWidget(m_SavePointsBtn);
lay2->addWidget(m_LoadPointsBtn);
//lay2->addSpacing();;
lay1->insertWidget(i,m_PointListView);
this->setLayout(lay1);
}
void QmitkPointListWidget::SetPointSet(mitk::PointSet* newPs)
{
if(newPs == NULL)
return;
this->m_PointSetNode->SetData(newPs);
dynamic_cast<QmitkPointListModel*>(this->m_PointListView->model())->SetPointSetNode(m_PointSetNode);
ObserveNewNode(m_PointSetNode);
}
void QmitkPointListWidget::SetPointSetNode(mitk::DataNode *newNode)
{
ObserveNewNode(newNode);
dynamic_cast<QmitkPointListModel*>(this->m_PointListView->model())->SetPointSetNode(newNode);
}
void QmitkPointListWidget::OnBtnSavePoints()
{
if ((dynamic_cast<mitk::PointSet*>(m_PointSetNode->GetData())) == NULL)
return; // don't write empty point sets. If application logic requires something else then do something else.
if ((dynamic_cast<mitk::PointSet*>(m_PointSetNode->GetData()))->GetSize() == 0)
return;
// let the user choose a file
std::string name("");
QString fileNameProposal = QString("/PointSet.mps");//.arg(m_PointSetNode->GetName().c_str()); //"PointSet.mps";
QString aFilename = QFileDialog::getSaveFileName( NULL, "Save point set", QDir::currentPath() + fileNameProposal, "MITK Pointset (*.mps)" );
if ( aFilename.isEmpty() )
return;
try
{
// instantiate the writer and add the point-sets to write
mitk::PointSetWriter::Pointer writer = mitk::PointSetWriter::New();
writer->SetInput( dynamic_cast<mitk::PointSet*>(m_PointSetNode->GetData()) );
writer->SetFileName( aFilename.toLatin1() );
writer->Update();
}
catch(...)
{
QMessageBox::warning( this, "Save point set",
QString("File writer reported problems writing %1\n\n"
"PLEASE CHECK output file!").arg(aFilename) );
}
}
void QmitkPointListWidget::OnBtnLoadPoints()
{
// get the name of the file to load
QString filename = QFileDialog::getOpenFileName( NULL, "Open MITK Pointset", "", "MITK Point Sets (*.mps)");
if ( filename.isEmpty() ) return;
// attempt to load file
try
{
mitk::PointSetReader::Pointer reader = mitk::PointSetReader::New();
reader->SetFileName( filename.toLatin1() );
reader->Update();
mitk::PointSet::Pointer pointSet = reader->GetOutput();
if ( pointSet.IsNull() )
{
QMessageBox::warning( this, "Load point set", QString("File reader could not read %1").arg(filename) );
return;
}
// loading successful
// bool interactionOn( m_Interactor.IsNotNull() );
// if (interactionOn)
// {
// OnEditPointSetButtonToggled(false);
// }
//
this->SetPointSet(pointSet);
// if (interactionOn)
// {
// OnEditPointSetButtonToggled(true);
// }
}
catch(...)
{
QMessageBox::warning( this, "Load point set", QString("File reader collapsed while reading %1").arg(filename) );
}
emit PointListChanged();
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
}
mitk::PointSet* QmitkPointListWidget::GetPointSet()
{
return dynamic_cast<mitk::PointSet*>(m_PointSetNode->GetData());
}
mitk::DataNode* QmitkPointListWidget::GetPointSetNode()
{
return m_PointSetNode;
}
void QmitkPointListWidget::SetMultiWidget(QmitkStdMultiWidget *multiWidget)
{
this->m_MultiWidget = multiWidget;
m_PointListView->SetMultiWidget(multiWidget);
}
void QmitkPointListWidget::RemoveSelectedPoint()
{
if (!m_PointSetNode) return;
mitk::PointSet* pointSet = dynamic_cast<mitk::PointSet*>( m_PointSetNode->GetData() );
if (!pointSet) return;
if (pointSet->GetSize() == 0) return;
QmitkPointListModel* pointListModel = dynamic_cast<QmitkPointListModel*>( m_PointListView->model() );
pointListModel->RemoveSelectedPoint();
emit PointListChanged();
}
void QmitkPointListWidget::MoveSelectedPointDown()
{
if (!m_PointSetNode) return;
mitk::PointSet* pointSet = dynamic_cast<mitk::PointSet*>( m_PointSetNode->GetData() );
if (!pointSet) return;
if (pointSet->GetSize() == 0) return;
QmitkPointListModel* pointListModel = dynamic_cast<QmitkPointListModel*>( m_PointListView->model() );
pointListModel->MoveSelectedPointDown();
emit PointListChanged();
}
void QmitkPointListWidget::MoveSelectedPointUp()
{
if (!m_PointSetNode) return;
mitk::PointSet* pointSet = dynamic_cast<mitk::PointSet*>( m_PointSetNode->GetData() );
if (!pointSet) return;
if (pointSet->GetSize() == 0) return;
QmitkPointListModel* pointListModel = dynamic_cast<QmitkPointListModel*>( m_PointListView->model() );
pointListModel->MoveSelectedPointUp();
emit PointListChanged();
}
void QmitkPointListWidget::OnBtnAddPoint(bool checked)
{
if (m_PointSetNode)
{
if (checked)
{
m_Interactor = dynamic_cast<mitk::PointSetInteractor*>(m_PointSetNode->GetInteractor());
if (m_Interactor.IsNull())//if not present, instanciate one
m_Interactor = mitk::PointSetInteractor::New("pointsetinteractor", m_PointSetNode);
//add it to global interaction to activate it
mitk::GlobalInteraction::GetInstance()->AddInteractor( m_Interactor );
}
else if ( m_Interactor )
{
mitk::GlobalInteraction::GetInstance()->RemoveInteractor( m_Interactor );
m_Interactor = NULL;
}
emit EditPointSets(checked);
}
}
void QmitkPointListWidget::OnBtnAddPointManually()
{
mitk::PointSet* pointSet = this->GetPointSet();
int currentPosition = pointSet->GetSize();
QmitkEditPointDialog editPointDialog(this);
editPointDialog.SetPoint(pointSet, currentPosition, m_TimeStep);
editPointDialog.exec();
}
void QmitkPointListWidget::OnListDoubleClick()
{
;
}
void QmitkPointListWidget::OnPointSelectionChanged()
{
emit this->PointSelectionChanged();
}
void QmitkPointListWidget::DeactivateInteractor(bool /*deactivate*/)
{
;
}
void QmitkPointListWidget::EnableEditButton( bool enabled )
{
m_EditAllowed = enabled;
if (enabled == false)
m_ToggleAddPoint->setEnabled(false);
else
m_ToggleAddPoint->setEnabled(true);
OnBtnAddPoint(enabled);
}
void QmitkPointListWidget::ObserveNewNode( mitk::DataNode* node )
{
// remove old observer
if ( m_PointSetNode )
{
if (m_Interactor)
{
mitk::GlobalInteraction::GetInstance()->RemoveInteractor( m_Interactor );
m_Interactor = NULL;
m_ToggleAddPoint->setChecked( false );
}
m_PointSetNode->RemoveObserver( m_NodeObserverTag );
m_NodeObserverTag = 0;
}
m_PointSetNode = node;
// add new observer if necessary
if ( m_PointSetNode )
{
itk::ReceptorMemberCommand<QmitkPointListWidget>::Pointer command = itk::ReceptorMemberCommand<QmitkPointListWidget>::New();
command->SetCallbackFunction( this, &QmitkPointListWidget::OnNodeDeleted );
m_NodeObserverTag = m_PointSetNode->AddObserver( itk::DeleteEvent(), command );
}
else
{
m_NodeObserverTag = 0;
}
if (m_EditAllowed == true)
m_ToggleAddPoint->setEnabled( m_PointSetNode );
else
m_ToggleAddPoint->setEnabled( false );
m_RemovePointBtn->setEnabled( m_PointSetNode );
m_LoadPointsBtn->setEnabled( m_PointSetNode );
m_SavePointsBtn->setEnabled(m_PointSetNode);
m_AddPoint->setEnabled(m_PointSetNode);
}
void QmitkPointListWidget::OnNodeDeleted( const itk::EventObject & /*e*/ )
{
if(m_PointSetNode.IsNotNull() && ! m_NodeObserverTag)
m_PointSetNode->RemoveObserver( m_NodeObserverTag );
m_NodeObserverTag = 0;
m_PointSetNode = NULL;
m_PointListView->SetPointSetNode(NULL);
m_ToggleAddPoint->setEnabled(false);
m_RemovePointBtn->setEnabled( false );
m_LoadPointsBtn->setEnabled( false );
m_SavePointsBtn->setEnabled(false);
m_AddPoint->setEnabled(false);
}
void QmitkPointListWidget::SetSnc1(mitk::SliceNavigationController* snc)
{
if (snc == NULL)
{
m_PointListView->RemoveSliceNavigationController(m_Snc1);
}
else
{
m_PointListView->AddSliceNavigationController(snc);
}
m_Snc1 = snc;
}
void QmitkPointListWidget::SetSnc2(mitk::SliceNavigationController* snc)
{
if (snc == NULL)
{
m_PointListView->RemoveSliceNavigationController(m_Snc2);
}
else
{
m_PointListView->AddSliceNavigationController(snc);
}
m_Snc2 = snc;
}
void QmitkPointListWidget::SetSnc3(mitk::SliceNavigationController* snc)
{
if (snc == NULL)
{
m_PointListView->RemoveSliceNavigationController(m_Snc3);
}
else
{
m_PointListView->AddSliceNavigationController(snc);
}
m_Snc3 = snc;
}
void QmitkPointListWidget::AddSliceNavigationController(mitk::SliceNavigationController* snc)
{
m_PointListView->AddSliceNavigationController(snc);
}
void QmitkPointListWidget::RemoveSliceNavigationController(mitk::SliceNavigationController* snc)
{
m_PointListView->RemoveSliceNavigationController(snc);
}
void QmitkPointListWidget::UnselectEditButton()
{
m_ToggleAddPoint->setChecked(false);
}
|
/*
the vast starry sky,
bright for those who chase the light.
*/
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
#define mk make_pair
const int inf=(int)1e9;
const ll INF=(ll)5e18;
const int MOD=998244353;
int _abs(int x){return x<0 ? -x : x;}
int add(int x,int y){x+=y; return x>=MOD ? x-MOD : x;}
int sub(int x,int y){x-=y; return x<0 ? x+MOD : x;}
#define mul(x,y) (ll)(x)*(y)%MOD
void Add(int &x,int y){x+=y; if(x>=MOD) x-=MOD;}
void Sub(int &x,int y){x-=y; if(x<0) x+=MOD;}
void Mul(int &x,int y){x=mul(x,y);}
int qpow(int x,int y){int ret=1; while(y){if(y&1) ret=mul(ret,x); x=mul(x,x); y>>=1;} return ret;}
void checkmin(int &x,int y){if(x>y) x=y;}
void checkmax(int &x,int y){if(x<y) x=y;}
void checkmin(ll &x,ll y){if(x>y) x=y;}
void checkmax(ll &x,ll y){if(x<y) x=y;}
#define out(x) cerr<<#x<<'='<<x<<' '
#define outln(x) cerr<<#x<<'='<<x<<endl
#define sz(x) (int)(x).size()
inline int read(){
int x=0,f=1; char c=getchar();
while(c>'9'||c<'0'){if(c=='-') f=-1; c=getchar();}
while(c>='0'&&c<='9') x=(x<<1)+(x<<3)+(c^48),c=getchar();
return x*f;
}
const int N=200005;
vector<int> v[N];
char s[N];
int n;
bool check(){for(int i=1;i<=n;i++) if(s[i]=='0') return 0; return 1;}
bool check0(){for(int i=1;i<=n;i++) if(s[i]=='1') return 0;return 1;}
namespace solver1{
int mx1[N],mx2[N];
void dfs1(int u,int f){
for(auto &to : v[u]){
if(to==f) continue;
dfs1(to,u);
if(mx1[to]+1>mx1[u]){
mx2[u]=mx1[u];
mx1[u]=mx1[to]+1;
}
else if(mx1[to]+1>mx2[u]) mx2[u]=mx1[to]+1;
}
}
int up[N];
void dfs2(int u,int f){
if(f!=-1){
up[u]=up[f]+1;
int tmp=(mx1[u]+1==mx1[f] ? mx2[f] : mx1[f]);
checkmax(up[u],tmp+1);
}
for(auto &to : v[u]){
if(to==f) continue;
dfs2(to,u);
}
}
void main(){
dfs1(1,-1); dfs2(1,-1);
ll ans=0;
for(int i=1;i<=n;i++){
int tmp1,tmp2;
if(up[i]>mx1[i]){
tmp1=up[i];
tmp2=mx1[i];
}
else{
tmp1=mx1[i];
tmp2=max(up[i],mx2[i]);
}
ans+=min(tmp1-1,tmp2+1)+1;
}
cout<<ans+1<<endl;
}
}
namespace solver2{
int mx1[N],mx2[N];
int mi[N],bl[N],sum=0;
void dfs1(int u,int f){
if(s[u]=='1') bl[u]=1;
for(auto &to : v[u]){
if(to==f) continue;
dfs1(to,u); bl[u]+=bl[to];
if(bl[to]) checkmin(mi[u],mx1[to]+1);
if(mx1[to]+1>mx1[u]) mx2[u]=mx1[u],mx1[u]=mx1[to]+1;
else if(mx1[to]+1>mx2[u]) mx2[u]=mx1[to]+1;
}
}
int up[N],fa[N];
void dfs2(int u,int f){
if(f!=-1){
up[u]=up[f]+1; fa[u]=f;
int tmp=(mx1[u]+1==mx1[f] ? mx2[f] : mx1[f]);
checkmax(up[u],tmp+1);
if(sum-bl[u]) checkmin(mi[u],up[u]);
}
for(auto &to : v[u]){
if(to==f) continue;
dfs2(to,u);
}
}
void main(){
for(int i=1;i<=n;i++) mi[i]=inf,sum+=(s[i]=='1');
dfs1(1,-1); dfs2(1,-1);
ll ans=0;
for(int u=1;u<=n;u++){
int Max1,Max2;
if(up[u]>mx1[u]) Max1=up[u],Max2=mx1[u];
else Max1=mx1[u],Max2=max(up[u],mx2[u]);
int L=(s[u]=='0' ? mi[u] : 0);
ans+=max(min(Max1-1,Max2+1)+1-L,0);
}
cout<<ans+1<<endl;
}
}
int main()
{
n=read();
for(int i=1;i<n;i++){
int x=read(),y=read();
v[x].push_back(y);
v[y].push_back(x);
}
scanf("%s",s+1);
if(check0()){puts("1"); return 0;}
if(check()){
solver1::main();
return 0;
}
else solver2::main();
return 0;
}
|
/*
* Copyright (c) 2015 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include <array>
#include <memory>
#include "webrtc/base/checks.h"
#include "webrtc/base/fakeclock.h"
#include "webrtc/common_audio/mocks/mock_smoothing_filter.h"
#include "webrtc/common_types.h"
#include "webrtc/modules/audio_coding/audio_network_adaptor/mock/mock_audio_network_adaptor.h"
#include "webrtc/modules/audio_coding/codecs/opus/audio_encoder_opus.h"
#include "webrtc/test/field_trial.h"
#include "webrtc/test/gmock.h"
#include "webrtc/test/gtest.h"
#include "webrtc/system_wrappers/include/clock.h"
namespace webrtc {
using ::testing::NiceMock;
using ::testing::Return;
namespace {
const CodecInst kDefaultOpusSettings = {105, "opus", 48000, 960, 1, 32000};
constexpr int64_t kInitialTimeUs = 12345678;
AudioEncoderOpus::Config CreateConfig(const CodecInst& codec_inst) {
AudioEncoderOpus::Config config;
config.frame_size_ms = rtc::CheckedDivExact(codec_inst.pacsize, 48);
config.num_channels = codec_inst.channels;
config.bitrate_bps = rtc::Optional<int>(codec_inst.rate);
config.payload_type = codec_inst.pltype;
config.application = config.num_channels == 1 ? AudioEncoderOpus::kVoip
: AudioEncoderOpus::kAudio;
config.supported_frame_lengths_ms.push_back(config.frame_size_ms);
return config;
}
struct AudioEncoderOpusStates {
std::shared_ptr<MockAudioNetworkAdaptor*> mock_audio_network_adaptor;
MockSmoothingFilter* mock_bitrate_smoother;
std::unique_ptr<AudioEncoderOpus> encoder;
std::unique_ptr<SimulatedClock> simulated_clock;
AudioEncoderOpus::Config config;
};
AudioEncoderOpusStates CreateCodec(size_t num_channels) {
AudioEncoderOpusStates states;
states.mock_audio_network_adaptor =
std::make_shared<MockAudioNetworkAdaptor*>(nullptr);
std::weak_ptr<MockAudioNetworkAdaptor*> mock_ptr(
states.mock_audio_network_adaptor);
AudioEncoderOpus::AudioNetworkAdaptorCreator creator = [mock_ptr](
const std::string&, RtcEventLog* event_log, const Clock*) {
std::unique_ptr<MockAudioNetworkAdaptor> adaptor(
new NiceMock<MockAudioNetworkAdaptor>());
EXPECT_CALL(*adaptor, Die());
if (auto sp = mock_ptr.lock()) {
*sp = adaptor.get();
} else {
RTC_NOTREACHED();
}
return adaptor;
};
CodecInst codec_inst = kDefaultOpusSettings;
codec_inst.channels = num_channels;
states.config = CreateConfig(codec_inst);
std::unique_ptr<MockSmoothingFilter> bitrate_smoother(
new MockSmoothingFilter());
states.mock_bitrate_smoother = bitrate_smoother.get();
states.simulated_clock.reset(new SimulatedClock(kInitialTimeUs));
states.config.clock = states.simulated_clock.get();
states.encoder.reset(new AudioEncoderOpus(states.config, std::move(creator),
std::move(bitrate_smoother)));
return states;
}
AudioNetworkAdaptor::EncoderRuntimeConfig CreateEncoderRuntimeConfig() {
constexpr int kBitrate = 40000;
constexpr int kFrameLength = 60;
constexpr bool kEnableFec = true;
constexpr bool kEnableDtx = false;
constexpr size_t kNumChannels = 1;
constexpr float kPacketLossFraction = 0.1f;
AudioNetworkAdaptor::EncoderRuntimeConfig config;
config.bitrate_bps = rtc::Optional<int>(kBitrate);
config.frame_length_ms = rtc::Optional<int>(kFrameLength);
config.enable_fec = rtc::Optional<bool>(kEnableFec);
config.enable_dtx = rtc::Optional<bool>(kEnableDtx);
config.num_channels = rtc::Optional<size_t>(kNumChannels);
config.uplink_packet_loss_fraction =
rtc::Optional<float>(kPacketLossFraction);
return config;
}
void CheckEncoderRuntimeConfig(
const AudioEncoderOpus* encoder,
const AudioNetworkAdaptor::EncoderRuntimeConfig& config) {
EXPECT_EQ(*config.bitrate_bps, encoder->GetTargetBitrate());
EXPECT_EQ(*config.frame_length_ms, encoder->next_frame_length_ms());
EXPECT_EQ(*config.enable_fec, encoder->fec_enabled());
EXPECT_EQ(*config.enable_dtx, encoder->GetDtx());
EXPECT_EQ(*config.num_channels, encoder->num_channels_to_encode());
}
} // namespace
TEST(AudioEncoderOpusTest, DefaultApplicationModeMono) {
auto states = CreateCodec(1);
EXPECT_EQ(AudioEncoderOpus::kVoip, states.encoder->application());
}
TEST(AudioEncoderOpusTest, DefaultApplicationModeStereo) {
auto states = CreateCodec(2);
EXPECT_EQ(AudioEncoderOpus::kAudio, states.encoder->application());
}
TEST(AudioEncoderOpusTest, ChangeApplicationMode) {
auto states = CreateCodec(2);
EXPECT_TRUE(
states.encoder->SetApplication(AudioEncoder::Application::kSpeech));
EXPECT_EQ(AudioEncoderOpus::kVoip, states.encoder->application());
}
TEST(AudioEncoderOpusTest, ResetWontChangeApplicationMode) {
auto states = CreateCodec(2);
// Trigger a reset.
states.encoder->Reset();
// Verify that the mode is still kAudio.
EXPECT_EQ(AudioEncoderOpus::kAudio, states.encoder->application());
// Now change to kVoip.
EXPECT_TRUE(
states.encoder->SetApplication(AudioEncoder::Application::kSpeech));
EXPECT_EQ(AudioEncoderOpus::kVoip, states.encoder->application());
// Trigger a reset again.
states.encoder->Reset();
// Verify that the mode is still kVoip.
EXPECT_EQ(AudioEncoderOpus::kVoip, states.encoder->application());
}
TEST(AudioEncoderOpusTest, ToggleDtx) {
auto states = CreateCodec(2);
// Enable DTX
EXPECT_TRUE(states.encoder->SetDtx(true));
// Verify that the mode is still kAudio.
EXPECT_EQ(AudioEncoderOpus::kAudio, states.encoder->application());
// Turn off DTX.
EXPECT_TRUE(states.encoder->SetDtx(false));
}
TEST(AudioEncoderOpusTest,
OnReceivedUplinkBandwidthWithoutAudioNetworkAdaptor) {
auto states = CreateCodec(1);
// Constants are replicated from audio_states.encoderopus.cc.
const int kMinBitrateBps = 500;
const int kMaxBitrateBps = 512000;
// Set a too low bitrate.
states.encoder->OnReceivedUplinkBandwidth(kMinBitrateBps - 1,
rtc::Optional<int64_t>());
EXPECT_EQ(kMinBitrateBps, states.encoder->GetTargetBitrate());
// Set a too high bitrate.
states.encoder->OnReceivedUplinkBandwidth(kMaxBitrateBps + 1,
rtc::Optional<int64_t>());
EXPECT_EQ(kMaxBitrateBps, states.encoder->GetTargetBitrate());
// Set the minimum rate.
states.encoder->OnReceivedUplinkBandwidth(kMinBitrateBps,
rtc::Optional<int64_t>());
EXPECT_EQ(kMinBitrateBps, states.encoder->GetTargetBitrate());
// Set the maximum rate.
states.encoder->OnReceivedUplinkBandwidth(kMaxBitrateBps,
rtc::Optional<int64_t>());
EXPECT_EQ(kMaxBitrateBps, states.encoder->GetTargetBitrate());
// Set rates from 1000 up to 32000 bps.
for (int rate = 1000; rate <= 32000; rate += 1000) {
states.encoder->OnReceivedUplinkBandwidth(rate, rtc::Optional<int64_t>());
EXPECT_EQ(rate, states.encoder->GetTargetBitrate());
}
}
namespace {
// Returns a vector with the n evenly-spaced numbers a, a + (b - a)/(n - 1),
// ..., b.
std::vector<float> IntervalSteps(float a, float b, size_t n) {
RTC_DCHECK_GT(n, 1u);
const float step = (b - a) / (n - 1);
std::vector<float> points;
points.push_back(a);
for (size_t i = 1; i < n - 1; ++i)
points.push_back(a + i * step);
points.push_back(b);
return points;
}
// Sets the packet loss rate to each number in the vector in turn, and verifies
// that the loss rate as reported by the encoder is |expected_return| for all
// of them.
void TestSetPacketLossRate(AudioEncoderOpusStates* states,
const std::vector<float>& losses,
float expected_return) {
// |kSampleIntervalMs| is chosen to ease the calculation since
// 0.9999 ^ 184198 = 1e-8. Which minimizes the effect of
// PacketLossFractionSmoother used in AudioEncoderOpus.
constexpr int64_t kSampleIntervalMs = 184198;
for (float loss : losses) {
states->encoder->OnReceivedUplinkPacketLossFraction(loss);
states->simulated_clock->AdvanceTimeMilliseconds(kSampleIntervalMs);
EXPECT_FLOAT_EQ(expected_return, states->encoder->packet_loss_rate());
}
}
} // namespace
TEST(AudioEncoderOpusTest, PacketLossRateOptimized) {
auto states = CreateCodec(1);
auto I = [](float a, float b) { return IntervalSteps(a, b, 10); };
constexpr float eps = 1e-8f;
// Note that the order of the following calls is critical.
// clang-format off
TestSetPacketLossRate(&states, I(0.00f , 0.01f - eps), 0.00f);
TestSetPacketLossRate(&states, I(0.01f + eps, 0.06f - eps), 0.01f);
TestSetPacketLossRate(&states, I(0.06f + eps, 0.11f - eps), 0.05f);
TestSetPacketLossRate(&states, I(0.11f + eps, 0.22f - eps), 0.10f);
TestSetPacketLossRate(&states, I(0.22f + eps, 1.00f ), 0.20f);
TestSetPacketLossRate(&states, I(1.00f , 0.18f + eps), 0.20f);
TestSetPacketLossRate(&states, I(0.18f - eps, 0.09f + eps), 0.10f);
TestSetPacketLossRate(&states, I(0.09f - eps, 0.04f + eps), 0.05f);
TestSetPacketLossRate(&states, I(0.04f - eps, 0.01f + eps), 0.01f);
TestSetPacketLossRate(&states, I(0.01f - eps, 0.00f ), 0.00f);
// clang-format on
}
TEST(AudioEncoderOpusTest, SetReceiverFrameLengthRange) {
auto states = CreateCodec(2);
// Before calling to |SetReceiverFrameLengthRange|,
// |supported_frame_lengths_ms| should contain only the frame length being
// used.
using ::testing::ElementsAre;
EXPECT_THAT(states.encoder->supported_frame_lengths_ms(),
ElementsAre(states.encoder->next_frame_length_ms()));
states.encoder->SetReceiverFrameLengthRange(0, 12345);
EXPECT_THAT(states.encoder->supported_frame_lengths_ms(),
ElementsAre(20, 60));
states.encoder->SetReceiverFrameLengthRange(21, 60);
EXPECT_THAT(states.encoder->supported_frame_lengths_ms(), ElementsAre(60));
states.encoder->SetReceiverFrameLengthRange(20, 59);
EXPECT_THAT(states.encoder->supported_frame_lengths_ms(), ElementsAre(20));
}
TEST(AudioEncoderOpusTest,
InvokeAudioNetworkAdaptorOnReceivedUplinkPacketLossFraction) {
auto states = CreateCodec(2);
states.encoder->EnableAudioNetworkAdaptor("", nullptr, nullptr);
auto config = CreateEncoderRuntimeConfig();
EXPECT_CALL(**states.mock_audio_network_adaptor, GetEncoderRuntimeConfig())
.WillOnce(Return(config));
// Since using mock audio network adaptor, any packet loss fraction is fine.
constexpr float kUplinkPacketLoss = 0.1f;
EXPECT_CALL(**states.mock_audio_network_adaptor,
SetUplinkPacketLossFraction(kUplinkPacketLoss));
states.encoder->OnReceivedUplinkPacketLossFraction(kUplinkPacketLoss);
CheckEncoderRuntimeConfig(states.encoder.get(), config);
}
TEST(AudioEncoderOpusTest, InvokeAudioNetworkAdaptorOnReceivedUplinkBandwidth) {
auto states = CreateCodec(2);
states.encoder->EnableAudioNetworkAdaptor("", nullptr, nullptr);
auto config = CreateEncoderRuntimeConfig();
EXPECT_CALL(**states.mock_audio_network_adaptor, GetEncoderRuntimeConfig())
.WillOnce(Return(config));
// Since using mock audio network adaptor, any target audio bitrate is fine.
constexpr int kTargetAudioBitrate = 30000;
constexpr int64_t kProbingIntervalMs = 3000;
EXPECT_CALL(**states.mock_audio_network_adaptor,
SetTargetAudioBitrate(kTargetAudioBitrate));
EXPECT_CALL(*states.mock_bitrate_smoother,
SetTimeConstantMs(kProbingIntervalMs * 4));
EXPECT_CALL(*states.mock_bitrate_smoother, AddSample(kTargetAudioBitrate));
states.encoder->OnReceivedUplinkBandwidth(
kTargetAudioBitrate, rtc::Optional<int64_t>(kProbingIntervalMs));
CheckEncoderRuntimeConfig(states.encoder.get(), config);
}
TEST(AudioEncoderOpusTest, InvokeAudioNetworkAdaptorOnReceivedRtt) {
auto states = CreateCodec(2);
states.encoder->EnableAudioNetworkAdaptor("", nullptr, nullptr);
auto config = CreateEncoderRuntimeConfig();
EXPECT_CALL(**states.mock_audio_network_adaptor, GetEncoderRuntimeConfig())
.WillOnce(Return(config));
// Since using mock audio network adaptor, any rtt is fine.
constexpr int kRtt = 30;
EXPECT_CALL(**states.mock_audio_network_adaptor, SetRtt(kRtt));
states.encoder->OnReceivedRtt(kRtt);
CheckEncoderRuntimeConfig(states.encoder.get(), config);
}
TEST(AudioEncoderOpusTest, InvokeAudioNetworkAdaptorOnReceivedOverhead) {
auto states = CreateCodec(2);
states.encoder->EnableAudioNetworkAdaptor("", nullptr, nullptr);
auto config = CreateEncoderRuntimeConfig();
EXPECT_CALL(**states.mock_audio_network_adaptor, GetEncoderRuntimeConfig())
.WillOnce(Return(config));
// Since using mock audio network adaptor, any overhead is fine.
constexpr size_t kOverhead = 64;
EXPECT_CALL(**states.mock_audio_network_adaptor, SetOverhead(kOverhead));
states.encoder->OnReceivedOverhead(kOverhead);
CheckEncoderRuntimeConfig(states.encoder.get(), config);
}
TEST(AudioEncoderOpusTest,
PacketLossFractionSmoothedOnSetUplinkPacketLossFraction) {
auto states = CreateCodec(2);
// The values are carefully chosen so that if no smoothing is made, the test
// will fail.
constexpr float kPacketLossFraction_1 = 0.02f;
constexpr float kPacketLossFraction_2 = 0.198f;
// |kSecondSampleTimeMs| is chosen to ease the calculation since
// 0.9999 ^ 6931 = 0.5.
constexpr int64_t kSecondSampleTimeMs = 6931;
// First time, no filtering.
states.encoder->OnReceivedUplinkPacketLossFraction(kPacketLossFraction_1);
EXPECT_FLOAT_EQ(0.01f, states.encoder->packet_loss_rate());
states.simulated_clock->AdvanceTimeMilliseconds(kSecondSampleTimeMs);
states.encoder->OnReceivedUplinkPacketLossFraction(kPacketLossFraction_2);
// Now the output of packet loss fraction smoother should be
// (0.02 + 0.198) / 2 = 0.109, which reach the threshold for the optimized
// packet loss rate to increase to 0.05. If no smoothing has been made, the
// optimized packet loss rate should have been increase to 0.1.
EXPECT_FLOAT_EQ(0.05f, states.encoder->packet_loss_rate());
}
TEST(AudioEncoderOpusTest, DoNotInvokeSetTargetBitrateIfOverheadUnknown) {
test::ScopedFieldTrials override_field_trials(
"WebRTC-SendSideBwe-WithOverhead/Enabled/");
auto states = CreateCodec(2);
states.encoder->OnReceivedUplinkBandwidth(kDefaultOpusSettings.rate * 2,
rtc::Optional<int64_t>());
// Since |OnReceivedOverhead| has not been called, the codec bitrate should
// not change.
EXPECT_EQ(kDefaultOpusSettings.rate, states.encoder->GetTargetBitrate());
}
TEST(AudioEncoderOpusTest, OverheadRemovedFromTargetAudioBitrate) {
test::ScopedFieldTrials override_field_trials(
"WebRTC-SendSideBwe-WithOverhead/Enabled/");
auto states = CreateCodec(2);
constexpr size_t kOverheadBytesPerPacket = 64;
states.encoder->OnReceivedOverhead(kOverheadBytesPerPacket);
constexpr int kTargetBitrateBps = 40000;
states.encoder->OnReceivedUplinkBandwidth(kTargetBitrateBps,
rtc::Optional<int64_t>());
int packet_rate = rtc::CheckedDivExact(48000, kDefaultOpusSettings.pacsize);
EXPECT_EQ(kTargetBitrateBps -
8 * static_cast<int>(kOverheadBytesPerPacket) * packet_rate,
states.encoder->GetTargetBitrate());
}
TEST(AudioEncoderOpusTest, BitrateBounded) {
test::ScopedFieldTrials override_field_trials(
"WebRTC-SendSideBwe-WithOverhead/Enabled/");
constexpr int kMinBitrateBps = 500;
constexpr int kMaxBitrateBps = 512000;
auto states = CreateCodec(2);
constexpr size_t kOverheadBytesPerPacket = 64;
states.encoder->OnReceivedOverhead(kOverheadBytesPerPacket);
int packet_rate = rtc::CheckedDivExact(48000, kDefaultOpusSettings.pacsize);
// Set a target rate that is smaller than |kMinBitrateBps| when overhead is
// subtracted. The eventual codec rate should be bounded by |kMinBitrateBps|.
int target_bitrate =
kOverheadBytesPerPacket * 8 * packet_rate + kMinBitrateBps - 1;
states.encoder->OnReceivedUplinkBandwidth(target_bitrate,
rtc::Optional<int64_t>());
EXPECT_EQ(kMinBitrateBps, states.encoder->GetTargetBitrate());
// Set a target rate that is greater than |kMaxBitrateBps| when overhead is
// subtracted. The eventual codec rate should be bounded by |kMaxBitrateBps|.
target_bitrate =
kOverheadBytesPerPacket * 8 * packet_rate + kMaxBitrateBps + 1;
states.encoder->OnReceivedUplinkBandwidth(target_bitrate,
rtc::Optional<int64_t>());
EXPECT_EQ(kMaxBitrateBps, states.encoder->GetTargetBitrate());
}
// Verifies that the complexity adaptation in the config works as intended.
TEST(AudioEncoderOpusTest, ConfigComplexityAdaptation) {
AudioEncoderOpus::Config config;
config.low_rate_complexity = 8;
config.complexity = 6;
// Bitrate within hysteresis window. Expect empty output.
config.bitrate_bps = rtc::Optional<int>(12500);
EXPECT_EQ(rtc::Optional<int>(), config.GetNewComplexity());
// Bitrate below hysteresis window. Expect higher complexity.
config.bitrate_bps = rtc::Optional<int>(10999);
EXPECT_EQ(rtc::Optional<int>(8), config.GetNewComplexity());
// Bitrate within hysteresis window. Expect empty output.
config.bitrate_bps = rtc::Optional<int>(12500);
EXPECT_EQ(rtc::Optional<int>(), config.GetNewComplexity());
// Bitrate above hysteresis window. Expect lower complexity.
config.bitrate_bps = rtc::Optional<int>(14001);
EXPECT_EQ(rtc::Optional<int>(6), config.GetNewComplexity());
}
TEST(AudioEncoderOpusTest, EmptyConfigDoesNotAffectEncoderSettings) {
auto states = CreateCodec(2);
states.encoder->EnableAudioNetworkAdaptor("", nullptr, nullptr);
auto config = CreateEncoderRuntimeConfig();
AudioNetworkAdaptor::EncoderRuntimeConfig empty_config;
EXPECT_CALL(**states.mock_audio_network_adaptor, GetEncoderRuntimeConfig())
.WillOnce(Return(config))
.WillOnce(Return(empty_config));
constexpr size_t kOverhead = 64;
EXPECT_CALL(**states.mock_audio_network_adaptor, SetOverhead(kOverhead))
.Times(2);
states.encoder->OnReceivedOverhead(kOverhead);
states.encoder->OnReceivedOverhead(kOverhead);
CheckEncoderRuntimeConfig(states.encoder.get(), config);
}
TEST(AudioEncoderOpusTest, UpdateUplinkBandwidthInAudioNetworkAdaptor) {
rtc::ScopedFakeClock fake_clock;
auto states = CreateCodec(2);
states.encoder->EnableAudioNetworkAdaptor("", nullptr, nullptr);
std::array<int16_t, 480 * 2> audio;
audio.fill(0);
rtc::Buffer encoded;
EXPECT_CALL(*states.mock_bitrate_smoother, GetAverage())
.WillOnce(Return(rtc::Optional<float>(50000)));
EXPECT_CALL(**states.mock_audio_network_adaptor, SetUplinkBandwidth(50000));
states.encoder->Encode(
0, rtc::ArrayView<const int16_t>(audio.data(), audio.size()), &encoded);
// Repeat update uplink bandwidth tests.
for (int i = 0; i < 5; i++) {
// Don't update till it is time to update again.
fake_clock.AdvanceTime(rtc::TimeDelta::FromMilliseconds(
states.config.uplink_bandwidth_update_interval_ms - 1));
states.encoder->Encode(
0, rtc::ArrayView<const int16_t>(audio.data(), audio.size()), &encoded);
// Update when it is time to update.
EXPECT_CALL(*states.mock_bitrate_smoother, GetAverage())
.WillOnce(Return(rtc::Optional<float>(40000)));
EXPECT_CALL(**states.mock_audio_network_adaptor, SetUplinkBandwidth(40000));
fake_clock.AdvanceTime(rtc::TimeDelta::FromMilliseconds(1));
states.encoder->Encode(
0, rtc::ArrayView<const int16_t>(audio.data(), audio.size()), &encoded);
}
}
} // namespace webrtc
|
#include "hls_video.h"
#define HEIGHT 1080
#define WIDTH 1920
typedef hls::stream<ap_axiu<32,1,1,1> > AXI_STREAM;
typedef hls::Mat<HEIGHT, WIDTH, HLS_8UC1> MY_IMAGE;
//typedef hls::Mat<HEIGHT, WIDTH, HLS_32FC1> MY_IMAGE;
void image_filter(AXI_STREAM& INPUT_STREAM,
AXI_STREAM& OUTPUT_STREAM,
float k, int threshold) {
#pragma HLS Dataflow
#pragma HLS INTERFACE s_axilite port=return bundle=config
#pragma HLS INTERFACE s_axilite port=k bundle=config
#pragma HLS INTERFACE s_axilite port=threshold bundle=config
#pragma HLS INTERFACE axis register port=INPUT_STREAM
#pragma HLS INTERFACE axis register port=OUTPUT_STREAM
//Create AXI streaming interfaces for the core
MY_IMAGE img_0(HEIGHT, WIDTH);
MY_IMAGE img_1(HEIGHT, WIDTH);
// Convert AXI4 Stream data to hls::mat format
hls::AXIvideo2Mat(INPUT_STREAM, img_0);
hls::Harris<3, 3>(img_0, img_1, k, threshold);
// Convert the hls::mat format to AXI4 Stream format
hls::Mat2AXIvideo(img_1, OUTPUT_STREAM);
}
|
// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
/*
*******************************************************************************
* Copyright (C) 2004-2015, International Business Machines
* Corporation and others. All Rights Reserved.
*******************************************************************************
* file name: uregex.cpp
*/
#include "unicode/utypes.h"
#if !UCONFIG_NO_REGULAR_EXPRESSIONS
#include "unicode/regex.h"
#include "unicode/uregex.h"
#include "unicode/unistr.h"
#include "unicode/ustring.h"
#include "unicode/uchar.h"
#include "unicode/uobject.h"
#include "unicode/utf16.h"
#include "cmemory.h"
#include "uassert.h"
#include "uhash.h"
#include "umutex.h"
#include "uvectr32.h"
#include "regextxt.h"
U_NAMESPACE_BEGIN
#define REMAINING_CAPACITY(idx,len) ((((len)-(idx))>0)?((len)-(idx)):0)
struct RegularExpression: public UMemory {
public:
RegularExpression();
~RegularExpression();
int32_t fMagic;
RegexPattern *fPat;
u_atomic_int32_t *fPatRefCount;
UChar *fPatString;
int32_t fPatStringLen;
RegexMatcher *fMatcher;
const UChar *fText; // Text from setText()
int32_t fTextLength; // Length provided by user with setText(), which
// may be -1.
UBool fOwnsText;
};
static const int32_t REXP_MAGIC = 0x72657870; // "rexp" in ASCII
RegularExpression::RegularExpression() {
fMagic = REXP_MAGIC;
fPat = NULL;
fPatRefCount = NULL;
fPatString = NULL;
fPatStringLen = 0;
fMatcher = NULL;
fText = NULL;
fTextLength = 0;
fOwnsText = FALSE;
}
RegularExpression::~RegularExpression() {
delete fMatcher;
fMatcher = NULL;
if (fPatRefCount!=NULL && umtx_atomic_dec(fPatRefCount)==0) {
delete fPat;
uprv_free(fPatString);
uprv_free((void *)fPatRefCount);
}
if (fOwnsText && fText!=NULL) {
uprv_free((void *)fText);
}
fMagic = 0;
}
U_NAMESPACE_END
U_NAMESPACE_USE
//----------------------------------------------------------------------------------------
//
// validateRE Do boilerplate style checks on API function parameters.
// Return TRUE if they look OK.
//----------------------------------------------------------------------------------------
static UBool validateRE(const RegularExpression *re, UBool requiresText, UErrorCode *status) {
if (U_FAILURE(*status)) {
return FALSE;
}
if (re == NULL || re->fMagic != REXP_MAGIC) {
*status = U_ILLEGAL_ARGUMENT_ERROR;
return FALSE;
}
// !!! Not sure how to update this with the new UText backing, which is stored in re->fMatcher anyway
if (requiresText && re->fText == NULL && !re->fOwnsText) {
*status = U_REGEX_INVALID_STATE;
return FALSE;
}
return TRUE;
}
//----------------------------------------------------------------------------------------
//
// uregex_open
//
//----------------------------------------------------------------------------------------
U_CAPI URegularExpression * U_EXPORT2
uregex_open( const UChar *pattern,
int32_t patternLength,
uint32_t flags,
UParseError *pe,
UErrorCode *status) {
if (U_FAILURE(*status)) {
return NULL;
}
if (pattern == NULL || patternLength < -1 || patternLength == 0) {
*status = U_ILLEGAL_ARGUMENT_ERROR;
return NULL;
}
int32_t actualPatLen = patternLength;
if (actualPatLen == -1) {
actualPatLen = u_strlen(pattern);
}
RegularExpression *re = new RegularExpression;
u_atomic_int32_t *refC = (u_atomic_int32_t *)uprv_malloc(sizeof(int32_t));
UChar *patBuf = (UChar *)uprv_malloc(sizeof(UChar)*(actualPatLen+1));
if (re == NULL || refC == NULL || patBuf == NULL) {
*status = U_MEMORY_ALLOCATION_ERROR;
delete re;
uprv_free((void *)refC);
uprv_free(patBuf);
return NULL;
}
re->fPatRefCount = refC;
*re->fPatRefCount = 1;
//
// Make a copy of the pattern string, so we can return it later if asked.
// For compiling the pattern, we will use a UText wrapper around
// this local copy, to avoid making even more copies.
//
re->fPatString = patBuf;
re->fPatStringLen = patternLength;
u_memcpy(patBuf, pattern, actualPatLen);
patBuf[actualPatLen] = 0;
UText patText = UTEXT_INITIALIZER;
utext_openUChars(&patText, patBuf, patternLength, status);
//
// Compile the pattern
//
if (pe != NULL) {
re->fPat = RegexPattern::compile(&patText, flags, *pe, *status);
} else {
re->fPat = RegexPattern::compile(&patText, flags, *status);
}
utext_close(&patText);
if (U_FAILURE(*status)) {
goto ErrorExit;
}
//
// Create the matcher object
//
re->fMatcher = re->fPat->matcher(*status);
if (U_SUCCESS(*status)) {
return (URegularExpression*)re;
}
ErrorExit:
delete re;
return NULL;
}
//----------------------------------------------------------------------------------------
//
// uregex_openUText
//
//----------------------------------------------------------------------------------------
U_CAPI URegularExpression * U_EXPORT2
uregex_openUText(UText *pattern,
uint32_t flags,
UParseError *pe,
UErrorCode *status) {
if (U_FAILURE(*status)) {
return NULL;
}
if (pattern == NULL) {
*status = U_ILLEGAL_ARGUMENT_ERROR;
return NULL;
}
int64_t patternNativeLength = utext_nativeLength(pattern);
if (patternNativeLength == 0) {
*status = U_ILLEGAL_ARGUMENT_ERROR;
return NULL;
}
RegularExpression *re = new RegularExpression;
UErrorCode lengthStatus = U_ZERO_ERROR;
int32_t pattern16Length = utext_extract(pattern, 0, patternNativeLength, NULL, 0, &lengthStatus);
u_atomic_int32_t *refC = (u_atomic_int32_t *)uprv_malloc(sizeof(int32_t));
UChar *patBuf = (UChar *)uprv_malloc(sizeof(UChar)*(pattern16Length+1));
if (re == NULL || refC == NULL || patBuf == NULL) {
*status = U_MEMORY_ALLOCATION_ERROR;
delete re;
uprv_free((void *)refC);
uprv_free(patBuf);
return NULL;
}
re->fPatRefCount = refC;
*re->fPatRefCount = 1;
//
// Make a copy of the pattern string, so we can return it later if asked.
// For compiling the pattern, we will use a read-only UText wrapper
// around this local copy, to avoid making even more copies.
//
re->fPatString = patBuf;
re->fPatStringLen = pattern16Length;
utext_extract(pattern, 0, patternNativeLength, patBuf, pattern16Length+1, status);
UText patText = UTEXT_INITIALIZER;
utext_openUChars(&patText, patBuf, pattern16Length, status);
//
// Compile the pattern
//
if (pe != NULL) {
re->fPat = RegexPattern::compile(&patText, flags, *pe, *status);
} else {
re->fPat = RegexPattern::compile(&patText, flags, *status);
}
utext_close(&patText);
if (U_FAILURE(*status)) {
goto ErrorExit;
}
//
// Create the matcher object
//
re->fMatcher = re->fPat->matcher(*status);
if (U_SUCCESS(*status)) {
return (URegularExpression*)re;
}
ErrorExit:
delete re;
return NULL;
}
//----------------------------------------------------------------------------------------
//
// uregex_close
//
//----------------------------------------------------------------------------------------
U_CAPI void U_EXPORT2
uregex_close(URegularExpression *re2) {
RegularExpression *re = (RegularExpression*)re2;
UErrorCode status = U_ZERO_ERROR;
if (validateRE(re, FALSE, &status) == FALSE) {
return;
}
delete re;
}
//----------------------------------------------------------------------------------------
//
// uregex_clone
//
//----------------------------------------------------------------------------------------
U_CAPI URegularExpression * U_EXPORT2
uregex_clone(const URegularExpression *source2, UErrorCode *status) {
RegularExpression *source = (RegularExpression*)source2;
if (validateRE(source, FALSE, status) == FALSE) {
return NULL;
}
RegularExpression *clone = new RegularExpression;
if (clone == NULL) {
*status = U_MEMORY_ALLOCATION_ERROR;
return NULL;
}
clone->fMatcher = source->fPat->matcher(*status);
if (U_FAILURE(*status)) {
delete clone;
return NULL;
}
clone->fPat = source->fPat;
clone->fPatRefCount = source->fPatRefCount;
clone->fPatString = source->fPatString;
clone->fPatStringLen = source->fPatStringLen;
umtx_atomic_inc(source->fPatRefCount);
// Note: fText is not cloned.
return (URegularExpression*)clone;
}
//------------------------------------------------------------------------------
//
// uregex_pattern
//
//------------------------------------------------------------------------------
U_CAPI const UChar * U_EXPORT2
uregex_pattern(const URegularExpression *regexp2,
int32_t *patLength,
UErrorCode *status) {
RegularExpression *regexp = (RegularExpression*)regexp2;
if (validateRE(regexp, FALSE, status) == FALSE) {
return NULL;
}
if (patLength != NULL) {
*patLength = regexp->fPatStringLen;
}
return regexp->fPatString;
}
//------------------------------------------------------------------------------
//
// uregex_patternUText
//
//------------------------------------------------------------------------------
U_CAPI UText * U_EXPORT2
uregex_patternUText(const URegularExpression *regexp2,
UErrorCode *status) {
RegularExpression *regexp = (RegularExpression*)regexp2;
return regexp->fPat->patternText(*status);
}
//------------------------------------------------------------------------------
//
// uregex_flags
//
//------------------------------------------------------------------------------
U_CAPI int32_t U_EXPORT2
uregex_flags(const URegularExpression *regexp2, UErrorCode *status) {
RegularExpression *regexp = (RegularExpression*)regexp2;
if (validateRE(regexp, FALSE, status) == FALSE) {
return 0;
}
int32_t flags = regexp->fPat->flags();
return flags;
}
//------------------------------------------------------------------------------
//
// uregex_setText
//
//------------------------------------------------------------------------------
U_CAPI void U_EXPORT2
uregex_setText(URegularExpression *regexp2,
const UChar *text,
int32_t textLength,
UErrorCode *status) {
RegularExpression *regexp = (RegularExpression*)regexp2;
if (validateRE(regexp, FALSE, status) == FALSE) {
return;
}
if (text == NULL || textLength < -1) {
*status = U_ILLEGAL_ARGUMENT_ERROR;
return;
}
if (regexp->fOwnsText && regexp->fText != NULL) {
uprv_free((void *)regexp->fText);
}
regexp->fText = text;
regexp->fTextLength = textLength;
regexp->fOwnsText = FALSE;
UText input = UTEXT_INITIALIZER;
utext_openUChars(&input, text, textLength, status);
regexp->fMatcher->reset(&input);
utext_close(&input); // reset() made a shallow clone, so we don't need this copy
}
//------------------------------------------------------------------------------
//
// uregex_setUText
//
//------------------------------------------------------------------------------
U_CAPI void U_EXPORT2
uregex_setUText(URegularExpression *regexp2,
UText *text,
UErrorCode *status) {
RegularExpression *regexp = (RegularExpression*)regexp2;
if (validateRE(regexp, FALSE, status) == FALSE) {
return;
}
if (text == NULL) {
*status = U_ILLEGAL_ARGUMENT_ERROR;
return;
}
if (regexp->fOwnsText && regexp->fText != NULL) {
uprv_free((void *)regexp->fText);
}
regexp->fText = NULL; // only fill it in on request
regexp->fTextLength = -1;
regexp->fOwnsText = TRUE;
regexp->fMatcher->reset(text);
}
//------------------------------------------------------------------------------
//
// uregex_getText
//
//------------------------------------------------------------------------------
U_CAPI const UChar * U_EXPORT2
uregex_getText(URegularExpression *regexp2,
int32_t *textLength,
UErrorCode *status) {
RegularExpression *regexp = (RegularExpression*)regexp2;
if (validateRE(regexp, FALSE, status) == FALSE) {
return NULL;
}
if (regexp->fText == NULL) {
// need to fill in the text
UText *inputText = regexp->fMatcher->inputText();
int64_t inputNativeLength = utext_nativeLength(inputText);
if (UTEXT_FULL_TEXT_IN_CHUNK(inputText, inputNativeLength)) {
regexp->fText = inputText->chunkContents;
regexp->fTextLength = (int32_t)inputNativeLength;
regexp->fOwnsText = FALSE; // because the UText owns it
} else {
UErrorCode lengthStatus = U_ZERO_ERROR;
regexp->fTextLength = utext_extract(inputText, 0, inputNativeLength, NULL, 0, &lengthStatus); // buffer overflow error
UChar *inputChars = (UChar *)uprv_malloc(sizeof(UChar)*(regexp->fTextLength+1));
utext_extract(inputText, 0, inputNativeLength, inputChars, regexp->fTextLength+1, status);
regexp->fText = inputChars;
regexp->fOwnsText = TRUE; // should already be set but just in case
}
}
if (textLength != NULL) {
*textLength = regexp->fTextLength;
}
return regexp->fText;
}
//------------------------------------------------------------------------------
//
// uregex_getUText
//
//------------------------------------------------------------------------------
U_CAPI UText * U_EXPORT2
uregex_getUText(URegularExpression *regexp2,
UText *dest,
UErrorCode *status) {
RegularExpression *regexp = (RegularExpression*)regexp2;
if (validateRE(regexp, FALSE, status) == FALSE) {
return dest;
}
return regexp->fMatcher->getInput(dest, *status);
}
//------------------------------------------------------------------------------
//
// uregex_refreshUText
//
//------------------------------------------------------------------------------
U_CAPI void U_EXPORT2
uregex_refreshUText(URegularExpression *regexp2,
UText *text,
UErrorCode *status) {
RegularExpression *regexp = (RegularExpression*)regexp2;
if (validateRE(regexp, FALSE, status) == FALSE) {
return;
}
regexp->fMatcher->refreshInputText(text, *status);
}
//------------------------------------------------------------------------------
//
// uregex_matches
//
//------------------------------------------------------------------------------
U_CAPI UBool U_EXPORT2
uregex_matches(URegularExpression *regexp2,
int32_t startIndex,
UErrorCode *status) {
return uregex_matches64( regexp2, (int64_t)startIndex, status);
}
U_CAPI UBool U_EXPORT2
uregex_matches64(URegularExpression *regexp2,
int64_t startIndex,
UErrorCode *status) {
RegularExpression *regexp = (RegularExpression*)regexp2;
UBool result = FALSE;
if (validateRE(regexp, TRUE, status) == FALSE) {
return result;
}
if (startIndex == -1) {
result = regexp->fMatcher->matches(*status);
} else {
result = regexp->fMatcher->matches(startIndex, *status);
}
return result;
}
//------------------------------------------------------------------------------
//
// uregex_lookingAt
//
//------------------------------------------------------------------------------
U_CAPI UBool U_EXPORT2
uregex_lookingAt(URegularExpression *regexp2,
int32_t startIndex,
UErrorCode *status) {
return uregex_lookingAt64( regexp2, (int64_t)startIndex, status);
}
U_CAPI UBool U_EXPORT2
uregex_lookingAt64(URegularExpression *regexp2,
int64_t startIndex,
UErrorCode *status) {
RegularExpression *regexp = (RegularExpression*)regexp2;
UBool result = FALSE;
if (validateRE(regexp, TRUE, status) == FALSE) {
return result;
}
if (startIndex == -1) {
result = regexp->fMatcher->lookingAt(*status);
} else {
result = regexp->fMatcher->lookingAt(startIndex, *status);
}
return result;
}
//------------------------------------------------------------------------------
//
// uregex_find
//
//------------------------------------------------------------------------------
U_CAPI UBool U_EXPORT2
uregex_find(URegularExpression *regexp2,
int32_t startIndex,
UErrorCode *status) {
return uregex_find64( regexp2, (int64_t)startIndex, status);
}
U_CAPI UBool U_EXPORT2
uregex_find64(URegularExpression *regexp2,
int64_t startIndex,
UErrorCode *status) {
RegularExpression *regexp = (RegularExpression*)regexp2;
UBool result = FALSE;
if (validateRE(regexp, TRUE, status) == FALSE) {
return result;
}
if (startIndex == -1) {
regexp->fMatcher->resetPreserveRegion();
result = regexp->fMatcher->find(*status);
} else {
result = regexp->fMatcher->find(startIndex, *status);
}
return result;
}
//------------------------------------------------------------------------------
//
// uregex_findNext
//
//------------------------------------------------------------------------------
U_CAPI UBool U_EXPORT2
uregex_findNext(URegularExpression *regexp2,
UErrorCode *status) {
RegularExpression *regexp = (RegularExpression*)regexp2;
if (validateRE(regexp, TRUE, status) == FALSE) {
return FALSE;
}
UBool result = regexp->fMatcher->find(*status);
return result;
}
//------------------------------------------------------------------------------
//
// uregex_groupCount
//
//------------------------------------------------------------------------------
U_CAPI int32_t U_EXPORT2
uregex_groupCount(URegularExpression *regexp2,
UErrorCode *status) {
RegularExpression *regexp = (RegularExpression*)regexp2;
if (validateRE(regexp, FALSE, status) == FALSE) {
return 0;
}
int32_t result = regexp->fMatcher->groupCount();
return result;
}
//------------------------------------------------------------------------------
//
// uregex_groupNumberFromName
//
//------------------------------------------------------------------------------
int32_t
uregex_groupNumberFromName(URegularExpression *regexp2,
const UChar *groupName,
int32_t nameLength,
UErrorCode *status) {
RegularExpression *regexp = (RegularExpression*)regexp2;
if (validateRE(regexp, FALSE, status) == FALSE) {
return 0;
}
int32_t result = regexp->fPat->groupNumberFromName(UnicodeString(groupName, nameLength), *status);
return result;
}
int32_t
uregex_groupNumberFromCName(URegularExpression *regexp2,
const char *groupName,
int32_t nameLength,
UErrorCode *status) {
RegularExpression *regexp = (RegularExpression*)regexp2;
if (validateRE(regexp, FALSE, status) == FALSE) {
return 0;
}
return regexp->fPat->groupNumberFromName(groupName, nameLength, *status);
}
//------------------------------------------------------------------------------
//
// uregex_group
//
//------------------------------------------------------------------------------
U_CAPI int32_t U_EXPORT2
uregex_group(URegularExpression *regexp2,
int32_t groupNum,
UChar *dest,
int32_t destCapacity,
UErrorCode *status) {
RegularExpression *regexp = (RegularExpression*)regexp2;
if (validateRE(regexp, TRUE, status) == FALSE) {
return 0;
}
if (destCapacity < 0 || (destCapacity > 0 && dest == NULL)) {
*status = U_ILLEGAL_ARGUMENT_ERROR;
return 0;
}
if (destCapacity == 0 || regexp->fText != NULL) {
// If preflighting or if we already have the text as UChars,
// this is a little cheaper than extracting from the UText
//
// Pick up the range of characters from the matcher
//
int32_t startIx = regexp->fMatcher->start(groupNum, *status);
int32_t endIx = regexp->fMatcher->end (groupNum, *status);
if (U_FAILURE(*status)) {
return 0;
}
//
// Trim length based on buffer capacity
//
int32_t fullLength = endIx - startIx;
int32_t copyLength = fullLength;
if (copyLength < destCapacity) {
dest[copyLength] = 0;
} else if (copyLength == destCapacity) {
*status = U_STRING_NOT_TERMINATED_WARNING;
} else {
copyLength = destCapacity;
*status = U_BUFFER_OVERFLOW_ERROR;
}
//
// Copy capture group to user's buffer
//
if (copyLength > 0) {
u_memcpy(dest, ®exp->fText[startIx], copyLength);
}
return fullLength;
} else {
int64_t start = regexp->fMatcher->start64(groupNum, *status);
int64_t limit = regexp->fMatcher->end64(groupNum, *status);
if (U_FAILURE(*status)) {
return 0;
}
// Note edge cases:
// Group didn't match: start == end == -1. UText trims to 0, UText gives zero length result.
// Zero Length Match: start == end.
int32_t length = utext_extract(regexp->fMatcher->inputText(), start, limit, dest, destCapacity, status);
return length;
}
}
//------------------------------------------------------------------------------
//
// uregex_groupUText
//
//------------------------------------------------------------------------------
U_CAPI UText * U_EXPORT2
uregex_groupUText(URegularExpression *regexp2,
int32_t groupNum,
UText *dest,
int64_t *groupLength,
UErrorCode *status) {
RegularExpression *regexp = (RegularExpression*)regexp2;
if (validateRE(regexp, TRUE, status) == FALSE) {
UErrorCode emptyTextStatus = U_ZERO_ERROR;
return (dest ? dest : utext_openUChars(NULL, NULL, 0, &emptyTextStatus));
}
return regexp->fMatcher->group(groupNum, dest, *groupLength, *status);
}
//------------------------------------------------------------------------------
//
// uregex_start
//
//------------------------------------------------------------------------------
U_CAPI int32_t U_EXPORT2
uregex_start(URegularExpression *regexp2,
int32_t groupNum,
UErrorCode *status) {
return (int32_t)uregex_start64( regexp2, groupNum, status);
}
U_CAPI int64_t U_EXPORT2
uregex_start64(URegularExpression *regexp2,
int32_t groupNum,
UErrorCode *status) {
RegularExpression *regexp = (RegularExpression*)regexp2;
if (validateRE(regexp, TRUE, status) == FALSE) {
return 0;
}
int64_t result = regexp->fMatcher->start64(groupNum, *status);
return result;
}
//------------------------------------------------------------------------------
//
// uregex_end
//
//------------------------------------------------------------------------------
U_CAPI int32_t U_EXPORT2
uregex_end(URegularExpression *regexp2,
int32_t groupNum,
UErrorCode *status) {
return (int32_t)uregex_end64( regexp2, groupNum, status);
}
U_CAPI int64_t U_EXPORT2
uregex_end64(URegularExpression *regexp2,
int32_t groupNum,
UErrorCode *status) {
RegularExpression *regexp = (RegularExpression*)regexp2;
if (validateRE(regexp, TRUE, status) == FALSE) {
return 0;
}
int64_t result = regexp->fMatcher->end64(groupNum, *status);
return result;
}
//------------------------------------------------------------------------------
//
// uregex_reset
//
//------------------------------------------------------------------------------
U_CAPI void U_EXPORT2
uregex_reset(URegularExpression *regexp2,
int32_t index,
UErrorCode *status) {
uregex_reset64( regexp2, (int64_t)index, status);
}
U_CAPI void U_EXPORT2
uregex_reset64(URegularExpression *regexp2,
int64_t index,
UErrorCode *status) {
RegularExpression *regexp = (RegularExpression*)regexp2;
if (validateRE(regexp, TRUE, status) == FALSE) {
return;
}
regexp->fMatcher->reset(index, *status);
}
//------------------------------------------------------------------------------
//
// uregex_setRegion
//
//------------------------------------------------------------------------------
U_CAPI void U_EXPORT2
uregex_setRegion(URegularExpression *regexp2,
int32_t regionStart,
int32_t regionLimit,
UErrorCode *status) {
uregex_setRegion64( regexp2, (int64_t)regionStart, (int64_t)regionLimit, status);
}
U_CAPI void U_EXPORT2
uregex_setRegion64(URegularExpression *regexp2,
int64_t regionStart,
int64_t regionLimit,
UErrorCode *status) {
RegularExpression *regexp = (RegularExpression*)regexp2;
if (validateRE(regexp, TRUE, status) == FALSE) {
return;
}
regexp->fMatcher->region(regionStart, regionLimit, *status);
}
//------------------------------------------------------------------------------
//
// uregex_setRegionAndStart
//
//------------------------------------------------------------------------------
U_CAPI void U_EXPORT2
uregex_setRegionAndStart(URegularExpression *regexp2,
int64_t regionStart,
int64_t regionLimit,
int64_t startIndex,
UErrorCode *status) {
RegularExpression *regexp = (RegularExpression*)regexp2;
if (validateRE(regexp, TRUE, status) == FALSE) {
return;
}
regexp->fMatcher->region(regionStart, regionLimit, startIndex, *status);
}
//------------------------------------------------------------------------------
//
// uregex_regionStart
//
//------------------------------------------------------------------------------
U_CAPI int32_t U_EXPORT2
uregex_regionStart(const URegularExpression *regexp2,
UErrorCode *status) {
return (int32_t)uregex_regionStart64(regexp2, status);
}
U_CAPI int64_t U_EXPORT2
uregex_regionStart64(const URegularExpression *regexp2,
UErrorCode *status) {
RegularExpression *regexp = (RegularExpression*)regexp2;
if (validateRE(regexp, TRUE, status) == FALSE) {
return 0;
}
return regexp->fMatcher->regionStart();
}
//------------------------------------------------------------------------------
//
// uregex_regionEnd
//
//------------------------------------------------------------------------------
U_CAPI int32_t U_EXPORT2
uregex_regionEnd(const URegularExpression *regexp2,
UErrorCode *status) {
return (int32_t)uregex_regionEnd64(regexp2, status);
}
U_CAPI int64_t U_EXPORT2
uregex_regionEnd64(const URegularExpression *regexp2,
UErrorCode *status) {
RegularExpression *regexp = (RegularExpression*)regexp2;
if (validateRE(regexp, TRUE, status) == FALSE) {
return 0;
}
return regexp->fMatcher->regionEnd();
}
//------------------------------------------------------------------------------
//
// uregex_hasTransparentBounds
//
//------------------------------------------------------------------------------
U_CAPI UBool U_EXPORT2
uregex_hasTransparentBounds(const URegularExpression *regexp2,
UErrorCode *status) {
RegularExpression *regexp = (RegularExpression*)regexp2;
if (validateRE(regexp, FALSE, status) == FALSE) {
return FALSE;
}
return regexp->fMatcher->hasTransparentBounds();
}
//------------------------------------------------------------------------------
//
// uregex_useTransparentBounds
//
//------------------------------------------------------------------------------
U_CAPI void U_EXPORT2
uregex_useTransparentBounds(URegularExpression *regexp2,
UBool b,
UErrorCode *status) {
RegularExpression *regexp = (RegularExpression*)regexp2;
if (validateRE(regexp, FALSE, status) == FALSE) {
return;
}
regexp->fMatcher->useTransparentBounds(b);
}
//------------------------------------------------------------------------------
//
// uregex_hasAnchoringBounds
//
//------------------------------------------------------------------------------
U_CAPI UBool U_EXPORT2
uregex_hasAnchoringBounds(const URegularExpression *regexp2,
UErrorCode *status) {
RegularExpression *regexp = (RegularExpression*)regexp2;
if (validateRE(regexp, FALSE, status) == FALSE) {
return FALSE;
}
return regexp->fMatcher->hasAnchoringBounds();
}
//------------------------------------------------------------------------------
//
// uregex_useAnchoringBounds
//
//------------------------------------------------------------------------------
U_CAPI void U_EXPORT2
uregex_useAnchoringBounds(URegularExpression *regexp2,
UBool b,
UErrorCode *status) {
RegularExpression *regexp = (RegularExpression*)regexp2;
if (validateRE(regexp, FALSE, status) == FALSE) {
return;
}
regexp->fMatcher->useAnchoringBounds(b);
}
//------------------------------------------------------------------------------
//
// uregex_hitEnd
//
//------------------------------------------------------------------------------
U_CAPI UBool U_EXPORT2
uregex_hitEnd(const URegularExpression *regexp2,
UErrorCode *status) {
RegularExpression *regexp = (RegularExpression*)regexp2;
if (validateRE(regexp, TRUE, status) == FALSE) {
return FALSE;
}
return regexp->fMatcher->hitEnd();
}
//------------------------------------------------------------------------------
//
// uregex_requireEnd
//
//------------------------------------------------------------------------------
U_CAPI UBool U_EXPORT2
uregex_requireEnd(const URegularExpression *regexp2,
UErrorCode *status) {
RegularExpression *regexp = (RegularExpression*)regexp2;
if (validateRE(regexp, TRUE, status) == FALSE) {
return FALSE;
}
return regexp->fMatcher->requireEnd();
}
//------------------------------------------------------------------------------
//
// uregex_setTimeLimit
//
//------------------------------------------------------------------------------
U_CAPI void U_EXPORT2
uregex_setTimeLimit(URegularExpression *regexp2,
int32_t limit,
UErrorCode *status) {
RegularExpression *regexp = (RegularExpression*)regexp2;
if (validateRE(regexp, FALSE, status)) {
regexp->fMatcher->setTimeLimit(limit, *status);
}
}
//------------------------------------------------------------------------------
//
// uregex_getTimeLimit
//
//------------------------------------------------------------------------------
U_CAPI int32_t U_EXPORT2
uregex_getTimeLimit(const URegularExpression *regexp2,
UErrorCode *status) {
int32_t retVal = 0;
RegularExpression *regexp = (RegularExpression*)regexp2;
if (validateRE(regexp, FALSE, status)) {
retVal = regexp->fMatcher->getTimeLimit();
}
return retVal;
}
//------------------------------------------------------------------------------
//
// uregex_setStackLimit
//
//------------------------------------------------------------------------------
U_CAPI void U_EXPORT2
uregex_setStackLimit(URegularExpression *regexp2,
int32_t limit,
UErrorCode *status) {
RegularExpression *regexp = (RegularExpression*)regexp2;
if (validateRE(regexp, FALSE, status)) {
regexp->fMatcher->setStackLimit(limit, *status);
}
}
//------------------------------------------------------------------------------
//
// uregex_getStackLimit
//
//------------------------------------------------------------------------------
U_CAPI int32_t U_EXPORT2
uregex_getStackLimit(const URegularExpression *regexp2,
UErrorCode *status) {
int32_t retVal = 0;
RegularExpression *regexp = (RegularExpression*)regexp2;
if (validateRE(regexp, FALSE, status)) {
retVal = regexp->fMatcher->getStackLimit();
}
return retVal;
}
//------------------------------------------------------------------------------
//
// uregex_setMatchCallback
//
//------------------------------------------------------------------------------
U_CAPI void U_EXPORT2
uregex_setMatchCallback(URegularExpression *regexp2,
URegexMatchCallback *callback,
const void *context,
UErrorCode *status) {
RegularExpression *regexp = (RegularExpression*)regexp2;
if (validateRE(regexp, FALSE, status)) {
regexp->fMatcher->setMatchCallback(callback, context, *status);
}
}
//------------------------------------------------------------------------------
//
// uregex_getMatchCallback
//
//------------------------------------------------------------------------------
U_CAPI void U_EXPORT2
uregex_getMatchCallback(const URegularExpression *regexp2,
URegexMatchCallback **callback,
const void **context,
UErrorCode *status) {
RegularExpression *regexp = (RegularExpression*)regexp2;
if (validateRE(regexp, FALSE, status)) {
regexp->fMatcher->getMatchCallback(*callback, *context, *status);
}
}
//------------------------------------------------------------------------------
//
// uregex_setMatchProgressCallback
//
//------------------------------------------------------------------------------
U_CAPI void U_EXPORT2
uregex_setFindProgressCallback(URegularExpression *regexp2,
URegexFindProgressCallback *callback,
const void *context,
UErrorCode *status) {
RegularExpression *regexp = (RegularExpression*)regexp2;
if (validateRE(regexp, FALSE, status)) {
regexp->fMatcher->setFindProgressCallback(callback, context, *status);
}
}
//------------------------------------------------------------------------------
//
// uregex_getMatchCallback
//
//------------------------------------------------------------------------------
U_CAPI void U_EXPORT2
uregex_getFindProgressCallback(const URegularExpression *regexp2,
URegexFindProgressCallback **callback,
const void **context,
UErrorCode *status) {
RegularExpression *regexp = (RegularExpression*)regexp2;
if (validateRE(regexp, FALSE, status)) {
regexp->fMatcher->getFindProgressCallback(*callback, *context, *status);
}
}
//------------------------------------------------------------------------------
//
// uregex_replaceAll
//
//------------------------------------------------------------------------------
U_CAPI int32_t U_EXPORT2
uregex_replaceAll(URegularExpression *regexp2,
const UChar *replacementText,
int32_t replacementLength,
UChar *destBuf,
int32_t destCapacity,
UErrorCode *status) {
RegularExpression *regexp = (RegularExpression*)regexp2;
if (validateRE(regexp, TRUE, status) == FALSE) {
return 0;
}
if (replacementText == NULL || replacementLength < -1 ||
(destBuf == NULL && destCapacity > 0) ||
destCapacity < 0) {
*status = U_ILLEGAL_ARGUMENT_ERROR;
return 0;
}
int32_t len = 0;
uregex_reset(regexp2, 0, status);
// Note: Seperate error code variables for findNext() and appendReplacement()
// are used so that destination buffer overflow errors
// in appendReplacement won't stop findNext() from working.
// appendReplacement() and appendTail() special case incoming buffer
// overflow errors, continuing to return the correct length.
UErrorCode findStatus = *status;
while (uregex_findNext(regexp2, &findStatus)) {
len += uregex_appendReplacement(regexp2, replacementText, replacementLength,
&destBuf, &destCapacity, status);
}
len += uregex_appendTail(regexp2, &destBuf, &destCapacity, status);
if (U_FAILURE(findStatus)) {
// If anything went wrong with the findNext(), make that error trump
// whatever may have happened with the append() operations.
// Errors in findNext() are not expected.
*status = findStatus;
}
return len;
}
//------------------------------------------------------------------------------
//
// uregex_replaceAllUText
//
//------------------------------------------------------------------------------
U_CAPI UText * U_EXPORT2
uregex_replaceAllUText(URegularExpression *regexp2,
UText *replacementText,
UText *dest,
UErrorCode *status) {
RegularExpression *regexp = (RegularExpression*)regexp2;
if (validateRE(regexp, TRUE, status) == FALSE) {
return 0;
}
if (replacementText == NULL) {
*status = U_ILLEGAL_ARGUMENT_ERROR;
return 0;
}
dest = regexp->fMatcher->replaceAll(replacementText, dest, *status);
return dest;
}
//------------------------------------------------------------------------------
//
// uregex_replaceFirst
//
//------------------------------------------------------------------------------
U_CAPI int32_t U_EXPORT2
uregex_replaceFirst(URegularExpression *regexp2,
const UChar *replacementText,
int32_t replacementLength,
UChar *destBuf,
int32_t destCapacity,
UErrorCode *status) {
RegularExpression *regexp = (RegularExpression*)regexp2;
if (validateRE(regexp, TRUE, status) == FALSE) {
return 0;
}
if (replacementText == NULL || replacementLength < -1 ||
(destBuf == NULL && destCapacity > 0) ||
destCapacity < 0) {
*status = U_ILLEGAL_ARGUMENT_ERROR;
return 0;
}
int32_t len = 0;
UBool findSucceeded;
uregex_reset(regexp2, 0, status);
findSucceeded = uregex_find(regexp2, 0, status);
if (findSucceeded) {
len = uregex_appendReplacement(regexp2, replacementText, replacementLength,
&destBuf, &destCapacity, status);
}
len += uregex_appendTail(regexp2, &destBuf, &destCapacity, status);
return len;
}
//------------------------------------------------------------------------------
//
// uregex_replaceFirstUText
//
//------------------------------------------------------------------------------
U_CAPI UText * U_EXPORT2
uregex_replaceFirstUText(URegularExpression *regexp2,
UText *replacementText,
UText *dest,
UErrorCode *status) {
RegularExpression *regexp = (RegularExpression*)regexp2;
if (validateRE(regexp, TRUE, status) == FALSE) {
return 0;
}
if (replacementText == NULL) {
*status = U_ILLEGAL_ARGUMENT_ERROR;
return 0;
}
dest = regexp->fMatcher->replaceFirst(replacementText, dest, *status);
return dest;
}
//------------------------------------------------------------------------------
//
// uregex_appendReplacement
//
//------------------------------------------------------------------------------
U_NAMESPACE_BEGIN
//
// Dummy class, because these functions need to be friends of class RegexMatcher,
// and stand-alone C functions don't work as friends
//
class RegexCImpl {
public:
inline static int32_t appendReplacement(RegularExpression *regexp,
const UChar *replacementText,
int32_t replacementLength,
UChar **destBuf,
int32_t *destCapacity,
UErrorCode *status);
inline static int32_t appendTail(RegularExpression *regexp,
UChar **destBuf,
int32_t *destCapacity,
UErrorCode *status);
inline static int32_t split(RegularExpression *regexp,
UChar *destBuf,
int32_t destCapacity,
int32_t *requiredCapacity,
UChar *destFields[],
int32_t destFieldsCapacity,
UErrorCode *status);
};
U_NAMESPACE_END
static const UChar BACKSLASH = 0x5c;
static const UChar DOLLARSIGN = 0x24;
static const UChar LEFTBRACKET = 0x7b;
static const UChar RIGHTBRACKET = 0x7d;
//
// Move a character to an output buffer, with bounds checking on the index.
// Index advances even if capacity is exceeded, for preflight size computations.
// This little sequence is used a LOT.
//
static inline void appendToBuf(UChar c, int32_t *idx, UChar *buf, int32_t bufCapacity) {
if (*idx < bufCapacity) {
buf[*idx] = c;
}
(*idx)++;
}
//
// appendReplacement, the actual implementation.
//
int32_t RegexCImpl::appendReplacement(RegularExpression *regexp,
const UChar *replacementText,
int32_t replacementLength,
UChar **destBuf,
int32_t *destCapacity,
UErrorCode *status) {
// If we come in with a buffer overflow error, don't suppress the operation.
// A series of appendReplacements, appendTail need to correctly preflight
// the buffer size when an overflow happens somewhere in the middle.
UBool pendingBufferOverflow = FALSE;
if (*status == U_BUFFER_OVERFLOW_ERROR && destCapacity != NULL && *destCapacity == 0) {
pendingBufferOverflow = TRUE;
*status = U_ZERO_ERROR;
}
//
// Validate all paramters
//
if (validateRE(regexp, TRUE, status) == FALSE) {
return 0;
}
if (replacementText == NULL || replacementLength < -1 ||
destCapacity == NULL || destBuf == NULL ||
(*destBuf == NULL && *destCapacity > 0) ||
*destCapacity < 0) {
*status = U_ILLEGAL_ARGUMENT_ERROR;
return 0;
}
RegexMatcher *m = regexp->fMatcher;
if (m->fMatch == FALSE) {
*status = U_REGEX_INVALID_STATE;
return 0;
}
UChar *dest = *destBuf;
int32_t capacity = *destCapacity;
int32_t destIdx = 0;
int32_t i;
// If it wasn't supplied by the caller, get the length of the replacement text.
// TODO: slightly smarter logic in the copy loop could watch for the NUL on
// the fly and avoid this step.
if (replacementLength == -1) {
replacementLength = u_strlen(replacementText);
}
// Copy input string from the end of previous match to start of current match
if (regexp->fText != NULL) {
int32_t matchStart;
int32_t lastMatchEnd;
if (UTEXT_USES_U16(m->fInputText)) {
lastMatchEnd = (int32_t)m->fLastMatchEnd;
matchStart = (int32_t)m->fMatchStart;
} else {
// !!!: Would like a better way to do this!
UErrorCode tempStatus = U_ZERO_ERROR;
lastMatchEnd = utext_extract(m->fInputText, 0, m->fLastMatchEnd, NULL, 0, &tempStatus);
tempStatus = U_ZERO_ERROR;
matchStart = lastMatchEnd + utext_extract(m->fInputText, m->fLastMatchEnd, m->fMatchStart, NULL, 0, &tempStatus);
}
for (i=lastMatchEnd; i<matchStart; i++) {
appendToBuf(regexp->fText[i], &destIdx, dest, capacity);
}
} else {
UErrorCode possibleOverflowError = U_ZERO_ERROR; // ignore
destIdx += utext_extract(m->fInputText, m->fLastMatchEnd, m->fMatchStart,
dest==NULL?NULL:&dest[destIdx], REMAINING_CAPACITY(destIdx, capacity),
&possibleOverflowError);
}
U_ASSERT(destIdx >= 0);
// scan the replacement text, looking for substitutions ($n) and \escapes.
int32_t replIdx = 0;
while (replIdx < replacementLength && U_SUCCESS(*status)) {
UChar c = replacementText[replIdx];
replIdx++;
if (c != DOLLARSIGN && c != BACKSLASH) {
// Common case, no substitution, no escaping,
// just copy the char to the dest buf.
appendToBuf(c, &destIdx, dest, capacity);
continue;
}
if (c == BACKSLASH) {
// Backslash Escape. Copy the following char out without further checks.
// Note: Surrogate pairs don't need any special handling
// The second half wont be a '$' or a '\', and
// will move to the dest normally on the next
// loop iteration.
if (replIdx >= replacementLength) {
break;
}
c = replacementText[replIdx];
if (c==0x55/*U*/ || c==0x75/*u*/) {
// We have a \udddd or \Udddddddd escape sequence.
UChar32 escapedChar =
u_unescapeAt(uregex_ucstr_unescape_charAt,
&replIdx, // Index is updated by unescapeAt
replacementLength, // Length of replacement text
(void *)replacementText);
if (escapedChar != (UChar32)0xFFFFFFFF) {
if (escapedChar <= 0xffff) {
appendToBuf((UChar)escapedChar, &destIdx, dest, capacity);
} else {
appendToBuf(U16_LEAD(escapedChar), &destIdx, dest, capacity);
appendToBuf(U16_TRAIL(escapedChar), &destIdx, dest, capacity);
}
continue;
}
// Note: if the \u escape was invalid, just fall through and
// treat it as a plain \<anything> escape.
}
// Plain backslash escape. Just put out the escaped character.
appendToBuf(c, &destIdx, dest, capacity);
replIdx++;
continue;
}
// We've got a $. Pick up the following capture group name or number.
// For numbers, consume only digits that produce a valid capture group for the pattern.
int32_t groupNum = 0;
U_ASSERT(c == DOLLARSIGN);
UChar32 c32 = -1;
if (replIdx < replacementLength) {
U16_GET(replacementText, 0, replIdx, replacementLength, c32);
}
if (u_isdigit(c32)) {
int32_t numDigits = 0;
int32_t numCaptureGroups = m->fPattern->fGroupMap->size();
for (;;) {
if (replIdx >= replacementLength) {
break;
}
U16_GET(replacementText, 0, replIdx, replacementLength, c32);
if (u_isdigit(c32) == FALSE) {
break;
}
int32_t digitVal = u_charDigitValue(c32);
if (groupNum * 10 + digitVal <= numCaptureGroups) {
groupNum = groupNum * 10 + digitVal;
U16_FWD_1(replacementText, replIdx, replacementLength);
numDigits++;
} else {
if (numDigits == 0) {
*status = U_INDEX_OUTOFBOUNDS_ERROR;
}
break;
}
}
} else if (c32 == LEFTBRACKET) {
// Scan for Named Capture Group, ${name}.
UnicodeString groupName;
U16_FWD_1(replacementText, replIdx, replacementLength);
while (U_SUCCESS(*status) && c32 != RIGHTBRACKET) {
if (replIdx >= replacementLength) {
*status = U_REGEX_INVALID_CAPTURE_GROUP_NAME;
break;
}
U16_NEXT(replacementText, replIdx, replacementLength, c32);
if ((c32 >= 0x41 && c32 <= 0x5a) || // A..Z
(c32 >= 0x61 && c32 <= 0x7a) || // a..z
(c32 >= 0x31 && c32 <= 0x39)) { // 0..9
groupName.append(c32);
} else if (c32 == RIGHTBRACKET) {
groupNum = uhash_geti(regexp->fPat->fNamedCaptureMap, &groupName);
if (groupNum == 0) {
// Name not defined by pattern.
*status = U_REGEX_INVALID_CAPTURE_GROUP_NAME;
}
} else {
// Character was something other than a name char or a closing '}'
*status = U_REGEX_INVALID_CAPTURE_GROUP_NAME;
}
}
} else {
// $ not followed by {name} or digits.
*status = U_REGEX_INVALID_CAPTURE_GROUP_NAME;
}
// Finally, append the capture group data to the destination.
if (U_SUCCESS(*status)) {
destIdx += uregex_group((URegularExpression*)regexp, groupNum,
dest==NULL?NULL:&dest[destIdx], REMAINING_CAPACITY(destIdx, capacity), status);
if (*status == U_BUFFER_OVERFLOW_ERROR) {
// Ignore buffer overflow when extracting the group. We need to
// continue on to get full size of the untruncated result. We will
// raise our own buffer overflow error at the end.
*status = U_ZERO_ERROR;
}
}
if (U_FAILURE(*status)) {
// bad group number or name.
break;
}
}
//
// Nul Terminate the dest buffer if possible.
// Set the appropriate buffer overflow or not terminated error, if needed.
//
if (destIdx < capacity) {
dest[destIdx] = 0;
} else if (U_SUCCESS(*status)) {
if (destIdx == *destCapacity) {
*status = U_STRING_NOT_TERMINATED_WARNING;
} else {
*status = U_BUFFER_OVERFLOW_ERROR;
}
}
//
// Return an updated dest buffer and capacity to the caller.
//
if (destIdx > 0 && *destCapacity > 0) {
if (destIdx < capacity) {
*destBuf += destIdx;
*destCapacity -= destIdx;
} else {
*destBuf += capacity;
*destCapacity = 0;
}
}
// If we came in with a buffer overflow, make sure we go out with one also.
// (A zero length match right at the end of the previous match could
// make this function succeed even though a previous call had overflowed the buf)
if (pendingBufferOverflow && U_SUCCESS(*status)) {
*status = U_BUFFER_OVERFLOW_ERROR;
}
return destIdx;
}
//
// appendReplacement the actual API function,
//
U_CAPI int32_t U_EXPORT2
uregex_appendReplacement(URegularExpression *regexp2,
const UChar *replacementText,
int32_t replacementLength,
UChar **destBuf,
int32_t *destCapacity,
UErrorCode *status) {
RegularExpression *regexp = (RegularExpression*)regexp2;
return RegexCImpl::appendReplacement(
regexp, replacementText, replacementLength,destBuf, destCapacity, status);
}
//
// uregex_appendReplacementUText...can just use the normal C++ method
//
U_CAPI void U_EXPORT2
uregex_appendReplacementUText(URegularExpression *regexp2,
UText *replText,
UText *dest,
UErrorCode *status) {
RegularExpression *regexp = (RegularExpression*)regexp2;
regexp->fMatcher->appendReplacement(dest, replText, *status);
}
//------------------------------------------------------------------------------
//
// uregex_appendTail
//
//------------------------------------------------------------------------------
int32_t RegexCImpl::appendTail(RegularExpression *regexp,
UChar **destBuf,
int32_t *destCapacity,
UErrorCode *status)
{
// If we come in with a buffer overflow error, don't suppress the operation.
// A series of appendReplacements, appendTail need to correctly preflight
// the buffer size when an overflow happens somewhere in the middle.
UBool pendingBufferOverflow = FALSE;
if (*status == U_BUFFER_OVERFLOW_ERROR && destCapacity != NULL && *destCapacity == 0) {
pendingBufferOverflow = TRUE;
*status = U_ZERO_ERROR;
}
if (validateRE(regexp, TRUE, status) == FALSE) {
return 0;
}
if (destCapacity == NULL || destBuf == NULL ||
(*destBuf == NULL && *destCapacity > 0) ||
*destCapacity < 0)
{
*status = U_ILLEGAL_ARGUMENT_ERROR;
return 0;
}
RegexMatcher *m = regexp->fMatcher;
int32_t destIdx = 0;
int32_t destCap = *destCapacity;
UChar *dest = *destBuf;
if (regexp->fText != NULL) {
int32_t srcIdx;
int64_t nativeIdx = (m->fMatch ? m->fMatchEnd : m->fLastMatchEnd);
if (nativeIdx == -1) {
srcIdx = 0;
} else if (UTEXT_USES_U16(m->fInputText)) {
srcIdx = (int32_t)nativeIdx;
} else {
UErrorCode newStatus = U_ZERO_ERROR;
srcIdx = utext_extract(m->fInputText, 0, nativeIdx, NULL, 0, &newStatus);
}
for (;;) {
U_ASSERT(destIdx >= 0);
if (srcIdx == regexp->fTextLength) {
break;
}
UChar c = regexp->fText[srcIdx];
if (c == 0 && regexp->fTextLength == -1) {
regexp->fTextLength = srcIdx;
break;
}
if (destIdx < destCap) {
dest[destIdx] = c;
} else {
// We've overflowed the dest buffer.
// If the total input string length is known, we can
// compute the total buffer size needed without scanning through the string.
if (regexp->fTextLength > 0) {
destIdx += (regexp->fTextLength - srcIdx);
break;
}
}
srcIdx++;
destIdx++;
}
} else {
int64_t srcIdx;
if (m->fMatch) {
// The most recent call to find() succeeded.
srcIdx = m->fMatchEnd;
} else {
// The last call to find() on this matcher failed().
// Look back to the end of the last find() that succeeded for src index.
srcIdx = m->fLastMatchEnd;
if (srcIdx == -1) {
// There has been no successful match with this matcher.
// We want to copy the whole string.
srcIdx = 0;
}
}
destIdx = utext_extract(m->fInputText, srcIdx, m->fInputLength, dest, destCap, status);
}
//
// NUL terminate the output string, if possible, otherwise issue the
// appropriate error or warning.
//
if (destIdx < destCap) {
dest[destIdx] = 0;
} else if (destIdx == destCap) {
*status = U_STRING_NOT_TERMINATED_WARNING;
} else {
*status = U_BUFFER_OVERFLOW_ERROR;
}
//
// Update the user's buffer ptr and capacity vars to reflect the
// amount used.
//
if (destIdx < destCap) {
*destBuf += destIdx;
*destCapacity -= destIdx;
} else if (*destBuf != NULL) {
*destBuf += destCap;
*destCapacity = 0;
}
if (pendingBufferOverflow && U_SUCCESS(*status)) {
*status = U_BUFFER_OVERFLOW_ERROR;
}
return destIdx;
}
//
// appendTail the actual API function
//
U_CAPI int32_t U_EXPORT2
uregex_appendTail(URegularExpression *regexp2,
UChar **destBuf,
int32_t *destCapacity,
UErrorCode *status) {
RegularExpression *regexp = (RegularExpression*)regexp2;
return RegexCImpl::appendTail(regexp, destBuf, destCapacity, status);
}
//
// uregex_appendTailUText...can just use the normal C++ method
//
U_CAPI UText * U_EXPORT2
uregex_appendTailUText(URegularExpression *regexp2,
UText *dest,
UErrorCode *status) {
RegularExpression *regexp = (RegularExpression*)regexp2;
return regexp->fMatcher->appendTail(dest, *status);
}
//------------------------------------------------------------------------------
//
// copyString Internal utility to copy a string to an output buffer,
// while managing buffer overflow and preflight size
// computation. NUL termination is added to destination,
// and the NUL is counted in the output size.
//
//------------------------------------------------------------------------------
#if 0
static void copyString(UChar *destBuffer, // Destination buffer.
int32_t destCapacity, // Total capacity of dest buffer
int32_t *destIndex, // Index into dest buffer. Updated on return.
// Update not clipped to destCapacity.
const UChar *srcPtr, // Pointer to source string
int32_t srcLen) // Source string len.
{
int32_t si;
int32_t di = *destIndex;
UChar c;
for (si=0; si<srcLen; si++) {
c = srcPtr[si];
if (di < destCapacity) {
destBuffer[di] = c;
di++;
} else {
di += srcLen - si;
break;
}
}
if (di<destCapacity) {
destBuffer[di] = 0;
}
di++;
*destIndex = di;
}
#endif
//------------------------------------------------------------------------------
//
// uregex_split
//
//------------------------------------------------------------------------------
int32_t RegexCImpl::split(RegularExpression *regexp,
UChar *destBuf,
int32_t destCapacity,
int32_t *requiredCapacity,
UChar *destFields[],
int32_t destFieldsCapacity,
UErrorCode *status) {
//
// Reset for the input text
//
regexp->fMatcher->reset();
UText *inputText = regexp->fMatcher->fInputText;
int64_t nextOutputStringStart = 0;
int64_t inputLen = regexp->fMatcher->fInputLength;
if (inputLen == 0) {
return 0;
}
//
// Loop through the input text, searching for the delimiter pattern
//
int32_t i; // Index of the field being processed.
int32_t destIdx = 0; // Next available position in destBuf;
int32_t numCaptureGroups = regexp->fMatcher->groupCount();
UErrorCode tStatus = U_ZERO_ERROR; // Want to ignore any buffer overflow errors so that the strings are still counted
for (i=0; ; i++) {
if (i>=destFieldsCapacity-1) {
// There are one or zero output strings left.
// Fill the last output string with whatever is left from the input, then exit the loop.
// ( i will be == destFieldsCapacity if we filled the output array while processing
// capture groups of the delimiter expression, in which case we will discard the
// last capture group saved in favor of the unprocessed remainder of the
// input string.)
if (inputLen > nextOutputStringStart) {
if (i != destFieldsCapacity-1) {
// No fields are left. Recycle the last one for holding the trailing part of
// the input string.
i = destFieldsCapacity-1;
destIdx = (int32_t)(destFields[i] - destFields[0]);
}
destFields[i] = &destBuf[destIdx];
destIdx += 1 + utext_extract(inputText, nextOutputStringStart, inputLen,
&destBuf[destIdx], REMAINING_CAPACITY(destIdx, destCapacity), status);
}
break;
}
if (regexp->fMatcher->find()) {
// We found another delimiter. Move everything from where we started looking
// up until the start of the delimiter into the next output string.
destFields[i] = &destBuf[destIdx];
destIdx += 1 + utext_extract(inputText, nextOutputStringStart, regexp->fMatcher->fMatchStart,
&destBuf[destIdx], REMAINING_CAPACITY(destIdx, destCapacity), &tStatus);
if (tStatus == U_BUFFER_OVERFLOW_ERROR) {
tStatus = U_ZERO_ERROR;
} else {
*status = tStatus;
}
nextOutputStringStart = regexp->fMatcher->fMatchEnd;
// If the delimiter pattern has capturing parentheses, the captured
// text goes out into the next n destination strings.
int32_t groupNum;
for (groupNum=1; groupNum<=numCaptureGroups; groupNum++) {
// If we've run out of output string slots, bail out.
if (i==destFieldsCapacity-1) {
break;
}
i++;
// Set up to extract the capture group contents into the dest buffer.
destFields[i] = &destBuf[destIdx];
tStatus = U_ZERO_ERROR;
int32_t t = uregex_group((URegularExpression*)regexp,
groupNum,
destFields[i],
REMAINING_CAPACITY(destIdx, destCapacity),
&tStatus);
destIdx += t + 1; // Record the space used in the output string buffer.
// +1 for the NUL that terminates the string.
if (tStatus == U_BUFFER_OVERFLOW_ERROR) {
tStatus = U_ZERO_ERROR;
} else {
*status = tStatus;
}
}
if (nextOutputStringStart == inputLen) {
// The delimiter was at the end of the string.
// Output an empty string, and then we are done.
if (destIdx < destCapacity) {
destBuf[destIdx] = 0;
}
if (i < destFieldsCapacity-1) {
++i;
}
if (destIdx < destCapacity) {
destFields[i] = destBuf + destIdx;
}
++destIdx;
break;
}
}
else
{
// We ran off the end of the input while looking for the next delimiter.
// All the remaining text goes into the current output string.
destFields[i] = &destBuf[destIdx];
destIdx += 1 + utext_extract(inputText, nextOutputStringStart, inputLen,
&destBuf[destIdx], REMAINING_CAPACITY(destIdx, destCapacity), status);
break;
}
}
// Zero out any unused portion of the destFields array
int j;
for (j=i+1; j<destFieldsCapacity; j++) {
destFields[j] = NULL;
}
if (requiredCapacity != NULL) {
*requiredCapacity = destIdx;
}
if (destIdx > destCapacity) {
*status = U_BUFFER_OVERFLOW_ERROR;
}
return i+1;
}
//
// uregex_split The actual API function
//
U_CAPI int32_t U_EXPORT2
uregex_split(URegularExpression *regexp2,
UChar *destBuf,
int32_t destCapacity,
int32_t *requiredCapacity,
UChar *destFields[],
int32_t destFieldsCapacity,
UErrorCode *status) {
RegularExpression *regexp = (RegularExpression*)regexp2;
if (validateRE(regexp, TRUE, status) == FALSE) {
return 0;
}
if ((destBuf == NULL && destCapacity > 0) ||
destCapacity < 0 ||
destFields == NULL ||
destFieldsCapacity < 1 ) {
*status = U_ILLEGAL_ARGUMENT_ERROR;
return 0;
}
return RegexCImpl::split(regexp, destBuf, destCapacity, requiredCapacity, destFields, destFieldsCapacity, status);
}
//
// uregex_splitUText...can just use the normal C++ method
//
U_CAPI int32_t U_EXPORT2
uregex_splitUText(URegularExpression *regexp2,
UText *destFields[],
int32_t destFieldsCapacity,
UErrorCode *status) {
RegularExpression *regexp = (RegularExpression*)regexp2;
return regexp->fMatcher->split(regexp->fMatcher->inputText(), destFields, destFieldsCapacity, *status);
}
#endif // !UCONFIG_NO_REGULAR_EXPRESSIONS
|
class Solution {
public:
void merge(vector<int>& a, int m, vector<int>& b, int n) {
cin.tie(0);
cout.tie(0);
int i=0,j=0,r=0;
vector<int> v(m+n);
while(j<n && i<m)
if(a[i]<=b[j])
v[r++]=a[i++];
else
v[r++]=b[j++];
while(i<m)
v[r++]=a[i++];
while(j<n)
v[r++]=b[j++];
a=v;
}
};
|
// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin Core developers
// Copyright (c) 2014-2017 The Dash Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "noui.h"
#include "ui_interface.h"
#include "util.h"
#include <cstdio>
#include <stdint.h>
#include <string>
static bool noui_ThreadSafeMessageBox(const std::string& message, const std::string& caption, unsigned int style)
{
bool fSecure = style & CClientUIInterface::SECURE;
style &= ~CClientUIInterface::SECURE;
std::string strCaption;
// Check for usage of predefined caption
switch (style) {
case CClientUIInterface::MSG_ERROR:
strCaption += _("Error");
break;
case CClientUIInterface::MSG_WARNING:
strCaption += _("Warning");
break;
case CClientUIInterface::MSG_INFORMATION:
strCaption += _("Information");
break;
default:
strCaption += caption; // Use supplied caption (can be empty)
}
if (!fSecure)
LogPrintf("%s: %s\n", strCaption, message);
fprintf(stderr, "%s: %s\n", strCaption.c_str(), message.c_str());
return false;
}
static bool noui_ThreadSafeQuestion(const std::string& /* ignored interactive message */, const std::string& message, const std::string& caption, unsigned int style)
{
return noui_ThreadSafeMessageBox(message, caption, style);
}
static void noui_InitMessage(const std::string& message)
{
LogPrintf("init message: %s\n", message);
}
void noui_connect()
{
// Connect ruxcryptod signal handlers
uiInterface.ThreadSafeMessageBox.connect(noui_ThreadSafeMessageBox);
uiInterface.ThreadSafeQuestion.connect(noui_ThreadSafeQuestion);
uiInterface.InitMessage.connect(noui_InitMessage);
}
|
#include "Quest.h"
|
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
#include "tink/aead/internal/cord_aes_gcm_boringssl.h"
#include <string>
#include <vector>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "absl/strings/cord_test_helpers.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_split.h"
#include "openssl/err.h"
#include "include/rapidjson/document.h"
#include "tink/subtle/aes_gcm_boringssl.h"
#include "tink/subtle/wycheproof_util.h"
#include "tink/util/secret_data.h"
#include "tink/util/status.h"
#include "tink/util/statusor.h"
#include "tink/util/test_matchers.h"
#include "tink/util/test_util.h"
namespace crypto {
namespace tink {
using ::crypto::tink::test::IsOk;
using ::testing::Eq;
namespace {
TEST(CordAesGcmBoringSslTest, EncryptDecryptCord) {
util::SecretData key = util::SecretDataFromStringView(
test::HexDecodeOrDie("000102030405060708090a0b0c0d0e0f"));
auto res = CordAesGcmBoringSsl::New(key);
EXPECT_TRUE(res.ok()) << res.status();
auto cipher = std::move(res.ValueOrDie());
const std::string message = "Some data to encrypt.";
const std::string aad = "Some data to authenticate.";
absl::Cord message_cord = absl::Cord(message);
absl::Cord aad_cord = absl::Cord(aad);
auto ct = cipher->Encrypt(message_cord, aad_cord);
EXPECT_THAT(ct.status(), IsOk());
EXPECT_EQ(ct.ValueOrDie().size(), message_cord.size() + 12 + 16);
auto pt = cipher->Decrypt(ct.ValueOrDie(), aad_cord);
EXPECT_THAT(pt.status(), IsOk());
EXPECT_EQ(pt.ValueOrDie(), message_cord.Flatten());
}
TEST(CordAesGcmBoringSslTest, ChunkyCordEncrypt) {
util::SecretData key = util::SecretDataFromStringView(
test::HexDecodeOrDie("000102030405060708090a0b0c0d0e0f"));
auto res = CordAesGcmBoringSsl::New(key);
EXPECT_TRUE(res.ok()) << res.status();
auto cipher = std::move(res.ValueOrDie());
std::string message = "This is some long message which will be fragmented.";
const std::string aad = "Some data to authenticate.";
absl::Cord message_cord =
absl::MakeFragmentedCord(absl::StrSplit(message, absl::ByLength(3)));
absl::Cord aad_cord = absl::Cord(aad);
auto ct = cipher->Encrypt(message_cord, aad_cord);
ASSERT_THAT(ct.status(), IsOk());
EXPECT_EQ(ct.ValueOrDie().size(), message_cord.size() + 12 + 16);
auto pt = cipher->Decrypt(ct.ValueOrDie(), aad_cord);
ASSERT_THAT(pt.status(), IsOk());
EXPECT_THAT(pt.ValueOrDie(), Eq(message));
}
TEST(CordAesGcmBoringSslTest, ChunkyCordDecrypt) {
util::SecretData key = util::SecretDataFromStringView(
test::HexDecodeOrDie("000102030405060708090a0b0c0d0e0f"));
auto res = CordAesGcmBoringSsl::New(key);
EXPECT_TRUE(res.ok()) << res.status();
auto cipher = std::move(res.ValueOrDie());
std::string message = "This is some long message which will be fragmented.";
const std::string aad = "Some data to authenticate.";
absl::Cord message_cord = absl::Cord(message);
absl::Cord aad_cord = absl::Cord(aad);
auto ct = cipher->Encrypt(message_cord, aad_cord);
ASSERT_THAT(ct.status(), IsOk());
auto fragmented_ct = absl::MakeFragmentedCord(
absl::StrSplit(ct.ValueOrDie().Flatten(), absl::ByLength(3)));
auto pt = cipher->Decrypt(fragmented_ct, aad_cord);
ASSERT_THAT(pt.status(), IsOk());
EXPECT_THAT(pt.ValueOrDie(), Eq(message));
}
TEST(CordAesGcmBoringSslTest, SameResultAsString) {
util::SecretData key = util::SecretDataFromStringView(
test::HexDecodeOrDie("000102030405060708090a0b0c0d0e0f"));
auto res = CordAesGcmBoringSsl::New(key);
EXPECT_TRUE(res.ok()) << res.status();
auto cipher = std::move(res.ValueOrDie());
const std::string message = "Some data to encrypt.";
const std::string aad = "Some data to authenticate.";
absl::Cord message_cord = absl::Cord(message);
absl::Cord aad_cord = absl::Cord(aad);
auto ct = cipher->Encrypt(message_cord, aad_cord);
ASSERT_THAT(ct.status(), IsOk());
EXPECT_EQ(ct.ValueOrDie().size(), message_cord.size() + 12 + 16);
auto pt = cipher->Decrypt(ct.ValueOrDie(), aad_cord);
ASSERT_THAT(pt.status(), IsOk());
EXPECT_EQ(pt.ValueOrDie(), message_cord.Flatten());
// Decrypt as string and check if it gives same result
auto res_string = subtle::AesGcmBoringSsl::New(key);
ASSERT_THAT(res_string.status(), IsOk());
auto cipher_string = std::move(res_string.ValueOrDie());
auto pt_string =
cipher_string->Decrypt(ct.ValueOrDie().Flatten(), aad_cord.Flatten());
ASSERT_THAT(pt.status(), IsOk());
EXPECT_EQ(pt.ValueOrDie(), message);
}
TEST(CordAesGcmBoringSslTest, ModifiedCord) {
util::SecretData key = util::SecretDataFromStringView(
test::HexDecodeOrDie("000102030405060708090a0b0c0d0e0f"));
auto cipher = std::move(CordAesGcmBoringSsl::New(key).ValueOrDie());
absl::Cord message = absl::Cord("Some data to encrypt.");
absl::Cord aad = absl::Cord("Some data to authenticate.");
absl::Cord ct = cipher->Encrypt(message, aad).ValueOrDie();
EXPECT_TRUE(cipher->Decrypt(ct, aad).ok());
// Modify the ciphertext
for (size_t i = 0; i < ct.size() * 8; i++) {
std::string modified_ct = std::string(ct.Flatten());
modified_ct[i / 8] ^= 1 << (i % 8);
absl::Cord modified_ct_cord;
modified_ct_cord = absl::Cord(modified_ct);
EXPECT_FALSE(cipher->Decrypt(modified_ct_cord, aad).ok()) << i;
}
// Modify the additional data
for (size_t i = 0; i < aad.size() * 8; i++) {
std::string modified_aad = std::string(aad.Flatten());
modified_aad[i / 8] ^= 1 << (i % 8);
absl::Cord modified_aad_cord;
modified_aad_cord = absl::Cord(modified_aad);
auto decrypted = cipher->Decrypt(ct, modified_aad_cord);
EXPECT_FALSE(decrypted.ok()) << i << " pt:" << decrypted.ValueOrDie();
}
// Truncate the ciphertext
for (size_t i = 0; i < ct.size(); i++) {
std::string truncated_ct(std::string(ct.Flatten()), 0, i);
absl::Cord truncated_ct_cord;
truncated_ct_cord = absl::Cord(truncated_ct);
EXPECT_FALSE(cipher->Decrypt(truncated_ct_cord, aad).ok()) << i;
}
}
static std::string GetError() {
auto err = ERR_peek_last_error();
// Sometimes there is no error message on the stack.
if (err == 0) {
return "";
}
std::string lib(ERR_lib_error_string(err));
std::string func(ERR_func_error_string(err));
std::string reason(ERR_reason_error_string(err));
return lib + ":" + func + ":" + reason;
}
// Test with test vectors from Wycheproof project.
bool WycheproofTest(const rapidjson::Document& root) {
int errors = 0;
for (const rapidjson::Value& test_group : root["testGroups"].GetArray()) {
const size_t iv_size = test_group["ivSize"].GetInt();
const size_t key_size = test_group["keySize"].GetInt();
const size_t tag_size = test_group["tagSize"].GetInt();
// CordAesGcmBoringSsl only supports 12-byte IVs and 16-byte authentication
// tag. Also 24-byte keys are not supported.
if (iv_size != 96 || tag_size != 128 || key_size == 192) {
// Not supported
continue;
}
for (const rapidjson::Value& test : test_group["tests"].GetArray()) {
std::string comment = test["comment"].GetString();
std::string key = subtle::WycheproofUtil::GetBytes(test["key"]);
std::string iv = subtle::WycheproofUtil::GetBytes(test["iv"]);
std::string msg = subtle::WycheproofUtil::GetBytes(test["msg"]);
std::string ct = subtle::WycheproofUtil::GetBytes(test["ct"]);
std::string aad = subtle::WycheproofUtil::GetBytes(test["aad"]);
std::string tag = subtle::WycheproofUtil::GetBytes(test["tag"]);
std::string id = absl::StrCat(test["tcId"].GetInt());
std::string expected = test["result"].GetString();
auto cipher = std::move(
CordAesGcmBoringSsl::New(util::SecretDataFromStringView(key))
.ValueOrDie());
// Convert to cord
absl::Cord ct_cord = absl::Cord(iv + ct + tag);
absl::Cord aad_cord = absl::Cord(aad);
auto result = cipher->Decrypt(ct_cord, aad_cord);
bool success = result.ok();
if (success) {
std::string decrypted = std::string(result.ValueOrDie().Flatten());
if (expected == "invalid") {
ADD_FAILURE() << "decrypted invalid ciphertext:" << id;
errors++;
} else if (msg != decrypted) {
ADD_FAILURE() << "Incorrect decryption:" << id;
errors++;
}
} else {
if (expected == "valid" || expected == "acceptable") {
ADD_FAILURE() << "Could not decrypt test with tcId:" << id
<< " iv_size:" << iv_size << " tag_size:" << tag_size
<< " key_size:" << key_size << " error:" << GetError();
errors++;
}
}
}
}
return errors == 0;
}
TEST(CordAesGcmBoringSslTest, TestVectors) {
std::unique_ptr<rapidjson::Document> root =
subtle::WycheproofUtil::ReadTestVectors("aes_gcm_test.json");
ASSERT_TRUE(WycheproofTest(*root));
}
} // namespace
} // namespace tink
} // namespace crypto
|
/*=============================================================================
Copyright (c) 2001-2006 Joel de Guzman
Copyright (c) 2006 Dan Marsden
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
==============================================================================*/
#ifndef BOOST_PP_IS_ITERATING
#if !defined(FUSION_ZIP_HPP_20060125_2058)
#define FUSION_ZIP_HPP_20060125_2058
#include <boost/fusion/view/zip_view.hpp>
#include <boost/fusion/adapted/mpl.hpp>
#include <boost/fusion/container/vector.hpp>
#include <boost/fusion/container/vector/convert.hpp>
#include <boost/type_traits/add_reference.hpp>
#include <boost/preprocessor/repetition/enum.hpp>
#include <boost/preprocessor/repetition/enum_params.hpp>
#include <boost/preprocessor/repetition/enum_binary_params.hpp>
#include <boost/preprocessor/repetition/repeat_from_to.hpp>
#include <boost/preprocessor/arithmetic/inc.hpp>
#include <boost/preprocessor/iteration/iterate.hpp>
#include <boost/mpl/vector.hpp>
#include <boost/mpl/transform.hpp>
#include <boost/mpl/placeholders.hpp>
#if !defined(FUSION_MAX_ZIP_SEQUENCES)
#define FUSION_MAX_ZIP_SEQUENCES 10
#endif
namespace boost { namespace fusion {
struct void_;
namespace result_of
{
template<BOOST_PP_ENUM_PARAMS_WITH_A_DEFAULT(BOOST_PP_INC(FUSION_MAX_ZIP_SEQUENCES), typename T, fusion::void_)>
struct zip;
}
#define BOOST_PP_FILENAME_1 \
<boost/fusion/algorithm/transformation/zip.hpp>
#define BOOST_PP_ITERATION_LIMITS (2, FUSION_MAX_ZIP_SEQUENCES)
#include BOOST_PP_ITERATE()
}}
#endif
#else
#define ZIP_ITERATION BOOST_PP_ITERATION()
namespace result_of
{
template< BOOST_PP_ENUM_PARAMS(ZIP_ITERATION, typename T) >
#if defined(BOOST_NO_PARTIAL_SPECIALIZATION_IMPLICIT_DEFAULT_ARGS)
#define TEXT(z, n, text) , text
struct zip< BOOST_PP_ENUM_PARAMS(ZIP_ITERATION, T) BOOST_PP_REPEAT_FROM_TO(BOOST_PP_DEC(ZIP_ITERATION), FUSION_MAX_ZIP_SEQUENCES, TEXT, void_) >
#undef TEXT
#else
struct zip< BOOST_PP_ENUM_PARAMS(ZIP_ITERATION, T) >
#endif
{
typedef mpl::vector< BOOST_PP_ENUM_PARAMS(ZIP_ITERATION, T) > sequences;
typedef typename mpl::transform<sequences, add_reference<mpl::_> >::type ref_params;
typedef zip_view<typename result_of::as_vector<ref_params>::type> type;
};
}
#define FUSION_REF_PARAM(z, n, data) const T ## n&
template<BOOST_PP_ENUM_PARAMS(ZIP_ITERATION, typename T)>
inline typename result_of::zip<BOOST_PP_ENUM_PARAMS(ZIP_ITERATION, const T)>::type
zip(BOOST_PP_ENUM_BINARY_PARAMS(ZIP_ITERATION, T, const& t))
{
fusion::vector<BOOST_PP_ENUM(ZIP_ITERATION, FUSION_REF_PARAM, _)> seqs(
BOOST_PP_ENUM_PARAMS(ZIP_ITERATION, t));
return typename result_of::zip<BOOST_PP_ENUM_PARAMS(ZIP_ITERATION, const T)>::type(
seqs);
}
#undef FUSION_REF_PARAM
#undef ZIP_ITERATION
#endif
|
/**
* @file LoRaPHYCN779.cpp
*
* @brief Implements LoRaPHY for Chinese 779 MHz band
*
* \code
* ______ _
* / _____) _ | |
* ( (____ _____ ____ _| |_ _____ ____| |__
* \____ \| ___ | (_ _) ___ |/ ___) _ \
* _____) ) ____| | | || |_| ____( (___| | | |
* (______/|_____)_|_|_| \__)_____)\____)_| |_|
* (C)2013 Semtech
* ___ _____ _ ___ _ _____ ___ ___ ___ ___
* / __|_ _/_\ / __| |/ / __/ _ \| _ \/ __| __|
* \__ \ | |/ _ \ (__| ' <| _| (_) | / (__| _|
* |___/ |_/_/ \_\___|_|\_\_| \___/|_|_\\___|___|
* embedded.connectivity.solutions===============
*
* \endcode
*
*
* License: Revised BSD License, see LICENSE.TXT file include in the project
*
* Maintainer: Miguel Luis ( Semtech ), Gregory Cristian ( Semtech ) and Daniel Jaeckle ( STACKFORCE )
*
* Copyright (c) 2017, Arm Limited and affiliates.
* SPDX-License-Identifier: BSD-3-Clause
*
*/
#include "LoRaPHYCN779.h"
#include "lora_phy_ds.h"
/*!
* Number of default channels
*/
#define CN779_NUMB_DEFAULT_CHANNELS 3
/*!
* Number of channels to apply for the CF list
*/
#define CN779_NUMB_CHANNELS_CF_LIST 5
/*!
* Minimal datarate that can be used by the node
*/
#define CN779_TX_MIN_DATARATE DR_0
/*!
* Maximal datarate that can be used by the node
*/
#define CN779_TX_MAX_DATARATE DR_7
/*!
* Minimal datarate that can be used by the node
*/
#define CN779_RX_MIN_DATARATE DR_0
/*!
* Maximal datarate that can be used by the node
*/
#define CN779_RX_MAX_DATARATE DR_7
#define CN779_DEFAULT_MAX_DATARATE DR_5
/*!
* Default datarate used by the node
*/
#define CN779_DEFAULT_DATARATE DR_0
/*!
* Minimal Rx1 receive datarate offset
*/
#define CN779_MIN_RX1_DR_OFFSET 0
/*!
* Maximal Rx1 receive datarate offset
*/
#define CN779_MAX_RX1_DR_OFFSET 5
/*!
* Default Rx1 receive datarate offset
*/
#define CN779_DEFAULT_RX1_DR_OFFSET 0
/*!
* Minimal Tx output power that can be used by the node
*/
#define CN779_MIN_TX_POWER TX_POWER_5
/*!
* Maximal Tx output power that can be used by the node
*/
#define CN779_MAX_TX_POWER TX_POWER_0
/*!
* Default Tx output power used by the node
*/
#define CN779_DEFAULT_TX_POWER TX_POWER_0
/*!
* Default Max EIRP
*/
#define CN779_DEFAULT_MAX_EIRP 12.15f
/*!
* Default antenna gain
*/
#define CN779_DEFAULT_ANTENNA_GAIN 2.15f
/*!
* ADR Ack limit
*/
#define CN779_ADR_ACK_LIMIT 64
/*!
* ADR Ack delay
*/
#define CN779_ADR_ACK_DELAY 32
/*!
* Enabled or disabled the duty cycle
*/
#define CN779_DUTY_CYCLE_ENABLED 1
/*!
* Maximum RX window duration
*/
#define CN779_MAX_RX_WINDOW 3000
/*!
* Receive delay 1
*/
#define CN779_RECEIVE_DELAY1 1000
/*!
* Receive delay 2
*/
#define CN779_RECEIVE_DELAY2 2000
/*!
* Join accept delay 1
*/
#define CN779_JOIN_ACCEPT_DELAY1 5000
/*!
* Join accept delay 2
*/
#define CN779_JOIN_ACCEPT_DELAY2 6000
/*!
* Maximum frame counter gap
*/
#define CN779_MAX_FCNT_GAP 16384
/*!
* Ack timeout
*/
#define CN779_ACKTIMEOUT 2000
/*!
* Random ack timeout limits
*/
#define CN779_ACK_TIMEOUT_RND 1000
/*!
* Verification of default datarate
*/
#if ( CN779_DEFAULT_DATARATE > DR_5 )
#error "A default DR higher than DR_5 may lead to connectivity loss."
#endif
/*!
* Second reception window channel frequency definition.
*/
#define CN779_RX_WND_2_FREQ 786000000
/*!
* Second reception window channel datarate definition.
*/
#define CN779_RX_WND_2_DR DR_0
/*!
* Band 0 definition
* { DutyCycle, TxMaxPower, LastJoinTxDoneTime, LastTxDoneTime, TimeOff }
*/
static const band_t CN779_BAND0 = {100, CN779_MAX_TX_POWER, 0, 0, 0, 779500000, 786500000}; // 1.0 %
/*!
* LoRaMac default channel 1
* Channel = { Frequency [Hz], RX1 Frequency [Hz], { ( ( DrMax << 4 ) | DrMin ) }, Band }
*/
static const channel_params_t CN779_LC1 = {779500000, 0, { ( ( DR_5 << 4 ) | DR_0 ) }, 0};
/*!
* LoRaMac default channel 2
* Channel = { Frequency [Hz], RX1 Frequency [Hz], { ( ( DrMax << 4 ) | DrMin ) }, Band }
*/
static const channel_params_t CN779_LC2 = {779700000, 0, { ( ( DR_5 << 4 ) | DR_0 ) }, 0};
/*!
* LoRaMac default channel 3
* Channel = { Frequency [Hz], RX1 Frequency [Hz], { ( ( DrMax << 4 ) | DrMin ) }, Band }
*/
static const channel_params_t CN779_LC3 = {779900000, 0, { ( ( DR_5 << 4 ) | DR_0 ) }, 0};
/*!
* LoRaMac channels which are allowed for the join procedure
*/
#define CN779_JOIN_CHANNELS (uint16_t) (LC(1) | LC(2) | LC(3))
/*!
* Data rates table definition
*/
static const uint8_t datarates_CN779[] = {12, 11, 10, 9, 8, 7, 7, 50};
/*!
* Bandwidths table definition in Hz
*/
static const uint32_t bandwidths_CN779[] = {125000, 125000, 125000, 125000, 125000, 125000, 250000, 0};
/*!
* Maximum payload with respect to the datarate index. Cannot operate with repeater.
*/
static const uint8_t max_payloads_CN779[] = {51, 51, 51, 115, 242, 242, 242, 242};
/*!
* Maximum payload with respect to the datarate index. Can operate with repeater.
*/
static const uint8_t max_payloads_with_repeater_CN779[] = {51, 51, 51, 115, 222, 222, 222, 222};
LoRaPHYCN779::LoRaPHYCN779()
{
bands[0] = CN779_BAND0;
// Channels
channels[0] = CN779_LC1;
channels[0].band = 0;
channels[1] = CN779_LC2;
channels[1].band = 0;
channels[2] = CN779_LC3;
channels[2].band = 0;
// Initialize the channels default mask
default_channel_mask[0] = LC(1) + LC(2) + LC(3);
// Update the channels mask
copy_channel_mask(channel_mask, default_channel_mask, CN779_CHANNEL_MASK_SIZE);
// set default channels
phy_params.channels.channel_list = channels;
phy_params.channels.channel_list_size = CN779_MAX_NB_CHANNELS;
phy_params.channels.mask = channel_mask;
phy_params.channels.default_mask = default_channel_mask;
phy_params.channels.mask_size = CN779_CHANNEL_MASK_SIZE;
// set bands for CN779 spectrum
phy_params.bands.table = bands;
phy_params.bands.size = CN779_MAX_NB_BANDS;
// set bandwidths available in CN779 spectrum
phy_params.bandwidths.table = (void *) bandwidths_CN779;
phy_params.bandwidths.size = 8;
// set data rates available in CN779 spectrum
phy_params.datarates.table = (void *) datarates_CN779;
phy_params.datarates.size = 8;
// set payload sizes with respect to data rates
phy_params.payloads.table = (void *) max_payloads_CN779;
phy_params.payloads.size = 8;
phy_params.payloads_with_repeater.table = (void *) max_payloads_with_repeater_CN779;
phy_params.payloads_with_repeater.size = 8;
// dwell time setting
phy_params.ul_dwell_time_setting = 0;
phy_params.dl_dwell_time_setting = 0;
// set initial and default parameters
phy_params.duty_cycle_enabled = CN779_DUTY_CYCLE_ENABLED;
phy_params.accept_tx_param_setup_req = false;
phy_params.fsk_supported = true;
phy_params.cflist_supported = true;
phy_params.dl_channel_req_supported = true;
phy_params.custom_channelplans_supported = true;
phy_params.default_channel_cnt = CN779_NUMB_DEFAULT_CHANNELS;
phy_params.max_channel_cnt = CN779_MAX_NB_CHANNELS;
phy_params.cflist_channel_cnt = CN779_NUMB_CHANNELS_CF_LIST;
phy_params.min_tx_datarate = CN779_TX_MIN_DATARATE;
phy_params.max_tx_datarate = CN779_TX_MAX_DATARATE;
phy_params.min_rx_datarate = CN779_RX_MIN_DATARATE;
phy_params.max_rx_datarate = CN779_RX_MAX_DATARATE;
phy_params.default_datarate = CN779_DEFAULT_DATARATE;
phy_params.default_max_datarate = CN779_DEFAULT_MAX_DATARATE;
phy_params.min_rx1_dr_offset = CN779_MIN_RX1_DR_OFFSET;
phy_params.max_rx1_dr_offset = CN779_MAX_RX1_DR_OFFSET;
phy_params.default_rx1_dr_offset = CN779_DEFAULT_RX1_DR_OFFSET;
phy_params.min_tx_power = CN779_MIN_TX_POWER;
phy_params.max_tx_power = CN779_MAX_TX_POWER;
phy_params.default_tx_power = CN779_DEFAULT_TX_POWER;
phy_params.default_max_eirp = CN779_DEFAULT_MAX_EIRP;
phy_params.default_antenna_gain = CN779_DEFAULT_ANTENNA_GAIN;
phy_params.adr_ack_limit = CN779_ADR_ACK_LIMIT;
phy_params.adr_ack_delay = CN779_ADR_ACK_DELAY;
phy_params.max_rx_window = CN779_MAX_RX_WINDOW;
phy_params.recv_delay1 = CN779_RECEIVE_DELAY1;
phy_params.recv_delay2 = CN779_RECEIVE_DELAY2;
phy_params.join_channel_mask = CN779_JOIN_CHANNELS;
phy_params.join_accept_delay1 = CN779_JOIN_ACCEPT_DELAY1;
phy_params.join_accept_delay2 = CN779_JOIN_ACCEPT_DELAY2;
phy_params.max_fcnt_gap = CN779_MAX_FCNT_GAP;
phy_params.ack_timeout = CN779_ACKTIMEOUT;
phy_params.ack_timeout_rnd = CN779_ACK_TIMEOUT_RND;
phy_params.rx_window2_datarate = CN779_RX_WND_2_DR;
phy_params.rx_window2_frequency = CN779_RX_WND_2_FREQ;
}
LoRaPHYCN779::~LoRaPHYCN779()
{
}
|
#include <mbgl/annotation/render_annotation_source.hpp>
#include <mbgl/annotation/annotation_tile.hpp>
#include <mbgl/renderer/render_tile.hpp>
#include <mbgl/renderer/paint_parameters.hpp>
#include <mbgl/algorithm/generate_clip_ids.hpp>
#include <mbgl/algorithm/generate_clip_ids_impl.hpp>
#include <mbgl/layermanager/layer_manager.hpp>
namespace mbgl {
using namespace style;
RenderAnnotationSource::RenderAnnotationSource(Immutable<AnnotationSource::Impl> impl_)
: RenderSource(impl_) {
assert(LayerManager::annotationsEnabled);
tilePyramid.setObserver(this);
}
const AnnotationSource::Impl& RenderAnnotationSource::impl() const {
return static_cast<const AnnotationSource::Impl&>(*baseImpl);
}
bool RenderAnnotationSource::isLoaded() const {
return tilePyramid.isLoaded();
}
void RenderAnnotationSource::update(Immutable<style::Source::Impl> baseImpl_,
const std::vector<Immutable<style::LayerProperties>>& layers,
const bool needsRendering,
const bool needsRelayout,
const TileParameters& parameters) {
std::swap(baseImpl, baseImpl_);
enabled = needsRendering;
tilePyramid.update(layers,
needsRendering,
needsRelayout,
parameters,
SourceType::Annotations,
util::tileSize,
// Zoom level 16 is typically sufficient for annotations.
// See https://github.com/mapbox/mapbox-gl-native/issues/10197
{ 0, 16 },
optional<LatLngBounds> {},
[&] (const OverscaledTileID& tileID) {
return std::make_unique<AnnotationTile>(tileID, parameters);
});
}
void RenderAnnotationSource::startRender(PaintParameters& parameters) {
parameters.clipIDGenerator.update(tilePyramid.getRenderTiles());
tilePyramid.startRender(parameters);
}
void RenderAnnotationSource::finishRender(PaintParameters& parameters) {
tilePyramid.finishRender(parameters);
}
std::vector<std::reference_wrapper<RenderTile>> RenderAnnotationSource::getRenderTiles() {
return tilePyramid.getRenderTiles();
}
std::unordered_map<std::string, std::vector<Feature>>
RenderAnnotationSource::queryRenderedFeatures(const ScreenLineString& geometry,
const TransformState& transformState,
const std::vector<const RenderLayer*>& layers,
const RenderedQueryOptions& options,
const mat4& projMatrix) const {
return tilePyramid.queryRenderedFeatures(geometry, transformState, layers, options, projMatrix);
}
std::vector<Feature> RenderAnnotationSource::querySourceFeatures(const SourceQueryOptions&) const {
return {};
}
void RenderAnnotationSource::reduceMemoryUse() {
tilePyramid.reduceMemoryUse();
}
void RenderAnnotationSource::dumpDebugLogs() const {
tilePyramid.dumpDebugLogs();
}
} // namespace mbgl
|
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/app_list/start_page_service_factory.h"
#include "base/command_line.h"
#include "chrome/browser/extensions/install_tracker_factory.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/app_list/start_page_service.h"
#include "chrome/common/chrome_switches.h"
#include "components/keyed_service/content/browser_context_dependency_manager.h"
#include "extensions/browser/extension_system_provider.h"
#include "extensions/browser/extensions_browser_client.h"
#include "ui/app_list/app_list_switches.h"
namespace app_list {
// static
StartPageService* StartPageServiceFactory::GetForProfile(Profile* profile) {
if (!app_list::switches::IsExperimentalAppListEnabled() &&
!app_list::switches::IsVoiceSearchEnabled()) {
return NULL;
}
return static_cast<StartPageService*>(
GetInstance()->GetServiceForBrowserContext(profile, true));
}
// static
StartPageServiceFactory* StartPageServiceFactory::GetInstance() {
return Singleton<StartPageServiceFactory>::get();
}
StartPageServiceFactory::StartPageServiceFactory()
: BrowserContextKeyedServiceFactory(
"AppListStartPageService",
BrowserContextDependencyManager::GetInstance()) {
DependsOn(
extensions::ExtensionsBrowserClient::Get()->GetExtensionSystemFactory());
DependsOn(extensions::InstallTrackerFactory::GetInstance());
}
StartPageServiceFactory::~StartPageServiceFactory() {}
KeyedService* StartPageServiceFactory::BuildServiceInstanceFor(
content::BrowserContext* context) const {
Profile* profile = static_cast<Profile*>(context);
return new StartPageService(profile);
}
} // namespace app_list
|
#define BIORBD_API_EXPORTS
#include "s2mMuscles.h"
#include "s2mMuscle.h"
#include "s2mError.h"
#include "s2mGroupeMusculaire.h"
#include "s2mGenCoord.h"
#include "s2mTau.h"
#include "s2mMuscleStateDynamics.h"
#include "s2mMuscleForce.h"
s2mMuscles::s2mMuscles(){
}
s2mMuscles::~s2mMuscles(){
}
void s2mMuscles::addMuscleGroup(const s2mString &name, const s2mString &originName, const s2mString &insertionName){
if (m_mus.size() > 0)
s2mError::s2mAssert(getGroupId(name)==-1, "Muscle group already defined");
m_mus.push_back(s2mGroupeMusculaire(name, originName, insertionName));
}
int s2mMuscles::getGroupId(const s2mString &name) const{
for (unsigned int i=0; i<m_mus.size(); ++i)
if (!name.compare(m_mus[i].name()))
return static_cast<int>(i);
return -1;
}
s2mGroupeMusculaire &s2mMuscles::muscleGroup_nonConst(unsigned int idx)
{
s2mError::s2mAssert(idx<nbMuscleGroups(), "Idx asked is higher than number of muscle groups");
return m_mus[idx];
}
const s2mGroupeMusculaire &s2mMuscles::muscleGroup(unsigned int idx) const{
s2mError::s2mAssert(idx<nbMuscleGroups(), "Idx asked is higher than number of muscle groups");
return m_mus[idx];
}
const s2mGroupeMusculaire &s2mMuscles::muscleGroup(const s2mString& name) const{
int idx = getGroupId(name);
s2mError::s2mAssert(idx!=-1, "Group name could not be found");
return muscleGroup(static_cast<unsigned int>(idx));
}
// From muscle activation (return muscle force)
s2mTau s2mMuscles::muscularJointTorque(s2mJoints& m, const std::vector<s2mMuscleStateDynamics> &state, Eigen::VectorXd & F, bool updateKin, const s2mGenCoord* Q, const s2mGenCoord* QDot){
// Update de la position musculaire
if (updateKin > 0)
updateMuscles(m,*Q,*QDot,updateKin);
std::vector<std::vector<std::shared_ptr<s2mMuscleForce>>> force_tp = musclesForces(m, state, false);
F = Eigen::VectorXd::Zero(static_cast<unsigned int>(force_tp.size()));
for (unsigned int i=0; i<force_tp.size(); ++i)
F(i) = (force_tp[i])[0]->norme();
return muscularJointTorque(m, F, false, Q, QDot);
}
// From muscle activation (do not return muscle force)
s2mTau s2mMuscles::muscularJointTorque(s2mJoints& m, const std::vector<s2mMuscleStateDynamics>& state, bool updateKin, const s2mGenCoord* Q, const s2mGenCoord* QDot){
s2mGenCoord dummy;
return muscularJointTorque(m, state, dummy, updateKin, Q, QDot);
}
// From Muscular Force
s2mTau s2mMuscles::muscularJointTorque(s2mJoints& m, const Eigen::VectorXd& F, bool updateKin, const s2mGenCoord* Q, const s2mGenCoord* QDot){
// Update de la position musculaire
if (updateKin > 0)
updateMuscles(m,*Q,*QDot,updateKin);
// Récupérer la matrice jacobienne et
// récupérer les forces de chaque muscles
s2mMatrix jaco(musclesLengthJacobian(m));
// Calcul de la réaction des forces sur les corps
return s2mTau(-jaco.transpose() * F);
}
std::vector<std::vector<std::shared_ptr<s2mMuscleForce>>> s2mMuscles::musclesForces(s2mJoints& m, const std::vector<s2mMuscleStateDynamics> &state, bool updateKin, const s2mGenCoord* Q, const s2mGenCoord* QDot){
// Update de la position musculaire
if (updateKin > 0)
updateMuscles(m,*Q,*QDot,updateKin);
// Variable de sortie
std::vector<std::vector<std::shared_ptr<s2mMuscleForce>>> forces; // Tous les muscles/Deux pointeurs par muscles (origine/insertion)
unsigned int cmpMus(0);
std::vector<s2mGroupeMusculaire>::iterator grp=m_mus.begin();
for (unsigned int i=0; i<m_mus.size(); ++i) // groupe musculaire
for (unsigned int j=0; j<(*(grp+i)).nbMuscles(); ++j){
// forces musculaire
forces.push_back((*(grp+i)).muscle(j)->force(*(state.begin()+cmpMus)));
cmpMus++;
}
// Les forces
return forces;
}
unsigned int s2mMuscles::nbMuscleGroups() const {
return static_cast<unsigned int>(m_mus.size());
}
s2mMatrix s2mMuscles::musclesLengthJacobian(s2mJoints &m)
{
s2mMatrix tp(s2mMatrix::Zero(nbMuscleTotal(), m.nbDof()));
unsigned int cmpMus(0);
for (unsigned int i=0; i<nbMuscleGroups(); ++i){ // groupe musculaire
for (unsigned int j=0; j<(m_mus[i]).nbMuscles(); ++j){
// forces musculaire
tp.block(cmpMus,0,1,m.nbDof()) = (m_mus[i]).muscle(j)->position().jacobianLength();
++cmpMus;
}
}
return tp;
}
s2mMatrix s2mMuscles::musclesLengthJacobian(s2mJoints& m, const s2mGenCoord &Q){
// Update de la position musculaire
updateMuscles(m, Q, true);
return musclesLengthJacobian(m);
}
unsigned int s2mMuscles::nbMuscleTotal() const{
unsigned int total(0);
for (unsigned int grp=0; grp<m_mus.size(); ++grp) // groupe musculaire
total += m_mus[grp].nbMuscles();
return total;
}
void s2mMuscles::updateMuscles(s2mJoints& m, const s2mGenCoord& Q, const s2mGenCoord& QDot, bool updateKin){
// Updater tous les muscles
int updateKinTP;
if (updateKin)
updateKinTP = 2;
else
updateKinTP = 0;
std::vector<s2mGroupeMusculaire>::iterator grp=m_mus.begin();
for (unsigned int i=0; i<m_mus.size(); ++i) // groupe musculaire
for (unsigned int j=0; j<(*(grp+i)).nbMuscles(); ++j){
(*(grp+i)).muscle(j)->updateOrientations(m, Q, QDot, updateKinTP);
updateKinTP=1;
}
}
void s2mMuscles::updateMuscles(s2mJoints& m, const s2mGenCoord& Q, bool updateKin){
// Updater tous les muscles
int updateKinTP;
if (updateKin)
updateKinTP = 2;
else
updateKinTP = 0;
// Updater tous les muscles
std::vector<s2mGroupeMusculaire>::iterator grp=m_mus.begin();
for (unsigned int i=0; i<m_mus.size(); ++i) // groupe musculaire
for (unsigned int j=0; j<(*(grp+i)).nbMuscles(); ++j){
(*(grp+i)).muscle(j)->updateOrientations(m, Q,updateKinTP);
updateKinTP=1;
}
}
void s2mMuscles::updateMuscles(std::vector<std::vector<s2mNodeMuscle>>& musclePointsInGlobal, std::vector<s2mMatrix> &jacoPointsInGlobal, const s2mGenCoord& QDot){
std::vector<s2mGroupeMusculaire>::iterator grp=m_mus.begin();
unsigned int cmpMuscle = 0;
for (unsigned int i=0; i<m_mus.size(); ++i) // groupe musculaire
for (unsigned int j=0; j<(*(grp+i)).nbMuscles(); ++j){
(*(grp+i)).muscle(j)->updateOrientations(musclePointsInGlobal[cmpMuscle], jacoPointsInGlobal[cmpMuscle], QDot);
++cmpMuscle;
}
}
void s2mMuscles::updateMuscles(std::vector<std::vector<s2mNodeMuscle>>& musclePointsInGlobal, std::vector<s2mMatrix> &jacoPointsInGlobal){
// Updater tous les muscles
std::vector<s2mGroupeMusculaire>::iterator grp=m_mus.begin();
unsigned int cmpMuscle = 0;
for (unsigned int i=0; i<m_mus.size(); ++i) // groupe musculaire
for (unsigned int j=0; j<(*(grp+i)).nbMuscles(); ++j){
(*(grp+i)).muscle(j)->updateOrientations(musclePointsInGlobal[cmpMuscle], jacoPointsInGlobal[cmpMuscle]);
++cmpMuscle;
}
}
|
//===-- ModuleUtils.cpp - Functions to manipulate Modules -----------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This family of functions perform manipulations on Modules.
//
//===----------------------------------------------------------------------===//
#include "llvm/Transforms/Utils/ModuleUtils.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/Module.h"
using namespace llvm;
static void appendToGlobalArray(const char *Array,
Module &M, Function *F, int Priority) {
IRBuilder<> IRB(M.getContext());
FunctionType *FnTy = FunctionType::get(IRB.getVoidTy(), false);
StructType *Ty = StructType::get(
IRB.getInt32Ty(), PointerType::getUnqual(FnTy), NULL);
Constant *RuntimeCtorInit = ConstantStruct::get(
Ty, IRB.getInt32(Priority), F, NULL);
// Get the current set of static global constructors and add the new ctor
// to the list.
SmallVector<Constant *, 16> CurrentCtors;
if (GlobalVariable * GVCtor = M.getNamedGlobal(Array)) {
if (Constant *Init = GVCtor->getInitializer()) {
unsigned n = Init->getNumOperands();
CurrentCtors.reserve(n + 1);
for (unsigned i = 0; i != n; ++i)
CurrentCtors.push_back(cast<Constant>(Init->getOperand(i)));
}
GVCtor->eraseFromParent();
}
CurrentCtors.push_back(RuntimeCtorInit);
// Create a new initializer.
ArrayType *AT = ArrayType::get(RuntimeCtorInit->getType(),
CurrentCtors.size());
Constant *NewInit = ConstantArray::get(AT, CurrentCtors);
// Create the new global variable and replace all uses of
// the old global variable with the new one.
(void)new GlobalVariable(M, NewInit->getType(), false,
GlobalValue::AppendingLinkage, NewInit, Array);
}
void llvm::appendToGlobalCtors(Module &M, Function *F, int Priority) {
appendToGlobalArray("llvm.global_ctors", M, F, Priority);
}
void llvm::appendToGlobalDtors(Module &M, Function *F, int Priority) {
appendToGlobalArray("llvm.global_dtors", M, F, Priority);
}
GlobalVariable *
llvm::collectUsedGlobalVariables(Module &M, SmallPtrSet<GlobalValue *, 8> &Set,
bool CompilerUsed) {
const char *Name = CompilerUsed ? "llvm.compiler.used" : "llvm.used";
GlobalVariable *GV = M.getGlobalVariable(Name);
if (!GV || !GV->hasInitializer())
return GV;
const ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
for (unsigned I = 0, E = Init->getNumOperands(); I != E; ++I) {
Value *Op = Init->getOperand(I);
GlobalValue *G = cast<GlobalValue>(Op->stripPointerCastsNoFollowAliases());
Set.insert(G);
}
return GV;
}
|
//+---------------------------------------------------------------------------
//
// Microsoft Windows
// Copyright (C) Microsoft Corporation, 1991 - 2000.
//
// File: BITSTM.hxx
//
// Contents: 'Bit streams'
//
// Classes: CBitStream, CWBitStream, CPBitStream, CRBitStream
//
// History: 03-Jul-91 KyleP Created
// 24-Aug-92 BartoszM Rewrote it
//
//----------------------------------------------------------------------------
#pragma once
#include <bitoff.hxx>
#include "physidx.hxx"
#include <ci64.hxx>
class CSmartBuffer
{
public:
enum EAccessMode { eReadExisting, eWriteExisting };
CSmartBuffer ( CPhysStorage& phStorage, EAccessMode mode );
CSmartBuffer ( CPhysStorage& phStorage, BOOL fCreate );
CSmartBuffer ( CPhysStorage& phStorage, ULONG numPage, EAccessMode mode, BOOL fIncrSig = TRUE );
CSmartBuffer ( CSmartBuffer& buf, ULONG numPage );
~CSmartBuffer ();
ULONG PageNum() { return _numPage; }
__forceinline ULONG* Get() { return _pBuffer + 1; }
BOOL isEmpty() { return _pBuffer == 0; }
void Refill ( ULONG numPage );
ULONG* Next();
ULONG* NextNew();
void Free();
BOOL IsWritable() { return _phStorage.IsWritable(); }
WCHAR const * GetPath() { return _phStorage.GetPath(); }
void InitSignature();
#ifdef CIEXTMODE
void CiExtDump(void *ciExtSelf);
#endif
private:
void CheckCorruption();
void IncrementSig();
CPhysStorage& _phStorage; // Source of pages
ULONG _numPage; // current page number
ULONG * _pBuffer; // Beginning of buffer.
BOOL _fWritable; // Access mode for existing buffers.
};
//+---------------------------------------------------------------------------
//
// Class: CBitStream
//
// Purpose: Bit Stream
//
// History: 08-Jul-91 KyleP Created.
// 10-Apr-94 SrikantS Added a "Refill" method to invalidate
// the current buffer and reload during
// master merge.
//
//----------------------------------------------------------------------------
class CBitStream
{
public:
__forceinline ULONG GetBits( unsigned cb);
__forceinline ULONG* EndBuf()
{
Win4Assert( _pEndBuf == ( _buffer.Get() + SMARTBUF_PAGE_SIZE_IN_DWORDS ) );
return _pEndBuf;
}
__forceinline void GetOffset ( BitOffset& off );
void GetBytes(BYTE * pb, unsigned cb);
#if CIDBG == 1
virtual void Dump();
unsigned PeekBit();
#endif // CIDBG == 1
void Seek ( const BitOffset& off );
void Refill();
//
// We can remove RefillStream() and FreeStream() once NTFS supports
// sparse file operations on parts of a file when other parts
// of the file are mapped. This probably won't happen any time soon.
//
void RefillStream()
{
if ( !_buffer.isEmpty() )
return;
//
// Re-map the stream if necessary, if unmapped for a shrink from
// front.
//
Win4Assert( _buffer.IsWritable() );
_buffer.Refill( _buffer.PageNum() );
_pCurPos = (ULONG *) ( _oBuffer + (ULONG_PTR) _buffer.Get() );
_pEndBuf = ( _buffer.Get() + SMARTBUF_PAGE_SIZE_IN_DWORDS );
ciDebugOut(( DEB_BITSTM,
"refilled stream '%ws', pCur 0x%x, pBase 0x%x, offset 0x%x, page 0x%x, this 0x%x\n",
_buffer.GetPath(),
_pCurPos,
_buffer.Get(),
_oBuffer,
_buffer.PageNum(),
this ));
_oBuffer = 0;
}
void FreeStream()
{
//
// If the stream is writable, unmap it so we can do a shrink from
// front on the index.
//
if ( _buffer.IsWritable() )
{
if ( !_buffer.isEmpty() )
{
_oBuffer = (ULONG)((ULONG_PTR) _pCurPos - (ULONG_PTR) _buffer.Get());
}
ciDebugOut(( DEB_BITSTM,
"tossing stream '%ws', pcur 0x%x, buf 0x%x, offset 0x%x, page 0x%x\n",
_buffer.GetPath(), _pCurPos, _buffer.Get(), _oBuffer, _buffer.PageNum() ));
_buffer.Free();
_pCurPos = 0;
}
}
#ifdef CIEXTMODE
void CiExtDump(void *ciExtSelf);
#endif
protected:
CBitStream(CPhysStorage& phStorage, CSmartBuffer::EAccessMode mode );
CBitStream(CPhysStorage& phStorage, BOOL fCreate);
CBitStream(CPhysStorage& phStorage, const BitOffset& off,
CSmartBuffer::EAccessMode mode, BOOL fIncrSig = TRUE);
CBitStream(CBitStream & orig);
__forceinline ULONG Position();
void SetPosition(ULONG off);
void NextDword();
void LoadNextPage();
void LoadNewPage();
ULONG IGetBits (unsigned cb);
unsigned _cbitLeftDW; // Bits left in the current DWord.
ULONG * _pCurPos; // Current (DWord) position in buffer.
ULONG * _pEndBuf;
ULONG _oBuffer; // offset when buffer is freed
CSmartBuffer _buffer;
};
//+---------------------------------------------------------------------------
//
// Class: CWBitStream
//
// Purpose: Writable Bit Stream
//
// Interface:
//
// History: 24-Aug-92 BartoszM Created
// 10-Apr-94 SrikantS Added the ability to open
// an existing stream for write
// access during Master Merge.
//
//----------------------------------------------------------------------------
class CWBitStream : public CBitStream
{
public:
CWBitStream ( CPhysStorage& phStorage ): CBitStream ( phStorage, TRUE ) {}
CWBitStream ( CPhysStorage& phStorage, const BitOffset & bitOff, BOOL fIncrSig = TRUE ) :
CBitStream( phStorage, bitOff, CSmartBuffer::eWriteExisting, fIncrSig ) {}
inline void PutBits(ULONG ul, unsigned cb);
void PutBytes(const BYTE * pb, unsigned cb);
void ZeroToEndOfPage();
void InitSignature();
#ifdef CIEXTMODE
void CiExtDump(void *ciExtSelf);
#endif
private:
void NextDword();
void IPutBits(ULONG ul, unsigned cb);
};
//+---------------------------------------------------------------------------
//
// Class: CPBitStream
//
// Purpose: Patch Bit Stream, used for back patching
//
// History: 24-Aug-92 BartoszM Created
//
// Notes: Seek is very cheap, since it doesn't load the page.
// Pages are loaded on demand when writing.
//
//----------------------------------------------------------------------------
class CPBitStream : public CBitStream
{
public:
CPBitStream ( CPhysStorage& phStorage );
void OverwriteBits(ULONG ul, unsigned cb);
__forceinline void SkipBits ( unsigned delta )
{
_bitOff += delta;
Win4Assert( _bitOff.Offset() < SMARTBUF_PAGE_SIZE_IN_BITS );
}
__forceinline void Seek ( const BitOffset& off )
{
_bitOff = off;
Win4Assert( _bitOff.Offset() < SMARTBUF_PAGE_SIZE_IN_BITS );
}
__forceinline void GetOffset ( BitOffset& off ) {
RtlCopyMemory( &off, &_bitOff, sizeof BitOffset );
}
#if CIDBG == 1
unsigned PeekBit();
virtual void Dump();
#endif // CIDBG == 1
#ifdef CIEXTMODE
void CiExtDump(void *ciExtSelf);
#endif
private:
void IOverwriteBits(ULONG ul, unsigned cb);
BitOffset _bitOff;
};
//+---------------------------------------------------------------------------
//
// Class: CRBitStream
//
// Purpose: Readable Bit Stream
//
// History: 24-Aug-92 BartoszM Created
//
//----------------------------------------------------------------------------
class CRBitStream : public CBitStream
{
public:
CRBitStream ( CPhysStorage& phStorage ): CBitStream ( phStorage, FALSE ) {}
CRBitStream ( CPhysStorage& phStorage, const BitOffset& off )
: CBitStream ( phStorage, off, CSmartBuffer::eReadExisting ) {}
};
//+---------------------------------------------------------------------------
//
// Member: CBitStream::GetOffset, public
//
// Synopsis: Returns bit offset within the index.
//
// Arguments: [off] -- (out) bit offset
//
// History: 28-Aug-92 BartoszM Created.
//
//----------------------------------------------------------------------------
__forceinline void CBitStream::GetOffset ( BitOffset& off )
{
off.Init( _buffer.PageNum(), Position() );
}
//+---------------------------------------------------------------------------
//
// Member: CBitStream::Position, private
//
// Synopsis: Returns bit position within current page
//
// History: 28-Aug-92 BartoszM Created.
//
//----------------------------------------------------------------------------
__forceinline ULONG CBitStream::Position()
{
return CiPtrToUlong(_pCurPos - _buffer.Get() + 1) * ULONG_BITS - _cbitLeftDW;
}
//+---------------------------------------------------------------------------
//
// Member: CBitStream::NextDword, private
//
// Synopsis: Increments current dword pointer,
// loads next page if necessary.
//
// History: 28-Aug-92 BartoszM Created.
//
//----------------------------------------------------------------------------
__forceinline void CBitStream::NextDword()
{
_pCurPos++;
_cbitLeftDW = ULONG_BITS;
if (_pCurPos >= EndBuf())
{
LoadNextPage();
}
}
//+---------------------------------------------------------------------------
//
// Member: CWBitStream::NextDword, private
//
// Synopsis: Increments current dword pointer,
// loads new page if necessary.
//
// History: 28-Aug-92 BartoszM Created.
//
//----------------------------------------------------------------------------
__forceinline void CWBitStream::NextDword()
{
_pCurPos++;
_cbitLeftDW = ULONG_BITS;
if (_pCurPos >= EndBuf())
{
LoadNewPage();
}
}
//+---------------------------------------------------------------------------
//
// Member: CWBitStream::PutBits, public
//
// Synopsis: Store bits in the buffer.
//
// Effects: Store the [cb] low bits in [ul] beginning at the 'bit-cursor'
//
// Arguments: [ul] -- A DWord containing data to store.
//
// [cb] -- The number of bits to store.
//
// History: 08-Jul-91 KyleP Created.
//
// Notes: Bits are stored 'big-endian'.
//
//----------------------------------------------------------------------------
__forceinline void CWBitStream::PutBits(ULONG ul, unsigned cb)
{
// ciDebugOut (( DEB_BITSTM , "PutBits %d\n", cb ));
Win4Assert(cb != 0 && cb <= ULONG_BITS);
//
// The ULONG we're storing must be zero-filled at the top.
//
Win4Assert( (cb == ULONG_BITS) || ( (ul >> cb) == 0 ) );
//
// The easy case is the one where all the data fits in 1 dword.
//
if (cb <= _cbitLeftDW)
{
Win4Assert ( _pCurPos < EndBuf() );
_cbitLeftDW -= cb;
*_pCurPos |= (ul << _cbitLeftDW);
}
else
{
IPutBits(ul, cb);
}
}
//+---------------------------------------------------------------------------
//
// Member: CBitStream::GetBits, public
//
// Synopsis: Retrieve bits from the buffer.
//
// Arguments: [cb] -- Count of bits to retrieve.
//
// History: 12-Jul-91 KyleP Created.
//
//----------------------------------------------------------------------------
__forceinline ULONG CBitStream::GetBits(unsigned cb)
{
// ciDebugOut (( DEB_BITSTM , "GetBits %d\n", cb ));
Win4Assert(cb != 0 && cb <= ULONG_BITS);
//
// The easy case is when the data can be extracted from the
// current dword.
//
if (cb <= _cbitLeftDW)
{
ULONG mask = 0xFFFFFFFF;
if (cb != ULONG_BITS)
{
mask = ~(mask << cb);
}
_cbitLeftDW -= cb;
return (*_pCurPos >> _cbitLeftDW) & mask;
}
else
{
return IGetBits( cb );
}
}
|
// SPDX-FileCopyrightText: 2021 Robin Lindén <dev@robinlinden.eu>
//
// SPDX-License-Identifier: BSD-2-Clause
#include "geom/geom.h"
#include "etest/etest.h"
using etest::expect;
using geom::EdgeSize;
using geom::Rect;
int main() {
etest::test("Rect::expanded", [] {
Rect r{0, 0, 10, 10};
expect(Rect{-10, 0, 20, 10} == r.expanded(EdgeSize{10, 0, 0, 0}));
expect(Rect{0, 0, 20, 10} == r.expanded(EdgeSize{0, 10, 0, 0}));
expect(Rect{0, -10, 10, 20} == r.expanded(EdgeSize{0, 0, 10, 0}));
expect(Rect{0, 0, 10, 20} == r.expanded(EdgeSize{0, 0, 0, 10}));
expect(Rect{-10, 0, 30, 10} == r.expanded(EdgeSize{10, 10, 0, 0}));
expect(Rect{0, -10, 10, 30} == r.expanded(EdgeSize{0, 0, 10, 10}));
expect(Rect{0, 0, 20, 20} == r.expanded(EdgeSize{0, 10, 0, 10}));
expect(Rect{-10, -10, 30, 30} == r.expanded(EdgeSize{10, 10, 10, 10}));
});
etest::test("Rect::scaled", [] {
Rect r{0, 0, 10, 10};
expect(Rect{} == r.scaled(0));
expect(r == r.scaled(1));
expect(Rect{0, 0, 20, 20} == r.scaled(2));
expect(Rect{0, 0, 30, 30} == r.scaled(3));
Rect r1{1, 1, 10, 10};
expect(r1 == r1.scaled(1));
expect(Rect{2, 2, 20, 20} == r1.scaled(2));
expect(Rect{3, 3, 30, 30} == r1.scaled(3));
Rect r2{1, 1, 10, 10};
expect(r2 == r2.scaled(1, {1, 1}));
expect(Rect{1, 1, 20, 20} == r2.scaled(2, {1, 1}));
expect(Rect{1, 1, 30, 30} == r2.scaled(3, {1, 1}));
Rect r3{0, 0, 10, 10};
expect(r3 == r3.scaled(1, {5, 5}));
expect(Rect{-5, -5, 20, 20} == r3.scaled(2, {5, 5}));
expect(Rect{-10, -10, 30, 30} == r3.scaled(3, {5, 5}));
});
etest::test("Rect::translated", [] {
Rect r{0, 0, 10, 10};
expect(Rect{10, 0, 10, 10} == r.translated(10, 0));
expect(Rect{0, 10, 10, 10} == r.translated(0, 10));
expect(Rect{-10, -10, 10, 10} == r.translated(-10, -10));
});
etest::test("Rect::contains", [] {
Rect r{0, 0, 10, 10};
expect(r.contains({0, 0}));
expect(r.contains({0, 10}));
expect(r.contains({10, 10}));
expect(r.contains({10, 0}));
expect(r.contains({5, 5}));
expect(!r.contains({-1, 0}));
expect(!r.contains({-1, 10}));
expect(!r.contains({10, 11}));
expect(!r.contains({11, 10}));
});
return etest::run_all_tests();
}
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/dns/host_resolver.h"
#include <string>
#include <utility>
#include <vector>
#include "base/bind.h"
#include "base/check.h"
#include "base/immediate_crash.h"
#include "base/macros.h"
#include "base/no_destructor.h"
#include "base/notreached.h"
#include "base/strings/string_number_conversions.h"
#include "base/values.h"
#include "net/base/address_list.h"
#include "net/base/net_errors.h"
#include "net/base/network_change_notifier.h"
#include "net/dns/context_host_resolver.h"
#include "net/dns/dns_client.h"
#include "net/dns/dns_util.h"
#include "net/dns/host_cache.h"
#include "net/dns/host_resolver_manager.h"
#include "net/dns/mapped_host_resolver.h"
#include "net/dns/resolve_context.h"
namespace net {
namespace {
class FailingRequestImpl : public HostResolver::ResolveHostRequest,
public HostResolver::ProbeRequest {
public:
explicit FailingRequestImpl(int error) : error_(error) {}
~FailingRequestImpl() override = default;
int Start(CompletionOnceCallback callback) override { return error_; }
int Start() override { return error_; }
const base::Optional<AddressList>& GetAddressResults() const override {
static base::NoDestructor<base::Optional<AddressList>> nullopt_result;
return *nullopt_result;
}
const base::Optional<std::vector<std::string>>& GetTextResults()
const override {
static const base::NoDestructor<base::Optional<std::vector<std::string>>>
nullopt_result;
return *nullopt_result;
}
const base::Optional<std::vector<HostPortPair>>& GetHostnameResults()
const override {
static const base::NoDestructor<base::Optional<std::vector<HostPortPair>>>
nullopt_result;
return *nullopt_result;
}
const base::Optional<std::vector<std::string>>& GetDnsAliasResults()
const override {
static const base::NoDestructor<base::Optional<std::vector<std::string>>>
nullopt_result;
return *nullopt_result;
}
ResolveErrorInfo GetResolveErrorInfo() const override {
return ResolveErrorInfo(error_);
}
const base::Optional<HostCache::EntryStaleness>& GetStaleInfo()
const override {
static const base::NoDestructor<base::Optional<HostCache::EntryStaleness>>
nullopt_result;
return *nullopt_result;
}
private:
const int error_;
DISALLOW_COPY_AND_ASSIGN(FailingRequestImpl);
};
} // namespace
const base::Optional<std::vector<bool>>&
HostResolver::ResolveHostRequest::GetExperimentalResultsForTesting() const {
IMMEDIATE_CRASH();
}
const size_t HostResolver::ManagerOptions::kDefaultRetryAttempts =
static_cast<size_t>(-1);
std::unique_ptr<HostResolver> HostResolver::Factory::CreateResolver(
HostResolverManager* manager,
base::StringPiece host_mapping_rules,
bool enable_caching) {
return HostResolver::CreateResolver(manager, host_mapping_rules,
enable_caching);
}
std::unique_ptr<HostResolver> HostResolver::Factory::CreateStandaloneResolver(
NetLog* net_log,
const ManagerOptions& options,
base::StringPiece host_mapping_rules,
bool enable_caching) {
return HostResolver::CreateStandaloneResolver(
net_log, options, host_mapping_rules, enable_caching);
}
HostResolver::ResolveHostParameters::ResolveHostParameters() = default;
HostResolver::ResolveHostParameters::ResolveHostParameters(
const ResolveHostParameters& other) = default;
HostResolver::~HostResolver() = default;
std::unique_ptr<HostResolver::ProbeRequest>
HostResolver::CreateDohProbeRequest() {
// Should be overridden in any HostResolver implementation where this method
// may be called.
NOTREACHED();
return nullptr;
}
std::unique_ptr<HostResolver::MdnsListener> HostResolver::CreateMdnsListener(
const HostPortPair& host,
DnsQueryType query_type) {
// Should be overridden in any HostResolver implementation where this method
// may be called.
NOTREACHED();
return nullptr;
}
HostCache* HostResolver::GetHostCache() {
return nullptr;
}
base::Value HostResolver::GetDnsConfigAsValue() const {
return base::Value(base::Value::Type::DICTIONARY);
}
void HostResolver::SetRequestContext(URLRequestContext* request_context) {
// Should be overridden in any HostResolver implementation where this method
// may be called.
NOTREACHED();
}
HostResolverManager* HostResolver::GetManagerForTesting() {
// Should be overridden in any HostResolver implementation where this method
// may be called.
NOTREACHED();
return nullptr;
}
const URLRequestContext* HostResolver::GetContextForTesting() const {
// Should be overridden in any HostResolver implementation where this method
// may be called.
NOTREACHED();
return nullptr;
}
// static
std::unique_ptr<HostResolver> HostResolver::CreateResolver(
HostResolverManager* manager,
base::StringPiece host_mapping_rules,
bool enable_caching) {
DCHECK(manager);
auto resolve_context = std::make_unique<ResolveContext>(
nullptr /* url_request_context */, enable_caching);
auto resolver = std::make_unique<ContextHostResolver>(
manager, std::move(resolve_context));
if (host_mapping_rules.empty())
return resolver;
auto remapped_resolver =
std::make_unique<MappedHostResolver>(std::move(resolver));
remapped_resolver->SetRulesFromString(host_mapping_rules);
return remapped_resolver;
}
// static
std::unique_ptr<HostResolver> HostResolver::CreateStandaloneResolver(
NetLog* net_log,
base::Optional<ManagerOptions> options,
base::StringPiece host_mapping_rules,
bool enable_caching) {
std::unique_ptr<ContextHostResolver> resolver =
CreateStandaloneContextResolver(net_log, std::move(options),
enable_caching);
if (host_mapping_rules.empty())
return resolver;
auto remapped_resolver =
std::make_unique<MappedHostResolver>(std::move(resolver));
remapped_resolver->SetRulesFromString(host_mapping_rules);
return remapped_resolver;
}
// static
std::unique_ptr<ContextHostResolver>
HostResolver::CreateStandaloneContextResolver(
NetLog* net_log,
base::Optional<ManagerOptions> options,
bool enable_caching) {
auto resolve_context = std::make_unique<ResolveContext>(
nullptr /* url_request_context */, enable_caching);
return std::make_unique<ContextHostResolver>(
std::make_unique<HostResolverManager>(
std::move(options).value_or(ManagerOptions()),
NetworkChangeNotifier::GetSystemDnsConfigNotifier(), net_log),
std::move(resolve_context));
}
// static
AddressFamily HostResolver::DnsQueryTypeToAddressFamily(
DnsQueryType dns_query_type) {
switch (dns_query_type) {
case DnsQueryType::UNSPECIFIED:
return ADDRESS_FAMILY_UNSPECIFIED;
case DnsQueryType::A:
return ADDRESS_FAMILY_IPV4;
case DnsQueryType::AAAA:
return ADDRESS_FAMILY_IPV6;
default:
// |dns_query_type| should be an address type (A or AAAA) or UNSPECIFIED.
NOTREACHED();
return ADDRESS_FAMILY_UNSPECIFIED;
}
}
// static
HostResolverFlags HostResolver::ParametersToHostResolverFlags(
const ResolveHostParameters& parameters) {
HostResolverFlags flags = 0;
if (parameters.include_canonical_name)
flags |= HOST_RESOLVER_CANONNAME;
if (parameters.loopback_only)
flags |= HOST_RESOLVER_LOOPBACK_ONLY;
if (parameters.avoid_multicast_resolution)
flags |= HOST_RESOLVER_AVOID_MULTICAST;
return flags;
}
// static
int HostResolver::SquashErrorCode(int error) {
// TODO(crbug.com/1040686): Once InProcessBrowserTests do not use
// ERR_NOT_IMPLEMENTED to simulate DNS failures, it should be ok to squash
// ERR_NOT_IMPLEMENTED.
// TODO(crbug.com/1043281): Consider squashing ERR_INTERNET_DISCONNECTED.
if (error == OK || error == ERR_IO_PENDING || error == ERR_NOT_IMPLEMENTED ||
error == ERR_INTERNET_DISCONNECTED || error == ERR_NAME_NOT_RESOLVED) {
return error;
} else {
return ERR_NAME_NOT_RESOLVED;
}
}
HostResolver::HostResolver() = default;
// static
std::unique_ptr<HostResolver::ResolveHostRequest>
HostResolver::CreateFailingRequest(int error) {
return std::make_unique<FailingRequestImpl>(error);
}
// static
std::unique_ptr<HostResolver::ProbeRequest>
HostResolver::CreateFailingProbeRequest(int error) {
return std::make_unique<FailingRequestImpl>(error);
}
} // namespace net
|
/*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2020 - Raw Material Software Limited
JUCE is an open source library subject to commercial or open-source
licensing.
By using JUCE, you agree to the terms of both the JUCE 6 End-User License
Agreement and JUCE Privacy Policy (both effective as of the 16th June 2020).
End User License Agreement: www.juce.com/juce-6-licence
Privacy Policy: www.juce.com/juce-privacy-policy
Or: You may also use this code under the terms of the GPL v3 (see
www.gnu.org/licenses).
JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
DISCLAIMED.
==============================================================================
*/
#include <JuceHeader.h>
namespace
{
String getBroadcastIPAddress()
{
return IPAddress::getLocalAddress().toString().upToLastOccurrenceOf (".", false, false) + ".255";
}
static const int masterPortNumber = 9001; // the UDP port the master sends on / the clients receive.
static const int clientPortNumber = 9002; // the UDP port the clients send on / the master receives.
static const String canvasStateOSCAddress = "/juce/nfd/canvasState";
static const String newClientOSCAddress = "/juce/nfd/newClient";
static const String userInputOSCAddress = "/juce/nfd/userInput";
}
#include "SharedCanvas.h"
#include "ClientComponent.h"
#include "Demos.h"
#include "MasterComponent.h"
//==============================================================================
class NetworkGraphicsDemoApplication : public JUCEApplication
{
public:
NetworkGraphicsDemoApplication() : properties (getPropertyFileOptions())
{}
const String getApplicationName() override { return ProjectInfo::projectName; }
const String getApplicationVersion() override { return ProjectInfo::versionString; }
bool moreThanOneInstanceAllowed() override { return true; }
void anotherInstanceStarted (const String&) override {}
//==============================================================================
void initialise (const String& commandLine) override
{
#if ! JUCE_IOS && ! JUCE_ANDROID
// Run as the master if we have a command-line flag "master" or if the exe itself
// has been renamed to include the word "master"..
bool isMaster = commandLine.containsIgnoreCase ("master")
|| File::getSpecialLocation (File::currentApplicationFile)
.getFileName().containsIgnoreCase ("master");
if (isMaster)
mainWindows.add (new MainWindow (properties));
#endif
mainWindows.add (new MainWindow (properties, 0));
Desktop::getInstance().setScreenSaverEnabled (false);
}
void shutdown() override
{
mainWindows.clear();
properties.saveIfNeeded();
}
void systemRequestedQuit() override
{
quit();
}
//==============================================================================
struct MainWindow : public DocumentWindow
{
explicit MainWindow (PropertiesFile& props)
: DocumentWindow ("JUCE Networked Graphics Demo - Master", Colours::white, DocumentWindow::allButtons)
{
setUsingNativeTitleBar (true);
setContentOwned (new MasterContentComponent (props), true);
setBounds (100, 50, getWidth(), getHeight());
setResizable (true, false);
setVisible (true);
glContext.attachTo (*this);
}
MainWindow (PropertiesFile& props, int windowIndex)
: DocumentWindow ("JUCE Networked Graphics Demo", Colours::black, DocumentWindow::allButtons)
{
setUsingNativeTitleBar (true);
setContentOwned (new ClientCanvasComponent (props, windowIndex), true);
setBounds (500, 100, getWidth(), getHeight());
setResizable (true, false);
setVisible (true);
#if ! JUCE_IOS
glContext.attachTo (*this);
#endif
#if JUCE_IOS || JUCE_ANDROID
setFullScreen (true);
#endif
}
~MainWindow() override
{
glContext.detach();
}
void closeButtonPressed() override
{
JUCEApplication::getInstance()->systemRequestedQuit();
}
OpenGLContext glContext;
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MainWindow)
};
static PropertiesFile::Options getPropertyFileOptions()
{
PropertiesFile::Options o;
o.applicationName = "JUCE Network Graphics Demo";
o.filenameSuffix = ".settings";
o.folderName = "JUCE Network Graphics Demo";
o.osxLibrarySubFolder = "Application Support/JUCE Network Graphics Demo";
o.millisecondsBeforeSaving = 2000;
return o;
}
PropertiesFile properties;
OwnedArray<MainWindow> mainWindows;
};
//==============================================================================
// This macro generates the main() routine that launches the app.
START_JUCE_APPLICATION (NetworkGraphicsDemoApplication)
|
/*
---------------------------------------------------------------------------
Open Asset Import Library (assimp)
---------------------------------------------------------------------------
Copyright (c) 2006-2020, assimp team
All rights reserved.
Redistribution and use of this software in source and binary forms,
with or without modification, are permitted provided that the following
conditions are met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the
following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other
materials provided with the distribution.
* Neither the name of the assimp team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the assimp team.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
---------------------------------------------------------------------------
*/
#include "assimp_view.h"
#include "richedit.h"
#include <commoncontrols.h>
#include <commdlg.h>
namespace AssimpView {
CLogWindow CLogWindow::s_cInstance;
extern HKEY g_hRegistry;
// header for the RTF log file
static const char* AI_VIEW_RTF_LOG_HEADER =
"{\\rtf1"
"\\ansi"
"\\deff0"
"{"
"\\fonttbl{\\f0 Courier New;}"
"}"
"{\\colortbl;"
"\\red255\\green0\\blue0;" // red for errors
"\\red255\\green120\\blue0;" // orange for warnings
"\\red0\\green150\\blue0;" // green for infos
"\\red0\\green0\\blue180;" // blue for debug messages
"\\red0\\green0\\blue0;" // black for everything else
"}}";
//-------------------------------------------------------------------------------
// Message procedure for the log window
//-------------------------------------------------------------------------------
INT_PTR CALLBACK LogDialogProc(HWND hwndDlg,UINT uMsg,
WPARAM wParam,LPARAM lParam)
{
(void)lParam;
switch (uMsg)
{
case WM_INITDIALOG:
{
return TRUE;
}
case WM_SIZE:
{
int x = LOWORD(lParam);
int y = HIWORD(lParam);
SetWindowPos(GetDlgItem(hwndDlg,IDC_EDIT1),NULL,0,0,
x-10,y-12,SWP_NOMOVE|SWP_NOZORDER);
return TRUE;
}
case WM_CLOSE:
EndDialog(hwndDlg,0);
CLogWindow::Instance().bIsVisible = false;
return TRUE;
};
return FALSE;
}
//-------------------------------------------------------------------------------
void CLogWindow::Init () {
this->hwnd = ::CreateDialog(g_hInstance,MAKEINTRESOURCE(IDD_LOGVIEW),
NULL,&LogDialogProc);
if (!this->hwnd) {
CLogDisplay::Instance().AddEntry("[ERROR] Unable to create logger window",
D3DCOLOR_ARGB(0xFF,0,0xFF,0));
}
// setup the log text
this->szText = AI_VIEW_RTF_LOG_HEADER;;
this->szPlainText = "";
}
//-------------------------------------------------------------------------------
void CLogWindow::Show() {
if (this->hwnd) {
ShowWindow(this->hwnd,SW_SHOW);
this->bIsVisible = true;
// contents aren't updated while the logger isn't displayed
this->Update();
}
}
//-------------------------------------------------------------------------------
void CMyLogStream::write(const char* message) {
CLogWindow::Instance().WriteLine(message);
}
//-------------------------------------------------------------------------------
void CLogWindow::Clear() {
this->szText = AI_VIEW_RTF_LOG_HEADER;;
this->szPlainText = "";
this->Update();
}
//-------------------------------------------------------------------------------
void CLogWindow::Update() {
if (this->bIsVisible) {
SETTEXTEX sInfo;
sInfo.flags = ST_DEFAULT;
sInfo.codepage = CP_ACP;
SendDlgItemMessage(this->hwnd,IDC_EDIT1,
EM_SETTEXTEX,(WPARAM)&sInfo,( LPARAM)this->szText.c_str());
}
}
//-------------------------------------------------------------------------------
void CLogWindow::Save() {
char szFileName[MAX_PATH];
DWORD dwTemp = MAX_PATH;
if(ERROR_SUCCESS != RegQueryValueEx(g_hRegistry,"LogDestination",NULL,NULL,(BYTE*)szFileName,&dwTemp)) {
// Key was not found. Use C:
strcpy(szFileName,"");
} else {
// need to remove the file name
char* sz = strrchr(szFileName,'\\');
if (!sz)
sz = strrchr(szFileName,'/');
if (sz)
*sz = 0;
}
OPENFILENAME sFilename1 = {
sizeof(OPENFILENAME),
g_hDlg,GetModuleHandle(NULL),
"Log files\0*.txt", NULL, 0, 1,
szFileName, MAX_PATH, NULL, 0, NULL,
"Save log to file",
OFN_OVERWRITEPROMPT | OFN_HIDEREADONLY | OFN_NOCHANGEDIR,
0, 1, ".txt", 0, NULL, NULL
};
if(GetSaveFileName(&sFilename1) == 0) return;
// Now store the file in the registry
RegSetValueExA(g_hRegistry,"LogDestination",0,REG_SZ,(const BYTE*)szFileName,MAX_PATH);
FILE* pFile = fopen(szFileName,"wt");
fprintf(pFile,this->szPlainText.c_str());
fclose(pFile);
CLogDisplay::Instance().AddEntry("[INFO] The log file has been saved",
D3DCOLOR_ARGB(0xFF,0xFF,0xFF,0));
}
//-------------------------------------------------------------------------------
void CLogWindow::WriteLine(const char* message) {
this->szPlainText.append(message);
this->szPlainText.append("\r\n");
if (0 != this->szText.length()) {
this->szText.resize(this->szText.length()-1);
}
switch (message[0])
{
case 'e':
case 'E':
this->szText.append("{\\pard \\cf1 \\b \\fs18 ");
break;
case 'w':
case 'W':
this->szText.append("{\\pard \\cf2 \\b \\fs18 ");
break;
case 'i':
case 'I':
this->szText.append("{\\pard \\cf3 \\b \\fs18 ");
break;
case 'd':
case 'D':
this->szText.append("{\\pard \\cf4 \\b \\fs18 ");
break;
default:
this->szText.append("{\\pard \\cf5 \\b \\fs18 ");
break;
}
std::string _message = message;
for (unsigned int i = 0; i < _message.length();++i) {
if ('\\' == _message[i] ||
'}' == _message[i] ||
'{' == _message[i]) {
_message.insert(i++,"\\");
}
}
this->szText.append(_message);
this->szText.append("\\par}}");
if (this->bIsVisible && this->bUpdate) {
SETTEXTEX sInfo;
sInfo.flags = ST_DEFAULT;
sInfo.codepage = CP_ACP;
SendDlgItemMessage(this->hwnd,IDC_EDIT1,
EM_SETTEXTEX,(WPARAM)&sInfo,( LPARAM)this->szText.c_str());
}
}
} //! AssimpView
|
#pragma once
#include "type_check.hpp"
#include "math.hpp"
#include "model_adapter.hpp"
#include "matrix_adapter.hpp"
#include "vector_adapter.hpp"
#include "manipulation.hpp"
#include "task_manager.hpp"
#include <vector>
namespace densitas {
/**
* The density estimator, once trained, predicts any given quantiles
* of the unknown probability distribution around the true value.
*
* Use the density estimator to solve regression problems when you need to
* predict certain quantiles instead of just a single expectation value.
*
* The performance of the density estimator will depend greatly on the
* model given by the user.
*
* SubType: The sub-class that is inheriting from density_estimator (CRTP)
* ModelType: Operations on the model type are defined in model_adapter.hpp.
* Specialize the functions in there if your model does things differently
* MatrixType: Operations on the matrix type are defined in matrix_adapter.hpp.
* Specialize the functions in there if your matrix does things differently
* VectorType: Operations on the vector type are defined in vector_adapter.hpp.
* Specialize the functions in there if your vector does things differently
* ElementType: Must be a floating point type, e.g., float or double
*/
template<typename SubType, typename ModelType, typename MatrixType, typename VectorType, typename ElementType=double>
class density_estimator {
public:
typedef density_estimator density_estimator_type;
typedef ModelType model_type;
typedef MatrixType matrix_type;
typedef VectorType vector_type;
typedef ElementType element_type;
/**
* Returns a clone of this density estimator
*/
virtual std::unique_ptr<density_estimator> clone() const
{
auto estimator = std::unique_ptr<SubType>{new SubType};
for (const auto& model : models_) {
estimator->models_.emplace_back(densitas::model_adapter::clone(*model));
}
estimator->trained_centers_ = trained_centers_;
estimator->predicted_quantiles_ = predicted_quantiles_;
estimator->accuracy_predicted_quantiles_ = accuracy_predicted_quantiles_;
return std::move(estimator);
}
/**
* Set the internal models using a reference model object
* @param model A binary classifier. Must be clonable
* @param n_models The number of models to use
*/
void set_models(const model_type& model, std::size_t n_models)
{
check_n_models(n_models);
models_.clear();
for (std::size_t i=0; i<n_models; ++i) {
models_.emplace_back(densitas::model_adapter::clone(model));
}
}
/**
* Sets the predicted quantiles which must be values between
* zero and one. Default: {0.05, 0.5, 0.95}
* @param quantiles The predicted quantiles
*/
void predicted_quantiles(const vector_type& quantiles)
{
predicted_quantiles_ = quantiles;
}
/**
* Sets the computation accuracy of the predicted quantiles. Must be
* a value between zero and one. The closer to zero the better
* the accuracy but the higher the computation demand. Default: 1e-2
* @param accuracy The predicted quantile accuracy
*/
void accuracy_predicted_quantiles(element_type accuracy)
{
accuracy_predicted_quantiles_ = accuracy;
}
/**
* Trains the density estimator
* @param X A matrix of shape (n_events, n_features)
* @param y A vector of shape (n_events)
* @param threads Max number of threads to launch, single-threaded if <= 1
*/
void train(const matrix_type& X, const vector_type& y, int threads=1)
{
check_n_models(models_.size());
const auto quantiles = densitas::math::linspace<vector_type, element_type>(0, 1, models_.size() + 1);
const auto trained_quantiles = densitas::math::quantiles<element_type>(y, quantiles);
trained_centers_ = densitas::math::centers<element_type>(y, trained_quantiles);
const auto params = train_params{y, trained_quantiles};
if (threads > 1) {
densitas::core::task_manager manager(threads);
for (std::size_t i=0; i<models_.size(); ++i) {
manager.wait_for_slot();
on_train_status(*models_[i], i, X, params);
manager.launch_new(density_estimator::train_model, std::ref(*models_[i]), i, X, std::ref(params));
}
} else {
for (std::size_t i=0; i<models_.size(); ++i) {
on_train_status(*models_[i], i, X, params);
density_estimator::train_model(*models_[i], i, X, params);
}
}
}
/**
* Predicts events using this trained density estimator
* @param X A matrix of shape (n_events, n_features)
* @param threads Max number of threads to launch, single-threaded if <= 1
* @return A matrix of shape (n_events, n_predicted_quantiles)
*/
matrix_type predict(const matrix_type& X, int threads=1) const
{
check_n_models(models_.size());
const auto n_rows = densitas::matrix_adapter::n_rows(X);
const auto n_quantiles = densitas::vector_adapter::n_elements(predicted_quantiles_);
auto prediction = densitas::matrix_adapter::construct_uninitialized<matrix_type>(n_rows, n_quantiles);
const auto params = predict_params{X, trained_centers_, predicted_quantiles_, accuracy_predicted_quantiles_};
if (threads > 1) {
densitas::core::task_manager manager(threads);
for (std::size_t i=0; i<n_rows; ++i) {
manager.wait_for_slot();
on_predict_status(prediction, models_, i, params);
manager.launch_new(density_estimator::predict_event, std::ref(prediction), std::ref(models_), i, std::ref(params));
}
} else {
for (std::size_t i=0; i<n_rows; ++i) {
on_predict_status(prediction, models_, i, params);
density_estimator::predict_event(prediction, models_, i, params);
}
}
return prediction;
}
density_estimator(const density_estimator&) = delete;
density_estimator& operator=(const density_estimator&) = delete;
density_estimator(density_estimator&&) = delete;
density_estimator& operator=(density_estimator&&) = delete;
virtual ~density_estimator() {}
protected:
/**
* Constructor
*/
density_estimator()
: models_{}, trained_centers_{}, predicted_quantiles_{}, accuracy_predicted_quantiles_{}
{
init();
}
/**
* Constructor
* @param model A binary classifier. Must be clonable
* @param n_models The number of models to use
*/
density_estimator(const model_type& model, std::size_t n_models)
: models_{}, trained_centers_{}, predicted_quantiles_{}, accuracy_predicted_quantiles_{}
{
init();
set_models(model, n_models);
}
std::vector<std::unique_ptr<model_type>> models_;
vector_type trained_centers_;
vector_type predicted_quantiles_;
element_type accuracy_predicted_quantiles_;
struct train_params {
const vector_type& y;
const vector_type& trained_quantiles;
};
struct predict_params {
const matrix_type& features;
const vector_type& centers;
const vector_type& quantiles;
const double accuracy;
};
virtual void on_train_status(const model_type&, std::size_t, const matrix_type&, const train_params&) const {}
virtual void on_predict_status(const matrix_type&, const std::vector<std::unique_ptr<model_type>>&, std::size_t, const predict_params&) const {}
virtual void init()
{
static_assert(std::is_base_of<density_estimator_type, SubType>::value, "SubType is not inheriting from density_estimator");
densitas::core::check_element_type<element_type>();
accuracy_predicted_quantiles_ = 1e-2;
trained_centers_ = densitas::vector_adapter::construct_uninitialized<vector_type>(0);
predicted_quantiles_ = densitas::vector_adapter::construct_uninitialized<vector_type>(3);
densitas::vector_adapter::set_element<element_type>(predicted_quantiles_, 0, 0.05);
densitas::vector_adapter::set_element<element_type>(predicted_quantiles_, 1, 0.5);
densitas::vector_adapter::set_element<element_type>(predicted_quantiles_, 2, 0.95);
}
virtual void check_n_models(std::size_t n_models) const
{
if (!(n_models > 1))
throw densitas::densitas_error("number of models must be larger than one");
}
static void train_model(model_type& model, std::size_t model_index, matrix_type features, const train_params& params)
{
const auto lower = densitas::vector_adapter::get_element<element_type>(params.trained_quantiles, model_index);
const auto upper = densitas::vector_adapter::get_element<element_type>(params.trained_quantiles, model_index + 1);
auto target = densitas::math::make_classification_target<model_type>(params.y, lower, upper);
densitas::model_adapter::train(model, features, target);
}
static void predict_event(matrix_type& prediction, const std::vector<std::unique_ptr<model_type>>& models, std::size_t event_index, const predict_params& params)
{
auto weights = densitas::vector_adapter::construct_uninitialized<vector_type>(models.size());
for (std::size_t j=0; j<models.size(); ++j) {
const auto prob_value = densitas::core::predict_proba_for_row<element_type, vector_type>(*models[j], params.features, event_index);
densitas::vector_adapter::set_element<element_type>(weights, j, prob_value);
}
const auto quants = densitas::math::quantiles_weighted<element_type>(params.centers, weights, params.quantiles, params.accuracy);
densitas::core::assign_vector_to_row<element_type>(prediction, event_index, quants);
}
};
} // densitas
|
#ifndef OPENPOSE_EXPERIMENTAL_3D_CAMERA_PARAMETER_READER_HPP
#define OPENPOSE_EXPERIMENTAL_3D_CAMERA_PARAMETER_READER_HPP
#include <opencv2/core/core.hpp>
#include <openpose/core/common.hpp>
namespace op
{
class OP_API CameraParameterReader
{
public:
explicit CameraParameterReader();
void readParameters(const std::string& cameraParameterPath,
const std::vector<std::string>& serialNumbers);
unsigned long long getNumberCameras() const;
const std::vector<cv::Mat>& getCameraMatrices() const;
const std::vector<cv::Mat>& getCameraIntrinsics() const;
const std::vector<cv::Mat>& getCameraDistortions() const;
private:
std::vector<std::string> mSerialNumbers;
unsigned long long mNumberCameras;
std::vector<cv::Mat> mCameraMatrices;
std::vector<cv::Mat> mCameraIntrinsics;
std::vector<cv::Mat> mCameraDistortions;
DELETE_COPY(CameraParameterReader);
};
}
#endif // OPENPOSE_EXPERIMENTAL_3D_CAMERA_PARAMETER_READER_HPP
|
#include "skse64/GameMenus.h"
#include "skse64/GameReferences.h"
#include "skse64/ObScript.h"
#include "skse64/PluginAPI.h"
#include "skse64_common/skse_version.h"
#include "skse64_common/SafeWrite.h"
#include "ActorManager.h"
#include "config.h"
#include "EventDebugLogger.h"
#include "hdtSkyrimPhysicsWorld.h"
#include "Hooks.h"
#include "HookEvents.h"
#include <numeric>
#include <shlobj_core.h>
#include "skse64/GameRTTI.h"
#include "skse64_common/BranchTrampoline.h"
namespace hdt
{
IDebugLog gLog;
EventDebugLogger g_eventDebugLogger;
class FreezeEventHandler : public BSTEventSink<MenuOpenCloseEvent>
{
public:
FreezeEventHandler()
{
}
EventResult ReceiveEvent(MenuOpenCloseEvent* evn, EventDispatcher<MenuOpenCloseEvent>* dispatcher) override
{
auto mm = MenuManager::GetSingleton();
if (evn && evn->opening && (!strcmp(evn->menuName.data, "Loading Menu") || !strcmp(
evn->menuName.data, "RaceSex Menu")))
{
_DMESSAGE("loading menu/racesexmenu detected, scheduling physics reset on world un-suspend");
SkyrimPhysicsWorld::get()->suspend(true);
}
if (evn && !evn->opening && !strcmp(evn->menuName.data, "RaceSex Menu"))
{
_DMESSAGE("racemenu closed, reloading meshes");
ActorManager::instance()->reloadMeshes();
}
return kEvent_Continue;
}
} g_freezeEventHandler;
void checkOldPlugins()
{
auto framework = GetModuleHandleA("hdtSSEFramework");
auto physics = GetModuleHandleA("hdtSSEPhysics");
auto hh = GetModuleHandleA("hdtSSEHighHeels");
if (physics)
{
MessageBox(nullptr, TEXT(
"hdtSSEPhysics.dll is loaded. This is an older verson of HDT-SMP and conflicts with hdtSMP64.dll. Please remove it."),
TEXT("hdtSMP64"), MB_OK);
}
if (framework && !hh)
{
MessageBox(nullptr, TEXT(
"hdtSSEFramework.dll is loaded but hdtSSEHighHeels.dll is not being used. You no longer need hdtSSEFramework.dll with this version of SMP. Please remove it."),
TEXT("hdtSMP64"), MB_OK);
}
}
NiTexturePtr* GetTextureFromIndex(BSLightingShaderMaterial* material, UInt32 index)
{
switch (index)
{
case 0:
return &material->texture1;
break;
case 1:
return &material->texture2;
break;
case 2:
{
if (material->GetShaderType() == BSShaderMaterial::kShaderType_FaceGen)
{
return &static_cast<BSLightingShaderMaterialFacegen*>(material)->unkB0;
}
if (material->GetShaderType() == BSShaderMaterial::kShaderType_GlowMap)
{
return &static_cast<BSLightingShaderMaterialFacegen*>(material)->unkB0;
}
return &material->texture3;
}
break;
case 3:
{
if (material->GetShaderType() == BSShaderMaterial::kShaderType_FaceGen)
{
return &static_cast<BSLightingShaderMaterialFacegen*>(material)->unkA8;
}
if (material->GetShaderType() == BSShaderMaterial::kShaderType_Parallax)
{
return &static_cast<BSLightingShaderMaterialParallax*>(material)->unkA0;
}
if (material->GetShaderType() == BSShaderMaterial::kShaderType_Parallax || material->GetShaderType() ==
BSShaderMaterial::kShaderType_ParallaxOcc)
{
return &static_cast<BSLightingShaderMaterialParallaxOcc*>(material)->unkA0;
}
}
break;
case 4:
{
if (material->GetShaderType() == BSShaderMaterial::kShaderType_Eye)
{
return &static_cast<BSLightingShaderMaterialEye*>(material)->unkA0;
}
if (material->GetShaderType() == BSShaderMaterial::kShaderType_EnvironmentMap)
{
return &static_cast<BSLightingShaderMaterialEnvmap*>(material)->unkA0;
}
if (material->GetShaderType() == BSShaderMaterial::kShaderType_MultilayerParallax)
{
return &static_cast<BSLightingShaderMaterialMultiLayerParallax*>(material)->unkA8;
}
}
break;
case 5:
{
if (material->GetShaderType() == BSShaderMaterial::kShaderType_Eye)
{
return &static_cast<BSLightingShaderMaterialEye*>(material)->unkA8;
}
if (material->GetShaderType() == BSShaderMaterial::kShaderType_EnvironmentMap)
{
return &static_cast<BSLightingShaderMaterialEnvmap*>(material)->unkA0;
}
if (material->GetShaderType() == BSShaderMaterial::kShaderType_MultilayerParallax)
{
return &static_cast<BSLightingShaderMaterialMultiLayerParallax*>(material)->unkB0;
}
}
break;
case 6:
{
if (material->GetShaderType() == BSShaderMaterial::kShaderType_FaceGen)
{
return &static_cast<BSLightingShaderMaterialFacegen*>(material)->renderedTexture;
}
if (material->GetShaderType() == BSShaderMaterial::kShaderType_MultilayerParallax)
{
return &static_cast<BSLightingShaderMaterialMultiLayerParallax*>(material)->unkA0;
}
}
break;
case 7:
return &material->texture4;
break;
}
return nullptr;
}
void DumpNodeChildren(NiAVObject* node)
{
_MESSAGE("{%s} {%s} {%X} [%f, %f, %f]", node->GetRTTI()->name, node->m_name, node, node->m_worldTransform.pos.x, node->m_worldTransform.pos.y, node->m_worldTransform.pos.z);
if (node->m_extraDataLen > 0)
{
gLog.Indent();
for (UInt16 i = 0; i < node->m_extraDataLen; i++)
{
_MESSAGE("{%s} {%s} {%X}", node->m_extraData[i]->GetRTTI()->name, node->m_extraData[i]->m_pcName, node);
}
gLog.Outdent();
}
NiNode* niNode = node->GetAsNiNode();
if (niNode && niNode->m_children.m_emptyRunStart > 0)
{
gLog.Indent();
for (int i = 0; i < niNode->m_children.m_emptyRunStart; i++)
{
NiAVObject* object = niNode->m_children.m_data[i];
if (object)
{
NiNode* childNode = object->GetAsNiNode();
BSGeometry* geometry = object->GetAsBSGeometry();
if (geometry)
{
_MESSAGE("{%s} {%s} {%X} [%f, %f, %f] - Geometry", object->GetRTTI()->name, object->m_name, object, geometry->m_worldTransform.pos.x, geometry->m_worldTransform.pos.y, geometry->m_worldTransform.pos.z);
if (geometry->m_spSkinInstance && geometry->m_spSkinInstance->m_spSkinData)
{
gLog.Indent();
for (int i = 0; i < geometry->m_spSkinInstance->m_spSkinData->m_uiBones; i++)
{
auto bone = geometry->m_spSkinInstance->m_ppkBones[i];
_MESSAGE("Bone %d - {%s} {%s} {%X} [%f, %f, %f]", i, bone->GetRTTI()->name, bone->m_name, bone, bone->m_worldTransform.pos.x, bone->m_worldTransform.pos.y, bone->m_worldTransform.pos.z);
}
gLog.Outdent();
}
NiPointer<BSShaderProperty> shaderProperty = niptr_cast<BSShaderProperty>(
geometry->m_spEffectState);
if (shaderProperty)
{
BSLightingShaderProperty* lightingShader =
ni_cast(shaderProperty, BSLightingShaderProperty);
if (lightingShader)
{
BSLightingShaderMaterial* material = static_cast<BSLightingShaderMaterial*>(
lightingShader->material);
gLog.Indent();
for (int i = 0; i < BSTextureSet::kNumTextures; ++i)
{
const char* texturePath = material->textureSet->GetTexturePath(i);
if (!texturePath)
{
continue;
}
const char* textureName = "";
NiTexturePtr* texture = GetTextureFromIndex(material, i);
if (texture && texture->get())
{
textureName = texture->get()->name;
}
_MESSAGE("Texture %d - %s (%s)", i, texturePath, textureName);
}
_MESSAGE("Flags - %08X %08X", lightingShader->shaderFlags1, lightingShader->shaderFlags2);
gLog.Outdent();
}
}
}
else if (childNode)
{
DumpNodeChildren(childNode);
}
else
{
_MESSAGE("{%s} {%s} {%X} [%f, %f, %f]", object->GetRTTI()->name, object->m_name, object, object->m_worldTransform.pos.x, object->m_worldTransform.pos.y, object->m_worldTransform.pos.z);
}
}
}
gLog.Outdent();
}
}
void SMPDebug_PrintDetailed(bool includeItems)
{
static std::map<ActorManager::SkeletonState, char*> stateStrings =
{ { ActorManager::SkeletonState::e_InactiveNotInScene, "Not in scene"},
{ActorManager::SkeletonState::e_InactiveTooFar, "Too far from player"},
{ActorManager::SkeletonState::e_ActiveIsPlayer, "Is player character"},
{ActorManager::SkeletonState::e_ActiveNearPlayer, "Is near player"} };
auto skeletons = ActorManager::instance()->getSkeletons();
std::vector<int>order(skeletons.size());
std::iota(order.begin(), order.end(), 0);
std::sort(order.begin(), order.end(), [&](int a, int b) { return skeletons[a].state < skeletons[b].state; });
for (int i : order)
{
auto& skeleton = skeletons[i];
TESObjectREFR* skelOwner = nullptr;
TESFullName* ownerName = nullptr;
if (skeleton.skeleton->m_owner)
{
skelOwner = skeleton.skeleton->m_owner;
if (skelOwner->baseForm)
ownerName = DYNAMIC_CAST(skelOwner->baseForm, TESForm, TESFullName);
}
Console_Print("[HDT-SMP] %s skeleton - owner %s (refr formid %08x, base formid %08x) - %s",
skeleton.state > ActorManager::SkeletonState::e_SkeletonActive ? "active" : "inactive",
ownerName ? ownerName->GetName() : "unk_name",
skelOwner ? skelOwner->formID : 0x00000000,
skelOwner && skelOwner->baseForm ? skelOwner->baseForm->formID : 0x00000000,
stateStrings[skeleton.state]
);
if (includeItems)
{
for (auto armor : skeleton.getArmors())
{
Console_Print("[HDT-SMP] -- tracked armor addon %s, %s",
armor.armorWorn->m_name,
armor.state() != ActorManager::ItemState::e_NoPhysics
? armor.state() == ActorManager::ItemState::e_Active
? "has active physics system"
: "has inactive physics system"
: "has no physics system");
if (armor.state() != ActorManager::ItemState::e_NoPhysics)
{
for (auto mesh : armor.meshes())
Console_Print("[HDT-SMP] ---- has collision mesh %s", mesh->m_name->cstr());
}
}
if (skeleton.head.headNode)
{
for (auto headPart : skeleton.head.headParts)
{
Console_Print("[HDT-SMP] -- tracked headpart %s, %s",
headPart.headPart->m_name,
headPart.state() != ActorManager::ItemState::e_NoPhysics
? headPart.state() == ActorManager::ItemState::e_Active
? "has active physics system"
: "has inactive physics system"
: "has no physics system");
if (headPart.state() != ActorManager::ItemState::e_NoPhysics)
{
for (auto mesh : headPart.meshes())
Console_Print("[HDT-SMP] ---- has collision mesh %s", mesh->m_name->cstr());
}
}
}
}
}
}
bool SMPDebug_Execute(const ObScriptParam* paramInfo, ScriptData* scriptData, TESObjectREFR* thisObj,
TESObjectREFR* containingObj, Script* scriptObj, ScriptLocals* locals, double& result,
UInt32& opcodeOffsetPtr)
{
char buffer[MAX_PATH];
memset(buffer, 0, MAX_PATH);
char buffer2[MAX_PATH];
memset(buffer2, 0, MAX_PATH);
if (!ObjScript_ExtractArgs(paramInfo, scriptData, opcodeOffsetPtr, thisObj, containingObj, scriptObj, locals,
buffer, buffer2))
{
return false;
}
if (_strnicmp(buffer, "reset", MAX_PATH) == 0)
{
Console_Print("running full smp reset");
SkyrimPhysicsWorld::get()->resetTransformsToOriginal();
ActorManager::instance()->reloadMeshes();
SkyrimPhysicsWorld::get()->resetSystems();
return true;
}
if (_strnicmp(buffer, "dumptree", MAX_PATH) == 0)
{
if (thisObj)
{
Console_Print("dumping targeted reference's node tree");
DumpNodeChildren(thisObj->GetNiRootNode(0));
}
else
{
Console_Print("error: you must target a reference to dump their node tree");
}
return true;
}
if (_strnicmp(buffer, "detail", MAX_PATH) == 0)
{
SMPDebug_PrintDetailed(true);
return true;
}
if(_strnicmp(buffer, "list", MAX_PATH) == 0)
{
SMPDebug_PrintDetailed(false);
return true;
}
auto skeletons = ActorManager::instance()->getSkeletons();
size_t activeSkeletons = 0;
size_t armors = 0;
size_t headParts = 0;
size_t activeArmors = 0;
size_t activeHeadParts = 0;
size_t activeCollisionMeshes = 0;
for (auto skeleton : skeletons)
{
if (skeleton.state > ActorManager::SkeletonState::e_SkeletonActive)
activeSkeletons++;
for (const auto armor : skeleton.getArmors())
{
armors++;
if (armor.state() == ActorManager::ItemState::e_Active)
{
activeArmors++;
activeCollisionMeshes += armor.meshes().size();
}
}
if (skeleton.head.headNode)
{
for (const auto headpart : skeleton.head.headParts)
{
headParts++;
if (headpart.state() == ActorManager::ItemState::e_Active)
{
activeHeadParts++;
activeCollisionMeshes += headpart.meshes().size();
}
}
}
}
Console_Print("[HDT-SMP] tracked skeletons: %d", skeletons.size());
Console_Print("[HDT-SMP] active skeletons: %d", activeSkeletons);
Console_Print("[HDT-SMP] tracked armor addons: %d", armors);
Console_Print("[HDT-SMP] tracked head parts: %d", headParts);
Console_Print("[HDT-SMP] active armor addons: %d", activeArmors);
Console_Print("[HDT-SMP] active head parts: %d", activeHeadParts);
Console_Print("[HDT-SMP] active collision meshes: %d", activeCollisionMeshes);
return true;
}
}
extern "C" {
bool SKSEPlugin_Query(const SKSEInterface* skse, PluginInfo* info)
{
// populate info structure
info->infoVersion = PluginInfo::kInfoVersion;
info->name = "hdtSSEPhysics";
info->version = 1;
hdt::gLog.OpenRelative(CSIDL_MYDOCUMENTS, "\\My Games\\Skyrim Special Edition\\SKSE\\hdtSMP64.log");
hdt::gLog.SetLogLevel(IDebugLog::LogLevel::kLevel_Message);
_MESSAGE("hdtSMP64 2.0");
if (skse->isEditor)
{
return false;
}
if (skse->runtimeVersion != CURRENT_RELEASE_RUNTIME)
{
_FATALERROR("attempted to load plugin into unsupported game version, exiting");
return false;
}
if (!g_branchTrampoline.Create(1024 * 1))
{
_FATALERROR("couldn't create branch trampoline. this is fatal. skipping remainder of init process.");
return false;
}
if (!g_localTrampoline.Create(1024 * 1, nullptr))
{
_FATALERROR("couldn't create codegen buffer. this is fatal. skipping remainder of init process.");
return false;
}
return true;
}
bool SKSEPlugin_Load(const SKSEInterface* skse)
{
hdt::g_frameEventDispatcher.addListener(hdt::ActorManager::instance());
hdt::g_frameEventDispatcher.addListener(hdt::SkyrimPhysicsWorld::get());
hdt::g_shutdownEventDispatcher.addListener(hdt::ActorManager::instance());
hdt::g_shutdownEventDispatcher.addListener(hdt::SkyrimPhysicsWorld::get());
hdt::g_armorAttachEventDispatcher.addListener(hdt::ActorManager::instance());
hdt::g_skinSingleHeadGeometryEventDispatcher.addListener(hdt::ActorManager::instance());
hdt::g_skinAllHeadGeometryEventDispatcher.addListener(hdt::ActorManager::instance());
hdt::hookAll();
const auto messageInterface = reinterpret_cast<SKSEMessagingInterface*>(skse->QueryInterface(kInterface_Messaging));
if (messageInterface)
{
const auto cameraDispatcher = static_cast<EventDispatcher<SKSECameraEvent>*>(messageInterface->
GetEventDispatcher(SKSEMessagingInterface::kDispatcher_CameraEvent));
if (cameraDispatcher)
cameraDispatcher->AddEventSink(hdt::SkyrimPhysicsWorld::get());
messageInterface->RegisterListener(skse->GetPluginHandle(), "SKSE", [](SKSEMessagingInterface::Message* msg)
{
if (msg && msg->type == SKSEMessagingInterface::kMessage_InputLoaded)
{
MenuManager* mm = MenuManager::GetSingleton();
if (mm)
mm->MenuOpenCloseEventDispatcher()->AddEventSink(&hdt::g_freezeEventHandler);
hdt::checkOldPlugins();
hdt::loadConfig();
#ifdef DEBUG
hdt::g_armorAttachEventDispatcher.addListener(&hdt::g_eventDebugLogger);
GetEventDispatcherList()->unk1B8.AddEventSink(&hdt::g_eventDebugLogger);
GetEventDispatcherList()->unk840.AddEventSink(&hdt::g_eventDebugLogger);
#endif
}
});
}
ObScriptCommand* hijackedCommand = nullptr;
for (ObScriptCommand* iter = g_firstConsoleCommand; iter->opcode < kObScript_NumConsoleCommands +
kObScript_ConsoleOpBase; ++iter)
{
if (!strcmp(iter->longName, "ShowRenderPasses"))
{
hijackedCommand = iter;
break;
}
}
if (hijackedCommand)
{
static ObScriptParam params[1];
params[0].typeID = ObScriptParam::kType_String;
params[0].typeStr = "String (optional)";
params[0].isOptional = 1;
ObScriptCommand cmd = *hijackedCommand;
cmd.longName = "SMPDebug";
cmd.shortName = "smp";
cmd.helpText = "smp <reset>";
cmd.needsParent = 0;
cmd.numParams = 1;
cmd.params = params;
cmd.execute = hdt::SMPDebug_Execute;
cmd.flags = 0;
SafeWriteBuf(reinterpret_cast<uintptr_t>(hijackedCommand), &cmd, sizeof(cmd));
}
return true;
}
}
|
/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
// Include CLBlast headers early, and then set EIGEN_HAS_CL_FP16
// if we have new enough CL (which we will only know after including
// cl.h). This ensures that Eigen's Half.h does not attempt to make its own
// __half typedef if CL has already defined one (and conversely, that we do
// not include <cl_fp16.h> after Half.h has made its typedef).
#include "cuda.h"
// #include "cl/include/cublas_v2.h"
// #if CL_VERSION >= 7050
// #define EIGEN_HAS_CL_FP16
// #endif
// #if CL_VERSION >= 8000
// #define SE_CL_DATA_HALF CL_R_16F
// #else
// #define SE_CL_DATA_HALF CUBLAS_DATA_HALF
// #endif
#include "tensorflow/stream_executor/cl/cl_blas.h"
#include <complex>
#include "tensorflow/stream_executor/cl/cl_activation.h"
#include "tensorflow/stream_executor/cl/cl_gpu_executor.h"
#include "tensorflow/stream_executor/cl/cl_helpers.h"
#include "tensorflow/stream_executor/cl/cl_platform_id.h"
#include "tensorflow/stream_executor/cl/cl_stream.h"
#include "tensorflow/stream_executor/device_memory.h"
// #include "tensorflow/stream_executor/dso_loader.h"
#include "tensorflow/stream_executor/lib/env.h"
#include "tensorflow/stream_executor/lib/initialize.h"
#include "tensorflow/stream_executor/lib/status.h"
#include "tensorflow/stream_executor/lib/status_macros.h"
#include "tensorflow/stream_executor/lib/strcat.h"
#include "tensorflow/stream_executor/lib/stringprintf.h"
#include "tensorflow/stream_executor/platform/logging.h"
#include "tensorflow/stream_executor/platform/port.h"
#include "tensorflow/stream_executor/plugin_registry.h"
#include "tensorflow/stream_executor/scratch_allocator.h"
#include "tensorflow/stream_executor/stream_executor.h"
#include <iostream>
namespace stream_executor {
namespace cl {
PLUGIN_REGISTRY_DEFINE_PLUGIN_ID(kClBlasPlugin);
namespace dynload {
// #define PERFTOOLS_GPUTOOLS_CUBLAS_WRAP(__name) \
// struct DynLoadShim__##__name { \
// static const char *kName; \
// using FuncPointerT = std::add_pointer<decltype(::__name)>::type; \
// static void *GetDsoHandle() { \
// static auto status = internal::CachedDsoLoader::GetCublasDsoHandle(); \
// return status.ValueOrDie(); \
// } \
// static FuncPointerT LoadOrDie() { \
// void *f; \
// port::Status s = port::Env::Default()->GetSymbolFromLibrary( \
// GetDsoHandle(), kName, &f); \
// CHECK(s.ok()) << "could not find " << kName \
// << " in CLBlast DSO; dlerror: " << s.error_message(); \
// return reinterpret_cast<FuncPointerT>(f); \
// } \
// static FuncPointerT DynLoad() { \
// static FuncPointerT f = LoadOrDie(); \
// return f; \
// } \
// template <typename... Args> \
// cublasStatus_t operator()(CLExecutor *parent, Args... args) { \
// cl::ScopedActivateExecutorContext sac{parent}; \
// return DynLoad()(args...); \
// } \
// } __name; \
// const char *DynLoadShim__##__name::kName = #__name;
// #define PERFTOOLS_GPUTOOLS_CUBLAS_V2_WRAP(__name) \
// PERFTOOLS_GPUTOOLS_CUBLAS_WRAP(__name)
//#define CUBLAS_BLAS_ROUTINE_EACH(__macro)
// __macro(cublasSgemm)
// __macro(cublasSnrm2)
// __macro(cublasDnrm2)
// __macro(cublasScnrm2)
// __macro(cublasDznrm2)
// __macro(cublasSdot)
// __macro(cublasDdot)
// __macro(cublasCdotu)
// __macro(cublasCdotc)
// __macro(cublasZdotu)
// __macro(cublasZdotc)
// __macro(cublasSscal)
// __macro(cublasDscal)
// __macro(cublasCscal)
// __macro(cublasCsscal)
// __macro(cublasZscal)
// __macro(cublasZdscal)
// __macro(cublasSaxpy)
// __macro(cublasDaxpy)
// __macro(cublasCaxpy)
// __macro(cublasZaxpy)
// __macro(cublasScopy)
// __macro(cublasDcopy)
// __macro(cublasCcopy)
// __macro(cublasZcopy)
// __macro(cublasSswap)
// __macro(cublasDswap)
// __macro(cublasCswap)
// __macro(cublasZswap)
// __macro(cublasIsamax)
// __macro(cublasIdamax)
// __macro(cublasIcamax)
// __macro(cublasIzamax)
// __macro(cublasIsamin)
// __macro(cublasIdamin)
// __macro(cublasIcamin)
// __macro(cublasIzamin)
// __macro(cublasSasum)
// __macro(cublasDasum)
// __macro(cublasScasum)
// __macro(cublasDzasum)
// __macro(cublasSrot)
// __macro(cublasDrot)
// __macro(cublasCrot)
// __macro(cublasCsrot)
// __macro(cublasZrot)
// __macro(cublasZdrot)
// __macro(cublasSrotg)
// __macro(cublasDrotg)
// __macro(cublasCrotg)
// __macro(cublasZrotg)
// __macro(cublasSrotm)
// __macro(cublasDrotm)
// __macro(cublasSrotmg)
// __macro(cublasDrotmg)
// __macro(cublasSgemv)
// __macro(cublasDgemv)
// __macro(cublasCgemv)
// __macro(cublasZgemv)
// __macro(cublasSgbmv)
// __macro(cublasDgbmv)
// __macro(cublasCgbmv)
// __macro(cublasZgbmv)
// __macro(cublasStrmv)
// __macro(cublasDtrmv)
// __macro(cublasCtrmv)
// __macro(cublasZtrmv)
// __macro(cublasStbmv)
// __macro(cublasDtbmv)
// __macro(cublasCtbmv)
// __macro(cublasZtbmv)
// __macro(cublasStpmv)
// __macro(cublasDtpmv)
// __macro(cublasCtpmv)
// __macro(cublasZtpmv)
// __macro(cublasStrsv)
// __macro(cublasDtrsv)
// __macro(cublasCtrsv)
// __macro(cublasZtrsv)
// __macro(cublasStpsv)
// __macro(cublasDtpsv)
// __macro(cublasCtpsv)
// __macro(cublasZtpsv)
// __macro(cublasStbsv)
// __macro(cublasDtbsv)
// __macro(cublasCtbsv)
// __macro(cublasZtbsv)
// __macro(cublasSsymv)
// __macro(cublasDsymv)
// __macro(cublasCsymv)
// __macro(cublasZsymv)
// __macro(cublasChemv)
// __macro(cublasZhemv)
// __macro(cublasSsbmv)
// __macro(cublasDsbmv)
// __macro(cublasChbmv)
// __macro(cublasZhbmv)
// __macro(cublasSspmv)
// __macro(cublasDspmv)
// __macro(cublasChpmv)
// __macro(cublasZhpmv)
// __macro(cublasSger)
// __macro(cublasDger)
// __macro(cublasCgeru)
// __macro(cublasCgerc)
// __macro(cublasZgeru)
// __macro(cublasZgerc)
// __macro(cublasSsyr)
// __macro(cublasDsyr)
// __macro(cublasCsyr)
// __macro(cublasZsyr)
// __macro(cublasCher)
// __macro(cublasZher)
// __macro(cublasSspr)
// __macro(cublasDspr)
// __macro(cublasChpr)
// __macro(cublasZhpr)
// __macro(cublasSsyr2)
// __macro(cublasDsyr2)
// __macro(cublasCsyr2)
// __macro(cublasZsyr2)
// __macro(cublasCher2)
// __macro(cublasZher2)
// __macro(cublasSspr2)
// __macro(cublasDspr2)
// __macro(cublasChpr2)
// __macro(cublasZhpr2)
// __macro(cublasDgemm)
// __macro(cublasCgemm)
// __macro(cublasZgemm)
// __macro(cublasSsyrk)
// __macro(cublasDsyrk)
// __macro(cublasCsyrk)
// __macro(cublasZsyrk)
// __macro(cublasCherk)
// __macro(cublasZherk)
// __macro(cublasSsyr2k)
// __macro(cublasDsyr2k)
// __macro(cublasCsyr2k)
// __macro(cublasZsyr2k)
// __macro(cublasCher2k)
// __macro(cublasZher2k)
// __macro(cublasSsyrkx)
// __macro(cublasDsyrkx)
// __macro(cublasCsyrkx)
// __macro(cublasZsyrkx)
// __macro(cublasCherkx)
// __macro(cublasZherkx)
// __macro(cublasSsymm)
// __macro(cublasDsymm)
// __macro(cublasCsymm)
// __macro(cublasZsymm)
// __macro(cublasChemm)
// __macro(cublasZhemm)
// __macro(cublasStrsm)
// __macro(cublasDtrsm)
// __macro(cublasCtrsm)
// __macro(cublasZtrsm)
// __macro(cublasStrmm)
// __macro(cublasDtrmm)
// __macro(cublasCtrmm)
// __macro(cublasZtrmm)
// __macro(cublasSgeam)
// __macro(cublasDgeam)
// __macro(cublasCgeam)
// __macro(cublasZgeam)
// __macro(cublasSdgmm)
// __macro(cublasDdgmm)
// __macro(cublasCdgmm)
// __macro(cublasZdgmm)
// PERFTOOLS_GPUTOOLS_CUBLAS_V2_WRAP(cublasCreate)
// PERFTOOLS_GPUTOOLS_CUBLAS_V2_WRAP(cublasDestroy)
// PERFTOOLS_GPUTOOLS_CUBLAS_V2_WRAP(cublasSetStream)
// PERFTOOLS_GPUTOOLS_CUBLAS_V2_WRAP(cublasSetPointerMode)
// PERFTOOLS_GPUTOOLS_CUBLAS_V2_WRAP(cublasGetPointerMode)
// PERFTOOLS_GPUTOOLS_CUBLAS_WRAP(cublasSgemmBatched)
// PERFTOOLS_GPUTOOLS_CUBLAS_WRAP(cublasDgemmBatched)
// PERFTOOLS_GPUTOOLS_CUBLAS_WRAP(cublasCgemmBatched)
// PERFTOOLS_GPUTOOLS_CUBLAS_WRAP(cublasZgemmBatched)
// CUBLAS_BLAS_ROUTINE_EACH(PERFTOOLS_GPUTOOLS_CUBLAS_V2_WRAP)
// #if CL_VERSION >= 7050
// PERFTOOLS_GPUTOOLS_CUBLAS_WRAP(cublasSgemmEx)
// #endif
} // namespace dynload
static string ToString(cublasStatus_t status) {
switch (status) {
case CUBLAS_STATUS_SUCCESS:
return "CUBLAS_STATUS_SUCCESS";
case CUBLAS_STATUS_NOT_INITIALIZED:
return "CUBLAS_STATUS_NOT_INITIALIZED";
case CUBLAS_STATUS_ALLOC_FAILED:
return "CUBLAS_STATUS_ALLOC_FAILED";
case CUBLAS_STATUS_INVALID_VALUE:
return "CUBLAS_STATUS_INVALID_VALUE";
case CUBLAS_STATUS_ARCH_MISMATCH:
return "CUBLAS_STATUS_ARCH_MISMATCH";
case CUBLAS_STATUS_MAPPING_ERROR:
return "CUBLAS_STATUS_MAPPING_ERROR";
case CUBLAS_STATUS_EXECUTION_FAILED:
return "CUBLAS_STATUS_EXECUTION_FAILED";
case CUBLAS_STATUS_INTERNAL_ERROR:
return "CUBLAS_STATUS_INTERNAL_ERROR";
default:
return port::StrCat("<invalid cublas status: ", status, ">");
}
}
// CLBlast has interfaces that permit pointers to be passed from either the host
// memory space or the device memory space; however, you must instruct it as to
// which address space those pointers are in with cublasSetPointerMode.
//
// This helper sets the CLBlast pointer mode to a desired value for a CLBlast call
// you are about to perform in a given scope.
//
// The prior CLBlast pointer mode is retained and restored when this object goes
// out of scope.
class ScopedCublasPointerMode {
public:
// Note that, because the setting of the cublas pointer mode is fallible,
// construction of this scoped datatype must be paired with a call to
// Init().
//
// Parameters:
// handle: The cublas library handle to act upon in setting the pointer mode.
explicit ScopedCublasPointerMode(CLExecutor *parent, cublasHandle_t handle)
: parent_(parent), handle_(handle), ok_(false) {}
// Attempts the switch to the requested scoped pointer mode, new_mode.
//
// Note that when false is returned, an appropriate error has already been
// logged.
bool Init(cublasPointerMode_t new_mode) {
cublasStatus_t ret =
cublasGetPointerMode_v2(handle_, &old_mode_);
if (ret != CUBLAS_STATUS_SUCCESS) {
LOG(ERROR) << "failed to get old cublas pointer mode: " << ToString(ret);
return ok_ = false;
}
ret = cublasSetPointerMode_v2(handle_, new_mode);
if (ret != CUBLAS_STATUS_SUCCESS) {
LOG(ERROR) << "failed to set new cublas pointer mode: " << ToString(ret);
return ok_ = false;
}
return ok_ = true;
}
// Switches back to the prior pointer mode, if the switch operation was
// successful in the first place.
~ScopedCublasPointerMode() {
if (ok_) {
cublasStatus_t ret =
cublasSetPointerMode_v2(handle_, old_mode_);
if (ret != CUBLAS_STATUS_SUCCESS) {
LOG(ERROR) << "failed to set former cublas pointer mode: "
<< ToString(ret);
}
}
}
private:
CLExecutor *parent_; // Executor establishing this pointer mode for.
cublasHandle_t handle_; // Handle to the CLBlast instance of interest.
cublasPointerMode_t old_mode_; // Prior CLBlast pointer mode, to be restored.
bool ok_; // Whether the change was successful.
};
bool CLBlas::Init() {
cublasStatus_t ret = cublasCreate_v2(&blas_);
if (ret != CUBLAS_STATUS_SUCCESS) {
LOG(ERROR) << "failed to create cublas handle: " << ToString(ret);
return false;
}
return true;
}
CLBlas::CLBlas(cl::CLExecutor *parent)
: parent_(CHECK_NOTNULL(parent)), blas_(nullptr) {
// std::cout << "CLBlast()" << std::endl;
}
CLBlas::~CLBlas() {
// std::cout << "~CLBlast()" << std::endl;
if (blas_ != nullptr) {
cublasDestroy_v2(blas_);
}
}
bool CLBlas::SetStream(Stream *stream) {
// std::cout << "CLBlas::SetStream()" << std::endl;
CHECK(stream != nullptr);
CHECK(AsCLStreamValue(stream) != nullptr);
CHECK(blas_ != nullptr);
cublasStatus_t ret =
cublasSetStream_v2(blas_, AsCLStreamValue(stream));
if (ret != CUBLAS_STATUS_SUCCESS) {
LOG(ERROR) << "failed to set stream for CLBlast calls: " << ToString(ret);
return false;
}
return true;
}
namespace {
// Helper functions transforming blas arguments into CLBlast arguments.
cublasOperation_t CLBlasTranspose(blas::Transpose trans) {
// std::cout << "CLBlas::CLBlasTranspoe()" << std::endl;
switch (trans) {
case blas::Transpose::kNoTranspose:
return CUBLAS_OP_N;
case blas::Transpose::kTranspose:
return CUBLAS_OP_T;
case blas::Transpose::kConjugateTranspose:
return CUBLAS_OP_C;
default:
LOG(FATAL) << "Invalid value of blas::Transpose.";
}
}
cublasFillMode_t CLBlasUpperLower(blas::UpperLower uplo) {
// std::cout << "CLBlas::CLBlasUpperLower()" << std::endl;
switch (uplo) {
case blas::UpperLower::kUpper:
return CUBLAS_FILL_MODE_UPPER;
case blas::UpperLower::kLower:
return CUBLAS_FILL_MODE_LOWER;
default:
LOG(FATAL) << "Invalid value of blas::UpperLower.";
}
}
cublasDiagType_t CLBlasDiagonal(blas::Diagonal diag) {
// std::cout << "CLBlas::CLBlasDiagonal()" << std::endl;
switch (diag) {
case blas::Diagonal::kUnit:
return CUBLAS_DIAG_UNIT;
case blas::Diagonal::kNonUnit:
return CUBLAS_DIAG_NON_UNIT;
default:
LOG(FATAL) << "Invalid value of blas::Diagonal.";
}
}
cublasSideMode_t CLBlasSide(blas::Side side) {
// std::cout << "CLBlas::CLBlasSide()" << std::endl;
switch (side) {
case blas::Side::kLeft:
return CUBLAS_SIDE_LEFT;
case blas::Side::kRight:
return CUBLAS_SIDE_RIGHT;
default:
LOG(FATAL) << "Invalid value of blas::Side.";
}
}
} // namespace
template <typename FuncT, typename... Args>
bool CLBlas::DoBlasInternal(FuncT cublas_func, Stream *stream,
bool pointer_mode_host, Args... args) {
// std::cout << "CLBlas::DoBlasInternal()" << std::endl;
mutex_lock lock{mu_};
CHECK(blas_ != nullptr);
if (!SetStream(stream)) {
return false;
}
ScopedCublasPointerMode pointer_mode{parent_, blas_};
if (!pointer_mode.Init(pointer_mode_host ? CUBLAS_POINTER_MODE_HOST
: CUBLAS_POINTER_MODE_DEVICE)) {
return false;
}
cublasStatus_t ret = cublas_func(blas_, args...);
if (ret != CUBLAS_STATUS_SUCCESS) {
// LOG(ERROR) << "failed to run CLBlast routine " << cublas_func.kName << ": "
// << ToString(ret);
LOG(ERROR) << "failed to run CLBlast routine " << ": "
<< ToString(ret);
return false;
}
return true;
}
bool CLBlas::DoBlasGemm(Stream *stream, blas::Transpose transa,
blas::Transpose transb, uint64 m, uint64 n, uint64 k,
float alpha, const DeviceMemory<float> &a, int lda,
const DeviceMemory<float> &b, int ldb, float beta,
DeviceMemory<float> *c, int ldc) {
// std::cout << "CLBlas::DoBlasGemm()" << std::endl;
VLOG(1) << port::Printf(
"doing CLBlast SGEMM: at=%d bt=%d m=%llu n=%llu "
"k=%llu alpha=%f a=%p lda=%d b=%p ldb=%d beta=%f "
"c=%p ldc=%d",
static_cast<int>(transa), static_cast<int>(transb), m, n, k, alpha,
a.opaque(), lda, b.opaque(), ldb, beta, c->opaque(), ldc);
if (transa == blas::Transpose::kNoTranspose) {
if (lda < static_cast<int64>(m)) {
LOG(WARNING) << "GEMM lda was smaller than m (no transpose case); "
"precondition violation";
}
} else {
if (lda < static_cast<int64>(k)) {
LOG(WARNING) << "GEMM lda (" << lda << ") was smaller than k (" << k
<< ") (transpose case); precondition violation";
}
}
if (transb == blas::Transpose::kNoTranspose) {
if (ldb < static_cast<int64>(k)) {
LOG(WARNING) << "GEMM ldb (" << ldb << ") was smaller than k (" << k
<< ") (no transpose case); precondition violation";
}
} else {
if (ldb < static_cast<int64>(n)) {
LOG(WARNING) << "GEMM ldb was smaller than n (transpose case); "
"precondition violation";
}
}
return DoBlasInternal(
cublasSgemm, stream, true /* = pointer_mode_host */,
CLBlasTranspose(transa), CLBlasTranspose(transb), m, n, k, &alpha,
CUDAMemory(a), lda, CUDAMemory(b), ldb, &beta, CUDAMemoryMutable(c), ldc);
}
bool CLBlas::DoBlasGemvWithProfiling(
Stream *stream, blas::Transpose trans, uint64 m, uint64 n, float alpha,
const DeviceMemory<float> &a, int lda, const DeviceMemory<float> &x,
int incx, float beta, DeviceMemory<float> *y, int incy,
blas::ProfileResult *output_profile_result) {
return DoBlasGemvWithProfilingImpl(stream, trans, m, n, alpha, a, lda, x,
incx, beta, y, incy,
output_profile_result);
}
bool CLBlas::DoBlasGemmWithProfiling(
Stream *stream, blas::Transpose transa, blas::Transpose transb, uint64 m,
uint64 n, uint64 k, float alpha, const DeviceMemory<float> &a, int lda,
const DeviceMemory<float> &b, int ldb, float beta, DeviceMemory<float> *c,
int ldc, blas::ProfileResult *output_profile_result) {
return DoBlasGemmWithProfilingImpl(stream, transa, transb, m, n, k, alpha, a,
lda, b, ldb, beta, c, ldc,
output_profile_result);
}
template <typename T>
bool CLBlas::DoBlasGemvWithProfilingImpl(
Stream *stream, blas::Transpose trans, uint64 m, uint64 n, const T &alpha,
const DeviceMemory<T> &a, int lda, const DeviceMemory<T> &x, int incx,
const T &beta, DeviceMemory<T> *y, int incy,
blas::ProfileResult *output_profile_result) {
return false;
// std::unique_ptr<CUDATimer, TimerDeleter> timer;
// if (output_profile_result != nullptr) {
// timer.reset(new CUDATimer(parent_));
// if (!timer->Init() || !timer->Start(AsCUDAStream(stream))) {
// return false;
// }
// }
//
// // Call blasGemm
// bool result = DoBlasGemm(stream, transa, transb, m, n, k, alpha, a, lda, b,
// ldb, beta, c, ldc);
//
// if (timer != nullptr && result) {
// // CUDATimer will CHECK-fail if we Stop() it while the stream is in an error
// // state.
// if (!timer->Stop(AsCUDAStream(stream))) {
// return false;
// }
// output_profile_result->set_is_valid(true);
// output_profile_result->set_algorithm(blas::kDefaultBlasGemm);
// output_profile_result->set_elapsed_time_in_ms(
// timer->GetElapsedMilliseconds());
// }
// return result;
}
template <typename T, typename ParamType>
bool CLBlas::DoBlasGemmWithProfilingImpl(
Stream *stream, blas::Transpose transa, blas::Transpose transb, uint64 m,
uint64 n, uint64 k, const ParamType &alpha, const DeviceMemory<T> &a,
int lda, const DeviceMemory<T> &b, int ldb, const ParamType &beta,
DeviceMemory<T> *c, int ldc, blas::ProfileResult *output_profile_result) {
return false;
// std::unique_ptr<CUDATimer, TimerDeleter> timer;
// if (output_profile_result != nullptr) {
// timer.reset(new CUDATimer(parent_));
// if (!timer->Init() || !timer->Start(AsCUDAStream(stream))) {
// return false;
// }
// }
//
// // Call blasGemm
// bool result = DoBlasGemm(stream, transa, transb, m, n, k, alpha, a, lda, b,
// ldb, beta, c, ldc);
//
// if (timer != nullptr && result) {
// // CUDATimer will CHECK-fail if we Stop() it while the stream is in an error
// // state.
// if (!timer->Stop(AsCUDAStream(stream))) {
// return false;
// }
// output_profile_result->set_is_valid(true);
// output_profile_result->set_algorithm(blas::kDefaultBlasGemm);
// output_profile_result->set_elapsed_time_in_ms(
// timer->GetElapsedMilliseconds());
// }
// return result;
}
template <typename InT, typename OutT, typename CompT>
bool CLBlas::DoBlasGemmWithAlgorithmImpl(
Stream *stream, blas::Transpose transa, blas::Transpose transb, uint64 m,
uint64 n, uint64 k, const HostOrDeviceScalar<CompT> &alpha,
const DeviceMemory<InT> &a, int lda, const DeviceMemory<InT> &b, int ldb,
const HostOrDeviceScalar<CompT> &beta, DeviceMemory<OutT> *c, int ldc,
blas::ComputationType computation_type, blas::AlgorithmType algorithm,
blas::ProfileResult *output_profile_result) {
// GPUs < sm_50 don't support cublasGemmEx.
int cc_major, cc_minor;
return false;
// if (stream->parent()->GetDeviceDescription().cuda_compute_capability(
// &cc_major, &cc_minor) &&
// cc_major < 5) {
// VLOG(2) << "DoBlasGemmWithAlgorithm returning false because sm" << cc_major
// << cc_minor << " devices don't support explicit gemm algorithms.";
// return false;
// }
//
// if (UsesTensorOps(algorithm) && !TensorOpsAvailable<InT>(cc_major)) {
// if (std::is_same<InT, Eigen::half>::value) {
// VLOG(2) << "DoBlasGemmWithAlgorithm returning false because algorithm "
// << algorithm
// << " uses tensor ops, but tensor ops are not available in sm"
// << cc_major << "X devices.";
// } else {
// VLOG(2) << "DoBlasGemmWithAlgorithm returning false because algorithm "
// << algorithm
// << " uses tensor ops, but the input data type is not fp16.";
// }
// return false;
// }
//
// // Either both 'alpha' and 'beta' need to be pointers to device memory, or
// // they need to be both host scalars.
// if (alpha.is_pointer() != beta.is_pointer()) {
// VLOG(2) << "DoBlasGemmWithAlgorithm returning false because one of `alpha` "
// "and `beta` is a pointer, but the other is not.";
// return false;
// }
//
// std::unique_ptr<CUDATimer, TimerDeleter> timer;
// if (output_profile_result != nullptr) {
// timer.reset(new CUDATimer(parent_));
// if (!timer->Init() || !timer->Start(AsCUDAStream(stream))) {
// VLOG(2) << "DoBlasGemmWithAlgorithm returning false because "
// "output_profile_result was given, but we were unable to "
// "create a CUDATimer.";
// return false;
// }
// }
//
// // Return false if we might be hitting a cuBLAS bug that produces the wrong
// // result. See nvbugs/2156201, b/79126339.
//#if CUDA_VERSION >= 9000 && CUDA_VERSION < 9020
// if ((algorithm == CUBLAS_GEMM_DEFAULT || algorithm >= CUBLAS_GEMM_ALGO13) &&
// std::max({m, n, k}) >= 2097153 && cc_major < 7) {
// VLOG(2) << "DoBlasGemmWithAlgorithm returning false to work around cudnn "
// "<9.2 bug with m, n, or k >= 2097153. See b/79126339.";
// return false;
// }
//#endif
//
// cudaDataType_t cuda_in_type = CUDADataType<InT>::type;
// // Since we are converting 'algorithm' to cublasGemmAlgo_t by static_cast,
// // we do the following compile-time check on the default value:
// static_assert(blas::kDefaultGemmAlgo == CUBLAS_GEMM_DFALT, "");
// // If 'alpha' and 'beta' are host scalars and CompT is Eigen::half, we
// // essentially reinterpet_cast to __half, which is safe because Eigen::half
// // inherits from __half.
// bool result = DoBlasInternalFailureOK(
// wrap::cublasGemmEx, stream, /* pointer_mode_host = */ !alpha.is_pointer(),
// CUDABlasTranspose(transa), CUDABlasTranspose(transb), m, n, k,
// alpha.is_pointer() ? CUDAMemory(alpha.pointer()) : &alpha.value(),
// CUDAMemory(a), cuda_in_type, lda, CUDAMemory(b), cuda_in_type, ldb,
// beta.is_pointer() ? CUDAMemory(beta.pointer()) : &beta.value(),
// CUDAMemoryMutable(c), CUDADataType<OutT>::type, ldc,
// CUDAComputationType(computation_type),
// static_cast<cublasGemmAlgo_t>(algorithm));
//
// if (timer != nullptr && result) {
// // CUDATimer will CHECK-fail if we Stop() it while the stream is in an error
// // state.
// if (!timer->Stop(AsCUDAStream(stream))) {
// VLOG(2) << "DoBlasGemmWithAlgorithm returning false; unable to stop "
// "CUDATimer.";
// return false;
// }
// output_profile_result->set_is_valid(true);
// output_profile_result->set_algorithm(algorithm);
// output_profile_result->set_elapsed_time_in_ms(
// timer->GetElapsedMilliseconds());
// }
// return result;
}
bool CLBlas::GetBlasGemmAlgorithms(
std::vector<blas::AlgorithmType> *out_algorithms) {
// cublasGemmAlgo_t (and the function that accepts this type, cublasGemmEx)
// were first introduced in CUDA 8.
//
// Note that when CUDA version and compute capability is not sufficient, we
// still return the out_algorithms. Caller needs to make sure that in this
// case, the returned vector is empty.
*out_algorithms = {
// CUBLAS_GEMM_DFALT,
// CUBLAS_GEMM_ALGO0,
// CUBLAS_GEMM_ALGO1,
// CUBLAS_GEMM_ALGO2,
};
return true;
}
bool CLBlas::DoBlasGemmWithAlgorithm(
Stream *stream, blas::Transpose transa, blas::Transpose transb, uint64 m,
uint64 n, uint64 k, const HostOrDeviceScalar<float> &alpha,
const DeviceMemory<float> &a, int lda, const DeviceMemory<float> &b,
int ldb, const HostOrDeviceScalar<float> &beta, DeviceMemory<float> *c,
int ldc, blas::ComputationType computation_type,
blas::AlgorithmType algorithm, blas::ProfileResult *output_profile_result) {
return DoBlasGemmWithAlgorithmImpl(
stream, transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc,
computation_type, algorithm, output_profile_result);
}
bool CLBlas::DoBlasAsum(Stream *stream, uint64 elem_count,
const DeviceMemory<float> &x, int incx,
DeviceMemory<float> *result) {
// cout << "CLBlas::DoBlasAsum" << endl;
return false;
// return DoBlasInternal(cublasSasum, stream,
// false = pointer_mode_host , elem_count,
// CLMemory(x), incx, CLMemoryMutable(result));
}
bool CLBlas::DoBlasAsum(Stream *stream, uint64 elem_count,
const DeviceMemory<double> &x, int incx,
DeviceMemory<double> *result) {
return false;
// return DoBlasInternal(cublasDasum, stream,
// false = pointer_mode_host , elem_count,
// CLMemory(x), incx, CLMemoryMutable(result));
}
bool CLBlas::DoBlasAsum(Stream *stream, uint64 elem_count,
const DeviceMemory<std::complex<float>> &x, int incx,
DeviceMemory<float> *result) {
return false;
// return DoBlasInternal(
// cublasScasum, stream, false = pointer_mode_host ,
// elem_count, CLComplex(CLMemory(x)), incx, CLMemoryMutable(result));
}
bool CLBlas::DoBlasAsum(Stream *stream, uint64 elem_count,
const DeviceMemory<std::complex<double>> &x, int incx,
DeviceMemory<double> *result) {
return false;
// return DoBlasInternal(
// cublasDzasum, stream, false = pointer_mode_host ,
// elem_count, CLComplex(CLMemory(x)), incx, CLMemoryMutable(result));
}
bool CLBlas::DoBlasAxpy(Stream *stream, uint64 elem_count, float alpha,
const DeviceMemory<float> &x, int incx,
DeviceMemory<float> *y, int incy) {
return false;
// return DoBlasInternal(cublasSaxpy, stream,
// true = pointer_mode_host , elem_count, &alpha,
// CLMemory(x), incx, CLMemoryMutable(y), incy);
}
bool CLBlas::DoBlasAxpy(Stream *stream, uint64 elem_count, double alpha,
const DeviceMemory<double> &x, int incx,
DeviceMemory<double> *y, int incy) {
return false;
// return DoBlasInternal(cublasDaxpy, stream,
// true = pointer_mode_host , elem_count, &alpha,
// CLMemory(x), incx, CLMemoryMutable(y), incy);
}
bool CLBlas::DoBlasAxpy(Stream *stream, uint64 elem_count,
std::complex<float> alpha,
const DeviceMemory<std::complex<float>> &x, int incx,
DeviceMemory<std::complex<float>> *y, int incy) {
return false;
// return DoBlasInternal(cublasCaxpy, stream,
// true /* = pointer_mode_host */, elem_count,
// CLComplex(&alpha), CLComplex(CLMemory(x)), incx,
// CLComplex(CLMemoryMutable(y)), incy);
}
bool CLBlas::DoBlasAxpy(Stream *stream, uint64 elem_count,
std::complex<double> alpha,
const DeviceMemory<std::complex<double>> &x, int incx,
DeviceMemory<std::complex<double>> *y, int incy) {
return false;
// return DoBlasInternal(cublasZaxpy, stream,
// true /* = pointer_mode_host */, elem_count,
// CLComplex(&alpha), CLComplex(CLMemory(x)), incx,
// CLComplex(CLMemoryMutable(y)), incy);
}
bool CLBlas::DoBlasCopy(Stream *stream, uint64 elem_count,
const DeviceMemory<float> &x, int incx,
DeviceMemory<float> *y, int incy) {
// std::cout << "CLBlas::DoBlasCopy()" << std::endl;
return false;
// return DoBlasInternal(cublasScopy, stream,
// true = pointer_mode_host , elem_count,
// CLMemory(x), incx, CLMemoryMutable(y), incy);
}
bool CLBlas::DoBlasCopy(Stream *stream, uint64 elem_count,
const DeviceMemory<double> &x, int incx,
DeviceMemory<double> *y, int incy) {
// cout << "CLBlas::DoBlasCopy" << endl;
return false;
// return DoBlasInternal(cublasDcopy, stream,
// true = pointer_mode_host , elem_count,
// CLMemory(x), incx, CLMemoryMutable(y), incy);
}
bool CLBlas::DoBlasCopy(Stream *stream, uint64 elem_count,
const DeviceMemory<std::complex<float>> &x, int incx,
DeviceMemory<std::complex<float>> *y, int incy) {
// cout << "CLBlas::DoBlasCopy" << endl;
return false;
// return DoBlasInternal(cublasCcopy, stream,
// true /* = pointer_mode_host */, elem_count,
// CLComplex(CLMemory(x)), incx,
// CLComplex(CLMemoryMutable(y)), incy);
}
bool CLBlas::DoBlasCopy(Stream *stream, uint64 elem_count,
const DeviceMemory<std::complex<double>> &x, int incx,
DeviceMemory<std::complex<double>> *y, int incy) {
// cout << "CLBlas::DoBlasCopy" << endl;
return false;
// return DoBlasInternal(cublasZcopy, stream,
// true /* = pointer_mode_host */, elem_count,
// CLComplex(CLMemory(x)), incx,
// CLComplex(CLMemoryMutable(y)), incy);
}
bool CLBlas::DoBlasDot(Stream *stream, uint64 elem_count,
const DeviceMemory<float> &x, int incx,
const DeviceMemory<float> &y, int incy,
DeviceMemory<float> *result) {
return false;
// return DoBlasInternal(
// cublasSdot, stream, false /* = pointer_mode_host */, elem_count,
// CLMemory(x), incx, CLMemory(y), incy, CLMemoryMutable(result));
}
bool CLBlas::DoBlasDot(Stream *stream, uint64 elem_count,
const DeviceMemory<double> &x, int incx,
const DeviceMemory<double> &y, int incy,
DeviceMemory<double> *result) {
return false;
// return DoBlasInternal(
// cublasDdot, stream, false /* = pointer_mode_host */, elem_count,
// CLMemory(x), incx, CLMemory(y), incy, CLMemoryMutable(result));
}
bool CLBlas::DoBlasDotc(Stream *stream, uint64 elem_count,
const DeviceMemory<std::complex<float>> &x, int incx,
const DeviceMemory<std::complex<float>> &y, int incy,
DeviceMemory<std::complex<float>> *result) {
return false;
// return DoBlasInternal(
// cublasCdotc, stream, false /* = pointer_mode_host */, elem_count,
// CLComplex(CLMemory(x)), incx, CLComplex(CLMemory(y)), incy,
// CLComplex(CLMemoryMutable(result)));
}
bool CLBlas::DoBlasDotc(Stream *stream, uint64 elem_count,
const DeviceMemory<std::complex<double>> &x, int incx,
const DeviceMemory<std::complex<double>> &y, int incy,
DeviceMemory<std::complex<double>> *result) {
return false;
// return DoBlasInternal(
// cublasZdotc, stream, false /* = pointer_mode_host */, elem_count,
// CLComplex(CLMemory(x)), incx, CLComplex(CLMemory(y)), incy,
// CLComplex(CLMemoryMutable(result)));
}
bool CLBlas::DoBlasDotu(Stream *stream, uint64 elem_count,
const DeviceMemory<std::complex<float>> &x, int incx,
const DeviceMemory<std::complex<float>> &y, int incy,
DeviceMemory<std::complex<float>> *result) {
return false;
// return DoBlasInternal(
// cublasCdotu, stream, false /* = pointer_mode_host */, elem_count,
// CLComplex(CLMemory(x)), incx, CLComplex(CLMemory(y)), incy,
// CLComplex(CLMemoryMutable(result)));
}
bool CLBlas::DoBlasDotu(Stream *stream, uint64 elem_count,
const DeviceMemory<std::complex<double>> &x, int incx,
const DeviceMemory<std::complex<double>> &y, int incy,
DeviceMemory<std::complex<double>> *result) {
return false;
// return DoBlasInternal(
// cublasZdotu, stream, false /* = pointer_mode_host */, elem_count,
// CLComplex(CLMemory(x)), incx, CLComplex(CLMemory(y)), incy,
// CLComplex(CLMemoryMutable(result)));
}
bool CLBlas::DoBlasNrm2(Stream *stream, uint64 elem_count,
const DeviceMemory<float> &x, int incx,
DeviceMemory<float> *result) {
return false;
// return DoBlasInternal(cublasSnrm2, stream,
// false = pointer_mode_host , elem_count,
// CLMemory(x), incx, CLMemoryMutable(result));
}
bool CLBlas::DoBlasNrm2(Stream *stream, uint64 elem_count,
const DeviceMemory<double> &x, int incx,
DeviceMemory<double> *result) {
return false;
// return DoBlasInternal(cublasDnrm2, stream,
// false = pointer_mode_host , elem_count,
// CLMemory(x), incx, CLMemoryMutable(result));
}
bool CLBlas::DoBlasNrm2(Stream *stream, uint64 elem_count,
const DeviceMemory<std::complex<float>> &x, int incx,
DeviceMemory<float> *result) {
return false;
// return DoBlasInternal(
// cublasScnrm2, stream, false = pointer_mode_host ,
// elem_count, CLComplex(CLMemory(x)), incx, CLMemoryMutable(result));
}
bool CLBlas::DoBlasNrm2(Stream *stream, uint64 elem_count,
const DeviceMemory<std::complex<double>> &x, int incx,
DeviceMemory<double> *result) {
return false;
// return DoBlasInternal(
// cublasDznrm2, stream, false = pointer_mode_host ,
// elem_count, CLComplex(CLMemory(x)), incx, CLMemoryMutable(result));
}
bool CLBlas::DoBlasRot(Stream *stream, uint64 elem_count,
DeviceMemory<float> *x, int incx,
DeviceMemory<float> *y, int incy, float c, float s) {
return false;
// return DoBlasInternal(
// cublasSrot, stream, true /* = pointer_mode_host */, elem_count,
// CLMemoryMutable(x), incx, CLMemoryMutable(y), incy, &c, &s);
}
bool CLBlas::DoBlasRot(Stream *stream, uint64 elem_count,
DeviceMemory<double> *x, int incx,
DeviceMemory<double> *y, int incy, double c,
double s) {
return false;
// return DoBlasInternal(
// cublasDrot, stream, true /* = pointer_mode_host */, elem_count,
// CLMemoryMutable(x), incx, CLMemoryMutable(y), incy, &c, &s);
}
bool CLBlas::DoBlasRot(Stream *stream, uint64 elem_count,
DeviceMemory<std::complex<float>> *x, int incx,
DeviceMemory<std::complex<float>> *y, int incy,
float c, float s) {
return false;
// return DoBlasInternal(cublasCsrot, stream,
// true /* = pointer_mode_host */, elem_count,
// CLComplex(CLMemoryMutable(x)), incx,
// CLComplex(CLMemoryMutable(y)), incy, &c, &s);
}
bool CLBlas::DoBlasRot(Stream *stream, uint64 elem_count,
DeviceMemory<std::complex<double>> *x, int incx,
DeviceMemory<std::complex<double>> *y, int incy,
double c, double s) {
return false;
// return DoBlasInternal(cublasZdrot, stream,
// true /* = pointer_mode_host */, elem_count,
// CLComplex(CLMemoryMutable(x)), incx,
// CLComplex(CLMemoryMutable(y)), incy, &c, &s);
}
bool CLBlas::DoBlasRotg(Stream *stream, DeviceMemory<float> *a,
DeviceMemory<float> *b, DeviceMemory<float> *c,
DeviceMemory<float> *s) {
return false;
// return DoBlasInternal(cublasSrotg, stream,
// false /* = pointer_mode_host */, CLMemoryMutable(a),
// CLMemoryMutable(b), CLMemoryMutable(c),
// CLMemoryMutable(s));
}
bool CLBlas::DoBlasRotg(Stream *stream, DeviceMemory<double> *a,
DeviceMemory<double> *b, DeviceMemory<double> *c,
DeviceMemory<double> *s) {
return false;
// return DoBlasInternal(cublasDrotg, stream,
// false /* = pointer_mode_host */,
// CLComplex(CLMemoryMutable(a)), CLMemoryMutable(b),
// CLMemoryMutable(c), CLMemoryMutable(s));
}
bool CLBlas::DoBlasRotg(Stream *stream, DeviceMemory<std::complex<float>> *a,
DeviceMemory<std::complex<float>> *b,
DeviceMemory<float> *c,
DeviceMemory<std::complex<float>> *s) {
return false;
// return DoBlasInternal(
// cublasCrotg, stream, false /* = pointer_mode_host */,
// CLComplex(CLMemoryMutable(a)), CLComplex(CLMemoryMutable(b)),
// CLComplex(CLMemoryMutable(c)), CLComplex(CLMemoryMutable(s)));
}
bool CLBlas::DoBlasRotg(Stream *stream, DeviceMemory<std::complex<double>> *a,
DeviceMemory<std::complex<double>> *b,
DeviceMemory<double> *c,
DeviceMemory<std::complex<double>> *s) {
return false;
// return DoBlasInternal(
// cublasZrotg, stream, false /* = pointer_mode_host */,
// CLComplex(CLMemoryMutable(a)), CLComplex(CLMemoryMutable(b)),
// CLComplex(CLMemoryMutable(c)), CLComplex(CLMemoryMutable(s)));
}
bool CLBlas::DoBlasRotm(Stream *stream, uint64 elem_count,
DeviceMemory<float> *x, int incx,
DeviceMemory<float> *y, int incy,
const DeviceMemory<float> ¶m) {
return false;
// return DoBlasInternal(cublasSrotm, stream,
// false /* = pointer_mode_host */, elem_count,
// CLMemoryMutable(x), incx, CLMemoryMutable(y), incy,
// CLMemory(param));
}
bool CLBlas::DoBlasRotm(Stream *stream, uint64 elem_count,
DeviceMemory<double> *x, int incx,
DeviceMemory<double> *y, int incy,
const DeviceMemory<double> ¶m) {
return false;
// return DoBlasInternal(cublasDrotm, stream,
// false /* = pointer_mode_host */, elem_count,
// CLMemoryMutable(x), incx, CLMemoryMutable(y), incy,
// CLMemory(param));
}
bool CLBlas::DoBlasRotmg(Stream *stream, DeviceMemory<float> *d1,
DeviceMemory<float> *d2, DeviceMemory<float> *x1,
const DeviceMemory<float> &y1,
DeviceMemory<float> *param) {
return false;
// return DoBlasInternal(cublasSrotmg, stream,
// false /* = pointer_mode_host */, CLMemoryMutable(d1),
// CLMemoryMutable(d2), CLMemoryMutable(x1),
// CLMemory(y1), CLMemoryMutable(param));
}
bool CLBlas::DoBlasRotmg(Stream *stream, DeviceMemory<double> *d1,
DeviceMemory<double> *d2, DeviceMemory<double> *x1,
const DeviceMemory<double> &y1,
DeviceMemory<double> *param) {
return false;
// return DoBlasInternal(cublasDrotmg, stream,
// false /* = pointer_mode_host */, CLMemoryMutable(d1),
// CLMemoryMutable(d2), CLMemoryMutable(x1),
// CLMemory(y1), CLMemoryMutable(param));
}
bool CLBlas::DoBlasScal(Stream *stream, uint64 elem_count, float alpha,
DeviceMemory<float> *x, int incx) {
return false;
// return DoBlasInternal(cublasSscal, stream,
// true = pointer_mode_host , elem_count, &alpha,
// CUDAMemoryMutable(x), incx);
}
bool CLBlas::DoBlasScal(Stream *stream, uint64 elem_count, double alpha,
DeviceMemory<double> *x, int incx) {
return false;
// return DoBlasInternal(cublasDscal, stream,
// true = pointer_mode_host , elem_count, &alpha,
// CLMemoryMutable(x), incx);
}
bool CLBlas::DoBlasScal(Stream *stream, uint64 elem_count, float alpha,
DeviceMemory<std::complex<float>> *x, int incx) {
return false;
// return DoBlasInternal(
// cublasCsscal, stream, true = pointer_mode_host , elem_count,
// CLComplex(&alpha), CLComplex(CLMemoryMutable(x)), incx);
}
bool CLBlas::DoBlasScal(Stream *stream, uint64 elem_count, double alpha,
DeviceMemory<std::complex<double>> *x, int incx) {
return false;
// return DoBlasInternal(
// cublasZdscal, stream, true = pointer_mode_host , elem_count,
// CLComplex(&alpha), CLComplex(CLMemoryMutable(x)), incx);
}
bool CLBlas::DoBlasScal(Stream *stream, uint64 elem_count,
std::complex<float> alpha,
DeviceMemory<std::complex<float>> *x, int incx) {
return false;
// return DoBlasInternal(
// cublasCscal, stream, true = pointer_mode_host , elem_count,
// CLComplex(&alpha), CLComplex(CLMemoryMutable(x)), incx);
}
bool CLBlas::DoBlasScal(Stream *stream, uint64 elem_count,
std::complex<double> alpha,
DeviceMemory<std::complex<double>> *x, int incx) {
return false;
// return DoBlasInternal(
// cublasZscal, stream, true = pointer_mode_host , elem_count,
// CLComplex(&alpha), CLComplex(CLMemoryMutable(x)), incx);
}
bool CLBlas::DoBlasSwap(Stream *stream, uint64 elem_count,
DeviceMemory<float> *x, int incx,
DeviceMemory<float> *y, int incy) {
// std::cout << "CLBlas::DoBlasSwap" << endl;
return false;
// return DoBlasInternal(cublasSswap, stream,
// true = pointer_mode_host , elem_count,
// CLMemoryMutable(x), incx, CLMemoryMutable(y), incy);
}
bool CLBlas::DoBlasSwap(Stream *stream, uint64 elem_count,
DeviceMemory<double> *x, int incx,
DeviceMemory<double> *y, int incy) {
// cout << "CLBlas::DoBlasSwap" << endl;
return false;
// return DoBlasInternal(cublasDswap, stream,
// true = pointer_mode_host , elem_count,
// CLMemoryMutable(x), incx, CLMemoryMutable(y), incy);
}
bool CLBlas::DoBlasSwap(Stream *stream, uint64 elem_count,
DeviceMemory<std::complex<float>> *x, int incx,
DeviceMemory<std::complex<float>> *y, int incy) {
// cout << "CLBlas::DoBlasSwap" << endl;
return false;
// return DoBlasInternal(cublasCswap, stream,
// true /* = pointer_mode_host */, elem_count,
// CLComplex(CLMemoryMutable(x)), incx,
// CLComplex(CLMemoryMutable(y)), incy);
}
bool CLBlas::DoBlasSwap(Stream *stream, uint64 elem_count,
DeviceMemory<std::complex<double>> *x, int incx,
DeviceMemory<std::complex<double>> *y, int incy) {
// cout << "CLBlas::DoBlasSwap" << endl;
return false;
// return DoBlasInternal(cublasZswap, stream,
// true /* = pointer_mode_host */, elem_count,
// CLComplex(CLMemoryMutable(x)), incx,
// CLComplex(CLMemoryMutable(y)), incy);
}
bool CLBlas::DoBlasIamax(Stream *stream, uint64 elem_count,
const DeviceMemory<float> &x, int incx,
DeviceMemory<int> *result) {
return false;
// return DoBlasInternal(cublasIsamax, stream,
// false = pointer_mode_host , elem_count,
// CLMemory(x), incx, CLMemoryMutable(result));
}
bool CLBlas::DoBlasIamax(Stream *stream, uint64 elem_count,
const DeviceMemory<double> &x, int incx,
DeviceMemory<int> *result) {
return false;
// return DoBlasInternal(cublasIdamax, stream,
// false = pointer_mode_host , elem_count,
// CLMemory(x), incx, CLMemoryMutable(result));
}
bool CLBlas::DoBlasIamax(Stream *stream, uint64 elem_count,
const DeviceMemory<std::complex<float>> &x, int incx,
DeviceMemory<int> *result) {
return false;
// return DoBlasInternal(
// cublasIcamax, stream, false = pointer_mode_host ,
// elem_count, CLComplex(CLMemory(x)), incx, CLMemoryMutable(result));
}
bool CLBlas::DoBlasIamax(Stream *stream, uint64 elem_count,
const DeviceMemory<std::complex<double>> &x,
int incx, DeviceMemory<int> *result) {
return false;
// return DoBlasInternal(
// cublasIzamax, stream, false = pointer_mode_host ,
// elem_count, CLComplex(CLMemory(x)), incx, CLMemoryMutable(result));
}
bool CLBlas::DoBlasIamin(Stream *stream, uint64 elem_count,
const DeviceMemory<float> &x, int incx,
DeviceMemory<int> *result) {
return false;
// return DoBlasInternal(
// cublasIsamin, stream, false = pointer_mode_host ,
// elem_count, CLComplex(CLMemory(x)), incx, CLMemoryMutable(result));
}
bool CLBlas::DoBlasIamin(Stream *stream, uint64 elem_count,
const DeviceMemory<double> &x, int incx,
DeviceMemory<int> *result) {
return false;
// return DoBlasInternal(
// cublasIdamin, stream, false = pointer_mode_host ,
// elem_count, CLComplex(CLMemory(x)), incx, CLMemoryMutable(result));
}
bool CLBlas::DoBlasIamin(Stream *stream, uint64 elem_count,
const DeviceMemory<std::complex<float>> &x, int incx,
DeviceMemory<int> *result) {
return false;
// return DoBlasInternal(
// cublasIcamin, stream, false = pointer_mode_host ,
// elem_count, CLComplex(CLMemory(x)), incx, CLMemoryMutable(result));
}
bool CLBlas::DoBlasIamin(Stream *stream, uint64 elem_count,
const DeviceMemory<std::complex<double>> &x,
int incx, DeviceMemory<int> *result) {
return false;
// return DoBlasInternal(
// cublasIzamin, stream, false = pointer_mode_host ,
// elem_count, CLComplex(CLMemory(x)), incx, CLMemoryMutable(result));
}
bool CLBlas::DoBlasGbmv(Stream *stream, blas::Transpose trans, uint64 m,
uint64 n, uint64 kl, uint64 ku, float alpha,
const DeviceMemory<float> &a, int lda,
const DeviceMemory<float> &x, int incx, float beta,
DeviceMemory<float> *y, int incy) {
return false;
// return DoBlasInternal(
// cublasSgbmv, stream, true /* = pointer_mode_host */,
// CLBlasTranspose(trans), m, n, kl, ku, &alpha, CLMemory(a), lda,
// CLMemory(x), incx, &beta, CLMemoryMutable(y), incy);
}
bool CLBlas::DoBlasGbmv(Stream *stream, blas::Transpose trans, uint64 m,
uint64 n, uint64 kl, uint64 ku, double alpha,
const DeviceMemory<double> &a, int lda,
const DeviceMemory<double> &x, int incx, double beta,
DeviceMemory<double> *y, int incy) {
return false;
// return DoBlasInternal(
// cublasDgbmv, stream, true /* = pointer_mode_host */,
// CLBlasTranspose(trans), m, n, kl, ku, &alpha, CLMemory(a), lda,
// CLMemory(x), incx, &beta, CLMemoryMutable(y), incy);
}
bool CLBlas::DoBlasGbmv(Stream *stream, blas::Transpose trans, uint64 m,
uint64 n, uint64 kl, uint64 ku,
std::complex<float> alpha,
const DeviceMemory<std::complex<float>> &a, int lda,
const DeviceMemory<std::complex<float>> &x, int incx,
std::complex<float> beta,
DeviceMemory<std::complex<float>> *y, int incy) {
return false;
// return DoBlasInternal(
// cublasCgbmv, stream, true /* = pointer_mode_host */,
// CLBlasTranspose(trans), m, n, kl, ku, CLComplex(&alpha),
// CLComplex(CLMemory(a)), lda, CLComplex(CLMemory(x)), incx,
// CLComplex(&beta), CLComplex(CLMemoryMutable(y)), incy);
}
bool CLBlas::DoBlasGbmv(Stream *stream, blas::Transpose trans, uint64 m,
uint64 n, uint64 kl, uint64 ku,
std::complex<double> alpha,
const DeviceMemory<std::complex<double>> &a, int lda,
const DeviceMemory<std::complex<double>> &x, int incx,
std::complex<double> beta,
DeviceMemory<std::complex<double>> *y, int incy) {
return false;
// return DoBlasInternal(
// cublasZgbmv, stream, true /* = pointer_mode_host */,
// CLBlasTranspose(trans), m, n, kl, ku, CLComplex(&alpha),
// CLComplex(CLMemory(a)), lda, CLComplex(CLMemory(x)), incx,
// CLComplex(&beta), CLComplex(CLMemoryMutable(y)), incy);
}
bool CLBlas::DoBlasGemv(Stream *stream, blas::Transpose trans, uint64 m,
uint64 n, float alpha, const DeviceMemory<float> &a,
int lda, const DeviceMemory<float> &x, int incx,
float beta, DeviceMemory<float> *y, int incy) {
return false;
// return DoBlasInternal(
// cublasSgemv, stream, true /* = pointer_mode_host */,
// CLBlasTranspose(trans), m, n, &alpha, CLMemory(a), lda, CLMemory(x),
// incx, &beta, CLMemoryMutable(y), incy);
}
bool CLBlas::DoBlasGemv(Stream *stream, blas::Transpose trans, uint64 m,
uint64 n, double alpha, const DeviceMemory<double> &a,
int lda, const DeviceMemory<double> &x, int incx,
double beta, DeviceMemory<double> *y, int incy) {
return false;
// return DoBlasInternal(
// cublasDgemv, stream, true /* = pointer_mode_host */,
// CLBlasTranspose(trans), m, n, &alpha, CLMemory(a), lda, CLMemory(x),
// incx, &beta, CLMemoryMutable(y), incy);
}
bool CLBlas::DoBlasGemv(Stream *stream, blas::Transpose trans, uint64 m,
uint64 n, std::complex<float> alpha,
const DeviceMemory<std::complex<float>> &a, int lda,
const DeviceMemory<std::complex<float>> &x, int incx,
std::complex<float> beta,
DeviceMemory<std::complex<float>> *y, int incy) {
return false;
// return DoBlasInternal(
// cublasCgemv, stream, true /* = pointer_mode_host */,
// CLBlasTranspose(trans), m, n, CLComplex(&alpha),
// CLComplex(CLMemory(a)), lda, CLComplex(CLMemory(x)), incx,
// CLComplex(&beta), CLComplex(CLMemoryMutable(y)), incy);
}
bool CLBlas::DoBlasGemv(Stream *stream, blas::Transpose trans, uint64 m,
uint64 n, std::complex<double> alpha,
const DeviceMemory<std::complex<double>> &a, int lda,
const DeviceMemory<std::complex<double>> &x, int incx,
std::complex<double> beta,
DeviceMemory<std::complex<double>> *y, int incy) {
return false;
// return DoBlasInternal(
// cublasZgemv, stream, true /* = pointer_mode_host */,
// CLBlasTranspose(trans), m, n, CLComplex(&alpha),
// CLComplex(CLMemory(a)), lda, CLComplex(CLMemory(x)), incx,
// CLComplex(&beta), CLComplex(CLMemoryMutable(y)), incy);
}
bool CLBlas::DoBlasGer(Stream *stream, uint64 m, uint64 n, float alpha,
const DeviceMemory<float> &x, int incx,
const DeviceMemory<float> &y, int incy,
DeviceMemory<float> *a, int lda) {
return false;
// return DoBlasInternal(
// cublasSger, stream, true /* = pointer_mode_host */, m, n, &alpha,
// CLMemory(x), incx, CLMemory(y), incy, CLMemoryMutable(a), lda);
}
bool CLBlas::DoBlasGer(Stream *stream, uint64 m, uint64 n, double alpha,
const DeviceMemory<double> &x, int incx,
const DeviceMemory<double> &y, int incy,
DeviceMemory<double> *a, int lda) {
return false;
// return DoBlasInternal(
// cublasDger, stream, true /* = pointer_mode_host */, m, n, &alpha,
// CLMemory(x), incx, CLMemory(y), incy, CLMemoryMutable(a), lda);
}
bool CLBlas::DoBlasGerc(Stream *stream, uint64 m, uint64 n,
std::complex<float> alpha,
const DeviceMemory<std::complex<float>> &x, int incx,
const DeviceMemory<std::complex<float>> &y, int incy,
DeviceMemory<std::complex<float>> *a, int lda) {
return false;
// return DoBlasInternal(
// cublasCgerc, stream, true /* = pointer_mode_host */, m, n,
// CLComplex(&alpha), CLComplex(CLMemory(x)), incx,
// CLComplex(CLMemory(y)), incy, CLComplex(CLMemoryMutable(a)), lda);
}
bool CLBlas::DoBlasGerc(Stream *stream, uint64 m, uint64 n,
std::complex<double> alpha,
const DeviceMemory<std::complex<double>> &x, int incx,
const DeviceMemory<std::complex<double>> &y, int incy,
DeviceMemory<std::complex<double>> *a, int lda) {
return false;
// return DoBlasInternal(
// cublasZgerc, stream, true /* = pointer_mode_host */, m, n,
// CLComplex(&alpha), CLComplex(CLMemory(x)), incx,
// CLComplex(CLMemory(y)), incy, CLComplex(CLMemoryMutable(a)), lda);
}
bool CLBlas::DoBlasGeru(Stream *stream, uint64 m, uint64 n,
std::complex<float> alpha,
const DeviceMemory<std::complex<float>> &x, int incx,
const DeviceMemory<std::complex<float>> &y, int incy,
DeviceMemory<std::complex<float>> *a, int lda) {
return false;
// return DoBlasInternal(
// cublasCgeru, stream, true /* = pointer_mode_host */, m, n,
// CLComplex(&alpha), CLComplex(CLMemory(x)), incx,
// CLComplex(CLMemory(y)), incy, CLComplex(CLMemoryMutable(a)), lda);
}
bool CLBlas::DoBlasGeru(Stream *stream, uint64 m, uint64 n,
std::complex<double> alpha,
const DeviceMemory<std::complex<double>> &x, int incx,
const DeviceMemory<std::complex<double>> &y, int incy,
DeviceMemory<std::complex<double>> *a, int lda) {
return false;
// return DoBlasInternal(
// cublasZgeru, stream, true /* = pointer_mode_host */, m, n,
// CLComplex(&alpha), CLComplex(CLMemory(x)), incx,
// CLComplex(CLMemory(y)), incy, CLComplex(CLMemoryMutable(a)), lda);
}
bool CLBlas::DoBlasHbmv(Stream *stream, blas::UpperLower uplo, uint64 n,
uint64 k, std::complex<float> alpha,
const DeviceMemory<std::complex<float>> &a, int lda,
const DeviceMemory<std::complex<float>> &x, int incx,
std::complex<float> beta,
DeviceMemory<std::complex<float>> *y, int incy) {
return false;
// return DoBlasInternal(
// cublasChbmv, stream, true /* = pointer_mode_host */,
// CLBlasUpperLower(uplo), n, k, CLComplex(&alpha),
// CLComplex(CLMemory(a)), lda, CLComplex(CLMemory(x)), incx,
// CLComplex(&beta), CLComplex(CLMemoryMutable(y)), incy);
}
bool CLBlas::DoBlasHbmv(Stream *stream, blas::UpperLower uplo, uint64 n,
uint64 k, std::complex<double> alpha,
const DeviceMemory<std::complex<double>> &a, int lda,
const DeviceMemory<std::complex<double>> &x, int incx,
std::complex<double> beta,
DeviceMemory<std::complex<double>> *y, int incy) {
return false;
// return DoBlasInternal(
// cublasZhbmv, stream, true /* = pointer_mode_host */,
// CLBlasUpperLower(uplo), n, k, CLComplex(&alpha),
// CLComplex(CLMemory(a)), lda, CLComplex(CLMemory(x)), incx,
// CLComplex(&beta), CLComplex(CLMemoryMutable(y)), incy);
}
bool CLBlas::DoBlasHemv(Stream *stream, blas::UpperLower uplo, uint64 n,
std::complex<float> alpha,
const DeviceMemory<std::complex<float>> &a, int lda,
const DeviceMemory<std::complex<float>> &x, int incx,
std::complex<float> beta,
DeviceMemory<std::complex<float>> *y, int incy) {
return false;
// return DoBlasInternal(
// cublasChemv, stream, true /* = pointer_mode_host */,
// CLBlasUpperLower(uplo), n, CLComplex(&alpha),
// CLComplex(CLMemory(a)), lda, CLComplex(CLMemory(x)), incx,
// CLComplex(&beta), CLComplex(CLMemoryMutable(y)), incy);
}
bool CLBlas::DoBlasHemv(Stream *stream, blas::UpperLower uplo, uint64 n,
std::complex<double> alpha,
const DeviceMemory<std::complex<double>> &a, int lda,
const DeviceMemory<std::complex<double>> &x, int incx,
std::complex<double> beta,
DeviceMemory<std::complex<double>> *y, int incy) {
return false;
// return DoBlasInternal(
// cublasZhemv, stream, true /* = pointer_mode_host */,
// CLBlasUpperLower(uplo), n, CLComplex(&alpha),
// CLComplex(CLMemory(a)), lda, CLComplex(CLMemory(x)), incx,
// CLComplex(&beta), CLComplex(CLMemoryMutable(y)), incy);
}
bool CLBlas::DoBlasHer(Stream *stream, blas::UpperLower uplo, uint64 n,
float alpha,
const DeviceMemory<std::complex<float>> &x, int incx,
DeviceMemory<std::complex<float>> *a, int lda) {
return false;
// return DoBlasInternal(
// cublasCher, stream, true /* = pointer_mode_host */,
// CLBlasUpperLower(uplo), n, &alpha, CLComplex(CLMemory(x)), incx,
// CLComplex(CLMemoryMutable(a)), lda);
}
bool CLBlas::DoBlasHer(Stream *stream, blas::UpperLower uplo, uint64 n,
double alpha,
const DeviceMemory<std::complex<double>> &x, int incx,
DeviceMemory<std::complex<double>> *a, int lda) {
return false;
// return DoBlasInternal(
// cublasZher, stream, true /* = pointer_mode_host */,
// CLBlasUpperLower(uplo), n, &alpha, CLComplex(CLMemory(x)), incx,
// CLComplex(CLMemoryMutable(a)), lda);
}
bool CLBlas::DoBlasHer2(Stream *stream, blas::UpperLower uplo, uint64 n,
std::complex<float> alpha,
const DeviceMemory<std::complex<float>> &x, int incx,
const DeviceMemory<std::complex<float>> &y, int incy,
DeviceMemory<std::complex<float>> *a, int lda) {
return false;
// return DoBlasInternal(
// cublasCher2, stream, true /* = pointer_mode_host */,
// CLBlasUpperLower(uplo), n, CLComplex(&alpha),
// CLComplex(CLMemory(x)), incx, CLComplex(CLMemory(y)), incy,
// CLComplex(CLMemoryMutable(a)), lda);
}
bool CLBlas::DoBlasHer2(Stream *stream, blas::UpperLower uplo, uint64 n,
std::complex<double> alpha,
const DeviceMemory<std::complex<double>> &x, int incx,
const DeviceMemory<std::complex<double>> &y, int incy,
DeviceMemory<std::complex<double>> *a, int lda) {
return false;
// return DoBlasInternal(
// cublasZher2, stream, true /* = pointer_mode_host */,
// CLBlasUpperLower(uplo), n, CLComplex(&alpha),
// CLComplex(CLMemory(x)), incx, CLComplex(CLMemory(y)), incy,
// CLComplex(CLMemoryMutable(a)), lda);
}
bool CLBlas::DoBlasHpmv(Stream *stream, blas::UpperLower uplo, uint64 n,
std::complex<float> alpha,
const DeviceMemory<std::complex<float>> &ap,
const DeviceMemory<std::complex<float>> &x, int incx,
std::complex<float> beta,
DeviceMemory<std::complex<float>> *y, int incy) {
return false;
// return DoBlasInternal(
// cublasChpmv, stream, true /* = pointer_mode_host */,
// CLBlasUpperLower(uplo), n, CLComplex(&alpha),
// CLComplex(CLMemory(ap)), CLComplex(CLMemory(x)), incx,
// CLComplex(&beta), CLComplex(CLMemoryMutable(y)), incy);
}
bool CLBlas::DoBlasHpmv(Stream *stream, blas::UpperLower uplo, uint64 n,
std::complex<double> alpha,
const DeviceMemory<std::complex<double>> &ap,
const DeviceMemory<std::complex<double>> &x, int incx,
std::complex<double> beta,
DeviceMemory<std::complex<double>> *y, int incy) {
return false;
// return DoBlasInternal(
// cublasZhpmv, stream, true /* = pointer_mode_host */,
// CLBlasUpperLower(uplo), n, CLComplex(&alpha),
// CLComplex(CLMemory(ap)), CLComplex(CLMemory(x)), incx,
// CLComplex(&beta), CLComplex(CLMemoryMutable(y)), incy);
}
bool CLBlas::DoBlasHpr(Stream *stream, blas::UpperLower uplo, uint64 n,
float alpha,
const DeviceMemory<std::complex<float>> &x, int incx,
DeviceMemory<std::complex<float>> *ap) {
return false;
// return DoBlasInternal(
// cublasChpr, stream, true /* = pointer_mode_host */,
// CLBlasUpperLower(uplo), n, CLComplex(&alpha),
// CLComplex(CLMemory(x)), incx, CLComplex(CLMemoryMutable(ap)));
}
bool CLBlas::DoBlasHpr(Stream *stream, blas::UpperLower uplo, uint64 n,
double alpha,
const DeviceMemory<std::complex<double>> &x, int incx,
DeviceMemory<std::complex<double>> *ap) {
return false;
// return DoBlasInternal(
// cublasZhpr, stream, true /* = pointer_mode_host */,
// CLBlasUpperLower(uplo), n, CLComplex(&alpha),
// CLComplex(CLMemory(x)), incx, CLComplex(CLMemoryMutable(ap)));
}
bool CLBlas::DoBlasHpr2(Stream *stream, blas::UpperLower uplo, uint64 n,
std::complex<float> alpha,
const DeviceMemory<std::complex<float>> &x, int incx,
const DeviceMemory<std::complex<float>> &y, int incy,
DeviceMemory<std::complex<float>> *ap) {
return false;
// return DoBlasInternal(
// cublasChpr2, stream, true /* = pointer_mode_host */,
// CLBlasUpperLower(uplo), n, CLComplex(&alpha),
// CLComplex(CLMemory(x)), incx, CLComplex(CLMemory(y)), incy,
// CLComplex(CLMemoryMutable(ap)));
}
bool CLBlas::DoBlasHpr2(Stream *stream, blas::UpperLower uplo, uint64 n,
std::complex<double> alpha,
const DeviceMemory<std::complex<double>> &x, int incx,
const DeviceMemory<std::complex<double>> &y, int incy,
DeviceMemory<std::complex<double>> *ap) {
return false;
// return DoBlasInternal(
// cublasZhpr2, stream, true /* = pointer_mode_host */,
// CLBlasUpperLower(uplo), n, CLComplex(&alpha),
// CLComplex(CLMemory(x)), incx, CLComplex(CLMemory(y)), incy,
// CLComplex(CLMemoryMutable(ap)));
}
bool CLBlas::DoBlasSbmv(Stream *stream, blas::UpperLower uplo, uint64 n,
uint64 k, float alpha, const DeviceMemory<float> &a,
int lda, const DeviceMemory<float> &x, int incx,
float beta, DeviceMemory<float> *y, int incy) {
return false;
// return DoBlasInternal(
// cublasSsbmv, stream, true /* = pointer_mode_host */,
// CLBlasUpperLower(uplo), n, k, &alpha, CLMemory(a), lda, CLMemory(x),
// incx, &beta, CLMemoryMutable(y), incy);
}
bool CLBlas::DoBlasSbmv(Stream *stream, blas::UpperLower uplo, uint64 n,
uint64 k, double alpha, const DeviceMemory<double> &a,
int lda, const DeviceMemory<double> &x, int incx,
double beta, DeviceMemory<double> *y, int incy) {
return false;
// return DoBlasInternal(
// cublasDsbmv, stream, true /* = pointer_mode_host */,
// CLBlasUpperLower(uplo), n, k, &alpha, CLMemory(a), lda, CLMemory(x),
// incx, &beta, CLMemoryMutable(y), incy);
}
bool CLBlas::DoBlasSpmv(Stream *stream, blas::UpperLower uplo, uint64 n,
float alpha, const DeviceMemory<float> &ap,
const DeviceMemory<float> &x, int incx, float beta,
DeviceMemory<float> *y, int incy) {
return false;
// return DoBlasInternal(cublasSspmv, stream,
// true /* = pointer_mode_host */,
// CLBlasUpperLower(uplo), n, &alpha, CLMemory(ap),
// CLMemory(x), incx, &beta, CLMemoryMutable(y), incy);
}
bool CLBlas::DoBlasSpmv(Stream *stream, blas::UpperLower uplo, uint64 n,
double alpha, const DeviceMemory<double> &ap,
const DeviceMemory<double> &x, int incx, double beta,
DeviceMemory<double> *y, int incy) {
return false;
// return DoBlasInternal(cublasDspmv, stream,
// true /* = pointer_mode_host */,
// CLBlasUpperLower(uplo), n, &alpha, CLMemory(ap),
// CLMemory(x), incx, &beta, CLMemoryMutable(y), incy);
}
bool CLBlas::DoBlasSpr(Stream *stream, blas::UpperLower uplo, uint64 n,
float alpha, const DeviceMemory<float> &x, int incx,
DeviceMemory<float> *ap) {
return false;
// return DoBlasInternal(cublasSspr, stream,
// true /* = pointer_mode_host */,
// CLBlasUpperLower(uplo), n, &alpha, CLMemory(x),
// incx, CLMemoryMutable(ap));
}
bool CLBlas::DoBlasSpr(Stream *stream, blas::UpperLower uplo, uint64 n,
double alpha, const DeviceMemory<double> &x, int incx,
DeviceMemory<double> *ap) {
return false;
// return DoBlasInternal(cublasDspr, stream,
// true /* = pointer_mode_host */,
// CLBlasUpperLower(uplo), n, &alpha, CLMemory(x),
// incx, CLMemoryMutable(ap));
}
bool CLBlas::DoBlasSpr2(Stream *stream, blas::UpperLower uplo, uint64 n,
float alpha, const DeviceMemory<float> &x, int incx,
const DeviceMemory<float> &y, int incy,
DeviceMemory<float> *ap) {
return false;
// return DoBlasInternal(cublasSspr2, stream,
// true /* = pointer_mode_host */,
// CLBlasUpperLower(uplo), n, &alpha, CLMemory(x),
// incx, CLMemory(y), incy, CLMemoryMutable(ap));
}
bool CLBlas::DoBlasSpr2(Stream *stream, blas::UpperLower uplo, uint64 n,
double alpha, const DeviceMemory<double> &x, int incx,
const DeviceMemory<double> &y, int incy,
DeviceMemory<double> *ap) {
return false;
// return DoBlasInternal(cublasDspr2, stream,
// true /* = pointer_mode_host */,
// CLBlasUpperLower(uplo), n, &alpha, CLMemory(x),
// incx, CLMemory(y), incy, CLMemoryMutable(ap));
}
bool CLBlas::DoBlasSymv(Stream *stream, blas::UpperLower uplo, uint64 n,
float alpha, const DeviceMemory<float> &a, int lda,
const DeviceMemory<float> &x, int incx, float beta,
DeviceMemory<float> *y, int incy) {
return false;
// return DoBlasInternal(cublasSsymv, stream,
// true /* = pointer_mode_host */,
// CLBlasUpperLower(uplo), n, &alpha, CLMemory(a), lda,
// CLMemory(x), incx, &beta, CLMemoryMutable(y), incy);
}
bool CLBlas::DoBlasSymv(Stream *stream, blas::UpperLower uplo, uint64 n,
double alpha, const DeviceMemory<double> &a, int lda,
const DeviceMemory<double> &x, int incx, double beta,
DeviceMemory<double> *y, int incy) {
return false;
// return DoBlasInternal(cublasDsymv, stream,
// true /* = pointer_mode_host */,
// CLBlasUpperLower(uplo), n, &alpha, CLMemory(a), lda,
// CLMemory(x), incx, &beta, CLMemoryMutable(y), incy);
}
bool CLBlas::DoBlasSyr(Stream *stream, blas::UpperLower uplo, uint64 n,
float alpha, const DeviceMemory<float> &x, int incx,
DeviceMemory<float> *a, int lda) {
return false;
// return DoBlasInternal(cublasSsyr, stream,
// true /* = pointer_mode_host */,
// CLBlasUpperLower(uplo), n, &alpha, CLMemory(x),
// incx, CLMemoryMutable(a), lda);
}
bool CLBlas::DoBlasSyr(Stream *stream, blas::UpperLower uplo, uint64 n,
double alpha, const DeviceMemory<double> &x, int incx,
DeviceMemory<double> *a, int lda) {
return false;
// return DoBlasInternal(cublasDsyr, stream,
// true /* = pointer_mode_host */,
// CLBlasUpperLower(uplo), n, &alpha, CLMemory(x),
// incx, CLMemoryMutable(a), lda);
}
bool CLBlas::DoBlasSyr2(Stream *stream, blas::UpperLower uplo, uint64 n,
float alpha, const DeviceMemory<float> &x, int incx,
const DeviceMemory<float> &y, int incy,
DeviceMemory<float> *a, int lda) {
return false;
// return DoBlasInternal(cublasSsyr2, stream,
// true /* = pointer_mode_host */,
// CLBlasUpperLower(uplo), n, &alpha, CLMemory(x),
// incx, CLMemory(y), incy, CLMemoryMutable(a), lda);
}
bool CLBlas::DoBlasSyr2(Stream *stream, blas::UpperLower uplo, uint64 n,
double alpha, const DeviceMemory<double> &x, int incx,
const DeviceMemory<double> &y, int incy,
DeviceMemory<double> *a, int lda) {
return false;
// return DoBlasInternal(cublasDsyr2, stream,
// true /* = pointer_mode_host */,
// CLBlasUpperLower(uplo), n, &alpha, CLMemory(x),
// incx, CLMemory(y), incy, CLMemoryMutable(a), lda);
}
bool CLBlas::DoBlasTbmv(Stream *stream, blas::UpperLower uplo,
blas::Transpose trans, blas::Diagonal diag, uint64 n,
uint64 k, const DeviceMemory<float> &a, int lda,
DeviceMemory<float> *x, int incx) {
return false;
// return DoBlasInternal(cublasStbmv, stream,
// true /* = pointer_mode_host */,
// CLBlasUpperLower(uplo), CLBlasTranspose(trans),
// CLBlasDiagonal(diag), n, k, CLMemory(a), lda,
// CLMemoryMutable(x), incx);
}
bool CLBlas::DoBlasTbmv(Stream *stream, blas::UpperLower uplo,
blas::Transpose trans, blas::Diagonal diag, uint64 n,
uint64 k, const DeviceMemory<double> &a, int lda,
DeviceMemory<double> *x, int incx) {
return false;
// return DoBlasInternal(cublasDtbmv, stream,
// true /* = pointer_mode_host */,
// CLBlasUpperLower(uplo), CLBlasTranspose(trans),
// CLBlasDiagonal(diag), n, k, CLMemory(a), lda,
// CLMemoryMutable(x), incx);
}
bool CLBlas::DoBlasTbmv(Stream *stream, blas::UpperLower uplo,
blas::Transpose trans, blas::Diagonal diag, uint64 n,
uint64 k, const DeviceMemory<std::complex<float>> &a,
int lda, DeviceMemory<std::complex<float>> *x,
int incx) {
return false;
// return DoBlasInternal(
// cublasCtbmv, stream, true /* = pointer_mode_host */,
// CLBlasUpperLower(uplo), CLBlasTranspose(trans),
// CLBlasDiagonal(diag), n, k, CLComplex(CLMemory(a)), lda,
// CLComplex(CLMemoryMutable(x)), incx);
}
bool CLBlas::DoBlasTbmv(Stream *stream, blas::UpperLower uplo,
blas::Transpose trans, blas::Diagonal diag, uint64 n,
uint64 k, const DeviceMemory<std::complex<double>> &a,
int lda, DeviceMemory<std::complex<double>> *x,
int incx) {
return false;
// return DoBlasInternal(
// cublasZtbmv, stream, true /* = pointer_mode_host */,
// CLBlasUpperLower(uplo), CLBlasTranspose(trans),
// CLBlasDiagonal(diag), n, k, CLComplex(CLMemory(a)), lda,
// CLComplex(CLMemoryMutable(x)), incx);
}
bool CLBlas::DoBlasTbsv(Stream *stream, blas::UpperLower uplo,
blas::Transpose trans, blas::Diagonal diag, uint64 n,
uint64 k, const DeviceMemory<float> &a, int lda,
DeviceMemory<float> *x, int incx) {
return false;
// return DoBlasInternal(cublasStbsv, stream,
// true /* = pointer_mode_host */,
// CLBlasUpperLower(uplo), CLBlasTranspose(trans),
// CLBlasDiagonal(diag), n, k, CLMemory(a), lda,
// CLMemoryMutable(x), incx);
}
bool CLBlas::DoBlasTbsv(Stream *stream, blas::UpperLower uplo,
blas::Transpose trans, blas::Diagonal diag, uint64 n,
uint64 k, const DeviceMemory<double> &a, int lda,
DeviceMemory<double> *x, int incx) {
return false;
// return DoBlasInternal(cublasDtbsv, stream,
// true /* = pointer_mode_host */,
// CLBlasUpperLower(uplo), CLBlasTranspose(trans),
// CLBlasDiagonal(diag), n, k, CLMemory(a), lda,
// CLMemoryMutable(x), incx);
}
bool CLBlas::DoBlasTbsv(Stream *stream, blas::UpperLower uplo,
blas::Transpose trans, blas::Diagonal diag, uint64 n,
uint64 k, const DeviceMemory<std::complex<float>> &a,
int lda, DeviceMemory<std::complex<float>> *x,
int incx) {
return false;
// return DoBlasInternal(
// cublasCtbsv, stream, true /* = pointer_mode_host */,
// CLBlasUpperLower(uplo), CLBlasTranspose(trans),
// CLBlasDiagonal(diag), n, k, CLComplex(CLMemory(a)), lda,
// CLComplex(CLMemoryMutable(x)), incx);
}
bool CLBlas::DoBlasTbsv(Stream *stream, blas::UpperLower uplo,
blas::Transpose trans, blas::Diagonal diag, uint64 n,
uint64 k, const DeviceMemory<std::complex<double>> &a,
int lda, DeviceMemory<std::complex<double>> *x,
int incx) {
return false;
// return DoBlasInternal(
// cublasZtbsv, stream, true /* = pointer_mode_host */,
// CLBlasUpperLower(uplo), CLBlasTranspose(trans),
// CLBlasDiagonal(diag), n, k, CLComplex(CLMemory(a)), lda,
// CLComplex(CLMemoryMutable(x)), incx);
}
bool CLBlas::DoBlasTpmv(Stream *stream, blas::UpperLower uplo,
blas::Transpose trans, blas::Diagonal diag, uint64 n,
const DeviceMemory<float> &ap, DeviceMemory<float> *x,
int incx) {
return false;
// return DoBlasInternal(
// cublasStpmv, stream, true /* = pointer_mode_host */,
// CLBlasUpperLower(uplo), CLBlasTranspose(trans),
// CLBlasDiagonal(diag), n, CLMemory(ap), CLMemoryMutable(x), incx);
}
bool CLBlas::DoBlasTpmv(Stream *stream, blas::UpperLower uplo,
blas::Transpose trans, blas::Diagonal diag, uint64 n,
const DeviceMemory<double> &ap,
DeviceMemory<double> *x, int incx) {
return false;
// return DoBlasInternal(
// cublasDtpmv, stream, true /* = pointer_mode_host */,
// CLBlasUpperLower(uplo), CLBlasTranspose(trans),
// CLBlasDiagonal(diag), n, CLMemory(ap), CLMemoryMutable(x), incx);
}
bool CLBlas::DoBlasTpmv(Stream *stream, blas::UpperLower uplo,
blas::Transpose trans, blas::Diagonal diag, uint64 n,
const DeviceMemory<std::complex<float>> &ap,
DeviceMemory<std::complex<float>> *x, int incx) {
return false;
// return DoBlasInternal(cublasCtpmv, stream,
// true /* = pointer_mode_host */,
// CLBlasUpperLower(uplo), CLBlasTranspose(trans),
// CLBlasDiagonal(diag), n, CLComplex(CLMemory(ap)),
// CLComplex(CLMemoryMutable(x)), incx);
}
bool CLBlas::DoBlasTpmv(Stream *stream, blas::UpperLower uplo,
blas::Transpose trans, blas::Diagonal diag, uint64 n,
const DeviceMemory<std::complex<double>> &ap,
DeviceMemory<std::complex<double>> *x, int incx) {
return false;
// return DoBlasInternal(cublasZtpmv, stream,
// true /* = pointer_mode_host */,
// CLBlasUpperLower(uplo), CLBlasTranspose(trans),
// CLBlasDiagonal(diag), n, CLComplex(CLMemory(ap)),
// CLComplex(CLMemoryMutable(x)), incx);
}
bool CLBlas::DoBlasTpsv(Stream *stream, blas::UpperLower uplo,
blas::Transpose trans, blas::Diagonal diag, uint64 n,
const DeviceMemory<float> &ap, DeviceMemory<float> *x,
int incx) {
return false;
// return DoBlasInternal(
// cublasStpsv, stream, true /* = pointer_mode_host */,
// CLBlasUpperLower(uplo), CLBlasTranspose(trans),
// CLBlasDiagonal(diag), n, CLMemory(ap), CLMemoryMutable(x), incx);
}
bool CLBlas::DoBlasTpsv(Stream *stream, blas::UpperLower uplo,
blas::Transpose trans, blas::Diagonal diag, uint64 n,
const DeviceMemory<double> &ap,
DeviceMemory<double> *x, int incx) {
return false;
// return DoBlasInternal(
// cublasDtpsv, stream, true /* = pointer_mode_host */,
// CLBlasUpperLower(uplo), CLBlasTranspose(trans),
// CLBlasDiagonal(diag), n, CLMemory(ap), CLMemoryMutable(x), incx);
}
bool CLBlas::DoBlasTpsv(Stream *stream, blas::UpperLower uplo,
blas::Transpose trans, blas::Diagonal diag, uint64 n,
const DeviceMemory<std::complex<float>> &ap,
DeviceMemory<std::complex<float>> *x, int incx) {
return false;
// return DoBlasInternal(cublasCtpsv, stream,
// true /* = pointer_mode_host */,
// CLBlasUpperLower(uplo), CLBlasTranspose(trans),
// CLBlasDiagonal(diag), n, CLComplex(CLMemory(ap)),
// CLComplex(CLMemoryMutable(x)), incx);
}
bool CLBlas::DoBlasTpsv(Stream *stream, blas::UpperLower uplo,
blas::Transpose trans, blas::Diagonal diag, uint64 n,
const DeviceMemory<std::complex<double>> &ap,
DeviceMemory<std::complex<double>> *x, int incx) {
return false;
// return DoBlasInternal(cublasZtpsv, stream,
// true /* = pointer_mode_host */,
// CLBlasUpperLower(uplo), CLBlasTranspose(trans),
// CLBlasDiagonal(diag), n, CLComplex(CLMemory(ap)),
// CLComplex(CLMemoryMutable(x)), incx);
}
bool CLBlas::DoBlasTrmv(Stream *stream, blas::UpperLower uplo,
blas::Transpose trans, blas::Diagonal diag, uint64 n,
const DeviceMemory<float> &a, int lda,
DeviceMemory<float> *x, int incx) {
return false;
// return DoBlasInternal(cublasStrmv, stream,
// true /* = pointer_mode_host */,
// CLBlasUpperLower(uplo), CLBlasTranspose(trans),
// CLBlasDiagonal(diag), n, CLMemory(a), lda,
// CLMemoryMutable(x), incx);
}
bool CLBlas::DoBlasTrmv(Stream *stream, blas::UpperLower uplo,
blas::Transpose trans, blas::Diagonal diag, uint64 n,
const DeviceMemory<double> &a, int lda,
DeviceMemory<double> *x, int incx) {
return false;
// return DoBlasInternal(cublasDtrmv, stream,
// true /* = pointer_mode_host */,
// CLBlasUpperLower(uplo), CLBlasTranspose(trans),
// CLBlasDiagonal(diag), n, CLMemory(a), lda,
// CLMemoryMutable(x), incx);
}
bool CLBlas::DoBlasTrmv(Stream *stream, blas::UpperLower uplo,
blas::Transpose trans, blas::Diagonal diag, uint64 n,
const DeviceMemory<std::complex<float>> &a, int lda,
DeviceMemory<std::complex<float>> *x, int incx) {
return false;
// return DoBlasInternal(cublasCtrmv, stream,
// true /* = pointer_mode_host */,
// CLBlasUpperLower(uplo), CLBlasTranspose(trans),
// CLBlasDiagonal(diag), n, CLComplex(CLMemory(a)),
// lda, CLComplex(CLMemoryMutable(x)), incx);
}
bool CLBlas::DoBlasTrmv(Stream *stream, blas::UpperLower uplo,
blas::Transpose trans, blas::Diagonal diag, uint64 n,
const DeviceMemory<std::complex<double>> &a, int lda,
DeviceMemory<std::complex<double>> *x, int incx) {
return false;
// return DoBlasInternal(cublasZtrmv, stream,
// true /* = pointer_mode_host */,
// CLBlasUpperLower(uplo), CLBlasTranspose(trans),
// CLBlasDiagonal(diag), n, CLComplex(CLMemory(a)),
// lda, CLComplex(CLMemoryMutable(x)), incx);
}
bool CLBlas::DoBlasTrsv(Stream *stream, blas::UpperLower uplo,
blas::Transpose trans, blas::Diagonal diag, uint64 n,
const DeviceMemory<float> &a, int lda,
DeviceMemory<float> *x, int incx) {
return false;
// return DoBlasInternal(cublasStrsv, stream,
// true /* = pointer_mode_host */,
// CLBlasUpperLower(uplo), CLBlasTranspose(trans),
// CLBlasDiagonal(diag), n, CLMemory(a), lda,
// CLMemoryMutable(x), incx);
}
bool CLBlas::DoBlasTrsv(Stream *stream, blas::UpperLower uplo,
blas::Transpose trans, blas::Diagonal diag, uint64 n,
const DeviceMemory<double> &a, int lda,
DeviceMemory<double> *x, int incx) {
return false;
// return DoBlasInternal(cublasDtrsv, stream,
// true /* = pointer_mode_host */,
// CLBlasUpperLower(uplo), CLBlasTranspose(trans),
// CLBlasDiagonal(diag), n, CLMemory(a), lda,
// CLMemoryMutable(x), incx);
}
bool CLBlas::DoBlasTrsv(Stream *stream, blas::UpperLower uplo,
blas::Transpose trans, blas::Diagonal diag, uint64 n,
const DeviceMemory<std::complex<float>> &a, int lda,
DeviceMemory<std::complex<float>> *x, int incx) {
return false;
// return DoBlasInternal(cublasCtrsv, stream,
// true /* = pointer_mode_host */,
// CLBlasUpperLower(uplo), CLBlasTranspose(trans),
// CLBlasDiagonal(diag), n, CLComplex(CLMemory(a)),
// lda, CLComplex(CLMemoryMutable(x)), incx);
}
bool CLBlas::DoBlasTrsv(Stream *stream, blas::UpperLower uplo,
blas::Transpose trans, blas::Diagonal diag, uint64 n,
const DeviceMemory<std::complex<double>> &a, int lda,
DeviceMemory<std::complex<double>> *x, int incx) {
return false;
// return DoBlasInternal(cublasZtrsv, stream,
// true /* = pointer_mode_host */,
// CLBlasUpperLower(uplo), CLBlasTranspose(trans),
// CLBlasDiagonal(diag), n, CLComplex(CLMemory(a)),
// lda, CLComplex(CLMemoryMutable(x)), incx);
}
bool CLBlas::DoBlasGemm(
Stream *stream, blas::Transpose transa,
blas::Transpose transb, uint64 m, uint64 n, uint64 k,
float alpha, const DeviceMemory<Eigen::half> &a, int lda,
const DeviceMemory<Eigen::half> &b, int ldb, float beta,
DeviceMemory<Eigen::half> *c, int ldc) {
return false;
// #if CL_VERSION >= 7050
// VLOG(1) << port::Printf(
// "doing CLBlast SGEMM: at=%d bt=%d m=%llu n=%llu "
// "k=%llu alpha=%f a=%p lda=%d b=%p ldb=%d beta=%f "
// "c=%p ldc=%d",
// static_cast<int>(transa), static_cast<int>(transb), m, n, k, alpha,
// a.opaque(), lda, b.opaque(), ldb, beta, c->opaque(), ldc);
// if (transa == blas::Transpose::kNoTranspose) {
// if (lda < static_cast<int64>(m)) {
// LOG(WARNING) << "GEMM lda was smaller than m (no transpose case); "
// "precondition violation";
// }
// } else {
// if (lda < static_cast<int64>(k)) {
// LOG(WARNING) << "GEMM lda (" << lda << ") was smaller than k (" << k
// << ") (transpose case); precondition violation";
// }
// }
// if (transb == blas::Transpose::kNoTranspose) {
// if (ldb < static_cast<int64>(k)) {
// LOG(WARNING) << "GEMM ldb (" << ldb << ") was smaller than k (" << k
// << ") (no transpose case); precondition violation";
// }
// } else {
// if (ldb < static_cast<int64>(n)) {
// LOG(WARNING) << "GEMM ldb was smaller than n (transpose case); "
// "precondition violation";
// }
// }
// // TODO(sesse): Consider supporting the Hgemm interface, which uses half
// // calculations internally (faster on newer devices, such as Pascal and TX1,
// // but less precise).
// return DoBlasInternal(
// cublasSgemmEx, stream, true /* = pointer_mode_host */,
// CLBlasTranspose(transa), CLBlasTranspose(transb), m, n, k, &alpha,
// CLMemory(a), SE_CL_DATA_HALF, lda,
// CLMemory(b), SE_CL_DATA_HALF, ldb,
// &beta,
// CLMemoryMutable(c), SE_CL_DATA_HALF, ldc);
// #else
// LOG(ERROR) << "fp16 sgemm is not implemented in this CLBlast version "
// << "(need at least CL 7.5)";
// return false;
// #endif
}
bool CLBlas::DoBlasGemm(Stream *stream, blas::Transpose transa,
blas::Transpose transb, uint64 m, uint64 n, uint64 k,
double alpha, const DeviceMemory<double> &a, int lda,
const DeviceMemory<double> &b, int ldb, double beta,
DeviceMemory<double> *c, int ldc) {
return false;
// return DoBlasInternal(
// cublasDgemm, stream, true /* = pointer_mode_host */,
// CLBlasTranspose(transa), CLBlasTranspose(transb), m, n, k, &alpha,
// CLMemory(a), lda, CLMemory(b), ldb, &beta, CLMemoryMutable(c), ldc);
}
bool CLBlas::DoBlasGemm(Stream *stream, blas::Transpose transa,
blas::Transpose transb, uint64 m, uint64 n, uint64 k,
std::complex<float> alpha,
const DeviceMemory<std::complex<float>> &a, int lda,
const DeviceMemory<std::complex<float>> &b, int ldb,
std::complex<float> beta,
DeviceMemory<std::complex<float>> *c, int ldc) {
return false;
// return DoBlasInternal(
// cublasCgemm, stream, true /* = pointer_mode_host */,
// CLBlasTranspose(transa), CLBlasTranspose(transb), m, n, k,
// CLComplex(&alpha), CLComplex(CLMemory(a)), lda,
// CLComplex(CLMemory(b)), ldb, CLComplex(&beta),
// CLComplex(CLMemoryMutable(c)), ldc);
}
bool CLBlas::DoBlasGemm(Stream *stream, blas::Transpose transa,
blas::Transpose transb, uint64 m, uint64 n, uint64 k,
std::complex<double> alpha,
const DeviceMemory<std::complex<double>> &a, int lda,
const DeviceMemory<std::complex<double>> &b, int ldb,
std::complex<double> beta,
DeviceMemory<std::complex<double>> *c, int ldc) {
return false;
// return DoBlasInternal(
// cublasZgemm, stream, true /* = pointer_mode_host */,
// CLBlasTranspose(transa), CLBlasTranspose(transb), m, n, k,
// CLComplex(&alpha), CLComplex(CLMemory(a)), lda,
// CLComplex(CLMemory(b)), ldb, CLComplex(&beta),
// CLComplex(CLMemoryMutable(c)), ldc);
}
template <typename T, typename FuncT>
port::Status CLBlas::DoBlasGemmBatchedInternal(
FuncT cublas_func, Stream *stream, blas::Transpose transa,
blas::Transpose transb, uint64 m, uint64 n, uint64 k, T alpha,
const port::ArraySlice<DeviceMemory<T> *> &a_ptrs_to_wrappers, int lda,
const port::ArraySlice<DeviceMemory<T> *> &b_ptrs_to_wrappers, int ldb,
T beta, const port::ArraySlice<DeviceMemory<T> *> &c_ptrs_to_wrappers,
int ldc, int batch_count, ScratchAllocator *scratch_allocator) {
// return false;
// std::vector<T *> a_raw_ptrs, b_raw_ptrs, c_raw_ptrs;
// for (int i = 0; i < batch_count; ++i) {
// a_raw_ptrs.push_back(static_cast<T *>(a_ptrs_to_wrappers[i]->opaque()));
// b_raw_ptrs.push_back(static_cast<T *>(b_ptrs_to_wrappers[i]->opaque()));
// c_raw_ptrs.push_back(static_cast<T *>(c_ptrs_to_wrappers[i]->opaque()));
// }
// typedef typename CLComplexT<T>::type CL_T;
// const size_t size = batch_count * sizeof(CL_T *);
// // Device-side copy of pointers to matrices.
// DeviceMemory<CL_T *> a;
// DeviceMemory<CL_T *> b;
// DeviceMemory<CL_T *> c;
// // If temporary space is allocated for device-side copies of pointers to
// // matrices, that temporary space should not be freed until this function
// // returns. Although the values for these unique_ptrs are not set here, they
// // are declared at this scope so they will be destroyed when the function
// // returns.
// //
// // If a scratch allocator is provided, these pointers will not be used at all.
// std::unique_ptr<TemporaryDeviceMemory<CL_T *>> a_temporary;
// std::unique_ptr<TemporaryDeviceMemory<CL_T *>> b_temporary;
// std::unique_ptr<TemporaryDeviceMemory<CL_T *>> c_temporary;
// // Decide how to allocate device-side copy of pointers to matrices based on
// // whether a scratch allocator was passed.
// if (scratch_allocator != nullptr) {
// SE_ASSIGN_OR_RETURN(DeviceMemory<uint8> a_bytes,
// scratch_allocator->AllocateBytes(stream, size));
// SE_ASSIGN_OR_RETURN(DeviceMemory<uint8> b_bytes,
// scratch_allocator->AllocateBytes(stream, size));
// SE_ASSIGN_OR_RETURN(DeviceMemory<uint8> c_bytes,
// scratch_allocator->AllocateBytes(stream, size));
// a = DeviceMemory<CL_T *>(a_bytes);
// b = DeviceMemory<CL_T *>(b_bytes);
// c = DeviceMemory<CL_T *>(c_bytes);
// } else {
// SE_ASSIGN_OR_RETURN(a_temporary,
// stream->AllocateTemporaryArray<CL_T *>(batch_count));
// SE_ASSIGN_OR_RETURN(b_temporary,
// stream->AllocateTemporaryArray<CL_T *>(batch_count));
// SE_ASSIGN_OR_RETURN(c_temporary,
// stream->AllocateTemporaryArray<CL_T *>(batch_count));
// a = DeviceMemory<CL_T *>(*a_temporary->mutable_device_memory());
// b = DeviceMemory<CL_T *>(*b_temporary->mutable_device_memory());
// c = DeviceMemory<CL_T *>(*c_temporary->mutable_device_memory());
// }
// if (!stream->ThenMemcpy(&a, a_raw_ptrs.data(), size).ok() ||
// !stream->ThenMemcpy(&b, b_raw_ptrs.data(), size).ok() ||
// !stream->ThenMemcpy(&c, c_raw_ptrs.data(), size).ok()) {
// return port::Status(port::error::INTERNAL,
// "failed to copy memory from host to device in "
// "CLBlas::DoBlasGemmBatched");
// }
// bool ok = DoBlasInternal(
// cublas_func, stream, true /* = pointer_mode_host */,
// CLBlasTranspose(transa), CLBlasTranspose(transb), m, n, k,
// CLComplex(&alpha), const_cast<const CL_T **>(CLMemory(a)), lda,
// const_cast<const CL_T **>(CLMemory(b)), ldb, CLComplex(&beta),
// const_cast<CL_T **>(CLMemory(c)), ldc, batch_count);
// if (ok) {
// return port::Status::OK();
// }
return port::Status(port::error::INTERNAL,
"failed BLAS call, see log for details");
}
bool CLBlas::DoBlasGemmBatched(
Stream *stream, blas::Transpose transa, blas::Transpose transb, uint64 m,
uint64 n, uint64 k, float alpha,
const port::ArraySlice<DeviceMemory<float> *> &a_array, int lda,
const port::ArraySlice<DeviceMemory<float> *> &b_array, int ldb, float beta,
const port::ArraySlice<DeviceMemory<float> *> &c_array, int ldc,
int batch_count, ScratchAllocator *scratch_allocator) {
std::cout << "CLBlas::DoBlasGemmBatched()" << std::endl;
return false;
// SE_RETURN_STATUS_AS_BOOL(DoBlasGemmBatchedInternal(
// cublasSgemmBatched, stream, transa, transb, m, n, k, alpha,
// a_array, lda, b_array, ldb, beta, c_array, ldc, batch_count,
// scratch_allocator));
}
bool CLBlas::DoBlasGemmBatched(
Stream *stream, blas::Transpose transa, blas::Transpose transb, uint64 m,
uint64 n, uint64 k, double alpha,
const port::ArraySlice<DeviceMemory<double> *> &a_array, int lda,
const port::ArraySlice<DeviceMemory<double> *> &b_array, int ldb,
double beta, const port::ArraySlice<DeviceMemory<double> *> &c_array,
int ldc, int batch_count, ScratchAllocator *scratch_allocator) {
return false;
// SE_RETURN_STATUS_AS_BOOL(DoBlasGemmBatchedInternal(
// cublasDgemmBatched, stream, transa, transb, m, n, k, alpha,
// a_array, lda, b_array, ldb, beta, c_array, ldc, batch_count,
// scratch_allocator));
}
//bool CLBlas::DoBlasGemmBatched(
// Stream *stream, blas::Transpose transa, blas::Transpose transb, uint64 m,
// uint64 n, uint64 k, std::complex<float> alpha,
// const port::ArraySlice<DeviceMemory<std::complex<float>> *> &a_array,
// int lda,
// const port::ArraySlice<DeviceMemory<std::complex<float>> *> &b_array,
// int ldb, std::complex<float> beta,
// const port::ArraySlice<DeviceMemory<std::complex<float>> *> &c_array,
// int ldc, int batch_count, ScratchAllocator *scratch_allocator) {
// return false;
// // SE_RETURN_STATUS_AS_BOOL(DoBlasGemmBatchedInternal(
// // cublasCgemmBatched, stream, transa, transb, m, n, k, alpha,
// // a_array, lda, b_array, ldb, beta, c_array, ldc, batch_count,
// // scratch_allocator));
//}
//
//bool CLBlas::DoBlasGemmBatched(
// Stream *stream, blas::Transpose transa, blas::Transpose transb, uint64 m,
// uint64 n, uint64 k, std::complex<double> alpha,
// const port::ArraySlice<DeviceMemory<std::complex<double>> *> &a_array,
// int lda,
// const port::ArraySlice<DeviceMemory<std::complex<double>> *> &b_array,
// int ldb, std::complex<double> beta,
// const port::ArraySlice<DeviceMemory<std::complex<double>> *> &c_array,
// int ldc, int batch_count, ScratchAllocator *scratch_allocator) {
// return false;
// // SE_RETURN_STATUS_AS_BOOL(DoBlasGemmBatchedInternal(
// // cublasZgemmBatched, stream, transa, transb, m, n, k, alpha,
// // a_array, lda, b_array, ldb, beta, c_array, ldc, batch_count,
// // scratch_allocator));
//}
bool CLBlas::DoBlasGemmStridedBatched(
Stream *stream, blas::Transpose transa, blas::Transpose transb, uint64 m,
uint64 n, uint64 k, float alpha, const DeviceMemory<float> &a, int lda,
int64 stride_a, const DeviceMemory<float> &b, int ldb, int64 stride_b,
float beta, DeviceMemory<float> *c, int ldc, int64 stride_c,
int batch_count) {
return false;
// return DoBlasInternal(
// wrap::cublasSgemmStridedBatched, stream, true /* = pointer_mode_host */,
// CUDABlasTranspose(transa), CUDABlasTranspose(transb), m, n, k, &alpha,
// CUDAMemory(a), lda, stride_a, CUDAMemory(b), ldb, stride_b, &beta,
// CUDAMemoryMutable(c), ldc, stride_c, batch_count);
}
bool CLBlas::DoBlasHemm(Stream *stream, blas::Side side,
blas::UpperLower uplo, uint64 m, uint64 n,
std::complex<float> alpha,
const DeviceMemory<std::complex<float>> &a, int lda,
const DeviceMemory<std::complex<float>> &b, int ldb,
std::complex<float> beta,
DeviceMemory<std::complex<float>> *c, int ldc) {
return false;
// return DoBlasInternal(
// cublasChemm, stream, true /* = pointer_mode_host */,
// CLBlasSide(side), CLBlasUpperLower(uplo), m, n, CLComplex(&alpha),
// CLComplex(CLMemory(a)), lda, CLComplex(CLMemory(b)), ldb,
// CLComplex(&beta), CLComplex(CLMemoryMutable(c)), ldc);
}
bool CLBlas::DoBlasHemm(Stream *stream, blas::Side side,
blas::UpperLower uplo, uint64 m, uint64 n,
std::complex<double> alpha,
const DeviceMemory<std::complex<double>> &a, int lda,
const DeviceMemory<std::complex<double>> &b, int ldb,
std::complex<double> beta,
DeviceMemory<std::complex<double>> *c, int ldc) {
return false;
// return DoBlasInternal(
// cublasZhemm, stream, true /* = pointer_mode_host */,
// CLBlasSide(side), CLBlasUpperLower(uplo), m, n, CLComplex(&alpha),
// CLComplex(CLMemory(a)), lda, CLComplex(CLMemory(b)), ldb,
// CLComplex(&beta), CLComplex(CLMemoryMutable(c)), ldc);
}
bool CLBlas::DoBlasHerk(Stream *stream, blas::UpperLower uplo,
blas::Transpose trans, uint64 n, uint64 k,
float alpha,
const DeviceMemory<std::complex<float>> &a, int lda,
float beta, DeviceMemory<std::complex<float>> *c,
int ldc) {
return false;
// return DoBlasInternal(cublasCherk, stream,
// true /* = pointer_mode_host */,
// CLBlasUpperLower(uplo), CLBlasTranspose(trans), n,
// k, CLComplex(&alpha), CLComplex(CLMemory(a)), lda,
// &beta, CLComplex(CLMemoryMutable(c)), ldc);
}
bool CLBlas::DoBlasHerk(Stream *stream, blas::UpperLower uplo,
blas::Transpose trans, uint64 n, uint64 k,
double alpha,
const DeviceMemory<std::complex<double>> &a, int lda,
double beta, DeviceMemory<std::complex<double>> *c,
int ldc) {
return false;
// return DoBlasInternal(cublasZherk, stream,
// true /* = pointer_mode_host */,
// CLBlasUpperLower(uplo), CLBlasTranspose(trans), n,
// k, CLComplex(&alpha), CLComplex(CLMemory(a)), lda,
// &beta, CLComplex(CLMemoryMutable(c)), ldc);
}
bool CLBlas::DoBlasHer2k(Stream *stream, blas::UpperLower uplo,
blas::Transpose trans, uint64 n, uint64 k,
std::complex<float> alpha,
const DeviceMemory<std::complex<float>> &a, int lda,
const DeviceMemory<std::complex<float>> &b, int ldb,
float beta, DeviceMemory<std::complex<float>> *c,
int ldc) {
return false;
// return DoBlasInternal(cublasCher2k, stream,
// true /* = pointer_mode_host */,
// CLBlasUpperLower(uplo), CLBlasTranspose(trans), n,
// k, CLComplex(&alpha), CLComplex(CLMemory(a)), lda,
// CLComplex(CLMemory(b)), ldb, &beta,
// CLComplex(CLMemoryMutable(c)), ldc);
}
bool CLBlas::DoBlasHer2k(Stream *stream, blas::UpperLower uplo,
blas::Transpose trans, uint64 n, uint64 k,
std::complex<double> alpha,
const DeviceMemory<std::complex<double>> &a, int lda,
const DeviceMemory<std::complex<double>> &b, int ldb,
double beta, DeviceMemory<std::complex<double>> *c,
int ldc) {
return false;
// return DoBlasInternal(cublasZher2k, stream,
// true /* = pointer_mode_host */,
// CLBlasUpperLower(uplo), CLBlasTranspose(trans), n,
// k, CLComplex(&alpha), CLComplex(CLMemory(a)), lda,
// CLComplex(CLMemory(b)), ldb, &beta,
// CLComplex(CLMemoryMutable(c)), ldc);
}
bool CLBlas::DoBlasSymm(Stream *stream, blas::Side side,
blas::UpperLower uplo, uint64 m, uint64 n,
float alpha, const DeviceMemory<float> &a, int lda,
const DeviceMemory<float> &b, int ldb, float beta,
DeviceMemory<float> *c, int ldc) {
return false;
// return DoBlasInternal(
// cublasSsymm, stream, true /* = pointer_mode_host */,
// CLBlasSide(side), CLBlasUpperLower(uplo), m, n, &alpha, CLMemory(a),
// lda, CLMemory(b), ldb, &beta, CLMemoryMutable(c), ldc);
}
bool CLBlas::DoBlasSymm(Stream *stream, blas::Side side,
blas::UpperLower uplo, uint64 m, uint64 n,
double alpha, const DeviceMemory<double> &a, int lda,
const DeviceMemory<double> &b, int ldb, double beta,
DeviceMemory<double> *c, int ldc) {
return false;
// return DoBlasInternal(
// cublasDsymm, stream, true /* = pointer_mode_host */,
// CLBlasSide(side), CLBlasUpperLower(uplo), m, n, &alpha, CLMemory(a),
// lda, CLMemory(b), ldb, &beta, CLMemoryMutable(c), ldc);
}
bool CLBlas::DoBlasSymm(Stream *stream, blas::Side side,
blas::UpperLower uplo, uint64 m, uint64 n,
std::complex<float> alpha,
const DeviceMemory<std::complex<float>> &a, int lda,
const DeviceMemory<std::complex<float>> &b, int ldb,
std::complex<float> beta,
DeviceMemory<std::complex<float>> *c, int ldc) {
return false;
// return DoBlasInternal(
// cublasCsymm, stream, true /* = pointer_mode_host */,
// CLBlasSide(side), CLBlasUpperLower(uplo), m, n, CLComplex(&alpha),
// CLComplex(CLMemory(a)), lda, CLComplex(CLMemory(b)), ldb,
// CLComplex(&beta), CLComplex(CLMemoryMutable(c)), ldc);
}
bool CLBlas::DoBlasSymm(Stream *stream, blas::Side side,
blas::UpperLower uplo, uint64 m, uint64 n,
std::complex<double> alpha,
const DeviceMemory<std::complex<double>> &a, int lda,
const DeviceMemory<std::complex<double>> &b, int ldb,
std::complex<double> beta,
DeviceMemory<std::complex<double>> *c, int ldc) {
return false;
// return DoBlasInternal(
// cublasZsymm, stream, true /* = pointer_mode_host */,
// CLBlasSide(side), CLBlasUpperLower(uplo), m, n, CLComplex(&alpha),
// CLComplex(CLMemory(a)), lda, CLComplex(CLMemory(b)), ldb,
// CLComplex(&beta), CLComplex(CLMemoryMutable(c)), ldc);
}
bool CLBlas::DoBlasSyrk(Stream *stream, blas::UpperLower uplo,
blas::Transpose trans, uint64 n, uint64 k,
float alpha, const DeviceMemory<float> &a, int lda,
float beta, DeviceMemory<float> *c, int ldc) {
return false;
// return DoBlasInternal(
// cublasSsyrk, stream, true /* = pointer_mode_host */,
// CLBlasUpperLower(uplo), CLBlasTranspose(trans), n, k, &alpha,
// CLMemory(a), lda, &beta, CLMemoryMutable(c), ldc);
}
bool CLBlas::DoBlasSyrk(Stream *stream, blas::UpperLower uplo,
blas::Transpose trans, uint64 n, uint64 k,
double alpha, const DeviceMemory<double> &a, int lda,
double beta, DeviceMemory<double> *c, int ldc) {
return false;
// return DoBlasInternal(
// cublasDsyrk, stream, true /* = pointer_mode_host */,
// CLBlasUpperLower(uplo), CLBlasTranspose(trans), n, k, &alpha,
// CLMemory(a), lda, &beta, CLMemoryMutable(c), ldc);
}
bool CLBlas::DoBlasSyrk(Stream *stream, blas::UpperLower uplo,
blas::Transpose trans, uint64 n, uint64 k,
std::complex<float> alpha,
const DeviceMemory<std::complex<float>> &a, int lda,
std::complex<float> beta,
DeviceMemory<std::complex<float>> *c, int ldc) {
return false;
// return DoBlasInternal(
// cublasCsyrk, stream, true /* = pointer_mode_host */,
// CLBlasUpperLower(uplo), CLBlasTranspose(trans), n, k,
// CLComplex(&alpha), CLComplex(CLMemory(a)), lda, CLComplex(&beta),
// CLComplex(CLMemoryMutable(c)), ldc);
}
bool CLBlas::DoBlasSyrk(Stream *stream, blas::UpperLower uplo,
blas::Transpose trans, uint64 n, uint64 k,
std::complex<double> alpha,
const DeviceMemory<std::complex<double>> &a, int lda,
std::complex<double> beta,
DeviceMemory<std::complex<double>> *c, int ldc) {
return false;
// return DoBlasInternal(
// cublasZsyrk, stream, true /* = pointer_mode_host */,
// CLBlasUpperLower(uplo), CLBlasTranspose(trans), n, k,
// CLComplex(&alpha), CLComplex(CLMemory(a)), lda, CLComplex(&beta),
// CLComplex(CLMemoryMutable(c)), ldc);
}
bool CLBlas::DoBlasSyr2k(Stream *stream, blas::UpperLower uplo,
blas::Transpose trans, uint64 n, uint64 k,
float alpha, const DeviceMemory<float> &a, int lda,
const DeviceMemory<float> &b, int ldb, float beta,
DeviceMemory<float> *c, int ldc) {
return false;
// return DoBlasInternal(
// cublasSsyr2k, stream, true /* = pointer_mode_host */,
// CLBlasUpperLower(uplo), CLBlasTranspose(trans), n, k, &alpha,
// CLMemory(a), lda, CLMemory(b), ldb, &beta, CLMemoryMutable(c), ldc);
}
bool CLBlas::DoBlasSyr2k(Stream *stream, blas::UpperLower uplo,
blas::Transpose trans, uint64 n, uint64 k,
double alpha, const DeviceMemory<double> &a, int lda,
const DeviceMemory<double> &b, int ldb, double beta,
DeviceMemory<double> *c, int ldc) {
return false;
// return DoBlasInternal(
// cublasDsyr2k, stream, true /* = pointer_mode_host */,
// CLBlasUpperLower(uplo), CLBlasTranspose(trans), n, k, &alpha,
// CLMemory(a), lda, CLMemory(b), ldb, &beta, CLMemoryMutable(c), ldc);
}
bool CLBlas::DoBlasSyr2k(Stream *stream, blas::UpperLower uplo,
blas::Transpose trans, uint64 n, uint64 k,
std::complex<float> alpha,
const DeviceMemory<std::complex<float>> &a, int lda,
const DeviceMemory<std::complex<float>> &b, int ldb,
std::complex<float> beta,
DeviceMemory<std::complex<float>> *c, int ldc) {
return false;
// return DoBlasInternal(cublasCsyr2k, stream,
// true /* = pointer_mode_host */,
// CLBlasUpperLower(uplo), CLBlasTranspose(trans), n,
// k, CLComplex(&alpha), CLComplex(CLMemory(a)), lda,
// CLComplex(CLMemory(b)), ldb, CLComplex(&beta),
// CLComplex(CLMemoryMutable(c)), ldc);
}
bool CLBlas::DoBlasSyr2k(Stream *stream, blas::UpperLower uplo,
blas::Transpose trans, uint64 n, uint64 k,
std::complex<double> alpha,
const DeviceMemory<std::complex<double>> &a, int lda,
const DeviceMemory<std::complex<double>> &b, int ldb,
std::complex<double> beta,
DeviceMemory<std::complex<double>> *c, int ldc) {
return false;
// return DoBlasInternal(cublasZsyr2k, stream,
// true /* = pointer_mode_host */,
// CLBlasUpperLower(uplo), CLBlasTranspose(trans), n,
// k, CLComplex(&alpha), CLComplex(CLMemory(a)), lda,
// CLComplex(CLMemory(b)), ldb, CLComplex(&beta),
// CLComplex(CLMemoryMutable(c)), ldc);
}
bool CLBlas::DoBlasTrmm(Stream *stream, blas::Side side,
blas::UpperLower uplo, blas::Transpose transa,
blas::Diagonal diag, uint64 m, uint64 n, float alpha,
const DeviceMemory<float> &a, int lda,
DeviceMemory<float> *b, int ldb) {
return false;
// return DoBlasInternal(
// cublasStrmm, stream, true /* = pointer_mode_host */,
// CLBlasSide(side), CLBlasUpperLower(uplo), CLBlasTranspose(transa),
// CLBlasDiagonal(diag), m, n, &alpha, CLMemory(a), lda,
// CLMemoryMutable(b), ldb, CLMemoryMutable(b), ldb);
}
bool CLBlas::DoBlasTrmm(Stream *stream, blas::Side side,
blas::UpperLower uplo, blas::Transpose transa,
blas::Diagonal diag, uint64 m, uint64 n, double alpha,
const DeviceMemory<double> &a, int lda,
DeviceMemory<double> *b, int ldb) {
return false;
// return DoBlasInternal(
// cublasDtrmm, stream, true /* = pointer_mode_host */,
// CLBlasSide(side), CLBlasUpperLower(uplo), CLBlasTranspose(transa),
// CLBlasDiagonal(diag), m, n, &alpha, CLMemory(a), lda,
// CLMemoryMutable(b), ldb, CLMemoryMutable(b), ldb);
}
bool CLBlas::DoBlasTrmm(Stream *stream, blas::Side side,
blas::UpperLower uplo, blas::Transpose transa,
blas::Diagonal diag, uint64 m, uint64 n,
std::complex<float> alpha,
const DeviceMemory<std::complex<float>> &a, int lda,
DeviceMemory<std::complex<float>> *b, int ldb) {
return false;
// return DoBlasInternal(
// cublasCtrmm, stream, true /* = pointer_mode_host */,
// CLBlasSide(side), CLBlasUpperLower(uplo), CLBlasTranspose(transa),
// CLBlasDiagonal(diag), m, n, CLComplex(&alpha),
// CLComplex(CLMemory(a)), lda, CLComplex(CLMemoryMutable(b)), ldb,
// CLComplex(CLMemoryMutable(b)), ldb);
}
bool CLBlas::DoBlasTrmm(Stream *stream, blas::Side side,
blas::UpperLower uplo, blas::Transpose transa,
blas::Diagonal diag, uint64 m, uint64 n,
std::complex<double> alpha,
const DeviceMemory<std::complex<double>> &a, int lda,
DeviceMemory<std::complex<double>> *b, int ldb) {
return false;
// return DoBlasInternal(
// cublasZtrmm, stream, true /* = pointer_mode_host */,
// CLBlasSide(side), CLBlasUpperLower(uplo), CLBlasTranspose(transa),
// CLBlasDiagonal(diag), m, n, CLComplex(&alpha),
// CLComplex(CLMemory(a)), lda, CLComplex(CLMemoryMutable(b)), ldb,
// CLComplex(CLMemoryMutable(b)), ldb);
}
bool CLBlas::DoBlasTrsm(Stream *stream, blas::Side side,
blas::UpperLower uplo, blas::Transpose transa,
blas::Diagonal diag, uint64 m, uint64 n, float alpha,
const DeviceMemory<float> &a, int lda,
DeviceMemory<float> *b, int ldb) {
return false;
// return DoBlasInternal(cublasStrsm, stream,
// true /* = pointer_mode_host */, CLBlasSide(side),
// CLBlasUpperLower(uplo), CLBlasTranspose(transa),
// CLBlasDiagonal(diag), m, n, &alpha, CLMemory(a),
// lda, CLMemoryMutable(b), ldb);
}
bool CLBlas::DoBlasTrsm(Stream *stream, blas::Side side,
blas::UpperLower uplo, blas::Transpose transa,
blas::Diagonal diag, uint64 m, uint64 n, double alpha,
const DeviceMemory<double> &a, int lda,
DeviceMemory<double> *b, int ldb) {
return false;
// return DoBlasInternal(cublasDtrsm, stream,
// true /* = pointer_mode_host */, CLBlasSide(side),
// CLBlasUpperLower(uplo), CLBlasTranspose(transa),
// CLBlasDiagonal(diag), m, n, &alpha, CLMemory(a),
// lda, CLMemoryMutable(b), ldb);
}
bool CLBlas::DoBlasTrsm(Stream *stream, blas::Side side,
blas::UpperLower uplo, blas::Transpose transa,
blas::Diagonal diag, uint64 m, uint64 n,
std::complex<float> alpha,
const DeviceMemory<std::complex<float>> &a, int lda,
DeviceMemory<std::complex<float>> *b, int ldb) {
return false;
// return DoBlasInternal(
// cublasCtrsm, stream, true /* = pointer_mode_host */,
// CLBlasSide(side), CLBlasUpperLower(uplo), CLBlasTranspose(transa),
// CLBlasDiagonal(diag), m, n, CLComplex(&alpha),
// CLComplex(CLMemory(a)), lda, CLComplex(CLMemoryMutable(b)), ldb);
}
bool CLBlas::DoBlasTrsm(Stream *stream, blas::Side side,
blas::UpperLower uplo, blas::Transpose transa,
blas::Diagonal diag, uint64 m, uint64 n,
std::complex<double> alpha,
const DeviceMemory<std::complex<double>> &a, int lda,
DeviceMemory<std::complex<double>> *b, int ldb) {
return false;
// return DoBlasInternal(
// cublasZtrsm, stream, true /* = pointer_mode_host */,
// CLBlasSide(side), CLBlasUpperLower(uplo), CLBlasTranspose(transa),
// CLBlasDiagonal(diag), m, n, CLComplex(&alpha),
// CLComplex(CLMemory(a)), lda, CLComplex(CLMemoryMutable(b)), ldb);
}
} // namespace cl
namespace gpu = ::stream_executor;
void initialize_clblas() {
// std::cout << "CLBlas::initialize_clblas()" << std::endl;
gpu::port::Status status =
gpu::PluginRegistry::Instance()
->RegisterFactory<gpu::PluginRegistry::BlasFactory>(
gpu::cl::kClPlatformId, gpu::cl::kClBlasPlugin, "CLBlast",
[](gpu::internal::StreamExecutorInterface
*parent) -> gpu::blas::BlasSupport * {
gpu::cl::CLExecutor *cl_executor =
dynamic_cast<gpu::cl::CLExecutor *>(parent);
if (cl_executor == nullptr) {
LOG(ERROR)
<< "Attempting to initialize an instance of the CLBlast "
<< "support library with a non-CL StreamExecutor";
return nullptr;
}
gpu::cl::CLBlas *blas =
new gpu::cl::CLBlas(cl_executor);
if (!blas->Init()) {
// Note: Init() will log a more specific error.
delete blas;
return nullptr;
}
return blas;
});
if (!status.ok()) {
LOG(ERROR) << "Unable to register CLBlast factory: "
<< status.error_message();
}
// Prime the CLBlast DSO. The loader will log more information.
// auto statusor = gpu::internal::CachedDsoLoader::GetCublasDsoHandle();
// if (!statusor.ok()) {
// LOG(INFO) << "Unable to load CLBlast DSO.";
// }
gpu::PluginRegistry::Instance()->SetDefaultFactory(gpu::cl::kClPlatformId,
gpu::PluginKind::kBlas,
gpu::cl::kClBlasPlugin);
}
} // namespace stream_executor
// REGISTER_MODULE_INITIALIZER(register_clblas,
// { perftools::gputools::initialize_clblas(); });
|
/*
* WebRTCConnection.cpp
*/
#include <map>
#include <algorithm>
#include <string>
#include <cstring>
#include <vector>
#include "WebRtcConnection.h"
#include "MediaStream.h"
#include "DtlsTransport.h"
#include "SdpInfo.h"
#include "bandwidth/MaxVideoBWDistributor.h"
#include "bandwidth/TargetVideoBWDistributor.h"
#include "rtp/RtpHeaders.h"
#include "rtp/RtpVP8Parser.h"
#include "rtp/RtcpAggregator.h"
#include "rtp/RtcpForwarder.h"
#include "rtp/RtpSlideShowHandler.h"
#include "rtp/RtpTrackMuteHandler.h"
#include "rtp/BandwidthEstimationHandler.h"
#include "rtp/FecReceiverHandler.h"
#include "rtp/RtcpProcessorHandler.h"
#include "rtp/RtpRetransmissionHandler.h"
#include "rtp/RtcpFeedbackGenerationHandler.h"
#include "rtp/RtpPaddingRemovalHandler.h"
#include "rtp/StatsHandler.h"
#include "rtp/SRPacketHandler.h"
#include "rtp/SenderBandwidthEstimationHandler.h"
#include "rtp/LayerDetectorHandler.h"
#include "rtp/LayerBitrateCalculationHandler.h"
#include "rtp/QualityFilterHandler.h"
#include "rtp/QualityManager.h"
#include "rtp/PliPacerHandler.h"
#include "rtp/RtpPaddingGeneratorHandler.h"
#include "rtp/RtpUtils.h"
namespace erizo {
DEFINE_LOGGER(WebRtcConnection, "WebRtcConnection");
WebRtcConnection::WebRtcConnection(std::shared_ptr<Worker> worker, std::shared_ptr<IOWorker> io_worker,
const std::string& connection_id, const IceConfig& ice_config, const std::vector<RtpMap> rtp_mappings,
const std::vector<erizo::ExtMap> ext_mappings, WebRtcConnectionEventListener* listener) :
connection_id_{connection_id},
audio_enabled_{false}, video_enabled_{false}, bundle_{false}, conn_event_listener_{listener},
ice_config_{ice_config}, rtp_mappings_{rtp_mappings}, extension_processor_{ext_mappings},
worker_{worker}, io_worker_{io_worker},
remote_sdp_{std::make_shared<SdpInfo>(rtp_mappings)}, local_sdp_{std::make_shared<SdpInfo>(rtp_mappings)},
audio_muted_{false}, video_muted_{false}, first_remote_sdp_processed_{false}
{
ELOG_INFO("%s message: constructor, stunserver: %s, stunPort: %d, minPort: %d, maxPort: %d",
toLog(), ice_config.stun_server.c_str(), ice_config.stun_port, ice_config.min_port, ice_config.max_port);
stats_ = std::make_shared<Stats>();
distributor_ = std::unique_ptr<BandwidthDistributionAlgorithm>(new TargetVideoBWDistributor());
global_state_ = CONN_INITIAL;
trickle_enabled_ = ice_config_.should_trickle;
slide_show_mode_ = false;
sending_ = true;
}
WebRtcConnection::~WebRtcConnection() {
ELOG_DEBUG("%s message:Destructor called", toLog());
ELOG_DEBUG("%s message: Destructor ended", toLog());
}
void WebRtcConnection::syncClose() {
ELOG_DEBUG("%s message: Close called", toLog());
if (!sending_) {
return;
}
sending_ = false;
media_streams_.clear();
if (video_transport_.get()) {
video_transport_->close();
}
if (audio_transport_.get()) {
audio_transport_->close();
}
global_state_ = CONN_FINISHED;
if (conn_event_listener_ != nullptr) {
conn_event_listener_ = nullptr;
}
ELOG_DEBUG("%s message: Close ended", toLog());
}
void WebRtcConnection::close() {
ELOG_DEBUG("%s message: Async close called", toLog());
std::shared_ptr<WebRtcConnection> shared_this = shared_from_this();
asyncTask([shared_this] (std::shared_ptr<WebRtcConnection> connection) {
shared_this->syncClose();
});
}
bool WebRtcConnection::init() {
maybeNotifyWebRtcConnectionEvent(global_state_, "");
return true;
}
boost::future<void> WebRtcConnection::createOffer(bool video_enabled, bool audio_enabled, bool bundle) {
return asyncTask([video_enabled, audio_enabled, bundle] (std::shared_ptr<WebRtcConnection> connection) {
connection->createOfferSync(video_enabled, audio_enabled, bundle);
});
}
bool WebRtcConnection::createOfferSync(bool video_enabled, bool audio_enabled, bool bundle) {
boost::mutex::scoped_lock lock(update_state_mutex_);
bundle_ = bundle;
video_enabled_ = video_enabled;
audio_enabled_ = audio_enabled;
local_sdp_->createOfferSdp(video_enabled_, audio_enabled_, bundle_);
local_sdp_->dtlsRole = ACTPASS;
if (local_sdp_->internal_dtls_role == ACTPASS) {
local_sdp_->internal_dtls_role = PASSIVE;
}
ELOG_DEBUG("%s message: Creating sdp offer, isBundle: %d, setup: %d",
toLog(), bundle_, local_sdp_->internal_dtls_role);
forEachMediaStream([this] (const std::shared_ptr<MediaStream> &media_stream) {
if (!media_stream->isReady() || media_stream->isPublisher()) {
ELOG_DEBUG("%s message: getting local SDPInfo stream not running, stream_id: %s", toLog(), media_stream->getId());
return;
}
if (video_enabled_) {
std::vector<uint32_t> video_ssrc_list = std::vector<uint32_t>();
if (media_stream->getVideoSinkSSRC() != kDefaultVideoSinkSSRC && media_stream->getVideoSinkSSRC() != 0) {
video_ssrc_list.push_back(media_stream->getVideoSinkSSRC());
}
ELOG_DEBUG("%s message: getting local SDPInfo, stream_id: %s, audio_ssrc: %u",
toLog(), media_stream->getId(), media_stream->getAudioSinkSSRC());
if (!video_ssrc_list.empty()) {
local_sdp_->video_ssrc_map[media_stream->getLabel()] = video_ssrc_list;
}
}
if (audio_enabled_) {
if (media_stream->getAudioSinkSSRC() != kDefaultAudioSinkSSRC && media_stream->getAudioSinkSSRC() != 0) {
local_sdp_->audio_ssrc_map[media_stream->getLabel()] = media_stream->getAudioSinkSSRC();
}
}
});
auto listener = std::dynamic_pointer_cast<TransportListener>(shared_from_this());
if (bundle_) {
if (video_transport_.get() == nullptr && (video_enabled_ || audio_enabled_)) {
video_transport_.reset(new DtlsTransport(VIDEO_TYPE, "video", connection_id_, bundle_, true,
listener, ice_config_ , "", "", true, worker_, io_worker_));
video_transport_->copyLogContextFrom(*this);
video_transport_->start();
}
} else {
if (video_transport_.get() == nullptr && video_enabled_) {
// For now we don't re/check transports, if they are already created we leave them there
video_transport_.reset(new DtlsTransport(VIDEO_TYPE, "video", connection_id_, bundle_, true,
listener, ice_config_ , "", "", true, worker_, io_worker_));
video_transport_->copyLogContextFrom(*this);
video_transport_->start();
}
if (audio_transport_.get() == nullptr && audio_enabled_) {
audio_transport_.reset(new DtlsTransport(AUDIO_TYPE, "audio", connection_id_, bundle_, true,
listener, ice_config_, "", "", true, worker_, io_worker_));
audio_transport_->copyLogContextFrom(*this);
audio_transport_->start();
}
}
std::string msg = this->getLocalSdp();
maybeNotifyWebRtcConnectionEvent(global_state_, msg);
return true;
}
boost::future<void> WebRtcConnection::addMediaStream(std::shared_ptr<MediaStream> media_stream) {
return asyncTask([media_stream] (std::shared_ptr<WebRtcConnection> connection) {
boost::mutex::scoped_lock lock(connection->update_state_mutex_);
ELOG_DEBUG("%s message: Adding mediaStream, id: %s", connection->toLog(), media_stream->getId().c_str());
connection->media_streams_.push_back(media_stream);
});
}
boost::future<void> WebRtcConnection::removeMediaStream(const std::string& stream_id) {
return asyncTask([stream_id] (std::shared_ptr<WebRtcConnection> connection) {
boost::mutex::scoped_lock lock(connection->update_state_mutex_);
ELOG_DEBUG("%s message: removing mediaStream, id: %s", connection->toLog(), stream_id.c_str());
connection->media_streams_.erase(std::remove_if(connection->media_streams_.begin(),
connection->media_streams_.end(),
[stream_id, connection](const std::shared_ptr<MediaStream> &stream) {
bool isStream = stream->getId() == stream_id;
if (isStream) {
auto video_it = connection->local_sdp_->video_ssrc_map.find(stream->getLabel());
if (video_it != connection->local_sdp_->video_ssrc_map.end()) {
connection->local_sdp_->video_ssrc_map.erase(video_it);
}
auto audio_it = connection->local_sdp_->audio_ssrc_map.find(stream->getLabel());
if (audio_it != connection->local_sdp_->audio_ssrc_map.end()) {
connection->local_sdp_->audio_ssrc_map.erase(audio_it);
}
}
return isStream;
}));
});
}
void WebRtcConnection::forEachMediaStream(std::function<void(const std::shared_ptr<MediaStream>&)> func) {
std::for_each(media_streams_.begin(), media_streams_.end(), func);
}
boost::future<void> WebRtcConnection::forEachMediaStreamAsync(
std::function<void(const std::shared_ptr<MediaStream>&)> func) {
auto futures = std::make_shared<std::vector<boost::future<void>>>();
std::for_each(media_streams_.begin(), media_streams_.end(),
[func, futures] (const std::shared_ptr<MediaStream> &stream) {
futures->push_back(stream->asyncTask([func] (const std::shared_ptr<MediaStream> &stream) {
func(stream);
}));
});
auto future_when = boost::when_all(futures->begin(), futures->end());
return future_when.then([](decltype(future_when)) {
});
}
void WebRtcConnection::forEachMediaStreamAsyncNoPromise(
std::function<void(const std::shared_ptr<MediaStream>&)> func) {
std::for_each(media_streams_.begin(), media_streams_.end(),
[func] (const std::shared_ptr<MediaStream> &stream) {
stream->asyncTask([func] (const std::shared_ptr<MediaStream> &stream) {
func(stream);
});
});
}
boost::future<void> WebRtcConnection::setRemoteSdpInfo(
std::shared_ptr<SdpInfo> sdp) {
std::weak_ptr<WebRtcConnection> weak_this = shared_from_this();
auto task_promise = std::make_shared<boost::promise<void>>();
worker_->task([weak_this, sdp, task_promise] {
if (auto connection = weak_this.lock()) {
ELOG_DEBUG("%s message: setting remote SDPInfo", connection->toLog());
if (!connection->sending_) {
task_promise->set_value();
return;
}
connection->remote_sdp_ = sdp;
boost::future<void> future = connection->processRemoteSdp().then(
[task_promise] (boost::future<void>) {
task_promise->set_value();
});
return;
}
task_promise->set_value();
});
return task_promise->get_future();
}
void WebRtcConnection::copyDataToLocalSdpIndo(std::shared_ptr<SdpInfo> sdp_info) {
asyncTask([sdp_info] (std::shared_ptr<WebRtcConnection> connection) {
if (connection->sending_) {
connection->local_sdp_->copyInfoFromSdp(sdp_info);
connection->local_sdp_->updateSupportedExtensionMap(connection->extension_processor_.getSupportedExtensionMap());
}
});
}
boost::future<std::shared_ptr<SdpInfo>> WebRtcConnection::getLocalSdpInfo() {
std::weak_ptr<WebRtcConnection> weak_this = shared_from_this();
auto task_promise = std::make_shared<boost::promise<std::shared_ptr<SdpInfo>>>();
worker_->task([weak_this, task_promise] {
std::shared_ptr<SdpInfo> info;
if (auto this_ptr = weak_this.lock()) {
info = this_ptr->getLocalSdpInfoSync();
} else {
ELOG_WARN("message: Error trying to getLocalSdpInfo - cannot lock WebrtcConnection, returning empty");
}
task_promise->set_value(info);
});
return task_promise->get_future();
}
std::shared_ptr<SdpInfo> WebRtcConnection::getLocalSdpInfoSync() {
boost::mutex::scoped_lock lock(update_state_mutex_);
ELOG_DEBUG("%s message: getting local SDPInfo", toLog());
forEachMediaStream([this] (const std::shared_ptr<MediaStream> &media_stream) {
if (!media_stream->isReady() || media_stream->isPublisher()) {
ELOG_DEBUG("%s message: getting local SDPInfo stream not running, stream_id: %s", toLog(), media_stream->getId());
return;
}
std::vector<uint32_t> video_ssrc_list = std::vector<uint32_t>();
if (media_stream->getVideoSinkSSRC() != kDefaultVideoSinkSSRC && media_stream->getVideoSinkSSRC() != 0) {
video_ssrc_list.push_back(media_stream->getVideoSinkSSRC());
}
ELOG_DEBUG("%s message: getting local SDPInfo, stream_id: %s, audio_ssrc: %u",
toLog(), media_stream->getId(), media_stream->getAudioSinkSSRC());
if (!video_ssrc_list.empty()) {
local_sdp_->video_ssrc_map[media_stream->getLabel()] = video_ssrc_list;
}
if (media_stream->getAudioSinkSSRC() != kDefaultAudioSinkSSRC && media_stream->getAudioSinkSSRC() != 0) {
local_sdp_->audio_ssrc_map[media_stream->getLabel()] = media_stream->getAudioSinkSSRC();
}
});
bool sending_audio = local_sdp_->audio_ssrc_map.size() > 0;
bool sending_video = local_sdp_->video_ssrc_map.size() > 0;
bool receiving_audio = remote_sdp_->audio_ssrc_map.size() > 0;
bool receiving_video = remote_sdp_->video_ssrc_map.size() > 0;
audio_enabled_ = sending_audio || receiving_audio;
video_enabled_ = sending_video || receiving_video;
if (!sending_audio && receiving_audio) {
local_sdp_->audioDirection = erizo::RECVONLY;
} else if (sending_audio && !receiving_audio) {
local_sdp_->audioDirection = erizo::SENDONLY;
} else {
local_sdp_->audioDirection = erizo::SENDRECV;
}
if (!sending_video && receiving_video) {
local_sdp_->videoDirection = erizo::RECVONLY;
} else if (sending_video && !receiving_video) {
local_sdp_->videoDirection = erizo::SENDONLY;
} else {
local_sdp_->videoDirection = erizo::SENDRECV;
}
auto local_sdp_copy = std::make_shared<SdpInfo>(*local_sdp_.get());
return local_sdp_copy;
}
boost::future<void> WebRtcConnection::setRemoteSdp(const std::string &sdp) {
std::shared_ptr<boost::promise<void>> p = std::make_shared<boost::promise<void>>();
boost::future<void> f = p->get_future();
asyncTask([sdp, p] (std::shared_ptr<WebRtcConnection> connection) {
ELOG_DEBUG("%s message: setting remote SDP", connection->toLog());
if (!connection->sending_) {
p->set_value();
return;
}
connection->remote_sdp_->initWithSdp(sdp, "");
boost::future<void> f = connection->processRemoteSdp();
f.then([p](boost::future<void> future) {
p->set_value();
});
});
return f;
}
boost::future<void> WebRtcConnection::setRemoteSdpsToMediaStreams() {
ELOG_DEBUG("%s message: setting remote SDP, streams: %d", toLog(), media_streams_.size());
std::weak_ptr<WebRtcConnection> weak_this = shared_from_this();
std::shared_ptr<SdpInfo> remote_sdp = std::make_shared<SdpInfo>(*remote_sdp_.get());
return forEachMediaStreamAsync([weak_this, remote_sdp](std::shared_ptr<MediaStream> media_stream) {
if (auto connection = weak_this.lock()) {
media_stream->setRemoteSdp(remote_sdp);
ELOG_DEBUG("%s message: setting remote SDP to stream, stream: %s",
connection->toLog(), media_stream->getId());
}
});
}
boost::future<void> WebRtcConnection::processRemoteSdp() {
ELOG_DEBUG("%s message: processing remote SDP", toLog());
if (!first_remote_sdp_processed_ && local_sdp_->internal_dtls_role == ACTPASS) {
local_sdp_->internal_dtls_role = ACTIVE;
}
local_sdp_->dtlsRole = local_sdp_->internal_dtls_role;
ELOG_DEBUG("%s message: process remote sdp, setup: %d", toLog(), local_sdp_->internal_dtls_role);
if (first_remote_sdp_processed_) {
return setRemoteSdpsToMediaStreams();
}
bundle_ = remote_sdp_->isBundle;
local_sdp_->setOfferSdp(remote_sdp_);
extension_processor_.setSdpInfo(local_sdp_);
local_sdp_->updateSupportedExtensionMap(extension_processor_.getSupportedExtensionMap());
audio_enabled_ = remote_sdp_->hasAudio;
video_enabled_ = remote_sdp_->hasVideo;
if (remote_sdp_->profile == SAVPF) {
if (remote_sdp_->isFingerprint) {
auto listener = std::dynamic_pointer_cast<TransportListener>(shared_from_this());
if (remote_sdp_->hasVideo || bundle_) {
std::string username = remote_sdp_->getUsername(VIDEO_TYPE);
std::string password = remote_sdp_->getPassword(VIDEO_TYPE);
if (video_transport_.get() == nullptr) {
ELOG_DEBUG("%s message: Creating videoTransport, ufrag: %s, pass: %s",
toLog(), username.c_str(), password.c_str());
video_transport_.reset(new DtlsTransport(VIDEO_TYPE, "video", connection_id_, bundle_, remote_sdp_->isRtcpMux,
listener, ice_config_ , username, password, false,
worker_, io_worker_));
video_transport_->copyLogContextFrom(*this);
video_transport_->start();
} else {
ELOG_DEBUG("%s message: Updating videoTransport, ufrag: %s, pass: %s",
toLog(), username.c_str(), password.c_str());
video_transport_->getIceConnection()->setRemoteCredentials(username, password);
}
}
if (!bundle_ && remote_sdp_->hasAudio) {
std::string username = remote_sdp_->getUsername(AUDIO_TYPE);
std::string password = remote_sdp_->getPassword(AUDIO_TYPE);
if (audio_transport_.get() == nullptr) {
ELOG_DEBUG("%s message: Creating audioTransport, ufrag: %s, pass: %s",
toLog(), username.c_str(), password.c_str());
audio_transport_.reset(new DtlsTransport(AUDIO_TYPE, "audio", connection_id_, bundle_, remote_sdp_->isRtcpMux,
listener, ice_config_, username, password, false,
worker_, io_worker_));
audio_transport_->copyLogContextFrom(*this);
audio_transport_->start();
} else {
ELOG_DEBUG("%s message: Update audioTransport, ufrag: %s, pass: %s",
toLog(), username.c_str(), password.c_str());
audio_transport_->getIceConnection()->setRemoteCredentials(username, password);
}
}
}
}
if (this->getCurrentState() >= CONN_GATHERED) {
if (!remote_sdp_->getCandidateInfos().empty()) {
ELOG_DEBUG("%s message: Setting remote candidates after gathered", toLog());
if (remote_sdp_->hasVideo) {
video_transport_->setRemoteCandidates(remote_sdp_->getCandidateInfos(), bundle_);
}
if (!bundle_ && remote_sdp_->hasAudio) {
audio_transport_->setRemoteCandidates(remote_sdp_->getCandidateInfos(), bundle_);
}
}
}
first_remote_sdp_processed_ = true;
return setRemoteSdpsToMediaStreams();
}
boost::future<void> WebRtcConnection::addRemoteCandidate(std::string mid, int mLineIndex, std::string sdp) {
return asyncTask([mid, mLineIndex, sdp] (std::shared_ptr<WebRtcConnection> connection) {
connection->addRemoteCandidateSync(mid, mLineIndex, sdp);
});
}
bool WebRtcConnection::addRemoteCandidateSync(std::string mid, int mLineIndex, std::string sdp) {
// TODO(pedro) Check type of transport.
ELOG_DEBUG("%s message: Adding remote Candidate, candidate: %s, mid: %s, sdpMLine: %d",
toLog(), sdp.c_str(), mid.c_str(), mLineIndex);
if (video_transport_ == nullptr && audio_transport_ == nullptr) {
ELOG_WARN("%s message: addRemoteCandidate on NULL transport", toLog());
return false;
}
MediaType theType;
std::string theMid;
// TODO(pedro) check if this works with video+audio and no bundle
if (mLineIndex == -1) {
ELOG_DEBUG("%s message: All candidates received", toLog());
if (video_transport_) {
video_transport_->getIceConnection()->setReceivedLastCandidate(true);
} else if (audio_transport_) {
audio_transport_->getIceConnection()->setReceivedLastCandidate(true);
}
return true;
}
if ((!mid.compare("video")) || (mLineIndex == remote_sdp_->videoSdpMLine)) {
theType = VIDEO_TYPE;
theMid = "video";
} else {
theType = AUDIO_TYPE;
theMid = "audio";
}
SdpInfo tempSdp(rtp_mappings_);
std::string username = remote_sdp_->getUsername(theType);
std::string password = remote_sdp_->getPassword(theType);
tempSdp.setCredentials(username, password, OTHER);
bool res = false;
if (tempSdp.initWithSdp(sdp, theMid)) {
if (theType == VIDEO_TYPE || bundle_) {
res = video_transport_->setRemoteCandidates(tempSdp.getCandidateInfos(), bundle_);
} else if (theType == AUDIO_TYPE) {
res = audio_transport_->setRemoteCandidates(tempSdp.getCandidateInfos(), bundle_);
} else {
ELOG_ERROR("%s message: add remote candidate with no Media (video or audio), candidate: %s",
toLog(), sdp.c_str() );
}
}
for (uint8_t it = 0; it < tempSdp.getCandidateInfos().size(); it++) {
remote_sdp_->addCandidate(tempSdp.getCandidateInfos()[it]);
}
return res;
}
std::string WebRtcConnection::getLocalSdp() {
ELOG_DEBUG("%s message: Getting Local Sdp", toLog());
if (video_transport_ != nullptr && getCurrentState() != CONN_READY) {
video_transport_->processLocalSdp(local_sdp_.get());
}
if (!bundle_ && audio_transport_ != nullptr && getCurrentState() != CONN_READY) {
audio_transport_->processLocalSdp(local_sdp_.get());
}
local_sdp_->profile = remote_sdp_->profile;
return local_sdp_->getSdp();
}
std::string WebRtcConnection::getJSONCandidate(const std::string& mid, const std::string& sdp) {
std::map <std::string, std::string> object;
object["sdpMid"] = mid;
object["candidate"] = sdp;
object["sdpMLineIndex"] =
std::to_string((mid.compare("video")?local_sdp_->audioSdpMLine : local_sdp_->videoSdpMLine));
std::ostringstream theString;
theString << "{";
for (std::map<std::string, std::string>::const_iterator it = object.begin(); it != object.end(); ++it) {
theString << "\"" << it->first << "\":\"" << it->second << "\"";
if (++it != object.end()) {
theString << ",";
}
--it;
}
theString << "}";
return theString.str();
}
void WebRtcConnection::onCandidate(const CandidateInfo& cand, Transport *transport) {
std::string sdp = local_sdp_->addCandidate(cand);
ELOG_DEBUG("%s message: Discovered New Candidate, candidate: %s", toLog(), sdp.c_str());
if (trickle_enabled_) {
if (!bundle_) {
std::string object = this->getJSONCandidate(transport->transport_name, sdp);
maybeNotifyWebRtcConnectionEvent(CONN_CANDIDATE, object);
} else {
if (remote_sdp_->hasAudio) {
std::string object = this->getJSONCandidate("audio", sdp);
maybeNotifyWebRtcConnectionEvent(CONN_CANDIDATE, object);
}
if (remote_sdp_->hasVideo) {
std::string object2 = this->getJSONCandidate("video", sdp);
maybeNotifyWebRtcConnectionEvent(CONN_CANDIDATE, object2);
}
}
}
}
void WebRtcConnection::onREMBFromTransport(RtcpHeader *chead, Transport *transport) {
std::vector<std::shared_ptr<MediaStream>> streams;
for (uint8_t index = 0; index < chead->getREMBNumSSRC(); index++) {
uint32_t ssrc_feed = chead->getREMBFeedSSRC(index);
forEachMediaStream([ssrc_feed, &streams] (const std::shared_ptr<MediaStream> &media_stream) {
if (media_stream->isSinkSSRC(ssrc_feed)) {
streams.push_back(media_stream);
}
});
}
distributor_->distribute(chead->getREMBBitRate(), chead->getSSRC(), streams, transport);
}
void WebRtcConnection::onRtcpFromTransport(std::shared_ptr<DataPacket> packet, Transport *transport) {
RtpUtils::forEachRtcpBlock(packet, [this, packet, transport](RtcpHeader *chead) {
uint32_t ssrc = chead->isFeedback() ? chead->getSourceSSRC() : chead->getSSRC();
if (chead->isREMB()) {
onREMBFromTransport(chead, transport);
return;
}
std::shared_ptr<DataPacket> rtcp = std::make_shared<DataPacket>(*packet);
rtcp->length = (ntohs(chead->length) + 1) * 4;
std::memcpy(rtcp->data, chead, rtcp->length);
forEachMediaStream([rtcp, transport, ssrc] (const std::shared_ptr<MediaStream> &media_stream) {
if (media_stream->isSourceSSRC(ssrc) || media_stream->isSinkSSRC(ssrc)) {
media_stream->onTransportData(rtcp, transport);
}
});
});
}
void WebRtcConnection::onTransportData(std::shared_ptr<DataPacket> packet, Transport *transport) {
if (getCurrentState() != CONN_READY) {
return;
}
char* buf = packet->data;
RtcpHeader *chead = reinterpret_cast<RtcpHeader*> (buf);
if (chead->isRtcp()) {
onRtcpFromTransport(packet, transport);
return;
} else {
RtpHeader *head = reinterpret_cast<RtpHeader*> (buf);
uint32_t ssrc = head->getSSRC();
forEachMediaStream([packet, transport, ssrc] (const std::shared_ptr<MediaStream> &media_stream) {
if (media_stream->isSourceSSRC(ssrc) || media_stream->isSinkSSRC(ssrc)) {
media_stream->onTransportData(packet, transport);
}
});
}
}
void WebRtcConnection::maybeNotifyWebRtcConnectionEvent(const WebRTCEvent& event, const std::string& message) {
boost::mutex::scoped_lock lock(event_listener_mutex_);
if (!conn_event_listener_) {
return;
}
conn_event_listener_->notifyEvent(event, message);
}
boost::future<void> WebRtcConnection::asyncTask(
std::function<void(std::shared_ptr<WebRtcConnection>)> f) {
auto task_promise = std::make_shared<boost::promise<void>>();
std::weak_ptr<WebRtcConnection> weak_this = shared_from_this();
worker_->task([weak_this, f, task_promise] {
if (auto this_ptr = weak_this.lock()) {
f(this_ptr);
}
task_promise->set_value();
});
return task_promise->get_future();
}
void WebRtcConnection::updateState(TransportState state, Transport * transport) {
boost::mutex::scoped_lock lock(update_state_mutex_);
WebRTCEvent temp = global_state_;
std::string msg = "";
ELOG_DEBUG("%s transportName: %s, new_state: %d", toLog(), transport->transport_name.c_str(), state);
if (video_transport_.get() == nullptr && audio_transport_.get() == nullptr) {
ELOG_ERROR("%s message: Updating NULL transport, state: %d", toLog(), state);
return;
}
if (global_state_ == CONN_FAILED) {
// if current state is failed -> noop
return;
}
switch (state) {
case TRANSPORT_STARTED:
if (bundle_) {
temp = CONN_STARTED;
} else {
if ((!remote_sdp_->hasAudio || (audio_transport_.get() != nullptr
&& audio_transport_->getTransportState() == TRANSPORT_STARTED)) &&
(!remote_sdp_->hasVideo || (video_transport_.get() != nullptr
&& video_transport_->getTransportState() == TRANSPORT_STARTED))) {
// WebRTCConnection will be ready only when all channels are ready.
temp = CONN_STARTED;
}
}
break;
case TRANSPORT_GATHERED:
if (bundle_) {
if (!remote_sdp_->getCandidateInfos().empty()) {
// Passing now new candidates that could not be passed before
if (remote_sdp_->hasVideo) {
video_transport_->setRemoteCandidates(remote_sdp_->getCandidateInfos(), bundle_);
}
if (!bundle_ && remote_sdp_->hasAudio) {
audio_transport_->setRemoteCandidates(remote_sdp_->getCandidateInfos(), bundle_);
}
}
if (!trickle_enabled_) {
temp = CONN_GATHERED;
msg = this->getLocalSdp();
}
} else {
if ((!local_sdp_->hasAudio || (audio_transport_.get() != nullptr
&& audio_transport_->getTransportState() == TRANSPORT_GATHERED)) &&
(!local_sdp_->hasVideo || (video_transport_.get() != nullptr
&& video_transport_->getTransportState() == TRANSPORT_GATHERED))) {
// WebRTCConnection will be ready only when all channels are ready.
if (!trickle_enabled_) {
temp = CONN_GATHERED;
msg = this->getLocalSdp();
}
}
}
break;
case TRANSPORT_READY:
if (bundle_) {
temp = CONN_READY;
trackTransportInfo();
forEachMediaStreamAsyncNoPromise([] (const std::shared_ptr<MediaStream> &media_stream) {
media_stream->sendPLIToFeedback();
});
} else {
if ((!remote_sdp_->hasAudio || (audio_transport_.get() != nullptr
&& audio_transport_->getTransportState() == TRANSPORT_READY)) &&
(!remote_sdp_->hasVideo || (video_transport_.get() != nullptr
&& video_transport_->getTransportState() == TRANSPORT_READY))) {
// WebRTCConnection will be ready only when all channels are ready.
temp = CONN_READY;
trackTransportInfo();
forEachMediaStreamAsyncNoPromise([] (const std::shared_ptr<MediaStream> &media_stream) {
media_stream->sendPLIToFeedback();
});
}
}
break;
case TRANSPORT_FAILED:
temp = CONN_FAILED;
sending_ = false;
msg = remote_sdp_->getSdp();
ELOG_ERROR("%s message: Transport Failed, transportType: %s", toLog(), transport->transport_name.c_str() );
cond_.notify_one();
break;
default:
ELOG_DEBUG("%s message: Doing nothing on state, state %d", toLog(), state);
break;
}
if (audio_transport_.get() != nullptr && video_transport_.get() != nullptr) {
ELOG_DEBUG("%s message: %s, transportName: %s, videoTransportState: %d"
", audioTransportState: %d, calculatedState: %d, globalState: %d",
toLog(),
"Update Transport State",
transport->transport_name.c_str(),
static_cast<int>(audio_transport_->getTransportState()),
static_cast<int>(video_transport_->getTransportState()),
static_cast<int>(temp),
static_cast<int>(global_state_));
}
if (global_state_ == temp) {
return;
}
global_state_ = temp;
ELOG_INFO("%s newGlobalState: %d", toLog(), temp);
maybeNotifyWebRtcConnectionEvent(global_state_, msg);
}
void WebRtcConnection::trackTransportInfo() {
CandidatePair candidate_pair;
std::string audio_info;
std::string video_info;
if (video_enabled_ && video_transport_) {
candidate_pair = video_transport_->getIceConnection()->getSelectedPair();
video_info = candidate_pair.clientHostType;
}
if (audio_enabled_ && audio_transport_) {
candidate_pair = audio_transport_->getIceConnection()->getSelectedPair();
audio_info = candidate_pair.clientHostType;
}
asyncTask([audio_info, video_info] (std::shared_ptr<WebRtcConnection> connection) {
connection->forEachMediaStreamAsyncNoPromise(
[audio_info, video_info] (const std::shared_ptr<MediaStream> &media_stream) {
media_stream->setTransportInfo(audio_info, video_info);
});
});
}
void WebRtcConnection::setMetadata(std::map<std::string, std::string> metadata) {
setLogContext(metadata);
}
void WebRtcConnection::setWebRtcConnectionEventListener(WebRtcConnectionEventListener* listener) {
boost::mutex::scoped_lock lock(event_listener_mutex_);
this->conn_event_listener_ = listener;
}
WebRTCEvent WebRtcConnection::getCurrentState() {
return global_state_;
}
void WebRtcConnection::write(std::shared_ptr<DataPacket> packet) {
asyncTask([packet] (std::shared_ptr<WebRtcConnection> connection) {
connection->syncWrite(packet);
});
}
void WebRtcConnection::syncWrite(std::shared_ptr<DataPacket> packet) {
if (!sending_) {
return;
}
Transport *transport = (bundle_ || packet->type == VIDEO_PACKET) ? video_transport_.get() : audio_transport_.get();
if (transport == nullptr) {
return;
}
this->extension_processor_.processRtpExtensions(packet);
transport->write(packet->data, packet->length);
}
void WebRtcConnection::setTransport(std::shared_ptr<Transport> transport) { // Only for Testing purposes
video_transport_ = std::move(transport);
bundle_ = true;
}
} // namespace erizo
|
// streamClases.cpp
#ifndef LINUX
#include "stdafx.h"
#endif
#include "stdio.h"
#include "stdlib.h"
#include "streamClasses.h"
LIBSTREAM_API LPSTR CTCHAR2A(LPCTSTR lpszBuffer)
{
static char output[4096];
LPSTR _lpa = output;
_lpa[0] = 0;
LPCWSTR _lpw = lpszBuffer;
if (NULL == _lpw)
return NULL;
int nChars = lstrlenW(_lpw)+1;
WideCharToMultiByte(CP_ACP, 0, _lpw, -1, _lpa, nChars, NULL, NULL);
return _lpa;
}
LIBSTREAM_API LPCSTR CTCHAR2CA(LPCTSTR lpszBuffer)
{
return (LPCSTR)CTCHAR2A(lpszBuffer);
}
LIBSTREAM_API LPSTR TCHAR2A(LPTSTR lpszBuffer)
{
return CTCHAR2A((LPCTSTR)lpszBuffer);
}
LIBSTREAM_API LPCSTR TCHAR2CA(LPTSTR lpszBuffer)
{
return (LPCSTR)CTCHAR2A((LPCTSTR)lpszBuffer);
}
|
// -------------------------------------------------------------------------------------------------
// Copyright 2016 - NumScale SAS
//
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file LICENSE.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
// -------------------------------------------------------------------------------------------------
/// bench for functor acsc in scalar mode for double type with no decorator (regular call).
#include <simd_bench.hpp>
#include <boost/simd/function/acsc.hpp>
namespace nsb = ns::bench;
namespace bs = boost::simd;
DEFINE_BENCH_MAIN()
{
using T = double;
run<T>(bs::acsc, nsbg::rand<T>(-10, -1));
}
|
#include <functional>
#include "KeyOnOffTest.h"
#include "SimpleIrqTest.h"
typedef std::function<CTest*()> TestFactoryFunction;
// clang-format off
static const TestFactoryFunction s_factories[] =
{
[]() { return new CKeyOnOffTest(); },
[]() { return new CSimpleIrqTest(); },
};
// clang-format on
int main(int argc, const char** argv)
{
for(const auto& factory : s_factories)
{
auto test = factory();
test->Execute();
delete test;
}
return 0;
}
|
#include "client.hpp"
#include <fmt/ostream.h>
#include <spdlog/spdlog.h>
#include <fstream>
#include <iostream>
#include "idle-inhibit-unstable-v1-client-protocol.h"
#include "util/clara.hpp"
#include "util/json.hpp"
#include "wlr-layer-shell-unstable-v1-client-protocol.h"
waybar::Client *waybar::Client::inst() {
static auto c = new Client();
return c;
}
const std::string waybar::Client::getValidPath(const std::vector<std::string> &paths) const {
wordexp_t p;
for (const std::string &path : paths) {
if (wordexp(path.c_str(), &p, 0) == 0) {
if (access(*p.we_wordv, F_OK) == 0) {
std::string result = *p.we_wordv;
wordfree(&p);
return result;
}
wordfree(&p);
}
}
return std::string();
}
void waybar::Client::handleGlobal(void *data, struct wl_registry *registry, uint32_t name,
const char *interface, uint32_t version) {
auto client = static_cast<Client *>(data);
if (strcmp(interface, zwlr_layer_shell_v1_interface.name) == 0) {
// limit version to a highest supported by the client protocol file
version = std::min<uint32_t>(version, zwlr_layer_shell_v1_interface.version);
client->layer_shell = static_cast<struct zwlr_layer_shell_v1 *>(
wl_registry_bind(registry, name, &zwlr_layer_shell_v1_interface, version));
} else if (strcmp(interface, zxdg_output_manager_v1_interface.name) == 0 &&
version >= ZXDG_OUTPUT_V1_NAME_SINCE_VERSION) {
client->xdg_output_manager = static_cast<struct zxdg_output_manager_v1 *>(wl_registry_bind(
registry, name, &zxdg_output_manager_v1_interface, ZXDG_OUTPUT_V1_NAME_SINCE_VERSION));
} else if (strcmp(interface, zwp_idle_inhibit_manager_v1_interface.name) == 0) {
client->idle_inhibit_manager = static_cast<struct zwp_idle_inhibit_manager_v1 *>(
wl_registry_bind(registry, name, &zwp_idle_inhibit_manager_v1_interface, 1));
}
}
void waybar::Client::handleGlobalRemove(void * data, struct wl_registry * /*registry*/,
uint32_t name) {
// Nothing here
}
void waybar::Client::handleOutput(struct waybar_output &output) {
static const struct zxdg_output_v1_listener xdgOutputListener = {
.logical_position = [](void *, struct zxdg_output_v1 *, int32_t, int32_t) {},
.logical_size = [](void *, struct zxdg_output_v1 *, int32_t, int32_t) {},
.done = &handleOutputDone,
.name = &handleOutputName,
.description = &handleOutputDescription,
};
// owned by output->monitor; no need to destroy
auto wl_output = gdk_wayland_monitor_get_wl_output(output.monitor->gobj());
output.xdg_output.reset(zxdg_output_manager_v1_get_xdg_output(xdg_output_manager, wl_output));
zxdg_output_v1_add_listener(output.xdg_output.get(), &xdgOutputListener, &output);
}
bool waybar::Client::isValidOutput(const Json::Value &config, struct waybar_output &output) {
if (config["output"].isArray()) {
for (auto const &output_conf : config["output"]) {
if (output_conf.isString() &&
(output_conf.asString() == output.name || output_conf.asString() == output.identifier)) {
return true;
}
}
return false;
} else if (config["output"].isString()) {
auto config_output = config["output"].asString();
if (!config_output.empty()) {
if (config_output.substr(0, 1) == "!") {
return config_output.substr(1) != output.name &&
config_output.substr(1) != output.identifier;
}
return config_output == output.name || config_output == output.identifier;
}
}
return true;
}
struct waybar::waybar_output &waybar::Client::getOutput(void *addr) {
auto it = std::find_if(
outputs_.begin(), outputs_.end(), [&addr](const auto &output) { return &output == addr; });
if (it == outputs_.end()) {
throw std::runtime_error("Unable to find valid output");
}
return *it;
}
std::vector<Json::Value> waybar::Client::getOutputConfigs(struct waybar_output &output) {
std::vector<Json::Value> configs;
if (config_.isArray()) {
for (auto const &config : config_) {
if (config.isObject() && isValidOutput(config, output)) {
configs.push_back(config);
}
}
} else if (isValidOutput(config_, output)) {
configs.push_back(config_);
}
return configs;
}
void waybar::Client::handleOutputDone(void *data, struct zxdg_output_v1 * /*xdg_output*/) {
auto client = waybar::Client::inst();
try {
auto &output = client->getOutput(data);
/**
* Multiple .done events may arrive in batch. In this case libwayland would queue
* xdg_output.destroy and dispatch all pending events, triggering this callback several times
* for the same output. .done events can also arrive after that for a scale or position changes.
* We wouldn't want to draw a duplicate bar for each such event either.
*
* All the properties we care about are immutable so it's safe to delete the xdg_output object
* on the first event and use the ptr value to check that the callback was already invoked.
*/
if (output.xdg_output) {
output.xdg_output.reset();
spdlog::debug("Output detection done: {} ({})", output.name, output.identifier);
auto configs = client->getOutputConfigs(output);
if (!configs.empty()) {
for (const auto &config : configs) {
client->bars.emplace_back(std::make_unique<Bar>(&output, config));
}
}
}
} catch (const std::exception &e) {
std::cerr << e.what() << std::endl;
}
}
void waybar::Client::handleOutputName(void * data, struct zxdg_output_v1 * /*xdg_output*/,
const char *name) {
auto client = waybar::Client::inst();
try {
auto &output = client->getOutput(data);
output.name = name;
} catch (const std::exception &e) {
std::cerr << e.what() << std::endl;
}
}
void waybar::Client::handleOutputDescription(void *data, struct zxdg_output_v1 * /*xdg_output*/,
const char *description) {
auto client = waybar::Client::inst();
try {
auto & output = client->getOutput(data);
const char *open_paren = strrchr(description, '(');
// Description format: "identifier (name)"
size_t identifier_length = open_paren - description;
output.identifier = std::string(description, identifier_length - 1);
} catch (const std::exception &e) {
std::cerr << e.what() << std::endl;
}
}
void waybar::Client::handleMonitorAdded(Glib::RefPtr<Gdk::Monitor> monitor) {
auto &output = outputs_.emplace_back();
output.monitor = monitor;
handleOutput(output);
}
void waybar::Client::handleMonitorRemoved(Glib::RefPtr<Gdk::Monitor> monitor) {
spdlog::debug("Output removed: {} {}", monitor->get_manufacturer(), monitor->get_model());
/* This event can be triggered from wl_display_roundtrip called by GTK or our code.
* Defer destruction of bars for the output to the next iteration of the event loop to avoid
* deleting objects referenced by currently executed code.
*/
Glib::signal_idle().connect_once(
sigc::bind(sigc::mem_fun(*this, &Client::handleDeferredMonitorRemoval), monitor),
Glib::PRIORITY_HIGH_IDLE);
}
void waybar::Client::handleDeferredMonitorRemoval(Glib::RefPtr<Gdk::Monitor> monitor) {
for (auto it = bars.begin(); it != bars.end();) {
if ((*it)->output->monitor == monitor) {
auto output_name = (*it)->output->name;
(*it)->window.hide();
gtk_app->remove_window((*it)->window);
it = bars.erase(it);
spdlog::info("Bar removed from output: {}", output_name);
} else {
++it;
}
}
outputs_.remove_if([&monitor](const auto &output) { return output.monitor == monitor; });
}
std::tuple<const std::string, const std::string> waybar::Client::getConfigs(
const std::string &config, const std::string &style) const {
auto config_file = config.empty() ? getValidPath({
"$XDG_CONFIG_HOME/waybar/config",
"$XDG_CONFIG_HOME/waybar/config.jsonc",
"$HOME/.config/waybar/config",
"$HOME/.config/waybar/config.jsonc",
"$HOME/waybar/config",
"$HOME/waybar/config.jsonc",
"/etc/xdg/waybar/config",
"/etc/xdg/waybar/config.jsonc",
SYSCONFDIR "/xdg/waybar/config",
"./resources/config",
})
: config;
auto css_file = style.empty() ? getValidPath({
"$XDG_CONFIG_HOME/waybar/style.css",
"$HOME/.config/waybar/style.css",
"$HOME/waybar/style.css",
"/etc/xdg/waybar/style.css",
SYSCONFDIR "/xdg/waybar/style.css",
"./resources/style.css",
})
: style;
if (css_file.empty() || config_file.empty()) {
throw std::runtime_error("Missing required resources files");
}
spdlog::info("Resources files: {}, {}", config_file, css_file);
return {config_file, css_file};
}
auto waybar::Client::setupConfig(const std::string &config_file, int depth) -> void {
if (depth > 100) {
throw std::runtime_error("Aborting due to likely recursive include in config files");
}
std::ifstream file(config_file);
if (!file.is_open()) {
throw std::runtime_error("Can't open config file");
}
std::string str((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
util::JsonParser parser;
Json::Value tmp_config_ = parser.parse(str);
if (tmp_config_.isArray()) {
for (auto &config_part : tmp_config_) {
resolveConfigIncludes(config_part, depth);
}
} else {
resolveConfigIncludes(tmp_config_, depth);
}
mergeConfig(config_, tmp_config_);
}
auto waybar::Client::resolveConfigIncludes(Json::Value &config, int depth) -> void {
Json::Value includes = config["include"];
if (includes.isArray()) {
for (const auto &include : includes) {
spdlog::info("Including resource file: {}", include.asString());
setupConfig(getValidPath({include.asString()}), ++depth);
}
} else if (includes.isString()) {
spdlog::info("Including resource file: {}", includes.asString());
setupConfig(getValidPath({includes.asString()}), ++depth);
}
}
auto waybar::Client::mergeConfig(Json::Value &a_config_, Json::Value &b_config_) -> void {
if (!a_config_) {
// For the first config
a_config_ = b_config_;
} else if (a_config_.isObject() && b_config_.isObject()) {
for (const auto &key : b_config_.getMemberNames()) {
if (a_config_[key].isObject() && b_config_[key].isObject()) {
mergeConfig(a_config_[key], b_config_[key]);
} else {
a_config_[key] = b_config_[key];
}
}
} else if (a_config_.isArray() && b_config_.isArray()) {
// This can happen only on the top-level array of a multi-bar config
for (Json::Value::ArrayIndex i = 0; i < b_config_.size(); i++) {
if (a_config_[i].isObject() && b_config_[i].isObject()) {
mergeConfig(a_config_[i], b_config_[i]);
}
}
} else {
spdlog::error("Cannot merge config, conflicting or invalid JSON types");
}
}
auto waybar::Client::setupCss(const std::string &css_file) -> void {
css_provider_ = Gtk::CssProvider::create();
style_context_ = Gtk::StyleContext::create();
// Load our css file, wherever that may be hiding
if (!css_provider_->load_from_path(css_file)) {
throw std::runtime_error("Can't open style file");
}
// there's always only one screen
style_context_->add_provider_for_screen(
Gdk::Screen::get_default(), css_provider_, GTK_STYLE_PROVIDER_PRIORITY_USER);
}
void waybar::Client::bindInterfaces() {
registry = wl_display_get_registry(wl_display);
static const struct wl_registry_listener registry_listener = {
.global = handleGlobal,
.global_remove = handleGlobalRemove,
};
wl_registry_add_listener(registry, ®istry_listener, this);
wl_display_roundtrip(wl_display);
if (layer_shell == nullptr || xdg_output_manager == nullptr) {
throw std::runtime_error("Failed to acquire required resources.");
}
// add existing outputs and subscribe to updates
for (auto i = 0; i < gdk_display->get_n_monitors(); ++i) {
auto monitor = gdk_display->get_monitor(i);
handleMonitorAdded(monitor);
}
gdk_display->signal_monitor_added().connect(sigc::mem_fun(*this, &Client::handleMonitorAdded));
gdk_display->signal_monitor_removed().connect(
sigc::mem_fun(*this, &Client::handleMonitorRemoved));
}
int waybar::Client::main(int argc, char *argv[]) {
bool show_help = false;
bool show_version = false;
std::string config;
std::string style;
std::string bar_id;
std::string log_level;
auto cli = clara::detail::Help(show_help) |
clara::detail::Opt(show_version)["-v"]["--version"]("Show version") |
clara::detail::Opt(config, "config")["-c"]["--config"]("Config path") |
clara::detail::Opt(style, "style")["-s"]["--style"]("Style path") |
clara::detail::Opt(
log_level,
"trace|debug|info|warning|error|critical|off")["-l"]["--log-level"]("Log level") |
clara::detail::Opt(bar_id, "id")["-b"]["--bar"]("Bar id");
auto res = cli.parse(clara::detail::Args(argc, argv));
if (!res) {
spdlog::error("Error in command line: {}", res.errorMessage());
return 1;
}
if (show_help) {
std::cout << cli << std::endl;
return 0;
}
if (show_version) {
std::cout << "Waybar v" << VERSION << std::endl;
return 0;
}
if (!log_level.empty()) {
spdlog::set_level(spdlog::level::from_str(log_level));
}
gtk_app = Gtk::Application::create(
argc, argv, "fr.arouillard.waybar", Gio::APPLICATION_HANDLES_COMMAND_LINE);
gdk_display = Gdk::Display::get_default();
if (!gdk_display) {
throw std::runtime_error("Can't find display");
}
if (!GDK_IS_WAYLAND_DISPLAY(gdk_display->gobj())) {
throw std::runtime_error("Bar need to run under Wayland");
}
wl_display = gdk_wayland_display_get_wl_display(gdk_display->gobj());
auto [config_file, css_file] = getConfigs(config, style);
setupConfig(config_file, 0);
setupCss(css_file);
bindInterfaces();
gtk_app->hold();
gtk_app->run();
bars.clear();
return 0;
}
void waybar::Client::reset() {
gtk_app->quit();
}
|
#include <iostream>
#include <thread>
void start_func(int *n)
{
std::cout << "thread execute.. " << std::endl;
*n = 10;
}
int main()
{
int n = 0;
std::thread t(start_func, &n);
std::cout << "thread id " << t.get_id() << std::endl;
t.join();
std::cout <<" n = " << n << std::endl;
return 0;
}
|
// This file is part of CAF, the C++ Actor Framework. See the file LICENSE in
// the main distribution directory for license terms and copyright or visit
// https://github.com/actor-framework/actor-framework/blob/master/LICENSE.
#pragma once
#include <cstdint>
#include <type_traits>
#include "caf/config.hpp"
#include "caf/detail/parser/add_ascii.hpp"
#include "caf/detail/parser/chars.hpp"
#include "caf/detail/parser/is_char.hpp"
#include "caf/detail/parser/is_digit.hpp"
#include "caf/detail/parser/sub_ascii.hpp"
#include "caf/detail/scope_guard.hpp"
#include "caf/pec.hpp"
CAF_PUSH_UNUSED_LABEL_WARNING
#include "caf/detail/parser/fsm.hpp"
namespace caf::detail::parser {
/// Reads a number, i.e., on success produces either an `int64_t` or a
/// `double`.
template <class State, class Consumer>
void read_signed_integer(State& ps, Consumer&& consumer) {
using consumer_type = typename std::decay<Consumer>::type;
using value_type = typename consumer_type::value_type;
static_assert(std::is_integral<value_type>::value
&& std::is_signed<value_type>::value,
"expected a signed integer type");
value_type result = 0;
// Computes the result on success.
auto g = caf::detail::make_scope_guard([&] {
if (ps.code <= pec::trailing_character) {
consumer.value(std::move(result));
}
});
// clang-format off
// Definition of our parser FSM.
start();
state(init) {
transition(init, " \t")
transition(has_plus, '+')
transition(has_minus, '-')
epsilon(has_plus)
}
// "+" or "-" alone aren't numbers.
state(has_plus) {
transition(pos_zero, '0')
epsilon(pos_dec, decimal_chars)
}
state(has_minus) {
transition(neg_zero, '0')
epsilon(neg_dec, decimal_chars)
}
// Disambiguate base.
term_state(pos_zero) {
transition(start_pos_bin, "bB")
transition(start_pos_hex, "xX")
epsilon(pos_oct)
}
term_state(neg_zero) {
transition(start_neg_bin, "bB")
transition(start_neg_hex, "xX")
epsilon(neg_oct)
}
// Binary integers.
state(start_pos_bin) {
epsilon(pos_bin, "01")
}
term_state(pos_bin) {
transition(pos_bin, "01", add_ascii<2>(result, ch), pec::integer_overflow)
}
state(start_neg_bin) {
epsilon(neg_bin, "01")
}
term_state(neg_bin) {
transition(neg_bin, "01", sub_ascii<2>(result, ch), pec::integer_underflow)
}
// Octal integers.
state(start_pos_oct) {
epsilon(pos_oct, octal_chars)
}
term_state(pos_oct) {
transition(pos_oct, octal_chars, add_ascii<8>(result, ch),
pec::integer_overflow)
}
state(start_neg_oct) {
epsilon(neg_oct, octal_chars)
}
term_state(neg_oct) {
transition(neg_oct, octal_chars, sub_ascii<8>(result, ch),
pec::integer_underflow)
}
// Hexal integers.
state(start_pos_hex) {
epsilon(pos_hex, hexadecimal_chars)
}
term_state(pos_hex) {
transition(pos_hex, hexadecimal_chars, add_ascii<16>(result, ch),
pec::integer_overflow)
}
state(start_neg_hex) {
epsilon(neg_hex, hexadecimal_chars)
}
term_state(neg_hex) {
transition(neg_hex, hexadecimal_chars, sub_ascii<16>(result, ch),
pec::integer_underflow)
}
// Reads the integer part of the mantissa or a positive decimal integer.
term_state(pos_dec) {
transition(pos_dec, decimal_chars, add_ascii<10>(result, ch),
pec::integer_overflow)
}
// Reads the integer part of the mantissa or a negative decimal integer.
term_state(neg_dec) {
transition(neg_dec, decimal_chars, sub_ascii<10>(result, ch),
pec::integer_underflow)
}
fin();
// clang-format on
}
} // namespace caf::detail::parser
#include "caf/detail/parser/fsm_undef.hpp"
CAF_POP_WARNINGS
|
// Copyright 2015 Markus Jylhänkangas
#include <iostream>
#include "battlefield.h"
#include <limits>
#include <time.h>
#include "version.h" // Version numbers from CMakeLists
using namespace std;
auto main() -> int {
Battlefield battle;
time_t t1, t2;
cout << "************************************\n"
<< "* Fight simulator 6000 *\n"
<< "* V" << VERSION_MAJOR << "." << VERSION_MINOR << "."
<< VERSION_PATCH << " *\n"
<< "************************************\n";
cout << endl << "How many fighters? ";
while (!(cin >> battle.count)) {
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Invalid input. Try again: ";
}
Guy* characters = new Guy[battle.count];
cout << "\n*******************\n"
<< "* Log *\n"
<< "*******************" << endl;
t1 = clock();
while (battle.running) {
battle.attack(characters);
battle.check(characters);
}
t2 = clock();
cout << "\n************************\n"
<< "* DONE *\n"
<< "************************" << endl;
battle.display(characters);
double diff = ((float)t2 - (float)t1) / CLOCKS_PER_SEC;
cout << "\nBattle took: " << diff << " sec" << endl;
delete[] characters;
#ifdef _WIN32
system("PAUSE");
#endif
return 0;
}
|
// Copyright (c) 2014-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#if defined(HAVE_CONFIG_H)
#include "config/royalbritishlegion-config.h"
#endif
#include "timedata.h"
#include "netaddress.h"
#include "sync.h"
#include "ui_interface.h"
#include "util.h"
#include "utilstrencodings.h"
#include "warnings.h"
#include <boost/foreach.hpp>
static CCriticalSection cs_nTimeOffset;
static int64_t nTimeOffset = 0;
/**
* "Never go to sea with two chronometers; take one or three."
* Our three time sources are:
* - System clock
* - Median of other nodes clocks
* - The user (asking the user to fix the system clock if the first two disagree)
*/
int64_t GetTimeOffset()
{
LOCK(cs_nTimeOffset);
return nTimeOffset;
}
int64_t GetAdjustedTime()
{
return GetTime() + GetTimeOffset();
}
static int64_t abs64(int64_t n)
{
return (n >= 0 ? n : -n);
}
#define BITCOIN_TIMEDATA_MAX_SAMPLES 200
void AddTimeData(const CNetAddr& ip, int64_t nOffsetSample)
{
LOCK(cs_nTimeOffset);
// Ignore duplicates
static std::set<CNetAddr> setKnown;
if (setKnown.size() == BITCOIN_TIMEDATA_MAX_SAMPLES)
return;
if (!setKnown.insert(ip).second)
return;
// Add data
static CMedianFilter<int64_t> vTimeOffsets(BITCOIN_TIMEDATA_MAX_SAMPLES, 0);
vTimeOffsets.input(nOffsetSample);
LogPrint("net","added time data, samples %d, offset %+d (%+d minutes)\n", vTimeOffsets.size(), nOffsetSample, nOffsetSample/60);
// There is a known issue here (see issue #4521):
//
// - The structure vTimeOffsets contains up to 200 elements, after which
// any new element added to it will not increase its size, replacing the
// oldest element.
//
// - The condition to update nTimeOffset includes checking whether the
// number of elements in vTimeOffsets is odd, which will never happen after
// there are 200 elements.
//
// But in this case the 'bug' is protective against some attacks, and may
// actually explain why we've never seen attacks which manipulate the
// clock offset.
//
// So we should hold off on fixing this and clean it up as part of
// a timing cleanup that strengthens it in a number of other ways.
//
if (vTimeOffsets.size() >= 5 && vTimeOffsets.size() % 2 == 1)
{
int64_t nMedian = vTimeOffsets.median();
std::vector<int64_t> vSorted = vTimeOffsets.sorted();
// Only let other nodes change our time by so much
if (abs64(nMedian) <= std::max<int64_t>(0, GetArg("-maxtimeadjustment", DEFAULT_MAX_TIME_ADJUSTMENT)))
{
nTimeOffset = nMedian;
}
else
{
nTimeOffset = 0;
static bool fDone;
if (!fDone)
{
// If nobody has a time different than ours but within 5 minutes of ours, give a warning
bool fMatch = false;
BOOST_FOREACH(int64_t nOffset, vSorted)
if (nOffset != 0 && abs64(nOffset) < 5 * 60)
fMatch = true;
if (!fMatch)
{
fDone = true;
std::string strMessage = strprintf(_("Please check that your computer's date and time are correct! If your clock is wrong, %s will not work properly."), _(PACKAGE_NAME));
SetMiscWarning(strMessage);
uiInterface.ThreadSafeMessageBox(strMessage, "", CClientUIInterface::MSG_WARNING);
}
}
}
BOOST_FOREACH(int64_t n, vSorted)
LogPrint("net", "%+d ", n);
LogPrint("net", "| ");
LogPrint("net", "nTimeOffset = %+d (%+d minutes)\n", nTimeOffset, nTimeOffset/60);
}
}
|
/*
* serialport.cpp
*
* Created on: 2012. 12. 27.
* Author: zerom
*/
#include <stdio.h>
#include <string.h>
#include <termios.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/time.h>
#include <sys/ioctl.h>
#include <linux/serial.h>
#include "serialport.h"
using namespace Thor;
SerialPort::SerialPort(const char* port_name) {
DEBUG_PRINT = false;
SocketFD = -1;
SetPortName(port_name);
}
SerialPort::~SerialPort() {
ClosePort();
}
void SerialPort::SetPortName(const char* port_name)
{
strcpy(PortName, port_name);
}
double SerialPort::GetCurrentTime()
{
struct timeval tv;
gettimeofday(&tv, NULL);
return ((double)tv.tv_sec*1000.0 + (double)tv.tv_usec/1000.0);
}
bool SerialPort::SetBaudDevisor(int speed)
{
// try to set a custom divisor
struct serial_struct ss;
if(ioctl(SocketFD, TIOCGSERIAL, &ss) != 0)
{
if(DEBUG_PRINT == true)
printf(" TIOCGSERIAL failed!\n");
return false;
}
ss.flags = (ss.flags & ~ASYNC_SPD_MASK) | ASYNC_SPD_CUST;
ss.custom_divisor = (ss.baud_base + (speed / 2)) / speed;
int closest_speed = ss.baud_base / ss.custom_divisor;
if(closest_speed < speed * 98 / 100 || closest_speed > speed * 102 / 100)
{
if(DEBUG_PRINT == true)
printf(" Cannot set speed to %d, closest is %d \n", speed, closest_speed);
return false;
}
if(ioctl(SocketFD, TIOCSSERIAL, &ss) < 0)
{
if(DEBUG_PRINT == true)
printf(" TIOCSSERIAL failed!\n");
return false;
}
return true;
}
int SerialPort::GetBaud(int baud)
{
switch (baud)
{
case 9600:
return B9600;
case 19200:
return B19200;
case 38400:
return B38400;
case 57600:
return B57600;
case 115200:
return B115200;
case 230400:
return B230400;
case 460800:
return B460800;
case 500000:
return B500000;
case 576000:
return B576000;
case 921600:
return B921600;
case 1000000:
return B1000000;
case 1152000:
return B1152000;
case 1500000:
return B1500000;
case 2000000:
return B2000000;
case 2500000:
return B2500000;
case 3000000:
return B3000000;
case 3500000:
return B3500000;
case 4000000:
return B4000000;
default:
return -1;
}
}
bool SerialPort::SetupSerialPort(int baud)
{
struct termios newtio;
SocketFD = open(PortName, O_RDWR|O_NOCTTY|O_NONBLOCK);
if(SocketFD < 0)
{
if(DEBUG_PRINT == true)
printf("Error opening serial port!\n");
return false;
}
// get the current device attributes
if( tcgetattr(SocketFD, &newtio) == -1 )
{
fprintf(stderr, "tcgetattr(%d,...) failed", SocketFD);
return false;
}
// RDK
// set up baudrate
speed_t ospeed = baud;
speed_t ispeed = baud;
if( cfsetospeed(&newtio, ospeed) == -1 ) // set output baudrate in structure
{
fprintf(stderr, "tcsetospeed(newtio,%u)", ospeed);
return false;
}
if( cfsetispeed(&newtio, ispeed) == -1 ) // set input baudrate in structure
{
fprintf(stderr, "tcsetispeed(newtio,%u)", ispeed);
return false;
}
// RDK
//bzero(&newtio, sizeof(newtio)); // clear struct for new port settings
//newtio.c_cflag = baud | CS8 | CLOCAL | CREAD;
newtio.c_cflag = CS8 | CLOCAL | CREAD;
newtio.c_iflag = IGNPAR;
newtio.c_oflag = 0;
newtio.c_lflag = 0;
newtio.c_cc[VTIME] = 0;
newtio.c_cc[VMIN] = 0;
// clean the buffer and activate the settings for the port
tcflush(SocketFD, TCIFLUSH);
tcsetattr(SocketFD, TCSANOW, &newtio);
return true;
}
bool SerialPort::OpenPort()
{
return SetBaudrate(DEFAULT_BAUDRATE);
}
void SerialPort::ClosePort()
{
if(SocketFD != -1)
close(SocketFD);
SocketFD = -1;
}
void SerialPort::ClearPort()
{
tcflush(SocketFD, TCIOFLUSH);
}
bool SerialPort::SetBaudrate(int baudrate)
{
int baud = GetBaud(baudrate);
ClosePort();
if(baud <= 0)
{
SetupSerialPort(B38400);
return SetBaudDevisor(baudrate);
}
else
{
return SetupSerialPort(baud);
}
}
int SerialPort::WritePort(unsigned char* packet, int packet_len)
{
return write(SocketFD, packet, packet_len);
}
int SerialPort::ReadPort(unsigned char* packet, int packet_len)
{
return read(SocketFD, packet, packet_len);
}
|
//***************************************************************************
// File name: TransactioalFee.cpp
// Author: Hannah Newby
// Date: 2/28/19
// Class: CS485
// Assignment: Bank
// Purpose: TransactionalFee class implamentation
//***************************************************************************
#include "TransactionalFee.h"
//***************************************************************************
// Constructor: TransactionalFee
//
// Description: Initialize TransactionalFee
//
// Parameters: None
//
// Returned: None
//***************************************************************************
TransactionalFee::TransactionalFee() : IFee() {
}
//***************************************************************************
// Constructor: TransactionalFee
//
// Description: Initialize TransactionalFee
//
// Parameters: minBalance - Minimum Balance
// amount - fee amount
//
// Returned: None
//***************************************************************************
TransactionalFee::TransactionalFee(long long minBalance,
long long amount) : IFee (amount) {
mMinBal = minBalance;
}
//***************************************************************************
// Destructor: TransactionalFee
//
// Description: Deconstructor for TransactionalFee
//
// Parameters: none
//
// Returned: None
//***************************************************************************
TransactionalFee::~TransactionalFee() {
}
//***************************************************************************
// Function: chargeMonthlyFee
//
// Description: charge the monthly fee to account
//
// Parameters: balance - balance of account
//
// Returned: long long
//***************************************************************************
long long TransactionalFee::chargeMonthlyFee(const long long balance) {
return 0;
//not a monthly fee no charge
}
//***************************************************************************
// Function: chargeDepositFee
//
// Description: charge the deposit fee to account
//
// Parameters: balance - balance of account
//
// Returned: long long
//***************************************************************************
long long TransactionalFee::chargeDepositFee(const long long balance) {
long long fee = 0;
if (balance < mMinBal)
{
fee = getAmount();
}
return fee;
}
//***************************************************************************
// Function: chargeWithdraeFee
//
// Description: charge the withdraw fee to account
//
// Parameters: balance - balance of account
//
// Returned: long long
//***************************************************************************
long long TransactionalFee::chargeWithdrawFee(const long long balance) {
long long fee = 0;
if (balance < mMinBal) {
fee = getAmount();
}
return fee;
}
//***************************************************************************
// Function: read
//
// Description: read in from stream to min balance
//
// Parameters: rcIn - reference to istream
//
// Returned: None
//***************************************************************************
void TransactionalFee::read(std::istream &rcIn) {
rcIn >> mMinBal; //minBal first because thats the way file is
IFee::read(rcIn);
}
//***************************************************************************
// Function: write
//
// Description: write to stream from min balance
//
// Parameters: rcOut - reference to ostream
//
// Returned: None
//***************************************************************************
void TransactionalFee::write(std::ostream &rcOut) {
rcOut << mMinBal << ", ";
IFee::write(rcOut);
}
|
#include "src1.h"
void foo() {
bar();
}
void bar() {
}
|
#include "./Material.h"
#include <iostream>
#include "../texture/TextureLoader.h"
//#include "stb_image_write.h"
#include "stb_image.h"
namespace TEngine {
Material::Material(Texture* albedoMap, Texture* normalMap, Texture* metallicMap, Texture* roughnessMap, Texture* ambientOcclusionMap, Texture* mixtureMap) :
mAlbedoMap(albedoMap), mNormalMap(normalMap),
mMetallicMap(metallicMap), mRoughnessMap(roughnessMap),
mAOMap(ambientOcclusionMap), mMixtureMap(mixtureMap)
{
}
Material::~Material()
{
}
void Material::SeperateMixture()
{
if (mMixtureMap != nullptr)
{
int width = mMixtureMap->GetWidth();
int height = mMixtureMap->GetHeight();
TextureSettings settings = mMixtureMap->GetTextureSettings();
int channel = settings.ChannelNum;
unsigned char* mixtureData = new unsigned char[width * height * channel];
unsigned char* metalData = new unsigned char[width * height];
unsigned char* roughData = new unsigned char[width * height];
unsigned char* aoData = new unsigned char[width * height];
//std::cout << "Mexture Channel:" << channel << "\n";
mMixtureMap->bind(0);
glGetTexImage(GL_TEXTURE_2D, 0, settings.dataFormat, GL_UNSIGNED_BYTE, mixtureData);
mMixtureMap->unbind();
//stbi_write_png("test.png", width, height,
// 3, mixtureData, width * 3);
if (channel == 1)
{
std::cerr << "WRONG MIXTURE FORMATE: Only one channel mixture\n";
return;
}
// for gltf r - ao, g - roughness, b - metallic
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
int index1 = (i * width + j) * channel;
int index2 = (i * width + j);
metalData[index2] = mixtureData[index1 + 2];
roughData[index2] = mixtureData[index1 + 1];
if (channel > 2)
aoData[index2] = mixtureData[index1];
}
}
mMetallicMap = new Texture();
mMetallicMap->Generate2DTexture(width, height, GL_RED, GL_UNSIGNED_BYTE, metalData);
delete[] metalData;
mRoughnessMap = new Texture();
mRoughnessMap->Generate2DTexture(width, height, GL_RED, GL_UNSIGNED_BYTE, roughData);
delete[] roughData;
if (channel > 2)
{
mAOMap = new Texture();
mAOMap->Generate2DTexture(width, height, GL_RED, GL_UNSIGNED_BYTE, aoData);
delete[] aoData;
}
}
else
{
std::cerr << "No mixture map has been set, sperate muxture failed!\n ";
}
}
void Material::BindMaterial(Shader* shader) const
{
// shader need to be bound outside before binding the material textures
// Texture unit 0 is reserved for the shadowmap
// Texture unit 1 is reserved for the irradianceMap used for indirect diffuse IBL
// Texture unit 2 is reserved for the prefilterMap
// Texture unit 3 is reserved for the brdfLUT
int currentTextureUnit = 4;
shader->SetUniform("material.texture_albedo", currentTextureUnit);
if (mAlbedoMap)
mAlbedoMap->bind(currentTextureUnit++);
else
TextureLoader::GetDefaultAlbedo()->bind(currentTextureUnit++);
shader->SetUniform("material.texture_normal", currentTextureUnit);
if (mNormalMap)
mNormalMap->bind(currentTextureUnit++);
else
TextureLoader::GetDefaultNormal()->bind(currentTextureUnit++);
shader->SetUniform("material.texture_metallic", currentTextureUnit);
if (mMetallicMap)
mMetallicMap->bind(currentTextureUnit++);
else
TextureLoader::GetDefaultMetallic()->bind(currentTextureUnit++);
shader->SetUniform("material.texture_roughness", currentTextureUnit);
if (mRoughnessMap)
mRoughnessMap->bind(currentTextureUnit++);
else
TextureLoader::GetDefaultRoughness()->bind(currentTextureUnit++);
shader->SetUniform("material.texture_ao", currentTextureUnit);
if (mAOMap)
mAOMap->bind(currentTextureUnit++);
else
TextureLoader::GetDefaultAO()->bind(currentTextureUnit++);
//shader->SetUniform("material.texture_displacement", currentTextureUnit);
//if (mDisplacementMap)
//{
// shader->SetUniform("hasDisplacement", true);
// shader->SetUniform("minMaxDisplacementSteps", glm::vec2(mParallaxMinSteps, mParallelMaxSteps));
// shader->SetUniform("parallaxStrength", mParallaxStrength);
// mDisplacementMap->bind(currentTextureUnit++);
//}
//else
// shader->SetUniform("hasDisplacement", false);
}
void Material::OnGui() {
//bad code smell, it's better to add name on Texture
if (mAlbedoMap)
{
if (ImGui::TreeNode("albedoMap"))
{
mAlbedoMap->displayTexture();
ImGui::TreePop();
}
}
if (mNormalMap) {
if (ImGui::TreeNode("normalMap"))
{
mNormalMap->displayTexture();
ImGui::TreePop();
}
}
if (mMetallicMap) {
if (ImGui::TreeNode("metalicMap"))
{
mMetallicMap->displayTexture();
ImGui::TreePop();
}
}
if (mRoughnessMap) {
if (ImGui::TreeNode("roughnessMap"))
{
mRoughnessMap->displayTexture();
ImGui::TreePop();
}
}
if (mAOMap) {
if (ImGui::TreeNode("aoMap"))
{
mAOMap->displayTexture();
ImGui::TreePop();
}
}
if (mMixtureMap) {
if (ImGui::TreeNode("mixtureMap"))
{
mMixtureMap->displayTexture();
ImGui::TreePop();
}
}
}
}
|
/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: Friederike Bock *
* Version 1 *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
//
#include <memory>
#include <vector>
#include "TParticle.h"
#include "TPDGCode.h"
#include "TMCProcess.h"
#include "TDatabasePDG.h"
#include "TList.h"
#include "TChain.h"
#include "TDirectory.h"
#include "TTree.h"
#include "TH1.h"
#include "TH1F.h"
#include "THnSparse.h"
#include "TH2F.h"
#include "AliAnalysisManager.h"
#include "AliESDInputHandler.h"
#include "AliESDtrack.h"
#include "AliMCEvent.h"
#include "AliMCEventHandler.h"
#include "AliPID.h"
#include "AliLog.h"
#include "AliESDtrackCuts.h"
#include "AliESDpidCuts.h"
#include "AliMCEvent.h"
#include "AliESDv0.h"
#include "AliESDEvent.h"
#include "AliESDpid.h"
#include "AliKFParticle.h"
#include "AliMCEventHandler.h"
#include "AliKFVertex.h"
#include "AliTriggerAnalysis.h"
#include "AliCentrality.h"
#include "AliMultiplicity.h"
#include "AliAODEvent.h"
#include "AliAnalysisTaskNeutralMesonToPiPlPiMiNeutralMeson.h"
#include "AliCaloTrackMatcher.h"
#include <vector>
ClassImp( AliAnalysisTaskNeutralMesonToPiPlPiMiNeutralMeson )
//-----------------------------------------------------------------------------------------------
AliAnalysisTaskNeutralMesonToPiPlPiMiNeutralMeson::AliAnalysisTaskNeutralMesonToPiPlPiMiNeutralMeson():
fV0Reader(nullptr),
fV0ReaderName("V0ReaderV1"),
fPionSelector(NULL),
fPionSelectorName("PionSelector"),
fBGHandlerPiPl(NULL),
fBGHandlerPiMi(NULL),
fInputEvent(NULL),
fMCEvent(NULL),
fCutFolder(NULL),
fESDList(NULL),
fTrueList(NULL),
fTrueTreeList(NULL),
fMCList(NULL),
fOutputContainer(0),
fReaderGammas(nullptr),
fSelectorNegPionIndex(0),
fSelectorPosPionIndex(0),
fGoodConvGammas(nullptr),
fClusterCandidates(nullptr),
fNeutralDecayParticleCandidates(nullptr),
fNeutralDecayParticleSidebandCandidates(nullptr),
fPosPionCandidates(nullptr),
fNegPionCandidates(nullptr),
fEventCutArray(nullptr),
fGammaCutArray(nullptr),
fClusterCutArray(nullptr),
fPionCutArray(nullptr),
fNeutralDecayMesonCutArray(nullptr),
fMesonCutArray(nullptr),
fEventCuts(nullptr),
fConversionCuts(nullptr),
fClusterCuts(nullptr),
fOutlierJetReader(nullptr),
fTreePiPiSameMother(nullptr),
fTreePiPiPiSameMother(nullptr),
fTreeEventInfoHNM(nullptr),
fCasePiPi(-1),
fSamePiPiMotherID(-1),
fSamePiPiMotherInvMass(-1),
fSamePiPiMotherPt(-1),
fSamePiPiPiMotherID(-1),
fSamePiPiPiMotherInvMass(-1),
fSamePiPiPiMotherPt(-1),
fV0MultiplicityHNMEvent(-1),
fTrackMultiplicityHNMEvent(-1),
fZVertexHNMEvent(-1),
fPtHNM(-1),
fPDGMassNDM(-1),
fNDMMinPtPossible(0.),
fPDGMassChargedPion(-1),
fPDGCodeNDM(-1),
fPDGCodeAnalyzedMeson(-1),
enableDalitzAllPt(kFALSE),
enableDalitzLowPt(kFALSE),
enableDalitzMidPt(kFALSE),
enableDalitzHighPt(kFALSE),
HistoDalitzPtRangeMin_LowPt(0.),
HistoDalitzPtRangeMax_LowPt(0.),
HistoDalitzPtRangeMin_MidPt(0.),
HistoDalitzPtRangeMax_MidPt(0.),
HistoDalitzPtRangeMin_HighPt(0.),
HistoDalitzPtRangeMax_HighPt(0.),
fHistoConvGammaPt(nullptr),
fHistoConvGammaEta(nullptr),
fHistoClusterGammaPt(nullptr),
fHistoClusterGammaEta(nullptr),
fHistoClusterGammaE(nullptr),
fHistoNegPionPt(nullptr),
fHistoPosPionPt(nullptr),
fHistoNegPionPhi(nullptr),
fHistoPosPionPhi(nullptr),
fHistoNegPionEta(nullptr),
fHistoPosPionEta(nullptr),
fHistoNegPionClsTPC(nullptr),
fHistoPosPionClsTPC(nullptr),
fHistoPionDCAxy(nullptr),
fHistoPionDCAz(nullptr),
fHistoPionTPCdEdxNSigma(nullptr),
fHistoPionTPCdEdx(nullptr),
fHistoPionPionInvMassPt(nullptr),
fHistoGammaGammaInvMassPt(nullptr),
fHistoGammaGammaInvMassPtBeforeCuts(nullptr),
fHistoMotherInvMassPt(nullptr),
fHistoMotherInvMassPtRejectedKinematic(nullptr),
fHistoDalitzPlotPosFixedPzNDM(nullptr),
fHistoDalitzPlotNegFixedPzNDM(nullptr),
fHistoDalitzPlotPosSubNDM(nullptr),
fHistoDalitzPlotNegSubNDM(nullptr),
fHistoDalitzPlotPosFixedPzNDM_LowPt(nullptr),
fHistoDalitzPlotNegFixedPzNDM_LowPt(nullptr),
fHistoDalitzPlotPosSubNDM_LowPt(nullptr),
fHistoDalitzPlotNegSubNDM_LowPt(nullptr),
fHistoDalitzPlotPosFixedPzNDM_MidPt(nullptr),
fHistoDalitzPlotNegFixedPzNDM_MidPt(nullptr),
fHistoDalitzPlotPosSubNDM_MidPt(nullptr),
fHistoDalitzPlotNegSubNDM_MidPt(nullptr),
fHistoDalitzPlotPosFixedPzNDM_HighPt(nullptr),
fHistoDalitzPlotNegFixedPzNDM_HighPt(nullptr),
fHistoDalitzPlotPosSubNDM_HighPt(nullptr),
fHistoDalitzPlotNegSubNDM_HighPt(nullptr),
fHistoBackInvMassPt(nullptr),
fHistoMotherLikeSignBackInvMassPt(nullptr),
fHistoAngleHNMesonPiPlPiMi(nullptr),
fHistoAngleHNMesonNDM(nullptr),
fHistoAngleHNMesonPiPl(nullptr),
fHistoAngleHNMesonPiMi(nullptr),
fHistoAnglePiPlPiMi(nullptr),
fHistoAngleNDMPiMi(nullptr),
fHistoAnglePiPlNDM(nullptr),
fHistoAngleSum(nullptr),
fHistoTrueAngleSum(nullptr),
fHistoTrueHNMesonPtvsNDMPt(nullptr),
fHistoMotherInvMassSubNDM(nullptr),
fHistoBackInvMassPtSubNDM(nullptr),
fHistoMotherLikeSignBackInvMassSubNDMPt(nullptr),
fHistoMotherInvMassFixedPzNDM(nullptr),
fHistoBackInvMassPtFixedPzNDM(nullptr),
fHistoMotherLikeSignBackInvMassFixedPzNDMPt(nullptr),
fHistoMCAllGammaPt(nullptr),
fHistoMCConvGammaPt(nullptr),
fHistoMCAllMesonPt(nullptr),
fHistoMCAllMesonEta(nullptr),
fHistoMCAllMesonPhi(nullptr),
fHistoMCMesonFromNeutralMesonPt(nullptr),
fHistoMCMesonFromNeutralMesonEta(nullptr),
fHistoMCMesonFromNeutralMesonPhi(nullptr),
fHistoMCAllPosPionsPt(nullptr),
fHistoMCAllPosPionsEta(nullptr),
fHistoMCAllPosPionsPhi(nullptr),
fHistoMCAllNegPionsPt(nullptr),
fHistoMCAllNegPionsEta(nullptr),
fHistoMCAllNegPionsPhi(nullptr),
fHistoMCGammaFromNeutralMesonPt(nullptr),
fHistoMCPosPionsFromNeutralMesonPt(nullptr),
fHistoMCPosPionsFromNeutralMesonEta(nullptr),
fHistoMCPosPionsFromNeutralMesonPhi(nullptr),
fHistoMCNegPionsFromNeutralMesonPt(nullptr),
fHistoMCNegPionsFromNeutralMesonEta(nullptr),
fHistoMCNegPionsFromNeutralMesonPhi(nullptr),
fHistoMCHNMPiPlPiMiNDMPt(nullptr),
fHistoMCHNMPiPlPiMiNDMEta(nullptr),
fHistoMCHNMPiPlPiMiNDMPhi(nullptr),
fHistoMCHNMPiPlPiMiNDMInAccPt(nullptr),
fHistoMCHNMInAccVsNDMPt(nullptr),
fHistoMCHeavyAllPt(nullptr),
fHistoMCHeavyAllEta(nullptr),
fHistoMCHeavyAllPhi(nullptr),
fHistoMCHeavyChannelPt(nullptr),
fHistoMCHeavyChannelEta(nullptr),
fHistoMCHeavyChannelPhi(nullptr),
fHistMCChannelNDMFromHeavyPt(nullptr),
fHistMCChannelNDMFromHeavyEta(nullptr),
fHistMCChannelNDMFromHeavyPhi(nullptr),
fHistMCChannelPiPlusFromHeavyPt(nullptr),
fHistMCChannelPiPlusFromHeavyEta(nullptr),
fHistMCChannelPiPlusFromHeavyPhi(nullptr),
fHistMCChannelPiMinusFromHeavyPt(nullptr),
fHistMCChannelPiMinusFromHeavyEta(nullptr),
fHistMCChannelPiPMinusFromHeavyPhi(nullptr),
fHistMCChannelNDMPtHeavyPt(nullptr),
fHistMCChannelPiPlusPtHeavyPt(nullptr),
fHistMCChannelPiMinusPtHeavyPt(nullptr),
fHistoMCHeavyReconstructiblePt(nullptr),
fHistoMCHeavyReconstructibleEta(nullptr),
fHistoMCHeavyReconstructiblePhi(nullptr),
fHistMCReconstructibleNDMFromHeavyPt(nullptr),
fHistMCReconstructibleNDMFromHeavyEta(nullptr),
fHistMCReconstructibleNDMFromHeavyPhi(nullptr),
fHistMCReconstructiblePiPlusFromHeavyPt(nullptr),
fHistMCReconstructiblePiPlusFromHeavyEta(nullptr),
fHistMCReconstructiblePiPlusFromHeavyPhi(nullptr),
fHistMCReconstructiblePiMinusFromHeavyPt(nullptr),
fHistMCReconstructiblePiMinusFromHeavyEta(nullptr),
fHistMCReconstructiblePiPMinusFromHeavyPhi(nullptr),
fHistMCReconstructibleNDMPtHeavyPt(nullptr),
fHistMCReconstructiblePiPlusPtHeavyPt(nullptr),
fHistMCReconstructiblePiMinusPtHeavyPt(nullptr),
fHistoTrueMesonFlags(nullptr),
fHistoTrueMotherPiPlPiMiNDMInvMassPt(nullptr),
fHistoTrueMotherPiPlPiMiNDMInvMassPtSubNDM(nullptr),
fHistoTrueMotherPiPlPiMiNDMInvMassPtFixedPzNDM(nullptr),
fHistoTrueMotherPiPlPiMiNDMInvMassPt_FromDifferent(nullptr),
fHistoTrueMotherPiPlPiMiNDMInvMassPt_FromEtaOmega(nullptr),
fHistoTrueMotherPiPlPiMiNDMInvMassPt_FromRho(nullptr),
fHistoTrueMotherPiPlPiMiNDMInvMassPt_FromK0s(nullptr),
fHistoTrueMotherPiPlPiMiNDMInvMassPt_FromK0l(nullptr),
fHistoTrueMotherPiPlPiMiNDMInvMassPt_FromEtaPrime(nullptr),
fHistoTrueMotherPiPlPiMiNDMInvMassPt_FromOther(nullptr),
fHistoTrueMotherPiPlPiMiNDMDalitzPlotPosFixedPzNDM(nullptr),
fHistoTrueMotherPiPlPiMiNDMDalitzPlotNegFixedPzNDM(nullptr),
fHistoTrueMotherPiPlPiMiNDMDalitzPlotPosSubNDM(nullptr),
fHistoTrueMotherPiPlPiMiNDMDalitzPlotNegSubNDM(nullptr),
fHistoTrueMotherPiPlPiMiNDMDalitzPlotPosFixedPzNDM_LowPt(nullptr),
fHistoTrueMotherPiPlPiMiNDMDalitzPlotNegFixedPzNDM_LowPt(nullptr),
fHistoTrueMotherPiPlPiMiNDMDalitzPlotPosSubNDM_LowPt(nullptr),
fHistoTrueMotherPiPlPiMiNDMDalitzPlotNegSubNDM_LowPt(nullptr),
fHistoTrueMotherPiPlPiMiNDMDalitzPlotPosFixedPzNDM_MidPt(nullptr),
fHistoTrueMotherPiPlPiMiNDMDalitzPlotNegFixedPzNDM_MidPt(nullptr),
fHistoTrueMotherPiPlPiMiNDMDalitzPlotPosSubNDM_MidPt(nullptr),
fHistoTrueMotherPiPlPiMiNDMDalitzPlotNegSubNDM_MidPt(nullptr),
fHistoTrueMotherPiPlPiMiNDMDalitzPlotPosFixedPzNDM_HighPt(nullptr),
fHistoTrueMotherPiPlPiMiNDMDalitzPlotNegFixedPzNDM_HighPt(nullptr),
fHistoTrueMotherPiPlPiMiNDMDalitzPlotPosSubNDM_HighPt(nullptr),
fHistoTrueMotherPiPlPiMiNDMDalitzPlotNegSubNDM_HighPt(nullptr),
fHistoTrueMotherGammaGammaInvMassPt(nullptr),
fHistoTrueMotherGammaGammaFromHNMInvMassPt(nullptr),
fHistoTrueConvGammaPt(nullptr),
fHistoTrueConvGammaFromNeutralMesonPt(nullptr),
fHistoTrueClusterGammaPt(nullptr),
fHistoTrueClusterGammaFromNeutralMesonPt(nullptr),
fHistoTruePosPionPt(nullptr),
fHistoTruePosPionFromNeutralMesonPt(nullptr),
fHistoTrueNegPionPt(nullptr),
fHistoTrueNegPionFromNeutralMesonPt(nullptr),
fHistoTruePionPionInvMassPt(nullptr),
fHistoTruePionPionFromSameMotherInvMassPt(nullptr),
fHistoTruePionPionFromHNMInvMassPt(nullptr),
fHistoTruePiPlPiMiSameMotherFromEtaInvMassPt(nullptr),
fHistoTruePiPlPiMiSameMotherFromOmegaInvMassPt(nullptr),
fHistoTruePiPlPiMiSameMotherFromRhoInvMassPt(nullptr),
fHistoTruePiPlPiMiSameMotherFromEtaPrimeInvMassPt(nullptr),
fHistoTruePiPlPiMiSameMotherFromK0sInvMassPt(nullptr),
fHistoTruePiPlPiMiSameMotherFromK0lInvMassPt(nullptr),
fHistoTruePiPlPiMiSameMotherFromOtherlInvMassPt(nullptr),
fHistoTruePiMiPiZeroSameMotherFromEtaInvMassPt(nullptr),
fHistoTruePiMiPiZeroSameMotherFromOmegaInvMassPt(nullptr),
fHistoTruePiMiPiZeroSameMotherFromRhoInvMassPt(nullptr),
fHistoTruePiMiPiZeroSameMotherFromK0lInvMassPt(nullptr),
fHistoTruePiMiPiZeroSameMotherFromOtherlInvMassPt(nullptr),
fHistoTruePiPlPiZeroSameMotherFromEtaInvMassPt(nullptr),
fHistoTruePiPlPiZeroSameMotherFromOmegaInvMassPt(nullptr),
fHistoTruePiPlPiZeroSameMotherFromRhoInvMassPt(nullptr),
fHistoTruePiPlPiZeroSameMotherFromK0lInvMassPt(nullptr),
fHistoTruePiPlPiZeroSameMotherFromOtherInvMassPt(nullptr),
fHistoTruePiPlPiMiNDMPureCombinatoricalInvMassPt(nullptr),
fHistoTruePiPlPiMiNDMCombinatoricalInvMassPt(nullptr),
fHistoTruePiPlPiMiNDMContaminationInvMassPt(nullptr),
fHistoTruePiPlPiMiNDMContamination_Pi0_InvMassPt(nullptr),
fHistoTruePiPlPiMiNDMContamination_PiPl_InvMassPt(nullptr),
fHistoTruePiPlPiMiNDMContamination_PiMi_InvMassPt(nullptr),
fHistoTruePiPlPiMiNDMContamination_Crosscheck_InvMassPt(nullptr),
fHistoTruePiPlPiMiNDMContamination_multipel_InvMassPt(nullptr),
fHistoDoubleCountTruePi0InvMassPt(nullptr),
fHistoDoubleCountTrueHNMInvMassPt(nullptr),
fHistoDoubleCountTrueConvGammaRPt(nullptr),
fVectorDoubleCountTruePi0s(0),
fVectorDoubleCountTrueHNMs(0),
fVectorDoubleCountTrueConvGammas(0),
fHistoNEvents(nullptr),
fHistoNEventsWOWeight(nullptr),
fProfileJetJetXSection(nullptr),
fHistoJetJetNTrials(nullptr),
fHistoNGoodESDTracks(nullptr),
fProfileEtaShift(nullptr),
fHistoSPDClusterTrackletBackground(nullptr),
fHistovParticleChi2PerNDF(nullptr),
fHistovParticleChi2PerNDFBothConstrained(nullptr),
fHistovParticleChi2PerNDFOneConstrained(nullptr),
fHistovParticledS(nullptr),
fHistovParticledSBothConstrained(nullptr),
fHistovParticledSOneConstrained(nullptr),
fHistoTruevParticleChi2PerNDF(nullptr),
fHistoTruevParticleFromSameMotherChi2PerNDF(nullptr),
fHistoTruevParticleFromHNMChi2PerNDF(nullptr),
fHistoTruevParticledS(nullptr),
fHistoTruevParticleFromSameMotherdS(nullptr),
fHistoTruevParticleFromHNMdS(nullptr),
fRandom(0),
fnCuts(0),
fiCut(0),
fNumberOfESDTracks(0),
fMoveParticleAccordingToVertex(kFALSE),
fIsHeavyIon(0),
fDoMesonAnalysis(kTRUE),
fDoMesonQA(0),
fIsFromMBHeader(kTRUE),
fIsFromDesiredHeader(kTRUE),
fIsOverlappingWithOtherHeader(kFALSE),
fAllowOverlapHeaders(kTRUE),
fIsMC(kFALSE),
fSelectedHeavyNeutralMeson(kFALSE),
fDoLightOutput(kFALSE),
fNDMRecoMode(0),
fTolerance(-1),
fWeightJetJetMC(1.),
fTrackMatcherRunningMode(0),
fMCEventPos(),
fMCEventNeg(),
fESDArrayPos(),
fESDArrayNeg()
{
}
//-----------------------------------------------------------------------------------------------
AliAnalysisTaskNeutralMesonToPiPlPiMiNeutralMeson::AliAnalysisTaskNeutralMesonToPiPlPiMiNeutralMeson( const char* name ):
AliAnalysisTaskSE(name),
fV0Reader(nullptr),
fV0ReaderName("V0ReaderV1"),
fPionSelector(NULL),
fPionSelectorName("PionSelector"),
fBGHandlerPiPl(NULL),
fBGHandlerPiMi(NULL),
fInputEvent(NULL),
fMCEvent(NULL),
fCutFolder(NULL),
fESDList(NULL),
fTrueList(NULL),
fTrueTreeList(NULL),
fMCList(NULL),
fOutputContainer(0),
fReaderGammas(nullptr),
fSelectorNegPionIndex(0),
fSelectorPosPionIndex(0),
fGoodConvGammas(nullptr),
fClusterCandidates(nullptr),
fNeutralDecayParticleCandidates(nullptr),
fNeutralDecayParticleSidebandCandidates(nullptr),
fPosPionCandidates(nullptr),
fNegPionCandidates(nullptr),
fEventCutArray(nullptr),
fGammaCutArray(nullptr),
fClusterCutArray(nullptr),
fPionCutArray(nullptr),
fNeutralDecayMesonCutArray(nullptr),
fMesonCutArray(nullptr),
fEventCuts(nullptr),
fConversionCuts(nullptr),
fClusterCuts(nullptr),
fOutlierJetReader(nullptr),
fTreePiPiSameMother(nullptr),
fTreePiPiPiSameMother(nullptr),
fTreeEventInfoHNM(nullptr),
fCasePiPi(-1),
fSamePiPiMotherID(-1),
fSamePiPiMotherInvMass(-1),
fSamePiPiMotherPt(-1),
fSamePiPiPiMotherID(-1),
fSamePiPiPiMotherInvMass(-1),
fSamePiPiPiMotherPt(-1),
fV0MultiplicityHNMEvent(-1),
fTrackMultiplicityHNMEvent(-1),
fZVertexHNMEvent(-1),
fPtHNM(-1),
fPDGMassNDM(-1),
fNDMMinPtPossible(0.),
fPDGMassChargedPion(-1),
fPDGCodeNDM(-1),
fPDGCodeAnalyzedMeson(-1),
enableDalitzAllPt(kFALSE),
enableDalitzLowPt(kFALSE),
enableDalitzMidPt(kFALSE),
enableDalitzHighPt(kFALSE),
HistoDalitzPtRangeMin_LowPt(0.),
HistoDalitzPtRangeMax_LowPt(0.),
HistoDalitzPtRangeMin_MidPt(0.),
HistoDalitzPtRangeMax_MidPt(0.),
HistoDalitzPtRangeMin_HighPt(0.),
HistoDalitzPtRangeMax_HighPt(0.),
fHistoConvGammaPt(nullptr),
fHistoConvGammaEta(nullptr),
fHistoClusterGammaPt(nullptr),
fHistoClusterGammaEta(nullptr),
fHistoClusterGammaE(nullptr),
fHistoNegPionPt(nullptr),
fHistoPosPionPt(nullptr),
fHistoNegPionPhi(nullptr),
fHistoPosPionPhi(nullptr),
fHistoNegPionEta(nullptr),
fHistoPosPionEta(nullptr),
fHistoNegPionClsTPC(nullptr),
fHistoPosPionClsTPC(nullptr),
fHistoPionDCAxy(nullptr),
fHistoPionDCAz(nullptr),
fHistoPionTPCdEdxNSigma(nullptr),
fHistoPionTPCdEdx(nullptr),
fHistoPionPionInvMassPt(nullptr),
fHistoGammaGammaInvMassPt(nullptr),
fHistoGammaGammaInvMassPtBeforeCuts(nullptr),
fHistoMotherInvMassPt(nullptr),
fHistoMotherInvMassPtRejectedKinematic(nullptr),
fHistoDalitzPlotPosFixedPzNDM(nullptr),
fHistoDalitzPlotNegFixedPzNDM(nullptr),
fHistoDalitzPlotPosSubNDM(nullptr),
fHistoDalitzPlotNegSubNDM(nullptr),
fHistoDalitzPlotPosFixedPzNDM_LowPt(nullptr),
fHistoDalitzPlotNegFixedPzNDM_LowPt(nullptr),
fHistoDalitzPlotPosSubNDM_LowPt(nullptr),
fHistoDalitzPlotNegSubNDM_LowPt(nullptr),
fHistoDalitzPlotPosFixedPzNDM_MidPt(nullptr),
fHistoDalitzPlotNegFixedPzNDM_MidPt(nullptr),
fHistoDalitzPlotPosSubNDM_MidPt(nullptr),
fHistoDalitzPlotNegSubNDM_MidPt(nullptr),
fHistoDalitzPlotPosFixedPzNDM_HighPt(nullptr),
fHistoDalitzPlotNegFixedPzNDM_HighPt(nullptr),
fHistoDalitzPlotPosSubNDM_HighPt(nullptr),
fHistoDalitzPlotNegSubNDM_HighPt(nullptr),
fHistoBackInvMassPt(nullptr),
fHistoMotherLikeSignBackInvMassPt(nullptr),
fHistoAngleHNMesonPiPlPiMi(nullptr),
fHistoAngleHNMesonNDM(nullptr),
fHistoAngleHNMesonPiPl(nullptr),
fHistoAngleHNMesonPiMi(nullptr),
fHistoAnglePiPlPiMi(nullptr),
fHistoAngleNDMPiMi(nullptr),
fHistoAnglePiPlNDM(nullptr),
fHistoAngleSum(nullptr),
fHistoTrueAngleSum(nullptr),
fHistoTrueHNMesonPtvsNDMPt(nullptr),
fHistoMotherInvMassSubNDM(nullptr),
fHistoBackInvMassPtSubNDM(nullptr),
fHistoMotherLikeSignBackInvMassSubNDMPt(nullptr),
fHistoMotherInvMassFixedPzNDM(nullptr),
fHistoBackInvMassPtFixedPzNDM(nullptr),
fHistoMotherLikeSignBackInvMassFixedPzNDMPt(nullptr),
fHistoMCAllGammaPt(nullptr),
fHistoMCConvGammaPt(nullptr),
fHistoMCAllMesonPt(nullptr),
fHistoMCAllMesonEta(nullptr),
fHistoMCAllMesonPhi(nullptr),
fHistoMCMesonFromNeutralMesonPt(nullptr),
fHistoMCMesonFromNeutralMesonEta(nullptr),
fHistoMCMesonFromNeutralMesonPhi(nullptr),
fHistoMCAllPosPionsPt(nullptr),
fHistoMCAllPosPionsEta(nullptr),
fHistoMCAllPosPionsPhi(nullptr),
fHistoMCAllNegPionsPt(nullptr),
fHistoMCAllNegPionsEta(nullptr),
fHistoMCAllNegPionsPhi(nullptr),
fHistoMCGammaFromNeutralMesonPt(nullptr),
fHistoMCPosPionsFromNeutralMesonPt(nullptr),
fHistoMCPosPionsFromNeutralMesonEta(nullptr),
fHistoMCPosPionsFromNeutralMesonPhi(nullptr),
fHistoMCNegPionsFromNeutralMesonPt(nullptr),
fHistoMCNegPionsFromNeutralMesonEta(nullptr),
fHistoMCNegPionsFromNeutralMesonPhi(nullptr),
fHistoMCHNMPiPlPiMiNDMPt(nullptr),
fHistoMCHNMPiPlPiMiNDMEta(nullptr),
fHistoMCHNMPiPlPiMiNDMPhi(nullptr),
fHistoMCHNMPiPlPiMiNDMInAccPt(nullptr),
fHistoMCHNMInAccVsNDMPt(nullptr),
fHistoMCHeavyAllPt(nullptr),
fHistoMCHeavyAllEta(nullptr),
fHistoMCHeavyAllPhi(nullptr),
fHistoMCHeavyChannelPt(nullptr),
fHistoMCHeavyChannelEta(nullptr),
fHistoMCHeavyChannelPhi(nullptr),
fHistMCChannelNDMFromHeavyPt(nullptr),
fHistMCChannelNDMFromHeavyEta(nullptr),
fHistMCChannelNDMFromHeavyPhi(nullptr),
fHistMCChannelPiPlusFromHeavyPt(nullptr),
fHistMCChannelPiPlusFromHeavyEta(nullptr),
fHistMCChannelPiPlusFromHeavyPhi(nullptr),
fHistMCChannelPiMinusFromHeavyPt(nullptr),
fHistMCChannelPiMinusFromHeavyEta(nullptr),
fHistMCChannelPiPMinusFromHeavyPhi(nullptr),
fHistMCChannelNDMPtHeavyPt(nullptr),
fHistMCChannelPiPlusPtHeavyPt(nullptr),
fHistMCChannelPiMinusPtHeavyPt(nullptr),
fHistoMCHeavyReconstructiblePt(nullptr),
fHistoMCHeavyReconstructibleEta(nullptr),
fHistoMCHeavyReconstructiblePhi(nullptr),
fHistMCReconstructibleNDMFromHeavyPt(nullptr),
fHistMCReconstructibleNDMFromHeavyEta(nullptr),
fHistMCReconstructibleNDMFromHeavyPhi(nullptr),
fHistMCReconstructiblePiPlusFromHeavyPt(nullptr),
fHistMCReconstructiblePiPlusFromHeavyEta(nullptr),
fHistMCReconstructiblePiPlusFromHeavyPhi(nullptr),
fHistMCReconstructiblePiMinusFromHeavyPt(nullptr),
fHistMCReconstructiblePiMinusFromHeavyEta(nullptr),
fHistMCReconstructiblePiPMinusFromHeavyPhi(nullptr),
fHistMCReconstructibleNDMPtHeavyPt(nullptr),
fHistMCReconstructiblePiPlusPtHeavyPt(nullptr),
fHistMCReconstructiblePiMinusPtHeavyPt(nullptr),
fHistoTrueMesonFlags(nullptr),
fHistoTrueMotherPiPlPiMiNDMInvMassPt(nullptr),
fHistoTrueMotherPiPlPiMiNDMInvMassPtSubNDM(nullptr),
fHistoTrueMotherPiPlPiMiNDMInvMassPtFixedPzNDM(nullptr),
fHistoTrueMotherPiPlPiMiNDMInvMassPt_FromDifferent(nullptr),
fHistoTrueMotherPiPlPiMiNDMInvMassPt_FromEtaOmega(nullptr),
fHistoTrueMotherPiPlPiMiNDMInvMassPt_FromRho(nullptr),
fHistoTrueMotherPiPlPiMiNDMInvMassPt_FromK0s(nullptr),
fHistoTrueMotherPiPlPiMiNDMInvMassPt_FromK0l(nullptr),
fHistoTrueMotherPiPlPiMiNDMInvMassPt_FromEtaPrime(nullptr),
fHistoTrueMotherPiPlPiMiNDMInvMassPt_FromOther(nullptr),
fHistoTrueMotherPiPlPiMiNDMDalitzPlotPosFixedPzNDM(nullptr),
fHistoTrueMotherPiPlPiMiNDMDalitzPlotNegFixedPzNDM(nullptr),
fHistoTrueMotherPiPlPiMiNDMDalitzPlotPosSubNDM(nullptr),
fHistoTrueMotherPiPlPiMiNDMDalitzPlotNegSubNDM(nullptr),
fHistoTrueMotherPiPlPiMiNDMDalitzPlotPosFixedPzNDM_LowPt(nullptr),
fHistoTrueMotherPiPlPiMiNDMDalitzPlotNegFixedPzNDM_LowPt(nullptr),
fHistoTrueMotherPiPlPiMiNDMDalitzPlotPosSubNDM_LowPt(nullptr),
fHistoTrueMotherPiPlPiMiNDMDalitzPlotNegSubNDM_LowPt(nullptr),
fHistoTrueMotherPiPlPiMiNDMDalitzPlotPosFixedPzNDM_MidPt(nullptr),
fHistoTrueMotherPiPlPiMiNDMDalitzPlotNegFixedPzNDM_MidPt(nullptr),
fHistoTrueMotherPiPlPiMiNDMDalitzPlotPosSubNDM_MidPt(nullptr),
fHistoTrueMotherPiPlPiMiNDMDalitzPlotNegSubNDM_MidPt(nullptr),
fHistoTrueMotherPiPlPiMiNDMDalitzPlotPosFixedPzNDM_HighPt(nullptr),
fHistoTrueMotherPiPlPiMiNDMDalitzPlotNegFixedPzNDM_HighPt(nullptr),
fHistoTrueMotherPiPlPiMiNDMDalitzPlotPosSubNDM_HighPt(nullptr),
fHistoTrueMotherPiPlPiMiNDMDalitzPlotNegSubNDM_HighPt(nullptr),
fHistoTrueMotherGammaGammaInvMassPt(nullptr),
fHistoTrueMotherGammaGammaFromHNMInvMassPt(nullptr),
fHistoTrueConvGammaPt(nullptr),
fHistoTrueConvGammaFromNeutralMesonPt(nullptr),
fHistoTrueClusterGammaPt(nullptr),
fHistoTrueClusterGammaFromNeutralMesonPt(nullptr),
fHistoTruePosPionPt(nullptr),
fHistoTruePosPionFromNeutralMesonPt(nullptr),
fHistoTrueNegPionPt(nullptr),
fHistoTrueNegPionFromNeutralMesonPt(nullptr),
fHistoTruePionPionInvMassPt(nullptr),
fHistoTruePionPionFromSameMotherInvMassPt(nullptr),
fHistoTruePionPionFromHNMInvMassPt(nullptr),
fHistoTruePiPlPiMiSameMotherFromEtaInvMassPt(nullptr),
fHistoTruePiPlPiMiSameMotherFromOmegaInvMassPt(nullptr),
fHistoTruePiPlPiMiSameMotherFromRhoInvMassPt(nullptr),
fHistoTruePiPlPiMiSameMotherFromEtaPrimeInvMassPt(nullptr),
fHistoTruePiPlPiMiSameMotherFromK0sInvMassPt(nullptr),
fHistoTruePiPlPiMiSameMotherFromK0lInvMassPt(nullptr),
fHistoTruePiPlPiMiSameMotherFromOtherlInvMassPt(nullptr),
fHistoTruePiMiPiZeroSameMotherFromEtaInvMassPt(nullptr),
fHistoTruePiMiPiZeroSameMotherFromOmegaInvMassPt(nullptr),
fHistoTruePiMiPiZeroSameMotherFromRhoInvMassPt(nullptr),
fHistoTruePiMiPiZeroSameMotherFromK0lInvMassPt(nullptr),
fHistoTruePiMiPiZeroSameMotherFromOtherlInvMassPt(nullptr),
fHistoTruePiPlPiZeroSameMotherFromEtaInvMassPt(nullptr),
fHistoTruePiPlPiZeroSameMotherFromOmegaInvMassPt(nullptr),
fHistoTruePiPlPiZeroSameMotherFromRhoInvMassPt(nullptr),
fHistoTruePiPlPiZeroSameMotherFromK0lInvMassPt(nullptr),
fHistoTruePiPlPiZeroSameMotherFromOtherInvMassPt(nullptr),
fHistoTruePiPlPiMiNDMPureCombinatoricalInvMassPt(nullptr),
fHistoTruePiPlPiMiNDMCombinatoricalInvMassPt(nullptr),
fHistoTruePiPlPiMiNDMContaminationInvMassPt(nullptr),
fHistoTruePiPlPiMiNDMContamination_Pi0_InvMassPt(nullptr),
fHistoTruePiPlPiMiNDMContamination_PiPl_InvMassPt(nullptr),
fHistoTruePiPlPiMiNDMContamination_PiMi_InvMassPt(nullptr),
fHistoTruePiPlPiMiNDMContamination_Crosscheck_InvMassPt(nullptr),
fHistoTruePiPlPiMiNDMContamination_multipel_InvMassPt(nullptr),
fHistoDoubleCountTruePi0InvMassPt(nullptr),
fHistoDoubleCountTrueHNMInvMassPt(nullptr),
fHistoDoubleCountTrueConvGammaRPt(nullptr),
fVectorDoubleCountTruePi0s(0),
fVectorDoubleCountTrueHNMs(0),
fVectorDoubleCountTrueConvGammas(0),
fHistoNEvents(nullptr),
fHistoNEventsWOWeight(nullptr),
fProfileJetJetXSection(nullptr),
fHistoJetJetNTrials(nullptr),
fHistoNGoodESDTracks(nullptr),
fProfileEtaShift(nullptr),
fHistoSPDClusterTrackletBackground(nullptr),
fHistovParticleChi2PerNDF(nullptr),
fHistovParticleChi2PerNDFBothConstrained(nullptr),
fHistovParticleChi2PerNDFOneConstrained(nullptr),
fHistovParticledS(nullptr),
fHistovParticledSBothConstrained(nullptr),
fHistovParticledSOneConstrained(nullptr),
fHistoTruevParticleChi2PerNDF(nullptr),
fHistoTruevParticleFromSameMotherChi2PerNDF(nullptr),
fHistoTruevParticleFromHNMChi2PerNDF(nullptr),
fHistoTruevParticledS(nullptr),
fHistoTruevParticleFromSameMotherdS(nullptr),
fHistoTruevParticleFromHNMdS(nullptr),
fRandom(0),
fnCuts(0),
fiCut(0),
fNumberOfESDTracks(0),
fMoveParticleAccordingToVertex(kFALSE),
fIsHeavyIon(0),
fDoMesonAnalysis(kTRUE),
fDoMesonQA(0),
fIsFromMBHeader(kTRUE),
fIsFromDesiredHeader(kTRUE),
fIsOverlappingWithOtherHeader(kFALSE),
fAllowOverlapHeaders(kTRUE),
fIsMC(kFALSE),
fSelectedHeavyNeutralMeson(kFALSE),
fDoLightOutput(kFALSE),
fNDMRecoMode(0),
fTolerance(-1),
fWeightJetJetMC(1.),
fTrackMatcherRunningMode(0),
fMCEventPos(),
fMCEventNeg(),
fESDArrayPos(),
fESDArrayNeg()
{
DefineOutput(1, TList::Class());
}
//-----------------------------------------------------------------------------------------------
AliAnalysisTaskNeutralMesonToPiPlPiMiNeutralMeson::~AliAnalysisTaskNeutralMesonToPiPlPiMiNeutralMeson()
{
//
// virtual destructor
//
cout<<"Destructor"<<endl;
if(fGoodConvGammas){
delete fGoodConvGammas;
}
if(fClusterCandidates){
delete fClusterCandidates;
}
if(fNeutralDecayParticleCandidates){
delete fNeutralDecayParticleCandidates;
}
if(fNeutralDecayParticleSidebandCandidates){
delete fNeutralDecayParticleSidebandCandidates;
}
if(fPosPionCandidates){
delete fPosPionCandidates;
}
if(fNegPionCandidates){
delete fNegPionCandidates;
}
if(fBGHandlerPiPl){
for(int icut = 0; icut < fnCuts; icut++)
delete fBGHandlerPiPl[icut];
delete[] fBGHandlerPiPl;
}
if(fBGHandlerPiMi){
for(int icut = 0; icut < fnCuts; icut++)
delete fBGHandlerPiMi[icut];
delete[] fBGHandlerPiMi;
}
}
//___________________________________________________________
void AliAnalysisTaskNeutralMesonToPiPlPiMiNeutralMeson::InitBack(){
fBGHandlerPiPl = new AliGammaConversionAODBGHandler*[fnCuts];
fBGHandlerPiMi = new AliGammaConversionAODBGHandler*[fnCuts];
for(Int_t iCut = 0; iCut<fnCuts;iCut++){
TString cutstringEvent = ((AliConvEventCuts*)fEventCutArray->At(iCut))->GetCutNumber();
TString cutstringPion = ((AliPrimaryPionCuts*)fPionCutArray->At(iCut))->GetCutNumber();
TString cutstringConvGamma = "";
if (fNDMRecoMode < 2) cutstringConvGamma = ((AliConversionPhotonCuts*)fGammaCutArray->At(iCut))->GetCutNumber();
TString cutstringCaloGamma = "";
if (fNDMRecoMode > 0) cutstringCaloGamma = ((AliCaloPhotonCuts*)fClusterCutArray->At(iCut))->GetCutNumber();
TString cutstringNeutralPion= ((AliConversionMesonCuts*)fNeutralDecayMesonCutArray->At(iCut))->GetCutNumber();
TString cutstringMeson = ((AliConversionMesonCuts*)fMesonCutArray->At(iCut))->GetCutNumber();
TString fullCutString = "";
if (fNDMRecoMode == 0) fullCutString = Form("%i_%s_%s_%s_%s_%s",fNDMRecoMode,cutstringEvent.Data(),cutstringConvGamma.Data(),cutstringNeutralPion.Data(), cutstringPion.Data(),cutstringMeson.Data());
else if (fNDMRecoMode == 1) fullCutString = Form("%i_%s_%s_%s_%s_%s_%s",fNDMRecoMode,cutstringEvent.Data(),cutstringConvGamma.Data(),cutstringCaloGamma.Data(),cutstringNeutralPion.Data(), cutstringPion.Data(),cutstringMeson.Data());
else if (fNDMRecoMode == 2) fullCutString = Form("%i_%s_%s_%s_%s_%s",fNDMRecoMode,cutstringEvent.Data(),cutstringCaloGamma.Data(),cutstringNeutralPion.Data(), cutstringPion.Data(),cutstringMeson.Data());
Int_t collisionSystem = atoi((TString)(((AliConvEventCuts*)fEventCutArray->At(iCut))->GetCutNumber())(0,1));
Int_t centMin = atoi((TString)(((AliConvEventCuts*)fEventCutArray->At(iCut))->GetCutNumber())(1,1));
Int_t centMax = atoi((TString)(((AliConvEventCuts*)fEventCutArray->At(iCut))->GetCutNumber())(2,1));
if(collisionSystem == 1 || collisionSystem == 2 ||
collisionSystem == 5 || collisionSystem == 8 ||
collisionSystem == 9){
centMin = centMin*10;
centMax = centMax*10;
}
else if(collisionSystem == 3 || collisionSystem == 6){
centMin = centMin*5;
centMax = centMax*5;
}
else if(collisionSystem == 4 || collisionSystem == 7){
centMin = ((centMin*5)+45);
centMax = ((centMax*5)+45);
}
fBGHandlerPiPl[iCut] = new AliGammaConversionAODBGHandler( collisionSystem,centMin,centMax,
((AliConversionMesonCuts*)fMesonCutArray->At(fiCut))->GetNumberOfBGEvents(),
((AliConversionMesonCuts*)fMesonCutArray->At(fiCut))->UseTrackMultiplicity(),
4,8,5);
fBGHandlerPiMi[iCut] = new AliGammaConversionAODBGHandler( collisionSystem,centMin,centMax,
((AliConversionMesonCuts*)fMesonCutArray->At(fiCut))->GetNumberOfBGEvents(),
((AliConversionMesonCuts*)fMesonCutArray->At(fiCut))->UseTrackMultiplicity(),
4,8,5);
}
}
//______________________________________________________________________
void AliAnalysisTaskNeutralMesonToPiPlPiMiNeutralMeson::UserCreateOutputObjects()
{
//
// Create ouput objects
//
if(((AliConvEventCuts*)fEventCutArray->At(0))->GetUseJetFinderForOutliers()){
fOutlierJetReader=(AliAnalysisTaskJetOutlierRemoval*)AliAnalysisManager::GetAnalysisManager()->GetTask("AliAnalysisTaskJetOutlierRemoval");
if(!fOutlierJetReader){AliFatal("Error: No AliAnalysisTaskJetOutlierRemoval");} // GetV0Reader
else{printf("Found AliAnalysisTaskJetOutlierRemoval used for outlier removal!\n");}
}
// Set pT and mass ranges
Double_t HistoNMassBins = 600;
Double_t HistoMassRange[2] = {0.4,1.0};
Double_t HistoNMassBinsSub = 600;
Double_t HistoMassRangeSub[2] = {0.4,1.0};
Double_t HistoNPtBins = 800;
Double_t HistoPtRange[2] = {0.,80.};
Double_t HistoNMassBinsDecayMeson = 450;
Double_t HistoMassRangeNDM[2] = {0.0,0.45};
Double_t HistoNMassBinsPiPlusPiMinus = 250;
Double_t HistoMassRangePiPlusPiMinus[2] = {0.0,2.0};
TString NameNeutralMesonAnalyzed = "not set";
TString NameNeutralMesonAnalyzedLatex = "not set";
TString NameNDM = "not set";
TString NameNDMLatex = "not set";
Double_t HistoMassRangeDalitzMin = 0.0;
Double_t HistoMassRangeDalitz = 3.0;
//fNDMRecoMode: 0=PCM-PCM, 1=PCM-Calo, 2=Calo-Calo
//fClusterCutArray->At(iCut))->GetClusterType(): 1=EMCAL, 2=PHOS, 3=DCAL, 4=EMCAL+DCAL, 0=All
if (fNDMRecoMode == 0){ //PCM-PCM
HistoDalitzPtRangeMin_LowPt = 1.6;
HistoDalitzPtRangeMax_LowPt = 2.0;
HistoDalitzPtRangeMin_MidPt = 5.0;
HistoDalitzPtRangeMax_MidPt = 6.0;
HistoDalitzPtRangeMin_HighPt = 10.0;
HistoDalitzPtRangeMax_HighPt = 12.0;
} else if (fNDMRecoMode == 1){ //PCM-Calo
if (((AliCaloPhotonCuts*)fClusterCutArray->At(fiCut))->GetClusterType()==2){ //PCM-PHOS
HistoDalitzPtRangeMin_LowPt = 2.5;
HistoDalitzPtRangeMax_LowPt = 3.0;
HistoDalitzPtRangeMin_MidPt = 5.0;
HistoDalitzPtRangeMax_MidPt = 6.0;
HistoDalitzPtRangeMin_HighPt = 10.0;
HistoDalitzPtRangeMax_HighPt = 12.0;
} else { //PCM-EMC
HistoDalitzPtRangeMin_LowPt = 2.5;
HistoDalitzPtRangeMax_LowPt = 3.0;
HistoDalitzPtRangeMin_MidPt = 5.0;
HistoDalitzPtRangeMax_MidPt = 6.0;
HistoDalitzPtRangeMin_HighPt = 10.0;
HistoDalitzPtRangeMax_HighPt = 12.0;
}
} else { //Calo-Calo
if (((AliCaloPhotonCuts*)fClusterCutArray->At(fiCut))->GetClusterType()==2){ //PHOS-PHOS
HistoDalitzPtRangeMin_LowPt = 3.5;
HistoDalitzPtRangeMax_LowPt = 4.0;
HistoDalitzPtRangeMin_MidPt = 5.0;
HistoDalitzPtRangeMax_MidPt = 6.0;
HistoDalitzPtRangeMin_HighPt = 8.0;
HistoDalitzPtRangeMax_HighPt = 10.0;
} else { //EMC-EMC
HistoDalitzPtRangeMin_LowPt = 3.0;
HistoDalitzPtRangeMax_LowPt = 4.0;
HistoDalitzPtRangeMin_MidPt = 8.0;
HistoDalitzPtRangeMax_MidPt = 10.0;
HistoDalitzPtRangeMin_HighPt = 16.0;
HistoDalitzPtRangeMax_HighPt = 20.0;
}
}
//Enable Histograms
if( fDoMesonQA>0 ) {
//fNDMRecoMode: 0=PCM-PCM, 1=PCM-Calo, 2=Calo-Calo
//fClusterCutArray->At(iCut))->GetClusterType(): 1=EMCAL, 2=PHOS, 3=DCAL, 4=EMCAL+DCAL, 0=All
if (fNDMRecoMode == 0){ //PCM-PCM
enableDalitzLowPt=kTRUE;
enableDalitzMidPt=kTRUE;
enableDalitzHighPt=kTRUE;
} else if (fNDMRecoMode == 1){ //PCM-Calo
enableDalitzLowPt=kTRUE;
enableDalitzMidPt=kTRUE;
enableDalitzHighPt=kTRUE;
} else { //Calo-Calo
enableDalitzLowPt=kTRUE;
enableDalitzMidPt=kTRUE;
enableDalitzHighPt=kTRUE;
}
}
switch( fSelectedHeavyNeutralMeson ) {
case 0: // ETA MESON
HistoNMassBins = 400;
HistoMassRange[0] = 0.3;
HistoMassRange[1] = 0.7;
HistoNMassBinsSub = 400;
HistoMassRangeSub[0] = 0.3;
HistoMassRangeSub[1] = 0.7;
HistoNMassBinsDecayMeson = 450;
HistoMassRangeNDM[0] = 0.0;
HistoMassRangeNDM[1] = 0.45;
NameNeutralMesonAnalyzed = "Eta";
NameNeutralMesonAnalyzedLatex = "#eta";
NameNDM = "NeutralPion";
NameNDMLatex = "#pi^{0}";
fPDGMassNDM = 0.1349766; // hard coded PDG value to keep results reproducable later
fPDGCodeNDM = 111; // PDG pi0
fPDGMassChargedPion = 0.1395706; // hard coded PDG 2018 value to keep results reproducable later
fPDGCodeAnalyzedMeson = 221; // PDG omega
break;
case 1: // OMEGA MESON
HistoNMassBins = 500;
HistoMassRange[0] = 0.5;
HistoMassRange[1] = 1.0;
HistoNMassBinsSub = 500;
HistoMassRangeSub[0] = 0.5;
HistoMassRangeSub[1] = 1.0;
HistoNMassBinsDecayMeson = 450;
HistoMassRangeNDM[0] = 0.0;
HistoMassRangeNDM[1] = 0.45;
NameNeutralMesonAnalyzed = "Omega";
NameNeutralMesonAnalyzedLatex = "#omega";
NameNDM = "NeutralPion";
NameNDMLatex = "#pi^{0}";
fPDGMassNDM = 0.1349766; // hard coded PDG value to keep results reproducable later
fPDGCodeNDM = 111; // PDG pi0
fPDGMassChargedPion = 0.1395706; // hard coded PDG 2018 value to keep results reproducable later
fPDGCodeAnalyzedMeson = 223; // PDG omega
break;
case 2: // ETA PRIME MESON
HistoNMassBins = 600;
HistoMassRange[0] = 0.6;
HistoMassRange[1] = 1.2;
HistoNMassBinsSub = 600;
HistoMassRangeSub[0] = 0.6;
HistoMassRangeSub[1] = 1.2;
HistoNMassBinsDecayMeson = 450;
HistoMassRangeNDM[0] = 0.4;
HistoMassRangeNDM[1] = 0.85;
NameNeutralMesonAnalyzed = "EtaPrime";
NameNeutralMesonAnalyzedLatex = "#eta'";
NameNDM = "EtaMeson";
NameNDMLatex = "#eta";
fPDGMassNDM = 0.547862; // hard coded PDG value to keep results reproducable later
fPDGCodeNDM = 221; // PDG value eta
fPDGMassChargedPion = 0.1395706; // hard coded PDG 2018 value to keep results reproducable later
fPDGCodeAnalyzedMeson = 331; // PDG value eta prime
HistoMassRangeDalitz = 3.0;
break;
case 3: // D0 MESON
HistoNMassBins = 600;
HistoMassRange[0] = 1.4;
HistoMassRange[1] = 2.0;
HistoNMassBinsSub = 400; // MF: Background subtraction?
HistoMassRangeSub[0] = 1.6;
HistoMassRangeSub[1] = 2.0;
HistoNMassBinsDecayMeson = 450;
HistoMassRangeNDM[0] = 0.0;
HistoMassRangeNDM[1] = 0.45;
HistoNPtBins = 500;
HistoPtRange[1] = 50.;
NameNeutralMesonAnalyzed = "D0";
NameNeutralMesonAnalyzedLatex = "D^{0}";
NameNDM = "NeutralPion";
NameNDMLatex = "#pi^{0}";
fPDGMassNDM = 0.1349766; // hard coded PDG value to keep results reproducable later
fPDGCodeNDM = 111; // PDG value pi0
fPDGMassChargedPion = 0.1395706; // hard coded PDG 2018 value to keep results reproducable later
fPDGCodeAnalyzedMeson = 421; // PDG value D0
break;
default:
AliError(Form("Heavy neutral meson not correctly selected (only 0,1,2,3 valid)... selected: %d",fSelectedHeavyNeutralMeson));
}
// Create the output container
if(fOutputContainer != nullptr){
delete fOutputContainer;
fOutputContainer = nullptr;
}
if(fOutputContainer == nullptr){
fOutputContainer = new TList();
fOutputContainer->SetOwner(kTRUE);
}
fGoodConvGammas = new TList();
fClusterCandidates = new TList();
fClusterCandidates->SetOwner(kTRUE);
fNeutralDecayParticleCandidates = new TList();
fNeutralDecayParticleCandidates->SetOwner(kTRUE);
fNeutralDecayParticleSidebandCandidates = new TList();
fNeutralDecayParticleSidebandCandidates->SetOwner(kTRUE);
fPosPionCandidates = new TList();
fPosPionCandidates->SetOwner(kTRUE);
fNegPionCandidates = new TList();
fNegPionCandidates->SetOwner(kTRUE);
fCutFolder = new TList*[fnCuts];
fESDList = new TList*[fnCuts];
fHistoNEvents = new TH1F*[fnCuts];
if(fIsMC > 1){
fHistoNEventsWOWeight = new TH1F*[fnCuts];
}
fHistoNGoodESDTracks = new TH1I*[fnCuts];
if(fIsMC == 2) {
fProfileJetJetXSection = new TProfile*[fnCuts];
fHistoJetJetNTrials = new TH1F*[fnCuts];
}
if (fNDMRecoMode > 0){
fHistoClusterGammaPt = new TH1F*[fnCuts];
fHistoClusterGammaEta = new TH1F*[fnCuts];
fHistoClusterGammaE = new TH1F*[fnCuts];
}
if(!fDoLightOutput){
fProfileEtaShift = new TProfile*[fnCuts];
fHistoSPDClusterTrackletBackground = new TH2F*[fnCuts];
fHistovParticleChi2PerNDF = new TH1F*[fnCuts];
fHistovParticleChi2PerNDFBothConstrained = new TH1F*[fnCuts];
fHistovParticleChi2PerNDFOneConstrained = new TH1F*[fnCuts];
fHistovParticledS = new TH1F*[fnCuts];
fHistovParticledSBothConstrained = new TH1F*[fnCuts];
fHistovParticledSOneConstrained = new TH1F*[fnCuts];
if (fNDMRecoMode < 2){
fHistoConvGammaPt = new TH1F*[fnCuts];
fHistoConvGammaEta = new TH1F*[fnCuts];
}
fHistoNegPionPt = new TH1F*[fnCuts];
fHistoPosPionPt = new TH1F*[fnCuts];
fHistoNegPionPhi = new TH1F*[fnCuts];
fHistoPosPionPhi = new TH1F*[fnCuts];
fHistoPionPionInvMassPt = new TH2F*[fnCuts];
if( fDoMesonQA>0 ) {
fHistoNegPionEta = new TH1F*[fnCuts];
fHistoPosPionEta = new TH1F*[fnCuts];
fHistoNegPionClsTPC = new TH2F*[fnCuts];
fHistoPosPionClsTPC = new TH2F*[fnCuts];
fHistoPionDCAxy = new TH2F*[fnCuts];
fHistoPionDCAz = new TH2F*[fnCuts];
fHistoPionTPCdEdxNSigma = new TH2F*[fnCuts];
fHistoPionTPCdEdx = new TH2F*[fnCuts];
if (enableDalitzAllPt){
fHistoDalitzPlotPosFixedPzNDM = new TH2F*[fnCuts];
fHistoDalitzPlotNegFixedPzNDM = new TH2F*[fnCuts];
fHistoDalitzPlotPosSubNDM = new TH2F*[fnCuts];
fHistoDalitzPlotNegSubNDM = new TH2F*[fnCuts];
}
if (enableDalitzLowPt){
fHistoDalitzPlotPosFixedPzNDM_LowPt = new TH2F*[fnCuts];
fHistoDalitzPlotNegFixedPzNDM_LowPt = new TH2F*[fnCuts];
fHistoDalitzPlotPosSubNDM_LowPt = new TH2F*[fnCuts];
fHistoDalitzPlotNegSubNDM_LowPt = new TH2F*[fnCuts];
}
if (enableDalitzMidPt){
fHistoDalitzPlotPosFixedPzNDM_MidPt = new TH2F*[fnCuts];
fHistoDalitzPlotNegFixedPzNDM_MidPt = new TH2F*[fnCuts];
fHistoDalitzPlotPosSubNDM_MidPt = new TH2F*[fnCuts];
fHistoDalitzPlotNegSubNDM_MidPt = new TH2F*[fnCuts];
}
if (enableDalitzHighPt){
fHistoDalitzPlotPosFixedPzNDM_HighPt = new TH2F*[fnCuts];
fHistoDalitzPlotNegFixedPzNDM_HighPt = new TH2F*[fnCuts];
fHistoDalitzPlotPosSubNDM_HighPt = new TH2F*[fnCuts];
fHistoDalitzPlotNegSubNDM_HighPt = new TH2F*[fnCuts];
}
}
fHistoAngleHNMesonPiPlPiMi = new TH2F*[fnCuts];
fHistoAngleHNMesonNDM = new TH2F*[fnCuts];
fHistoAngleHNMesonPiPl = new TH2F*[fnCuts];
fHistoAngleHNMesonPiMi = new TH2F*[fnCuts];
fHistoAngleNDMPiMi = new TH2F*[fnCuts];
fHistoAnglePiPlPiMi = new TH2F*[fnCuts];
fHistoAnglePiPlNDM = new TH2F*[fnCuts];
fHistoAngleSum = new TH2F*[fnCuts];
}
fHistoGammaGammaInvMassPt = new TH2F*[fnCuts];
fHistoGammaGammaInvMassPtBeforeCuts = new TH2F*[fnCuts];
fHistoMotherInvMassPt = new TH2F*[fnCuts];
fHistoMotherInvMassPtRejectedKinematic = new TH2F*[fnCuts];
fHistoBackInvMassPt = new TH2F*[fnCuts];
fHistoMotherLikeSignBackInvMassPt = new TH2F*[fnCuts];
fHistoMotherInvMassSubNDM = new TH2F*[fnCuts];
fHistoBackInvMassPtSubNDM = new TH2F*[fnCuts];
fHistoMotherLikeSignBackInvMassSubNDMPt = new TH2F*[fnCuts];
fHistoMotherInvMassFixedPzNDM = new TH2F*[fnCuts];
fHistoBackInvMassPtFixedPzNDM = new TH2F*[fnCuts];
fHistoMotherLikeSignBackInvMassFixedPzNDMPt = new TH2F*[fnCuts];
for(Int_t iCut = 0; iCut<fnCuts;iCut++){
TString cutstringEvent = ((AliConvEventCuts*)fEventCutArray->At(iCut))->GetCutNumber();
TString cutstringPion = ((AliPrimaryPionCuts*)fPionCutArray->At(iCut))->GetCutNumber();
TString cutstringConvGamma = "";
if (fNDMRecoMode < 2)
cutstringConvGamma = ((AliConversionPhotonCuts*)fGammaCutArray->At(iCut))->GetCutNumber();
TString cutstringCaloGamma = "";
if (fNDMRecoMode > 0)
cutstringCaloGamma = ((AliCaloPhotonCuts*)fClusterCutArray->At(iCut))->GetCutNumber();
TString cutstringNeutralPion = ((AliConversionMesonCuts*)fNeutralDecayMesonCutArray->At(iCut))->GetCutNumber();
TString cutstringMeson = ((AliConversionMesonCuts*)fMesonCutArray->At(iCut))->GetCutNumber();
TString fullCutString = "";
if (fNDMRecoMode == 0)
fullCutString = Form("%i_%s_%s_%s_%s_%s",fNDMRecoMode,cutstringEvent.Data(),cutstringConvGamma.Data(),cutstringNeutralPion.Data(), cutstringPion.Data(),cutstringMeson.Data());
else if (fNDMRecoMode == 1)
fullCutString = Form("%i_%s_%s_%s_%s_%s_%s",fNDMRecoMode,cutstringEvent.Data(),cutstringConvGamma.Data(),cutstringCaloGamma.Data(),cutstringNeutralPion.Data(), cutstringPion.Data(),cutstringMeson.Data());
else if (fNDMRecoMode == 2)
fullCutString = Form("%i_%s_%s_%s_%s_%s",fNDMRecoMode,cutstringEvent.Data(),cutstringCaloGamma.Data(),cutstringNeutralPion.Data(), cutstringPion.Data(),cutstringMeson.Data());
TString nameCutFolder = Form("Cut Number %s", fullCutString.Data());
TString nameESDList = Form("%s ESD histograms", fullCutString.Data());
// Set min pt of pi0 that each method is able to reconstruct -> will be used for MC studies
if(fSelectedHeavyNeutralMeson == 1){ // omega
if(fNDMRecoMode==0){ // PCM
fNDMMinPtPossible = 0.3;
} else if (fNDMRecoMode==1){ // mixed
if(cutstringCaloGamma(0,1).String().EqualTo("1") || cutstringCaloGamma(0,1).String().EqualTo("4")){
fNDMMinPtPossible = 0.8; //PCM-EMC
} else{
fNDMMinPtPossible = 0.4; //PCM-PHOS
}
} else if (fNDMRecoMode==2){ // pure
if(cutstringCaloGamma(0,1).String().EqualTo("1") || cutstringCaloGamma(0,1).String().EqualTo("4")){
fNDMMinPtPossible = 1.4; //EMC
} else{
fNDMMinPtPossible = 1.6; //PHOS
}
} else{
fNDMMinPtPossible = 0.;
}
}
fCutFolder[iCut] = new TList();
fCutFolder[iCut]->SetName(nameCutFolder.Data());
fCutFolder[iCut]->SetOwner(kTRUE);
fOutputContainer->Add(fCutFolder[iCut]);
fESDList[iCut] = new TList();
fESDList[iCut]->SetName(nameESDList.Data());
fESDList[iCut]->SetOwner(kTRUE);
fHistoNEvents[iCut] = new TH1F("NEvents","NEvents",14,-0.5,13.5);
fHistoNEvents[iCut]->GetXaxis()->SetBinLabel(1,"Accepted");
fHistoNEvents[iCut]->GetXaxis()->SetBinLabel(2,"Centrality");
fHistoNEvents[iCut]->GetXaxis()->SetBinLabel(3,"Miss. MC or inc. ev.");
if (((AliConvEventCuts*)fEventCutArray->At(iCut))->IsSpecialTrigger() > 1 ){
TString TriggerNames = "Not Trigger: ";
TriggerNames = TriggerNames+ ( (AliConvEventCuts*)fEventCutArray->At(iCut))->GetSpecialTriggerName();
fHistoNEvents[iCut]->GetXaxis()->SetBinLabel(4,TriggerNames.Data());
} else {
fHistoNEvents[iCut]->GetXaxis()->SetBinLabel(4,"Trigger");
}
fHistoNEvents[iCut]->GetXaxis()->SetBinLabel(5,"Vertex Z");
fHistoNEvents[iCut]->GetXaxis()->SetBinLabel(6,"Cont. Vertex");
fHistoNEvents[iCut]->GetXaxis()->SetBinLabel(7,"Pile-Up");
fHistoNEvents[iCut]->GetXaxis()->SetBinLabel(8,"no SDD");
fHistoNEvents[iCut]->GetXaxis()->SetBinLabel(9,"no V0AND");
fHistoNEvents[iCut]->GetXaxis()->SetBinLabel(10,"EMCAL/TPC problem");
fHistoNEvents[iCut]->GetXaxis()->SetBinLabel(12,"SPD hits vs tracklet");
fHistoNEvents[iCut]->GetXaxis()->SetBinLabel(13,"Out-of-Bunch pileup Past-Future");
fHistoNEvents[iCut]->GetXaxis()->SetBinLabel(14,"Pileup V0M-TPCout Tracks");
fHistoNEvents[iCut]->GetYaxis()->SetTitle("N_{events}");
fESDList[iCut]->Add(fHistoNEvents[iCut]);
if(fIsMC > 1){
fHistoNEventsWOWeight[iCut] = new TH1F("NEventsWOWeight","NEventsWOWeight",14,-0.5,13.5);
fHistoNEventsWOWeight[iCut]->GetXaxis()->SetBinLabel(1,"Accepted");
fHistoNEventsWOWeight[iCut]->GetXaxis()->SetBinLabel(2,"Centrality");
fHistoNEventsWOWeight[iCut]->GetXaxis()->SetBinLabel(3,"Miss. MC or inc. ev.");
if (((AliConvEventCuts*)fEventCutArray->At(iCut))->IsSpecialTrigger() > 1 ){
TString TriggerNames = "Not Trigger: ";
TriggerNames = TriggerNames+ ( (AliConvEventCuts*)fEventCutArray->At(iCut))->GetSpecialTriggerName();
fHistoNEventsWOWeight[iCut]->GetXaxis()->SetBinLabel(4,TriggerNames.Data());
} else {
fHistoNEventsWOWeight[iCut]->GetXaxis()->SetBinLabel(4,"Trigger");
}
fHistoNEventsWOWeight[iCut]->GetXaxis()->SetBinLabel(5,"Vertex Z");
fHistoNEventsWOWeight[iCut]->GetXaxis()->SetBinLabel(6,"Cont. Vertex");
fHistoNEventsWOWeight[iCut]->GetXaxis()->SetBinLabel(7,"Pile-Up");
fHistoNEventsWOWeight[iCut]->GetXaxis()->SetBinLabel(8,"no SDD");
fHistoNEventsWOWeight[iCut]->GetXaxis()->SetBinLabel(9,"no V0AND");
fHistoNEventsWOWeight[iCut]->GetXaxis()->SetBinLabel(10,"EMCAL problem");
fHistoNEventsWOWeight[iCut]->GetXaxis()->SetBinLabel(12,"SPD hits vs tracklet");
fHistoNEventsWOWeight[iCut]->GetXaxis()->SetBinLabel(13,"Out-of-Bunch pileup Past-Future");
fHistoNEventsWOWeight[iCut]->GetXaxis()->SetBinLabel(14,"Pileup V0M-TPCout Tracks");
fHistoNEventsWOWeight[iCut]->GetYaxis()->SetTitle("N_{events}");
fESDList[iCut]->Add(fHistoNEventsWOWeight[iCut]);
}
if (fIsMC == 2){
fProfileJetJetXSection[iCut] = new TProfile("XSection", "XSection", 1, -0.5, 0.5);
fESDList[iCut]->Add(fProfileJetJetXSection[iCut]);
fHistoJetJetNTrials[iCut] = new TH1F("NTrials", "#sum{NTrials}", 1, 0, 1);
fHistoJetJetNTrials[iCut]->GetXaxis()->SetBinLabel(1,"#sum{NTrials}");
fESDList[iCut]->Add(fHistoJetJetNTrials[iCut]);
}
if(fIsHeavyIon>0)
fHistoNGoodESDTracks[iCut] = new TH1I("GoodESDTracks","GoodESDTracks",3000,0,3000);
else
fHistoNGoodESDTracks[iCut] = new TH1I("GoodESDTracks","GoodESDTracks",200,0,200);
fHistoNGoodESDTracks[iCut]->GetXaxis()->SetTitle("N_{good ESD tracks}");
fHistoNGoodESDTracks[iCut]->GetYaxis()->SetTitle("N_{events}");
fHistoNGoodESDTracks[iCut]->Sumw2();
fESDList[iCut]->Add(fHistoNGoodESDTracks[iCut]);
if (fNDMRecoMode > 0){
fHistoClusterGammaPt[iCut] = new TH1F("ESD_ClusterGamma_Pt","ESD_ClusterGamma_Pt",HistoNPtBins,HistoPtRange[0],HistoPtRange[1]);
fHistoClusterGammaPt[iCut]->GetXaxis()->SetTitle("p_{T} (GeV/c)");
fHistoClusterGammaPt[iCut]->GetYaxis()->SetTitle("N_{#gamma,cluster}");
fHistoClusterGammaPt[iCut]->Sumw2();
fESDList[iCut]->Add(fHistoClusterGammaPt[iCut]);
fHistoClusterGammaEta[iCut] = new TH1F("ESD_ClusterGamma_Eta","ESD_ClusterGamma_Eta",600,-1.5,1.5);
fHistoClusterGammaEta[iCut]->GetXaxis()->SetTitle("#eta");
fHistoClusterGammaEta[iCut]->GetYaxis()->SetTitle("N_{#gamma,cluster}");
fHistoClusterGammaEta[iCut]->Sumw2();
fESDList[iCut]->Add(fHistoClusterGammaEta[iCut]);
fHistoClusterGammaE[iCut] = new TH1F("ESD_ClusterGamma_E","ESD_ClusterGamma_E",HistoNPtBins,HistoPtRange[0],HistoPtRange[1]);
fHistoClusterGammaE[iCut]->GetXaxis()->SetTitle("E (GeV)");
fHistoClusterGammaE[iCut]->GetYaxis()->SetTitle("N_{#gamma,cluster}");
fHistoClusterGammaE[iCut]->Sumw2();
fESDList[iCut]->Add(fHistoClusterGammaE[iCut]);
}
if(!fDoLightOutput){
fProfileEtaShift[iCut] = new TProfile("Eta Shift","Eta Shift",1, -0.5,0.5);
fESDList[iCut]->Add(fProfileEtaShift[iCut]);
fHistoSPDClusterTrackletBackground[iCut] = new TH2F("SPD tracklets vs SPD clusters","SPD tracklets vs SPD clusters",100,0,200,250,0,1000);
fHistoSPDClusterTrackletBackground[iCut]->GetXaxis()->SetTitle("N_{SPD tracklets}");
fHistoSPDClusterTrackletBackground[iCut]->GetYaxis()->SetTitle("N_{SPD clusters}");
fHistoSPDClusterTrackletBackground[iCut]->Sumw2();
fESDList[iCut]->Add(fHistoSPDClusterTrackletBackground[iCut]);
fHistovParticleChi2PerNDF[iCut] = new TH1F("fHistovParticleChi2PerNDF","fHistovParticleChi2PerNDF",300,0,300);
fHistovParticleChi2PerNDF[iCut]->GetXaxis()->SetTitle("#chi^{2}/ndf");
fHistovParticleChi2PerNDF[iCut]->Sumw2();
fESDList[iCut]->Add(fHistovParticleChi2PerNDF[iCut]);
fHistovParticleChi2PerNDFBothConstrained[iCut] = new TH1F("fHistovParticleChi2PerNDFBothConstrained","fHistovParticleChi2PerNDFBothConstrained",300,0,300);
fHistovParticleChi2PerNDFBothConstrained[iCut]->GetXaxis()->SetTitle("#chi^{2}/ndf");
fHistovParticleChi2PerNDFBothConstrained[iCut]->Sumw2();
fESDList[iCut]->Add(fHistovParticleChi2PerNDFBothConstrained[iCut]);
fHistovParticleChi2PerNDFOneConstrained[iCut] = new TH1F("fHistovParticleChi2PerNDFOneConstrained","fHistovParticleChi2PerNDFOneConstrained",300,0,300);
fHistovParticleChi2PerNDFOneConstrained[iCut]->GetXaxis()->SetTitle("#chi^{2}/ndf");
fHistovParticleChi2PerNDFOneConstrained[iCut]->Sumw2();
fESDList[iCut]->Add(fHistovParticleChi2PerNDFOneConstrained[iCut]);
fHistovParticledS[iCut] = new TH1F("fHistovParticledS","fHistovParticledS",400,-4,4);
fHistovParticledS[iCut]->GetXaxis()->SetTitle("dS");
fHistovParticledS[iCut]->Sumw2();
fESDList[iCut]->Add(fHistovParticledS[iCut]);
fHistovParticledSBothConstrained[iCut] = new TH1F("fHistovParticledSBothConstrained","fHistovParticledSBothConstrained",400,-4,4);
fHistovParticledSBothConstrained[iCut]->GetXaxis()->SetTitle("dS");
fHistovParticledSBothConstrained[iCut]->Sumw2();
fESDList[iCut]->Add(fHistovParticledSBothConstrained[iCut]);
fHistovParticledSOneConstrained[iCut] = new TH1F("fHistovParticledSOneConstrained","fHistovParticledSOneConstrained",400,-4,4);
fHistovParticledSOneConstrained[iCut]->GetXaxis()->SetTitle("dS");
fHistovParticledSOneConstrained[iCut]->Sumw2();
fESDList[iCut]->Add(fHistovParticledSOneConstrained[iCut]);
if (fNDMRecoMode < 2){
fHistoConvGammaPt[iCut] = new TH1F("ESD_ConvGamma_Pt","ESD_ConvGamma_Pt",HistoNPtBins,HistoPtRange[0],HistoPtRange[1]);
fHistoConvGammaPt[iCut]->GetXaxis()->SetTitle("p_{T} (GeV/c)");
fHistoConvGammaPt[iCut]->GetYaxis()->SetTitle("N_{#gamma,conv}");
fHistoConvGammaPt[iCut]->Sumw2();
fESDList[iCut]->Add(fHistoConvGammaPt[iCut]);
fHistoConvGammaEta[iCut] = new TH1F("ESD_ConvGamma_Eta","ESD_ConvGamma_Eta",600,-1.5,1.5);
fHistoConvGammaEta[iCut]->GetXaxis()->SetTitle("#eta");
fHistoConvGammaEta[iCut]->GetYaxis()->SetTitle("N_{#gamma,conv}");
fHistoConvGammaEta[iCut]->Sumw2();
fESDList[iCut]->Add(fHistoConvGammaEta[iCut]);
}
fHistoNegPionPt[iCut] = new TH1F("ESD_PrimaryNegPions_Pt","ESD_PrimaryNegPions_Pt",HistoNPtBins,HistoPtRange[0],HistoPtRange[1]);
fHistoNegPionPt[iCut]->GetXaxis()->SetTitle("p_{T} (GeV/c)");
fHistoNegPionPt[iCut]->GetYaxis()->SetTitle("N_{#pi^{-}}");
fHistoNegPionPt[iCut]->Sumw2();
fESDList[iCut]->Add(fHistoNegPionPt[iCut]);
fHistoPosPionPt[iCut] = new TH1F("ESD_PrimaryPosPions_Pt","ESD_PrimaryPosPions_Pt",HistoNPtBins,HistoPtRange[0],HistoPtRange[1]);
fHistoPosPionPt[iCut]->GetXaxis()->SetTitle("p_{T} (GeV/c)");
fHistoPosPionPt[iCut]->GetYaxis()->SetTitle("N_{#pi^{+}}");
fHistoPosPionPt[iCut]->Sumw2();
fESDList[iCut]->Add(fHistoPosPionPt[iCut]);
fHistoNegPionPhi[iCut] = new TH1F("ESD_PrimaryNegPions_Phi","ESD_PrimaryNegPions_Phi",360,0,2*TMath::Pi());
fHistoNegPionPhi[iCut]->GetXaxis()->SetTitle("#phi");
fHistoNegPionPhi[iCut]->GetYaxis()->SetTitle("N_{#pi^{-}}");
fHistoNegPionPhi[iCut]->Sumw2();
fESDList[iCut]->Add(fHistoNegPionPhi[iCut]);
fHistoPosPionPhi[iCut] = new TH1F("ESD_PrimaryPosPions_Phi","ESD_PrimaryPosPions_Phi",360,0,2*TMath::Pi());
fHistoPosPionPhi[iCut]->GetXaxis()->SetTitle("#phi");
fHistoPosPionPhi[iCut]->GetYaxis()->SetTitle("N_{#pi^{+}}");
fHistoPosPionPhi[iCut]->Sumw2();
fESDList[iCut]->Add(fHistoPosPionPhi[iCut]);
fHistoPionPionInvMassPt[iCut] = new TH2F("ESD_PiPlusPiNeg_InvMassPt","ESD_PiPlusPiNeg_InvMassPt",HistoNMassBinsPiPlusPiMinus,HistoMassRangePiPlusPiMinus[0],HistoMassRangePiPlusPiMinus[1],HistoNPtBins,HistoPtRange[0],HistoPtRange[1]);
fHistoPionPionInvMassPt[iCut]->GetXaxis()->SetTitle("M_{#pi^{+}#pi^{-}} (GeV/c^{2})");
fHistoPionPionInvMassPt[iCut]->GetYaxis()->SetTitle("p_{T} (GeV/c)");
fHistoPionPionInvMassPt[iCut]->Sumw2();
fESDList[iCut]->Add(fHistoPionPionInvMassPt[iCut]);
if ( fDoMesonQA>0 ) {
fHistoNegPionEta[iCut] = new TH1F("ESD_PrimaryNegPions_Eta","ESD_PrimaryNegPions_Eta",600,-1.5,1.5);
fHistoNegPionEta[iCut]->GetXaxis()->SetTitle("#eta");
fHistoNegPionEta[iCut]->GetYaxis()->SetTitle("N_{#pi^{-}}");
fHistoNegPionEta[iCut]->Sumw2();
fESDList[iCut]->Add(fHistoNegPionEta[iCut]);
fHistoPosPionEta[iCut] = new TH1F("ESD_PrimaryPosPions_Eta","ESD_PrimaryPosPions_Eta",600,-1.5,1.5);
fHistoPosPionEta[iCut]->GetXaxis()->SetTitle("#eta");
fHistoPosPionEta[iCut]->GetYaxis()->SetTitle("N_{#pi^{+}}");
fHistoPosPionEta[iCut]->Sumw2();
fESDList[iCut]->Add(fHistoPosPionEta[iCut]);
fHistoNegPionClsTPC[iCut] = new TH2F("ESD_PrimaryNegPions_ClsTPC","ESD_PrimaryNegPions_ClsTPC",100,0,1,400,0.,10.);
fHistoNegPionClsTPC[iCut]->GetXaxis()->SetTitle("N_{findable cls. TPC #pi^{-}}");
fHistoNegPionClsTPC[iCut]->GetYaxis()->SetTitle("p_{T} (GeV/c)");
fHistoNegPionClsTPC[iCut]->Sumw2();
fESDList[iCut]->Add(fHistoNegPionClsTPC[iCut]);
fHistoPosPionClsTPC[iCut] = new TH2F("ESD_PrimaryPosPions_ClsTPC","ESD_PrimaryPosPions_ClsTPC",100,0,1,400,0.,10.);
fHistoPosPionClsTPC[iCut]->GetXaxis()->SetTitle("N_{findable cls. TPC #pi^{+}}");
fHistoPosPionClsTPC[iCut]->GetYaxis()->SetTitle("p_{T} (GeV/c)");
fHistoPosPionClsTPC[iCut]->Sumw2();
fESDList[iCut]->Add(fHistoPosPionClsTPC[iCut]);
fHistoPionDCAxy[iCut] = new TH2F("ESD_PrimaryPions_DCAxy","ESD_PrimaryPions_DCAxy",800,-4.0,4.0,400,0.,10.);
fHistoPionDCAxy[iCut]->GetXaxis()->SetTitle("DCA_{xy}");
fHistoPionDCAxy[iCut]->GetYaxis()->SetTitle("p_{T} (GeV/c)");
fHistoPionDCAxy[iCut]->Sumw2();
fESDList[iCut]->Add(fHistoPionDCAxy[iCut]);
fHistoPionDCAz[iCut] = new TH2F("ESD_PrimaryPions_DCAz","ESD_PrimaryPions_DCAz",800,-4.0,4.0,400,0.,10.);
fHistoPionDCAz[iCut]->GetXaxis()->SetTitle("DCA_{z}");
fHistoPionDCAz[iCut]->GetYaxis()->SetTitle("p_{T} (GeV/c)");
fHistoPionDCAz[iCut]->Sumw2();
fESDList[iCut]->Add(fHistoPionDCAz[iCut]);
fHistoPionTPCdEdxNSigma[iCut] = new TH2F("ESD_PrimaryPions_TPCdEdx","ESD_PrimaryPions_TPCdEdx",150,0.05,20,400,-10,10);
fHistoPionTPCdEdxNSigma[iCut]->GetXaxis()->SetTitle("p (GeV/c)");
fHistoPionTPCdEdxNSigma[iCut]->GetYaxis()->SetTitle("#sigma_{PID,TPC}");
fHistoPionTPCdEdxNSigma[iCut]->Sumw2();
fESDList[iCut]->Add(fHistoPionTPCdEdxNSigma[iCut]);
fHistoPionTPCdEdx[iCut] = new TH2F("ESD_PrimaryPions_TPCdEdxSignal","ESD_PrimaryPions_TPCdEdxSignal" ,150,0.05,20.0,800,0.0,200);
fHistoPionTPCdEdx[iCut]->GetXaxis()->SetTitle("p (GeV/c)");
fHistoPionTPCdEdx[iCut]->GetYaxis()->SetTitle("dE/dx signal (au)");
fHistoPionTPCdEdx[iCut]->Sumw2();
fESDList[iCut]->Add(fHistoPionTPCdEdx[iCut]);
//---------------------------------------
//Dalitz All Pt
if (enableDalitzAllPt){
fHistoDalitzPlotPosFixedPzNDM[iCut] = new TH2F("ESD_DalitzPlotPos_FixedPz","ESD_DalitzPlotPos_FixedPz", HistoNMassBins, HistoMassRangeDalitzMin, HistoMassRangeDalitz, HistoNMassBins, HistoMassRangeDalitzMin, HistoMassRangeDalitz);
fHistoDalitzPlotPosFixedPzNDM[iCut]->GetXaxis()->SetTitle("M_{#pi^{+} #pi^{-}} (GeV/c^{2})");
fHistoDalitzPlotPosFixedPzNDM[iCut]->GetYaxis()->SetTitle(Form("M_{#pi^{+} %s} (GeV/c^{2}",NameNDMLatex.Data()));
fHistoDalitzPlotPosFixedPzNDM[iCut]->Sumw2();
fESDList[iCut]->Add(fHistoDalitzPlotPosFixedPzNDM[iCut]);
fHistoDalitzPlotNegFixedPzNDM[iCut] = new TH2F("ESD_DalitzPlotNeg_FixedPz","ESD_DalitzPlotNeg_FixedPz", HistoNMassBins, HistoMassRangeDalitzMin, HistoMassRangeDalitz, HistoNMassBins, HistoMassRangeDalitzMin, HistoMassRangeDalitz);
fHistoDalitzPlotNegFixedPzNDM[iCut]->GetXaxis()->SetTitle("M_{#pi^{+} #pi^{-}} (GeV/c^{2})");
fHistoDalitzPlotNegFixedPzNDM[iCut]->GetYaxis()->SetTitle(Form("M_{#pi^{-} %s} (GeV/c^{2}",NameNDMLatex.Data()));
fHistoDalitzPlotNegFixedPzNDM[iCut]->Sumw2();
fESDList[iCut]->Add(fHistoDalitzPlotNegFixedPzNDM[iCut]);
fHistoDalitzPlotPosSubNDM[iCut] = new TH2F("ESD_DalitzPlotPos_Sub","ESD_DalitzPlotPos_Sub", HistoNMassBins, HistoMassRangeDalitzMin, HistoMassRangeDalitz, HistoNMassBins, HistoMassRangeDalitzMin, HistoMassRangeDalitz);
fHistoDalitzPlotPosSubNDM[iCut]->GetXaxis()->SetTitle("M_{#pi^{+} #pi^{-}} (GeV/c^{2})");
fHistoDalitzPlotPosSubNDM[iCut]->GetYaxis()->SetTitle(Form("M_{#pi^{+} %s} (GeV/c^{2}",NameNDMLatex.Data()));
fHistoDalitzPlotPosSubNDM[iCut]->Sumw2();
fESDList[iCut]->Add(fHistoDalitzPlotPosSubNDM[iCut]);
fHistoDalitzPlotNegSubNDM[iCut] = new TH2F("ESD_DalitzPlotNeg_Sub","ESD_DalitzPlotNeg_Sub", HistoNMassBins, HistoMassRangeDalitzMin, HistoMassRangeDalitz, HistoNMassBins, HistoMassRangeDalitzMin, HistoMassRangeDalitz);
fHistoDalitzPlotNegSubNDM[iCut]->GetXaxis()->SetTitle("M_{#pi^{+} #pi^{-}} (GeV/c^{2})");
fHistoDalitzPlotNegSubNDM[iCut]->GetYaxis()->SetTitle(Form("M_{#pi^{-} %s} (GeV/c^{2}",NameNDMLatex.Data()));
fHistoDalitzPlotNegSubNDM[iCut]->Sumw2();
fESDList[iCut]->Add(fHistoDalitzPlotNegSubNDM[iCut]);
}
//---------------------------------------
//Dalitz Low Pt
if (enableDalitzLowPt){
fHistoDalitzPlotPosFixedPzNDM_LowPt[iCut] = new TH2F("ESD_DalitzPlotPos_FixedPz_LowPt", Form("ESD_DalitzPlotPos_FixedPz_LowPt (%3.1f to %3.1f)Gev/c", HistoDalitzPtRangeMin_LowPt, HistoDalitzPtRangeMax_LowPt), HistoNMassBins, HistoMassRangeDalitzMin, HistoMassRangeDalitz, HistoNMassBins, HistoMassRangeDalitzMin, HistoMassRangeDalitz);
fHistoDalitzPlotPosFixedPzNDM_LowPt[iCut]->GetXaxis()->SetTitle("M_{#pi^{+} #pi^{-}} (GeV/c^{2})");
fHistoDalitzPlotPosFixedPzNDM_LowPt[iCut]->GetYaxis()->SetTitle(Form("M_{#pi^{+} %s} (GeV/c^{2}",NameNDMLatex.Data()));
fHistoDalitzPlotPosFixedPzNDM_LowPt[iCut]->Sumw2();
fESDList[iCut]->Add(fHistoDalitzPlotPosFixedPzNDM_LowPt[iCut]);
fHistoDalitzPlotNegFixedPzNDM_LowPt[iCut] = new TH2F("ESD_DalitzPlotNeg_FixedPz_LowPt", Form("ESD_DalitzPlotNeg_FixedPz_LowPt (%3.1f to %3.1f)Gev/c", HistoDalitzPtRangeMin_LowPt, HistoDalitzPtRangeMax_LowPt), HistoNMassBins, HistoMassRangeDalitzMin, HistoMassRangeDalitz, HistoNMassBins, HistoMassRangeDalitzMin, HistoMassRangeDalitz);
fHistoDalitzPlotNegFixedPzNDM_LowPt[iCut]->GetXaxis()->SetTitle("M_{#pi^{+} #pi^{-}} (GeV/c^{2})");
fHistoDalitzPlotNegFixedPzNDM_LowPt[iCut]->GetYaxis()->SetTitle(Form("M_{#pi^{-} %s} (GeV/c^{2}",NameNDMLatex.Data()));
fHistoDalitzPlotNegFixedPzNDM_LowPt[iCut]->Sumw2();
fESDList[iCut]->Add(fHistoDalitzPlotNegFixedPzNDM_LowPt[iCut]);
fHistoDalitzPlotPosSubNDM_LowPt[iCut] = new TH2F("ESD_DalitzPlotPos_Sub_LowPt", Form("ESD_DalitzPlotPos_Sub_LowPt (%3.1f to %3.1f)Gev/c", HistoDalitzPtRangeMin_LowPt, HistoDalitzPtRangeMax_LowPt), HistoNMassBins, HistoMassRangeDalitzMin, HistoMassRangeDalitz, HistoNMassBins, HistoMassRangeDalitzMin, HistoMassRangeDalitz);
fHistoDalitzPlotPosSubNDM_LowPt[iCut]->GetXaxis()->SetTitle("M_{#pi^{+} #pi^{-}} (GeV/c^{2})");
fHistoDalitzPlotPosSubNDM_LowPt[iCut]->GetYaxis()->SetTitle(Form("M_{#pi^{+} %s} (GeV/c^{2}",NameNDMLatex.Data()));
fHistoDalitzPlotPosSubNDM_LowPt[iCut]->Sumw2();
fESDList[iCut]->Add(fHistoDalitzPlotPosSubNDM_LowPt[iCut]);
fHistoDalitzPlotNegSubNDM_LowPt[iCut] = new TH2F("ESD_DalitzPlotNeg_Sub_LowPt", Form("ESD_DalitzPlotNeg_Sub_LowPt (%3.1f to %3.1f)Gev/c", HistoDalitzPtRangeMin_LowPt, HistoDalitzPtRangeMax_LowPt), HistoNMassBins, HistoMassRangeDalitzMin, HistoMassRangeDalitz, HistoNMassBins, HistoMassRangeDalitzMin, HistoMassRangeDalitz);
fHistoDalitzPlotNegSubNDM_LowPt[iCut]->GetXaxis()->SetTitle("M_{#pi^{+} #pi^{-}} (GeV/c^{2})");
fHistoDalitzPlotNegSubNDM_LowPt[iCut]->GetYaxis()->SetTitle(Form("M_{#pi^{-} %s} (GeV/c^{2}",NameNDMLatex.Data()));
fHistoDalitzPlotNegSubNDM_LowPt[iCut]->Sumw2();
fESDList[iCut]->Add(fHistoDalitzPlotNegSubNDM_LowPt[iCut]);
}
//---------------------------------------
//Dalitz Mid Pt
if (enableDalitzMidPt){
fHistoDalitzPlotPosFixedPzNDM_MidPt[iCut] = new TH2F("ESD_DalitzPlotPos_FixedPz_MidPt", Form("ESD_DalitzPlotPos_FixedPz_MidPt (%3.1f to %3.1f)Gev/c", HistoDalitzPtRangeMin_MidPt, HistoDalitzPtRangeMax_MidPt), HistoNMassBins, HistoMassRangeDalitzMin, HistoMassRangeDalitz, HistoNMassBins, HistoMassRangeDalitzMin, HistoMassRangeDalitz);
fHistoDalitzPlotPosFixedPzNDM_MidPt[iCut]->GetXaxis()->SetTitle("M_{#pi^{+} #pi^{-}} (GeV/c^{2})");
fHistoDalitzPlotPosFixedPzNDM_MidPt[iCut]->GetYaxis()->SetTitle(Form("M_{#pi^{+} %s} (GeV/c^{2}",NameNDMLatex.Data()));
fHistoDalitzPlotPosFixedPzNDM_MidPt[iCut]->Sumw2();
fESDList[iCut]->Add(fHistoDalitzPlotPosFixedPzNDM_MidPt[iCut]);
fHistoDalitzPlotNegFixedPzNDM_MidPt[iCut] = new TH2F("ESD_DalitzPlotNeg_FixedPz_MidPt", Form("ESD_DalitzPlotNeg_FixedPz_MidPt (%3.1f to %3.1f)Gev/c", HistoDalitzPtRangeMin_MidPt, HistoDalitzPtRangeMax_MidPt), HistoNMassBins, HistoMassRangeDalitzMin, HistoMassRangeDalitz, HistoNMassBins, HistoMassRangeDalitzMin, HistoMassRangeDalitz);
fHistoDalitzPlotNegFixedPzNDM_MidPt[iCut]->GetXaxis()->SetTitle("M_{#pi^{+} #pi^{-}} (GeV/c^{2})");
fHistoDalitzPlotNegFixedPzNDM_MidPt[iCut]->GetYaxis()->SetTitle(Form("M_{#pi^{-} %s} (GeV/c^{2}",NameNDMLatex.Data()));
fHistoDalitzPlotNegFixedPzNDM_MidPt[iCut]->Sumw2();
fESDList[iCut]->Add(fHistoDalitzPlotNegFixedPzNDM_MidPt[iCut]);
fHistoDalitzPlotPosSubNDM_MidPt[iCut] = new TH2F("ESD_DalitzPlotPos_Sub_MidPt", Form("ESD_DalitzPlotPos_Sub_MidPt (%3.1f to %3.1f)Gev/c", HistoDalitzPtRangeMin_MidPt, HistoDalitzPtRangeMax_MidPt), HistoNMassBins, HistoMassRangeDalitzMin, HistoMassRangeDalitz, HistoNMassBins, HistoMassRangeDalitzMin, HistoMassRangeDalitz);
fHistoDalitzPlotPosSubNDM_MidPt[iCut]->GetXaxis()->SetTitle("M_{#pi^{+} #pi^{-}} (GeV/c^{2})");
fHistoDalitzPlotPosSubNDM_MidPt[iCut]->GetYaxis()->SetTitle(Form("M_{#pi^{+} %s} (GeV/c^{2}",NameNDMLatex.Data()));
fHistoDalitzPlotPosSubNDM_MidPt[iCut]->Sumw2();
fESDList[iCut]->Add(fHistoDalitzPlotPosSubNDM_MidPt[iCut]);
fHistoDalitzPlotNegSubNDM_MidPt[iCut] = new TH2F("ESD_DalitzPlotNeg_Sub_MidPt", Form("ESD_DalitzPlotNeg_Sub_MidPt (%3.1f to %3.1f)Gev/c", HistoDalitzPtRangeMin_MidPt, HistoDalitzPtRangeMax_MidPt), HistoNMassBins, HistoMassRangeDalitzMin, HistoMassRangeDalitz, HistoNMassBins, HistoMassRangeDalitzMin, HistoMassRangeDalitz);
fHistoDalitzPlotNegSubNDM_MidPt[iCut]->GetXaxis()->SetTitle("M_{#pi^{+} #pi^{-}} (GeV/c^{2})");
fHistoDalitzPlotNegSubNDM_MidPt[iCut]->GetYaxis()->SetTitle(Form("M_{#pi^{-} %s} (GeV/c^{2}",NameNDMLatex.Data()));
fHistoDalitzPlotNegSubNDM_MidPt[iCut]->Sumw2();
fESDList[iCut]->Add(fHistoDalitzPlotNegSubNDM_MidPt[iCut]);
}
//---------------------------------------
//Dalitz High Pt
if (enableDalitzHighPt){
fHistoDalitzPlotPosFixedPzNDM_HighPt[iCut] = new TH2F("ESD_DalitzPlotPos_FixedPz_HighPt", Form("ESD_DalitzPlotPos_FixedPz_HighPt (%3.1f to %3.1f)Gev/c", HistoDalitzPtRangeMin_HighPt, HistoDalitzPtRangeMax_HighPt), HistoNMassBins, HistoMassRangeDalitzMin, HistoMassRangeDalitz, HistoNMassBins, HistoMassRangeDalitzMin, HistoMassRangeDalitz);
fHistoDalitzPlotPosFixedPzNDM_HighPt[iCut]->GetXaxis()->SetTitle("M_{#pi^{+} #pi^{-}} (GeV/c^{2})");
fHistoDalitzPlotPosFixedPzNDM_HighPt[iCut]->GetYaxis()->SetTitle(Form("M_{#pi^{+} %s} (GeV/c^{2}",NameNDMLatex.Data()));
fHistoDalitzPlotPosFixedPzNDM_HighPt[iCut]->Sumw2();
fESDList[iCut]->Add(fHistoDalitzPlotPosFixedPzNDM_HighPt[iCut]);
fHistoDalitzPlotNegFixedPzNDM_HighPt[iCut] = new TH2F("ESD_DalitzPlotNeg_FixedPz_HighPt", Form("ESD_DalitzPlotNeg_FixedPz_HighPt (%3.1f to %3.1f)Gev/c", HistoDalitzPtRangeMin_HighPt, HistoDalitzPtRangeMax_HighPt), HistoNMassBins, HistoMassRangeDalitzMin, HistoMassRangeDalitz, HistoNMassBins, HistoMassRangeDalitzMin, HistoMassRangeDalitz);
fHistoDalitzPlotNegFixedPzNDM_HighPt[iCut]->GetXaxis()->SetTitle("M_{#pi^{+} #pi^{-}} (GeV/c^{2})");
fHistoDalitzPlotNegFixedPzNDM_HighPt[iCut]->GetYaxis()->SetTitle(Form("M_{#pi^{-} %s} (GeV/c^{2}",NameNDMLatex.Data()));
fHistoDalitzPlotNegFixedPzNDM_HighPt[iCut]->Sumw2();
fESDList[iCut]->Add(fHistoDalitzPlotNegFixedPzNDM_HighPt[iCut]);
fHistoDalitzPlotPosSubNDM_HighPt[iCut] = new TH2F("ESD_DalitzPlotPos_Sub_HighPt", Form("ESD_DalitzPlotPos_Sub_HighPt (%3.1f to %3.1f)Gev/c", HistoDalitzPtRangeMin_HighPt, HistoDalitzPtRangeMax_HighPt), HistoNMassBins, HistoMassRangeDalitzMin, HistoMassRangeDalitz, HistoNMassBins, HistoMassRangeDalitzMin, HistoMassRangeDalitz);
fHistoDalitzPlotPosSubNDM_HighPt[iCut]->GetXaxis()->SetTitle("M_{#pi^{+} #pi^{-}} (GeV/c^{2})");
fHistoDalitzPlotPosSubNDM_HighPt[iCut]->GetYaxis()->SetTitle(Form("M_{#pi^{+} %s} (GeV/c^{2}",NameNDMLatex.Data()));
fHistoDalitzPlotPosSubNDM_HighPt[iCut]->Sumw2();
fESDList[iCut]->Add(fHistoDalitzPlotPosSubNDM_HighPt[iCut]);
fHistoDalitzPlotNegSubNDM_HighPt[iCut] = new TH2F("ESD_DalitzPlotNeg_Sub_HighPt", Form("ESD_DalitzPlotNeg_Sub_HighPt (%3.1f to %3.1f)Gev/c", HistoDalitzPtRangeMin_HighPt, HistoDalitzPtRangeMax_HighPt), HistoNMassBins, HistoMassRangeDalitzMin, HistoMassRangeDalitz, HistoNMassBins, HistoMassRangeDalitzMin, HistoMassRangeDalitz);
fHistoDalitzPlotNegSubNDM_HighPt[iCut]->GetXaxis()->SetTitle("M_{#pi^{+} #pi^{-}} (GeV/c^{2})");
fHistoDalitzPlotNegSubNDM_HighPt[iCut]->GetYaxis()->SetTitle(Form("M_{#pi^{-} %s} (GeV/c^{2}",NameNDMLatex.Data()));
fHistoDalitzPlotNegSubNDM_HighPt[iCut]->Sumw2();
fESDList[iCut]->Add(fHistoDalitzPlotNegSubNDM_HighPt[iCut]);
}
//---------------------------------------
//End of Dalitz
}
fHistoGammaGammaInvMassPt[iCut] = new TH2F("ESD_GammaGamma_InvMass_Pt","ESD_GammaGamma_InvMass_Pt",HistoNMassBinsDecayMeson,HistoMassRangeNDM[0],HistoMassRangeNDM[1],HistoNPtBins,HistoPtRange[0],HistoPtRange[1]);
fHistoGammaGammaInvMassPt[iCut]->GetXaxis()->SetTitle("M_{#gamma #gamma} (GeV/c^{2})");
fHistoGammaGammaInvMassPt[iCut]->GetYaxis()->SetTitle("p_{T} (GeV/c)");
fHistoGammaGammaInvMassPt[iCut]->Sumw2();
fESDList[iCut]->Add(fHistoGammaGammaInvMassPt[iCut]);
fHistoGammaGammaInvMassPtBeforeCuts[iCut] = new TH2F("ESD_GammaGamma_InvMass_Pt_Before_Cuts","ESD_GammaGamma_InvMass_Pt_Before_Cuts",HistoNMassBinsDecayMeson,HistoMassRangeNDM[0],HistoMassRangeNDM[1],HistoNPtBins,HistoPtRange[0],HistoPtRange[1]);
fHistoGammaGammaInvMassPtBeforeCuts[iCut]->GetXaxis()->SetTitle("M_{#gamma #gamma} (GeV/c^{2})");
fHistoGammaGammaInvMassPtBeforeCuts[iCut]->GetYaxis()->SetTitle("p_{T} (GeV/c)");
fHistoGammaGammaInvMassPtBeforeCuts[iCut]->Sumw2();
fESDList[iCut]->Add(fHistoGammaGammaInvMassPtBeforeCuts[iCut]);
}
fHistoMotherInvMassPt[iCut] = new TH2F("ESD_Mother_InvMass_Pt","ESD_Mother_InvMass_Pt",HistoNMassBins,HistoMassRange[0],HistoMassRange[1],HistoNPtBins,HistoPtRange[0],HistoPtRange[1]);
fHistoMotherInvMassPt[iCut]->GetXaxis()->SetTitle(Form("M_{#pi^{+} #pi^{-} %s} (GeV/c^{2})",NameNDMLatex.Data()));
fHistoMotherInvMassPt[iCut]->GetYaxis()->SetTitle("p_{T} (GeV/c)");
fHistoMotherInvMassPt[iCut]->Sumw2();
fESDList[iCut]->Add(fHistoMotherInvMassPt[iCut]);
fHistoMotherInvMassPtRejectedKinematic[iCut] = new TH2F("ESD_Mother_InvMass_Pt_KinematicRejected","ESD_Mother_InvMass_Pt_KinematicRejected",HistoNMassBins,HistoMassRange[0],HistoMassRange[1],HistoNPtBins,HistoPtRange[0],HistoPtRange[1]);
fHistoMotherInvMassPtRejectedKinematic[iCut]->GetXaxis()->SetTitle(Form("M_{#pi^{+} #pi^{-} %s} (GeV/c^{2})",NameNDMLatex.Data()));
fHistoMotherInvMassPtRejectedKinematic[iCut]->GetYaxis()->SetTitle("p_{T} (GeV/c)");
fHistoMotherInvMassPtRejectedKinematic[iCut]->Sumw2();
fESDList[iCut]->Add(fHistoMotherInvMassPtRejectedKinematic[iCut]);
fHistoBackInvMassPt[iCut] = new TH2F("ESD_Background_InvMass_Pt","ESD_Background_InvMass_Pt",HistoNMassBins,HistoMassRange[0],HistoMassRange[1],HistoNPtBins,HistoPtRange[0],HistoPtRange[1]);
fHistoBackInvMassPt[iCut]->Sumw2();
fHistoBackInvMassPt[iCut]->GetXaxis()->SetTitle(Form("M_{#pi^{+} #pi^{-} %s} (GeV/c^{2})",NameNDMLatex.Data()));
fHistoBackInvMassPt[iCut]->GetYaxis()->SetTitle("p_{T} (GeV/c)");
if(!(((AliConversionMesonCuts*)fMesonCutArray->At(iCut))->UseLikeSignMixing())&&(((AliConversionMesonCuts*)fMesonCutArray->At(iCut))->DoBGCalculation())){
fESDList[iCut]->Add(fHistoBackInvMassPt[iCut]);
}
fHistoMotherLikeSignBackInvMassPt[iCut] = new TH2F("ESD_Background_LikeSign_InvMass_Pt","ESD_Background_LikeSign_InvMass_Pt",HistoNMassBins,HistoMassRange[0],HistoMassRange[1],HistoNPtBins,HistoPtRange[0],HistoPtRange[1]);
fHistoMotherLikeSignBackInvMassPt[iCut]->GetXaxis()->SetTitle(Form("M_{#pi^{#pm} #pi^{#pm} %s} (GeV/c^{2})",NameNDMLatex.Data()));
fHistoMotherLikeSignBackInvMassPt[iCut]->GetYaxis()->SetTitle("p_{T} (GeV/c)");
fHistoMotherLikeSignBackInvMassPt[iCut]->Sumw2();
if(((AliConversionMesonCuts*)fMesonCutArray->At(iCut))->UseLikeSignMixing()){
fESDList[iCut]->Add(fHistoMotherLikeSignBackInvMassPt[iCut]);
}
fHistoMotherInvMassSubNDM[iCut] = new TH2F("ESD_InvMass_Mother_Sub_InvMass_Neutral_Pt","ESD_InvMass_Mother_Sub_InvMass_Neutral_Pt",HistoNMassBinsSub,HistoMassRangeSub[0],HistoMassRangeSub[1],HistoNPtBins,HistoPtRange[0],HistoPtRange[1]);
fHistoMotherInvMassSubNDM[iCut]->GetXaxis()->SetTitle(Form("M_{#pi^{+} #pi^{-} %s} - (M_{%s}-M_{%s},PDG}) (GeV/c^{2})",NameNDMLatex.Data(),NameNDMLatex.Data(),NameNDMLatex.Data()));
fHistoMotherInvMassSubNDM[iCut]->GetYaxis()->SetTitle("p_{T} (GeV/c)");
fHistoMotherInvMassSubNDM[iCut]->Sumw2();
fESDList[iCut]->Add(fHistoMotherInvMassSubNDM[iCut]);
fHistoBackInvMassPtSubNDM[iCut] = new TH2F("ESD_Background_InvMass_Sub_InvMass_Neutral_Pt","ESD_Background_InvMass_Sub_InvMass_Neutral_Pt",
HistoNMassBinsSub,HistoMassRangeSub[0],HistoMassRangeSub[1],HistoNPtBins,HistoPtRange[0],HistoPtRange[1]);
fHistoBackInvMassPtSubNDM[iCut]->GetXaxis()->SetTitle(Form("M_{#pi^{+} #pi^{-} %s} - (M_{%s}-M_{%s},PDG}) (GeV/c^{2})",NameNDMLatex.Data(),NameNDMLatex.Data(),NameNDMLatex.Data()));
fHistoBackInvMassPtSubNDM[iCut]->GetYaxis()->SetTitle("p_{T} (GeV/c)");
fHistoBackInvMassPtSubNDM[iCut]->Sumw2();
if(!(((AliConversionMesonCuts*)fMesonCutArray->At(iCut))->UseLikeSignMixing())&&(((AliConversionMesonCuts*)fMesonCutArray->At(iCut))->DoBGCalculation())){
fESDList[iCut]->Add(fHistoBackInvMassPtSubNDM[iCut]);
}
fHistoMotherLikeSignBackInvMassSubNDMPt[iCut] = new TH2F("ESD_Background_LikeSign_InvMass_Sub_InvMass_Neutral_Pt","ESD_Background_LikeSign_InvMass_Sub_InvMass_Neutral_Pt",
HistoNMassBinsSub,HistoMassRangeSub[0],HistoMassRangeSub[1],HistoNPtBins,HistoPtRange[0],HistoPtRange[1]);
fHistoMotherLikeSignBackInvMassSubNDMPt[iCut]->GetXaxis()->SetTitle(Form("M_{#pi^{#pm} #pi^{#pm} %s} - M_{%s} (GeV/c^{2})",NameNDMLatex.Data(),NameNDMLatex.Data()));
fHistoMotherLikeSignBackInvMassSubNDMPt[iCut]->GetYaxis()->SetTitle("p_{T} (GeV/c)");
fHistoMotherLikeSignBackInvMassSubNDMPt[iCut]->Sumw2();
if(((AliConversionMesonCuts*)fMesonCutArray->At(iCut))->UseLikeSignMixing()){
fESDList[iCut]->Add(fHistoMotherLikeSignBackInvMassSubNDMPt[iCut]);
}
fHistoMotherInvMassFixedPzNDM[iCut] = new TH2F("ESD_InvMass_Mother_FixedPz_Neutral_Pt","ESD_Mother_InvMass_FixedPz_Neutral_Pt",HistoNMassBins,HistoMassRange[0],HistoMassRange[1],HistoNPtBins,HistoPtRange[0],HistoPtRange[1]);
fHistoMotherInvMassFixedPzNDM[iCut]->GetXaxis()->SetTitle(Form("M_{#pi^{+} #pi^{-} %s} (GeV/c^{2})",NameNDMLatex.Data()));
fHistoMotherInvMassFixedPzNDM[iCut]->GetYaxis()->SetTitle("p_{T} (GeV/c)");
fHistoMotherInvMassFixedPzNDM[iCut]->Sumw2();
fESDList[iCut]->Add(fHistoMotherInvMassFixedPzNDM[iCut]);
fHistoBackInvMassPtFixedPzNDM[iCut] = new TH2F("ESD_Background_InvMass_FixedPz_Neutral_Pt","ESD_Background_InvMass_FixedPz_Neutral_Pt",HistoNMassBins,HistoMassRange[0],HistoMassRange[1],HistoNPtBins,HistoPtRange[0],HistoPtRange[1]);
fHistoBackInvMassPtFixedPzNDM[iCut]->GetXaxis()->SetTitle(Form("M_{#pi^{+} #pi^{-} %s} (GeV/c^{2})",NameNDMLatex.Data()));
fHistoBackInvMassPtFixedPzNDM[iCut]->GetYaxis()->SetTitle("p_{T} (GeV/c)");
fHistoBackInvMassPtFixedPzNDM[iCut]->Sumw2();
if(!(((AliConversionMesonCuts*)fMesonCutArray->At(iCut))->UseLikeSignMixing()) && (((AliConversionMesonCuts*)fMesonCutArray->At(iCut))->DoBGCalculation())){
fESDList[iCut]->Add(fHistoBackInvMassPtFixedPzNDM[iCut]);
}
fHistoMotherLikeSignBackInvMassFixedPzNDMPt[iCut] = new TH2F("ESD_Background_LikeSign_InvMass_FixedPz_Neutral_Pt","ESD_Background_LikeSign_InvMass_FixedPz_Neutral_Pt",HistoNMassBins,HistoMassRange[0],HistoMassRange[1],HistoNPtBins,HistoPtRange[0],HistoPtRange[1]);
fHistoMotherLikeSignBackInvMassFixedPzNDMPt[iCut]->GetXaxis()->SetTitle(Form("M_{#pi^{#pm} #pi^{#pm} %s} (GeV/c^{2})",NameNDMLatex.Data()));
fHistoMotherLikeSignBackInvMassFixedPzNDMPt[iCut]->GetYaxis()->SetTitle("p_{T} (GeV/c)");
fHistoMotherLikeSignBackInvMassFixedPzNDMPt[iCut]->Sumw2();
if(((AliConversionMesonCuts*)fMesonCutArray->At(iCut))->UseLikeSignMixing()){
fESDList[iCut]->Add(fHistoMotherLikeSignBackInvMassFixedPzNDMPt[iCut]);
}
if(!fDoLightOutput){
fHistoAngleHNMesonPiPlPiMi[iCut] = new TH2F(Form("ESD_Mother_Angle%sNegPionsPosPions_Pt",NameNeutralMesonAnalyzed.Data()),Form("ESD_Mother_Angle%sNegPionsPosPions_Pt",NameNeutralMesonAnalyzed.Data()),HistoNPtBins,HistoPtRange[0],HistoPtRange[1],360,0,TMath::Pi());
fHistoAngleHNMesonPiPlPiMi[iCut]->GetXaxis()->SetTitle("p_{T} (GeV/c)");
fHistoAngleHNMesonPiPlPiMi[iCut]->GetYaxis()->SetTitle("#angle (meson,#pi^{+}#pi^{-})");
fHistoAngleHNMesonPiPlPiMi[iCut]->Sumw2();
fESDList[iCut]->Add(fHistoAngleHNMesonPiPlPiMi[iCut]);
fHistoAngleHNMesonPiMi[iCut] = new TH2F(Form("ESD_Mother_Angle%sNegPions_Pt",NameNeutralMesonAnalyzed.Data()),Form("ESD_Mother_Angle%sNegPions_Pt",NameNeutralMesonAnalyzed.Data()),HistoNPtBins,HistoPtRange[0],HistoPtRange[1],360,0,TMath::Pi());
fHistoAngleHNMesonPiMi[iCut]->GetXaxis()->SetTitle("p_{T} (GeV/c)");
fHistoAngleHNMesonPiMi[iCut]->GetYaxis()->SetTitle("#angle (meson,#pi^{-})");
fHistoAngleHNMesonPiMi[iCut]->Sumw2();
fESDList[iCut]->Add(fHistoAngleHNMesonPiMi[iCut]);
fHistoAngleHNMesonPiPl[iCut] = new TH2F(Form("ESD_Mother_Angle%sPosPions_Pt",NameNeutralMesonAnalyzed.Data()),Form("ESD_Mother_Angle%sPosPions_Pt",NameNeutralMesonAnalyzed.Data()),HistoNPtBins,HistoPtRange[0],HistoPtRange[1],360,0,TMath::Pi());
fHistoAngleHNMesonPiPl[iCut]->GetXaxis()->SetTitle("p_{T} (GeV/c)");
fHistoAngleHNMesonPiPl[iCut]->GetYaxis()->SetTitle("#angle (meson,#pi^{+})");
fHistoAngleHNMesonPiPl[iCut]->Sumw2();
fESDList[iCut]->Add(fHistoAngleHNMesonPiPl[iCut]);
fHistoAngleHNMesonNDM[iCut] = new TH2F(Form("ESD_Mother_Angle%s%s_Pt",NameNeutralMesonAnalyzed.Data(),NameNDM.Data()),Form("ESD_Mother_Angle%s%s_Pt",NameNeutralMesonAnalyzed.Data(),NameNDM.Data()),HistoNPtBins,HistoPtRange[0],HistoPtRange[1],360,0,TMath::Pi());
fHistoAngleHNMesonNDM[iCut]->GetXaxis()->SetTitle("p_{T} (GeV/c)");
fHistoAngleHNMesonNDM[iCut]->GetYaxis()->SetTitle(Form("#angle (meson,%s)",NameNDMLatex.Data()));
fHistoAngleHNMesonNDM[iCut]->Sumw2();
fESDList[iCut]->Add(fHistoAngleHNMesonNDM[iCut]);
fHistoAnglePiPlNDM[iCut] = new TH2F(Form("ESD_Mother_AnglePosPions%s_Pt",NameNDM.Data()),Form("ESD_Mother_AnglePosPions%s_Pt",NameNDM.Data()),HistoNPtBins,HistoPtRange[0],HistoPtRange[1],360,0,TMath::Pi());
fHistoAnglePiPlNDM[iCut]->GetXaxis()->SetTitle("p_{T} (GeV/c)");
fHistoAnglePiPlNDM[iCut]->GetYaxis()->SetTitle(Form("#angle (#pi^{+},%s)",NameNDMLatex.Data()));
fHistoAnglePiPlNDM[iCut]->Sumw2();
fESDList[iCut]->Add(fHistoAnglePiPlNDM[iCut]);
fHistoAnglePiPlPiMi[iCut] = new TH2F("ESD_Mother_AnglePosPionsNegPions_Pt","ESD_Mother_AnglePosPionsNegPions_Pt",HistoNPtBins,HistoPtRange[0],HistoPtRange[1],360,0,TMath::Pi());
fHistoAnglePiPlPiMi[iCut]->GetXaxis()->SetTitle("p_{T} (GeV/c)");
fHistoAnglePiPlPiMi[iCut]->GetYaxis()->SetTitle("#angle (#pi^{+},#pi^{-})");
fHistoAnglePiPlPiMi[iCut]->Sumw2();
fESDList[iCut]->Add(fHistoAnglePiPlPiMi[iCut]);
fHistoAngleNDMPiMi[iCut] = new TH2F(Form("ESD_Mother_Angle%sNegPions_Pt",NameNDM.Data()),Form("ESD_Mother_Angle%sNegPions_Pt",NameNDM.Data()),HistoNPtBins,HistoPtRange[0],HistoPtRange[1],360,0,TMath::Pi());
fHistoAngleNDMPiMi[iCut]->GetXaxis()->SetTitle("p_{T} (GeV/c)");
fHistoAngleNDMPiMi[iCut]->GetYaxis()->SetTitle(Form("#angle (%s,#pi^{-})",NameNDMLatex.Data()));
fHistoAngleNDMPiMi[iCut]->Sumw2();
fESDList[iCut]->Add(fHistoAngleNDMPiMi[iCut]);
fHistoAngleSum[iCut] = new TH2F("ESD_Mother_AngleSum_Pt","ESD_Mother_AngleSum_Pt",HistoNPtBins,HistoPtRange[0],HistoPtRange[1],720,0,2*TMath::Pi());
fHistoAngleSum[iCut]->GetXaxis()->SetTitle("p_{T} (GeV/c)");
fHistoAngleSum[iCut]->GetYaxis()->SetTitle("#sum #angle");
fHistoAngleSum[iCut]->Sumw2();
fESDList[iCut]->Add(fHistoAngleSum[iCut]);
}
if ( fDoMesonQA>0 && (!fDoLightOutput) ) {
TAxis *AxisAfter = fHistoPionTPCdEdxNSigma[iCut]->GetXaxis();
Int_t bins = AxisAfter->GetNbins();
Double_t from = AxisAfter->GetXmin();
Double_t to = AxisAfter->GetXmax();
Double_t *newBins = new Double_t[bins+1];
newBins[0] = from;
Double_t factor = TMath::Power(to/from, 1./bins);
for(Int_t i=1; i<=bins; ++i) newBins[i] = factor * newBins[i-1];
AxisAfter->Set(bins, newBins);
AxisAfter = fHistoPionTPCdEdx[iCut]->GetXaxis();
AxisAfter->Set(bins, newBins);
delete [] newBins;
}
fCutFolder[iCut]->Add(fESDList[iCut]);
}
if( fIsMC ){
// MC Histogramms
fMCList = new TList*[fnCuts];
// True Histogramms
fTrueList = new TList*[fnCuts];
if(!fDoLightOutput){
if (fNDMRecoMode < 2){
fHistoTrueConvGammaPt = new TH1F*[fnCuts];
fHistoDoubleCountTrueConvGammaRPt = new TH2F*[fnCuts];
fHistoTrueConvGammaFromNeutralMesonPt = new TH1F*[fnCuts];
}
if (fNDMRecoMode > 0){
fHistoTrueClusterGammaPt = new TH1F*[fnCuts];
fHistoTrueClusterGammaFromNeutralMesonPt = new TH1F*[fnCuts];
}
fHistoTruePosPionPt = new TH1F*[fnCuts];
fHistoTrueNegPionPt = new TH1F*[fnCuts];
fHistoTruePosPionFromNeutralMesonPt = new TH1F*[fnCuts];
fHistoTrueNegPionFromNeutralMesonPt = new TH1F*[fnCuts];
fHistoMCAllGammaPt = new TH1F*[fnCuts];
if (fNDMRecoMode < 2){
fHistoMCConvGammaPt = new TH1F*[fnCuts];
}
fHistoMCAllPosPionsPt = new TH1F*[fnCuts];
fHistoMCAllNegPionsPt = new TH1F*[fnCuts];
fHistoMCGammaFromNeutralMesonPt = new TH1F*[fnCuts];
fHistoMCPosPionsFromNeutralMesonPt = new TH1F*[fnCuts];
fHistoMCNegPionsFromNeutralMesonPt = new TH1F*[fnCuts];
if(fDoMesonQA > 0){
fHistoMCAllMesonPt = new TH1F*[fnCuts];
fHistoMCAllMesonEta = new TH1F*[fnCuts];
fHistoMCAllMesonPhi = new TH1F*[fnCuts];
fHistoMCMesonFromNeutralMesonPt = new TH1F*[fnCuts];
fHistoMCMesonFromNeutralMesonEta = new TH1F*[fnCuts];
fHistoMCMesonFromNeutralMesonPhi = new TH1F*[fnCuts];
fHistoMCAllPosPionsEta = new TH1F*[fnCuts];
fHistoMCAllPosPionsPhi = new TH1F*[fnCuts];
fHistoMCAllNegPionsEta = new TH1F*[fnCuts];
fHistoMCAllNegPionsPhi = new TH1F*[fnCuts];
fHistoMCPosPionsFromNeutralMesonEta = new TH1F*[fnCuts];
fHistoMCPosPionsFromNeutralMesonPhi = new TH1F*[fnCuts];
fHistoMCNegPionsFromNeutralMesonEta = new TH1F*[fnCuts];
fHistoMCNegPionsFromNeutralMesonPhi = new TH1F*[fnCuts];
fHistoMCHeavyAllPt = new TH1F*[fnCuts];
fHistoMCHeavyAllEta = new TH1F*[fnCuts];
fHistoMCHeavyAllPhi = new TH1F*[fnCuts];
fHistoMCHeavyChannelPt = new TH1F*[fnCuts];
fHistoMCHeavyChannelEta = new TH1F*[fnCuts];
fHistoMCHeavyChannelPhi = new TH1F*[fnCuts];
fHistMCChannelNDMFromHeavyPt = new TH1F*[fnCuts];
fHistMCChannelNDMFromHeavyEta = new TH1F*[fnCuts];
fHistMCChannelNDMFromHeavyPhi = new TH1F*[fnCuts];
fHistMCChannelPiPlusFromHeavyPt = new TH1F*[fnCuts];
fHistMCChannelPiPlusFromHeavyEta = new TH1F*[fnCuts];
fHistMCChannelPiPlusFromHeavyPhi = new TH1F*[fnCuts];
fHistMCChannelPiMinusFromHeavyPt = new TH1F*[fnCuts];
fHistMCChannelPiMinusFromHeavyEta = new TH1F*[fnCuts];
fHistMCChannelPiPMinusFromHeavyPhi = new TH1F*[fnCuts];
fHistMCChannelNDMPtHeavyPt = new TH2F*[fnCuts];
fHistMCChannelPiPlusPtHeavyPt = new TH2F*[fnCuts];
fHistMCChannelPiMinusPtHeavyPt = new TH2F*[fnCuts];
fHistoMCHeavyReconstructiblePt = new TH1F*[fnCuts];
fHistoMCHeavyReconstructibleEta = new TH1F*[fnCuts];
fHistoMCHeavyReconstructiblePhi = new TH1F*[fnCuts];
fHistMCReconstructibleNDMFromHeavyPt = new TH1F*[fnCuts];
fHistMCReconstructibleNDMFromHeavyEta = new TH1F*[fnCuts];
fHistMCReconstructibleNDMFromHeavyPhi = new TH1F*[fnCuts];
fHistMCReconstructiblePiPlusFromHeavyPt = new TH1F*[fnCuts];
fHistMCReconstructiblePiPlusFromHeavyEta = new TH1F*[fnCuts];
fHistMCReconstructiblePiPlusFromHeavyPhi = new TH1F*[fnCuts];
fHistMCReconstructiblePiMinusFromHeavyPt = new TH1F*[fnCuts];
fHistMCReconstructiblePiMinusFromHeavyEta = new TH1F*[fnCuts];
fHistMCReconstructiblePiPMinusFromHeavyPhi = new TH1F*[fnCuts];
fHistMCReconstructibleNDMPtHeavyPt = new TH2F*[fnCuts];
fHistMCReconstructiblePiPlusPtHeavyPt = new TH2F*[fnCuts];
fHistMCReconstructiblePiMinusPtHeavyPt = new TH2F*[fnCuts];
}
}
fHistoMCHNMPiPlPiMiNDMPt = new TH1F*[fnCuts];
fHistoMCHNMPiPlPiMiNDMInAccPt = new TH1F*[fnCuts];
if(!fDoLightOutput){
fHistoMCHNMInAccVsNDMPt = new TH2F*[fnCuts];
fHistoMCHNMPiPlPiMiNDMEta = new TH1F*[fnCuts];
fHistoMCHNMPiPlPiMiNDMPhi = new TH1F*[fnCuts];
fHistoDoubleCountTruePi0InvMassPt = new TH2F*[fnCuts];
fHistoDoubleCountTrueHNMInvMassPt = new TH2F*[fnCuts];
}
fHistoTrueMotherPiPlPiMiNDMInvMassPt = new TH2F*[fnCuts];
fHistoTrueMotherPiPlPiMiNDMInvMassPtSubNDM = new TH2F*[fnCuts];
fHistoTrueMotherPiPlPiMiNDMInvMassPtFixedPzNDM = new TH2F*[fnCuts];
fHistoTrueMotherPiPlPiMiNDMInvMassPt_FromDifferent = new TH2F*[fnCuts];
fHistoTruePiPlPiMiNDMCombinatoricalInvMassPt = new TH2F*[fnCuts];
fHistoTruePiPlPiMiNDMContaminationInvMassPt = new TH2F*[fnCuts];
if(!fDoLightOutput){
fHistoTrueMotherGammaGammaInvMassPt = new TH2F*[fnCuts];
fHistoTrueMotherGammaGammaFromHNMInvMassPt = new TH2F*[fnCuts];
fHistoTrueAngleSum = new TH2F*[fnCuts];
fHistoTrueHNMesonPtvsNDMPt = new TH2F*[fnCuts];
}
if(!fDoLightOutput){
if (fDoMesonQA>0){
fHistoTruePionPionInvMassPt = new TH2F*[fnCuts];
fHistoTruePionPionFromSameMotherInvMassPt = new TH2F*[fnCuts];
fHistoTruePionPionFromHNMInvMassPt = new TH2F*[fnCuts];
fHistoTrueMesonFlags = new TH1F*[fnCuts];
fHistoTrueMotherPiPlPiMiNDMInvMassPt_FromEtaOmega = new TH2F*[fnCuts];
fHistoTrueMotherPiPlPiMiNDMInvMassPt_FromRho = new TH2F*[fnCuts];
fHistoTrueMotherPiPlPiMiNDMInvMassPt_FromK0s = new TH2F*[fnCuts];
fHistoTrueMotherPiPlPiMiNDMInvMassPt_FromK0l = new TH2F*[fnCuts];
fHistoTrueMotherPiPlPiMiNDMInvMassPt_FromEtaPrime = new TH2F*[fnCuts];
fHistoTrueMotherPiPlPiMiNDMInvMassPt_FromOther = new TH2F*[fnCuts];
fHistoTruePiPlPiMiSameMotherFromEtaInvMassPt = new TH2F*[fnCuts];
fHistoTruePiPlPiMiSameMotherFromOmegaInvMassPt = new TH2F*[fnCuts];
fHistoTruePiPlPiMiSameMotherFromRhoInvMassPt = new TH2F*[fnCuts];
fHistoTruePiPlPiMiSameMotherFromEtaPrimeInvMassPt = new TH2F*[fnCuts];
fHistoTruePiPlPiMiSameMotherFromK0sInvMassPt = new TH2F*[fnCuts];
fHistoTruePiPlPiMiSameMotherFromK0lInvMassPt = new TH2F*[fnCuts];
fHistoTruePiPlPiMiSameMotherFromOtherlInvMassPt = new TH2F*[fnCuts];
fHistoTruePiMiPiZeroSameMotherFromEtaInvMassPt = new TH2F*[fnCuts];
fHistoTruePiMiPiZeroSameMotherFromOmegaInvMassPt = new TH2F*[fnCuts];
fHistoTruePiMiPiZeroSameMotherFromRhoInvMassPt = new TH2F*[fnCuts];
fHistoTruePiMiPiZeroSameMotherFromK0lInvMassPt = new TH2F*[fnCuts];
fHistoTruePiMiPiZeroSameMotherFromOtherlInvMassPt = new TH2F*[fnCuts];
fHistoTruePiPlPiZeroSameMotherFromEtaInvMassPt = new TH2F*[fnCuts];
fHistoTruePiPlPiZeroSameMotherFromOmegaInvMassPt = new TH2F*[fnCuts];
fHistoTruePiPlPiZeroSameMotherFromRhoInvMassPt = new TH2F*[fnCuts];
fHistoTruePiPlPiZeroSameMotherFromK0lInvMassPt = new TH2F*[fnCuts];
fHistoTruePiPlPiZeroSameMotherFromOtherInvMassPt = new TH2F*[fnCuts];
fHistoTruePiPlPiMiNDMPureCombinatoricalInvMassPt = new TH2F*[fnCuts];
fHistoTruePiPlPiMiNDMContamination_Pi0_InvMassPt = new TH2F*[fnCuts];
fHistoTruePiPlPiMiNDMContamination_PiPl_InvMassPt = new TH2F*[fnCuts];
fHistoTruePiPlPiMiNDMContamination_PiMi_InvMassPt = new TH2F*[fnCuts];
fHistoTruePiPlPiMiNDMContamination_Crosscheck_InvMassPt = new TH2F*[fnCuts];
fHistoTruePiPlPiMiNDMContamination_multipel_InvMassPt = new TH2F*[fnCuts];
//Dalitz All Pt
if (enableDalitzAllPt){
fHistoTrueMotherPiPlPiMiNDMDalitzPlotPosFixedPzNDM = new TH2F*[fnCuts];
fHistoTrueMotherPiPlPiMiNDMDalitzPlotNegFixedPzNDM = new TH2F*[fnCuts];
fHistoTrueMotherPiPlPiMiNDMDalitzPlotPosSubNDM = new TH2F*[fnCuts];
fHistoTrueMotherPiPlPiMiNDMDalitzPlotNegSubNDM = new TH2F*[fnCuts];
}
//Dalitz Low Pt
if (enableDalitzLowPt){
fHistoTrueMotherPiPlPiMiNDMDalitzPlotPosFixedPzNDM_LowPt = new TH2F*[fnCuts];
fHistoTrueMotherPiPlPiMiNDMDalitzPlotNegFixedPzNDM_LowPt = new TH2F*[fnCuts];
fHistoTrueMotherPiPlPiMiNDMDalitzPlotPosSubNDM_LowPt = new TH2F*[fnCuts];
fHistoTrueMotherPiPlPiMiNDMDalitzPlotNegSubNDM_LowPt = new TH2F*[fnCuts];
}
//Dalitz Mid Pt
if (enableDalitzMidPt){
fHistoTrueMotherPiPlPiMiNDMDalitzPlotPosFixedPzNDM_MidPt = new TH2F*[fnCuts];
fHistoTrueMotherPiPlPiMiNDMDalitzPlotNegFixedPzNDM_MidPt = new TH2F*[fnCuts];
fHistoTrueMotherPiPlPiMiNDMDalitzPlotPosSubNDM_MidPt = new TH2F*[fnCuts];
fHistoTrueMotherPiPlPiMiNDMDalitzPlotNegSubNDM_MidPt = new TH2F*[fnCuts];
}
if (enableDalitzHighPt){
//Dalitz High Pt
fHistoTrueMotherPiPlPiMiNDMDalitzPlotPosFixedPzNDM_HighPt = new TH2F*[fnCuts];
fHistoTrueMotherPiPlPiMiNDMDalitzPlotNegFixedPzNDM_HighPt = new TH2F*[fnCuts];
fHistoTrueMotherPiPlPiMiNDMDalitzPlotPosSubNDM_HighPt = new TH2F*[fnCuts];
fHistoTrueMotherPiPlPiMiNDMDalitzPlotNegSubNDM_HighPt = new TH2F*[fnCuts];
}
fHistoTruevParticleChi2PerNDF = new TH1F*[fnCuts];
fHistoTruevParticleFromSameMotherChi2PerNDF = new TH1F*[fnCuts];
fHistoTruevParticleFromHNMChi2PerNDF = new TH1F*[fnCuts];
fHistoTruevParticledS = new TH1F*[fnCuts];
fHistoTruevParticleFromSameMotherdS = new TH1F*[fnCuts];
fHistoTruevParticleFromHNMdS = new TH1F*[fnCuts];
if (fDoMesonQA>1){
fTrueTreeList = new TList*[fnCuts];
fTreePiPiSameMother = new TTree*[fnCuts];
fTreePiPiPiSameMother = new TTree*[fnCuts];
fTreeEventInfoHNM = new TTree*[fnCuts];
}
}
}
for(Int_t iCut = 0; iCut<fnCuts;iCut++){
TString cutstringEvent = ((AliConvEventCuts*)fEventCutArray->At(iCut))->GetCutNumber();
TString cutstringPion = ((AliPrimaryPionCuts*)fPionCutArray->At(iCut))->GetCutNumber();
TString cutstringConvGamma = "";
if (fNDMRecoMode < 2)
cutstringConvGamma = ((AliConversionPhotonCuts*)fGammaCutArray->At(iCut))->GetCutNumber();
TString cutstringCaloGamma = "";
if (fNDMRecoMode > 0)
cutstringCaloGamma = ((AliCaloPhotonCuts*)fClusterCutArray->At(iCut))->GetCutNumber();
TString cutstringNeutralPion = ((AliConversionMesonCuts*)fNeutralDecayMesonCutArray->At(iCut))->GetCutNumber();
TString cutstringMeson = ((AliConversionMesonCuts*)fMesonCutArray->At(iCut))->GetCutNumber();
TString fullCutString = "";
if (fNDMRecoMode == 0)
fullCutString = Form("%i_%s_%s_%s_%s_%s",fNDMRecoMode,cutstringEvent.Data(),cutstringConvGamma.Data(),cutstringNeutralPion.Data(), cutstringPion.Data(),
cutstringMeson.Data());
else if (fNDMRecoMode == 1)
fullCutString = Form("%i_%s_%s_%s_%s_%s_%s",fNDMRecoMode,cutstringEvent.Data(),cutstringConvGamma.Data(),cutstringCaloGamma.Data(), cutstringNeutralPion.Data(),
cutstringPion.Data(), cutstringMeson.Data());
else if (fNDMRecoMode == 2)
fullCutString = Form("%i_%s_%s_%s_%s_%s",fNDMRecoMode,cutstringEvent.Data(), cutstringCaloGamma.Data(), cutstringNeutralPion.Data(), cutstringPion.Data(),
cutstringMeson.Data());
TString nameMCList = Form("%s MC histograms", fullCutString.Data());
TString nameTrueRecList = Form("%s True histograms", fullCutString.Data());
TString nameTrueRecTTreeList = Form("%s True TTrees", fullCutString.Data());
fMCList[iCut] = new TList();
fMCList[iCut]->SetName(nameMCList.Data());
fMCList[iCut]->SetOwner(kTRUE);
fCutFolder[iCut]->Add(fMCList[iCut]);
if(!fDoLightOutput){
fHistoMCAllGammaPt[iCut] = new TH1F("MC_AllGamma_Pt","MC_AllGamma_Pt",HistoNPtBins,HistoPtRange[0],HistoPtRange[1]);
fHistoMCAllGammaPt[iCut]->GetXaxis()->SetTitle("p_{T} (GeV/c)");
fHistoMCAllGammaPt[iCut]->GetYaxis()->SetTitle("N_{#gamma}");
fHistoMCAllGammaPt[iCut]->Sumw2();
fMCList[iCut]->Add(fHistoMCAllGammaPt[iCut]);
if (fNDMRecoMode < 2){
fHistoMCConvGammaPt[iCut] = new TH1F("MC_ConvGamma_Pt","MC_ConvGamma_Pt",HistoNPtBins,HistoPtRange[0],HistoPtRange[1]);
fHistoMCConvGammaPt[iCut]->GetXaxis()->SetTitle("p_{T} (GeV/c)");
fHistoMCConvGammaPt[iCut]->GetYaxis()->SetTitle("N_{#gamma,conv}");
fHistoMCConvGammaPt[iCut]->Sumw2();
fMCList[iCut]->Add(fHistoMCConvGammaPt[iCut]);
}
fHistoMCGammaFromNeutralMesonPt[iCut] = new TH1F("MC_GammaFromNeutralMeson_Pt","MC_GammaFromNeutralMeson_Pt",HistoNPtBins,HistoPtRange[0],HistoPtRange[1]);
fHistoMCGammaFromNeutralMesonPt[iCut]->GetXaxis()->SetTitle("p_{T} (GeV/c)");
fHistoMCGammaFromNeutralMesonPt[iCut]->GetYaxis()->SetTitle("N_{#gamma}");
fHistoMCGammaFromNeutralMesonPt[iCut]->Sumw2();
fMCList[iCut]->Add(fHistoMCGammaFromNeutralMesonPt[iCut]);
fHistoMCAllPosPionsPt[iCut] = new TH1F("MC_AllPosPions_Pt","MC_AllPosPions_Pt",HistoNPtBins,HistoPtRange[0],HistoPtRange[1]);
fHistoMCAllPosPionsPt[iCut]->GetXaxis()->SetTitle("p_{T} (GeV/c)");
fHistoMCAllPosPionsPt[iCut]->GetYaxis()->SetTitle("N_{#pi^{+}}");
fHistoMCAllPosPionsPt[iCut]->Sumw2();
fMCList[iCut]->Add(fHistoMCAllPosPionsPt[iCut]);
fHistoMCAllNegPionsPt[iCut] = new TH1F("MC_AllNegPions_Pt","MC_AllNegPions_Pt",HistoNPtBins,HistoPtRange[0],HistoPtRange[1]);
fHistoMCAllNegPionsPt[iCut]->GetXaxis()->SetTitle("p_{T} (GeV/c)");
fHistoMCAllNegPionsPt[iCut]->GetYaxis()->SetTitle("N_{#pi^{-}}");
fHistoMCAllNegPionsPt[iCut]->Sumw2();
fMCList[iCut]->Add(fHistoMCAllNegPionsPt[iCut]);
fHistoMCNegPionsFromNeutralMesonPt[iCut] = new TH1F("MC_NegPionsFromNeutralMeson_Pt","MC_NegPionsFromNeutralMeson_Pt",HistoNPtBins,HistoPtRange[0],HistoPtRange[1]);
fHistoMCNegPionsFromNeutralMesonPt[iCut]->GetXaxis()->SetTitle("p_{T} (GeV/c)");
fHistoMCNegPionsFromNeutralMesonPt[iCut]->GetYaxis()->SetTitle("N_{#pi^{-}}");
fHistoMCNegPionsFromNeutralMesonPt[iCut]->Sumw2();
fMCList[iCut]->Add(fHistoMCNegPionsFromNeutralMesonPt[iCut]);
fHistoMCPosPionsFromNeutralMesonPt[iCut] = new TH1F("MC_PosPionsFromNeutralMeson_Pt","MC_PosPionsFromNeutralMeson_Pt",HistoNPtBins,HistoPtRange[0],HistoPtRange[1]);
fHistoMCPosPionsFromNeutralMesonPt[iCut]->GetXaxis()->SetTitle("p_{T} (GeV/c)");
fHistoMCPosPionsFromNeutralMesonPt[iCut]->GetYaxis()->SetTitle("N_{#pi^{+}}");
fHistoMCPosPionsFromNeutralMesonPt[iCut]->Sumw2();
fMCList[iCut]->Add(fHistoMCPosPionsFromNeutralMesonPt[iCut]);
if (fDoMesonQA>0){
fHistoMCAllMesonPt[iCut] = new TH1F("MC_AllNDM_Pt", "MC_AllNDM_Pt", HistoNPtBins, HistoPtRange[0], HistoPtRange[1]);
fHistoMCAllMesonPt[iCut]->GetXaxis()->SetTitle("p_{T} (GeV/c)");
fHistoMCAllMesonPt[iCut]->GetYaxis()->SetTitle(Form("N_{%s}}", NameNDMLatex.Data()));
fHistoMCAllMesonPt[iCut]->Sumw2();
fMCList[iCut]->Add(fHistoMCAllMesonPt[iCut]);
fHistoMCAllMesonEta[iCut] = new TH1F("MC_AllNDM_Eta", "MC_AllNDM_Eta", 200, -2, 2);
fHistoMCAllMesonEta[iCut]->GetXaxis()->SetTitle("#eta");
fHistoMCAllMesonEta[iCut]->GetYaxis()->SetTitle(Form("N_{%s}}", NameNDMLatex.Data()));
fHistoMCAllMesonEta[iCut]->Sumw2();
fMCList[iCut]->Add(fHistoMCAllMesonEta[iCut]);
fHistoMCAllMesonPhi[iCut] = new TH1F("MC_AllNDM_Phi", "MC_AllNDM_Phi", 200, 0, TMath::TwoPi());
fHistoMCAllMesonPhi[iCut]->GetXaxis()->SetTitle("#varphi");
fHistoMCAllMesonPhi[iCut]->GetYaxis()->SetTitle(Form("N_{%s}}", NameNDMLatex.Data()));
fHistoMCAllMesonPhi[iCut]->Sumw2();
fMCList[iCut]->Add(fHistoMCAllMesonPhi[iCut]);
fHistoMCMesonFromNeutralMesonPt[iCut] = new TH1F("MC_NDMFromNeutralMeson_Pt", "MC_NDMFormNeutralMeson_Pt", HistoNPtBins, HistoPtRange[0], HistoPtRange[1]);
fHistoMCMesonFromNeutralMesonPt[iCut]->GetXaxis()->SetTitle("p_{T} (GeV/c)");
fHistoMCMesonFromNeutralMesonPt[iCut]->GetYaxis()->SetTitle(Form("N_{%s}}", NameNDMLatex.Data()));
fHistoMCMesonFromNeutralMesonPt[iCut]->Sumw2();
fMCList[iCut]->Add(fHistoMCMesonFromNeutralMesonPt[iCut]);
fHistoMCMesonFromNeutralMesonEta[iCut] = new TH1F("MC_NDMFromNeutralMeson_Eta", "MC_NDMFromNeutralMeson_Eta", 200, -2, 2);
fHistoMCMesonFromNeutralMesonEta[iCut]->GetXaxis()->SetTitle("#eta");
fHistoMCMesonFromNeutralMesonEta[iCut]->GetYaxis()->SetTitle(Form("N_{%s}}", NameNDMLatex.Data()));
fHistoMCMesonFromNeutralMesonEta[iCut]->Sumw2();
fMCList[iCut]->Add(fHistoMCMesonFromNeutralMesonEta[iCut]);
fHistoMCMesonFromNeutralMesonPhi[iCut] = new TH1F("MC_NDMFromNeutralMeson_Phi", "MC_NDMFromNeutralMeson_Phi", 200, 0, TMath::TwoPi());
fHistoMCMesonFromNeutralMesonPhi[iCut]->GetXaxis()->SetTitle("#varphi");
fHistoMCMesonFromNeutralMesonPhi[iCut]->GetYaxis()->SetTitle(Form("N_{%s}}", NameNDMLatex.Data()));
fHistoMCMesonFromNeutralMesonPhi[iCut]->Sumw2();
fMCList[iCut]->Add(fHistoMCMesonFromNeutralMesonPhi[iCut]);
fHistoMCAllPosPionsEta[iCut] = new TH1F("MC_AllPosPions_Eta","MC_AllPosPions_Eta", 200, -2., 2.);
fHistoMCAllPosPionsEta[iCut]->GetXaxis()->SetTitle("#eta");
fHistoMCAllPosPionsEta[iCut]->GetYaxis()->SetTitle("N_{#pi^{+}}");
fHistoMCAllPosPionsEta[iCut]->Sumw2();
fMCList[iCut]->Add(fHistoMCAllPosPionsEta[iCut]);
fHistoMCAllPosPionsPhi[iCut] = new TH1F("MC_AllPosPions_Phi","MC_AllPosPions_Phi", 200, 0., TMath::TwoPi());
fHistoMCAllPosPionsPhi[iCut]->GetXaxis()->SetTitle("#phi");
fHistoMCAllPosPionsPhi[iCut]->GetYaxis()->SetTitle("N_{#pi^{+}}");
fHistoMCAllPosPionsPhi[iCut]->Sumw2();
fMCList[iCut]->Add(fHistoMCAllPosPionsPhi[iCut]);
fHistoMCAllNegPionsEta[iCut] = new TH1F("MC_AllNegPions_Eta","MC_AllNegPions_Eta", 200, -2., 2.);
fHistoMCAllNegPionsEta[iCut]->GetXaxis()->SetTitle("#eta");
fHistoMCAllNegPionsEta[iCut]->GetYaxis()->SetTitle("N_{#pi^{-}}");
fHistoMCAllNegPionsEta[iCut]->Sumw2();
fMCList[iCut]->Add(fHistoMCAllNegPionsEta[iCut]);
fHistoMCAllNegPionsPhi[iCut] = new TH1F("MC_AllNegPions_Phi","MC_AllNegPions_Phi", 200, 0., TMath::TwoPi());
fHistoMCAllNegPionsPhi[iCut]->GetXaxis()->SetTitle("#phi");
fHistoMCAllNegPionsPhi[iCut]->GetYaxis()->SetTitle("N_{#pi^{-}}");
fHistoMCAllNegPionsPhi[iCut]->Sumw2();
fMCList[iCut]->Add(fHistoMCAllNegPionsPhi[iCut]);
fHistoMCPosPionsFromNeutralMesonEta[iCut] = new TH1F("MC_PosPionsFromNeutralMeson_Eta","MC_PosPionsFromNeutralMeson_Eta", 200, -2., 2.);
fHistoMCPosPionsFromNeutralMesonEta[iCut]->GetXaxis()->SetTitle("#eta");
fHistoMCPosPionsFromNeutralMesonEta[iCut]->GetYaxis()->SetTitle("N_{#pi^{+}}");
fHistoMCPosPionsFromNeutralMesonEta[iCut]->Sumw2();
fMCList[iCut]->Add(fHistoMCPosPionsFromNeutralMesonEta[iCut]);
fHistoMCPosPionsFromNeutralMesonPhi[iCut] = new TH1F("MC_PosPionsFromNeutralMeson_Phi","MC_PosPionsFromNeutralMeson_Phi", 200, 0., TMath::TwoPi());
fHistoMCPosPionsFromNeutralMesonPhi[iCut]->GetXaxis()->SetTitle("#phi");
fHistoMCPosPionsFromNeutralMesonPhi[iCut]->GetYaxis()->SetTitle("N_{#pi^{+}}");
fHistoMCPosPionsFromNeutralMesonPhi[iCut]->Sumw2();
fMCList[iCut]->Add(fHistoMCPosPionsFromNeutralMesonPhi[iCut]);
fHistoMCNegPionsFromNeutralMesonEta[iCut] = new TH1F("MC_NegPionsFromNeutralMeson_Eta","MC_NegPionsFromNeutralMeson_Eta", 200, -2., 2.);
fHistoMCNegPionsFromNeutralMesonEta[iCut]->GetXaxis()->SetTitle("#eta");
fHistoMCNegPionsFromNeutralMesonEta[iCut]->GetYaxis()->SetTitle("N_{#pi^{-}}");
fHistoMCNegPionsFromNeutralMesonEta[iCut]->Sumw2();
fMCList[iCut]->Add(fHistoMCNegPionsFromNeutralMesonEta[iCut]);
fHistoMCNegPionsFromNeutralMesonPhi[iCut] = new TH1F("MC_NegPionsFromNeutralMeson_Phi","MC_NegPionsFromNeutralMeson_Phi", 200, 0., TMath::TwoPi());
fHistoMCNegPionsFromNeutralMesonPhi[iCut]->GetXaxis()->SetTitle("#phi");
fHistoMCNegPionsFromNeutralMesonPhi[iCut]->GetYaxis()->SetTitle("N_{#pi^{-}}");
fHistoMCNegPionsFromNeutralMesonPhi[iCut]->Sumw2();
fMCList[iCut]->Add(fHistoMCNegPionsFromNeutralMesonPhi[iCut]);
fHistoMCHeavyAllPt[iCut] = new TH1F("MC_HeavyAll_Pt", "MC_HeavyAll_Pt", HistoNPtBins, HistoPtRange[0], HistoPtRange[1]);
fHistoMCHeavyAllPt[iCut]->SetXTitle("p_{t} (GeV/c)");
fHistoMCHeavyAllPt[iCut]->SetYTitle(Form("N_{%s}", NameNeutralMesonAnalyzedLatex.Data()));
fHistoMCHeavyAllPt[iCut]->Sumw2();
fMCList[iCut]->Add(fHistoMCHeavyAllPt[iCut]);
fHistoMCHeavyAllEta[iCut] = new TH1F("MC_HeavyAll_Eta", "MC_HeavyAll_Eta", 200, -2., 2.);
fHistoMCHeavyAllEta[iCut]->SetXTitle("#eta");
fHistoMCHeavyAllEta[iCut]->SetYTitle(Form("N_{%s}", NameNeutralMesonAnalyzedLatex.Data()));
fHistoMCHeavyAllEta[iCut]->Sumw2();
fMCList[iCut]->Add(fHistoMCHeavyAllEta[iCut]);
fHistoMCHeavyAllPhi[iCut] = new TH1F("MC_HeavyAll_Phi", "MC_HeavyAll_Phi", 200, 0., TMath::TwoPi());
fHistoMCHeavyAllPhi[iCut]->SetXTitle("#phi{t} (GeV/c");
fHistoMCHeavyAllPhi[iCut]->SetYTitle(Form("N_{%s}", NameNeutralMesonAnalyzedLatex.Data()));
fHistoMCHeavyAllPhi[iCut]->Sumw2();
fMCList[iCut]->Add(fHistoMCHeavyAllPhi[iCut]);
fHistoMCHeavyChannelPt[iCut] = new TH1F("MC_HeavyChannel_Pt", "MC_HeavyChannel_Pt", HistoNPtBins, HistoPtRange[0], HistoPtRange[1]);
fHistoMCHeavyChannelPt[iCut]->SetXTitle("p_{t} (GeV/c)");
fHistoMCHeavyChannelPt[iCut]->SetYTitle(Form("N_{%s}", NameNeutralMesonAnalyzedLatex.Data()));
fHistoMCHeavyChannelPt[iCut]->Sumw2();
fMCList[iCut]->Add(fHistoMCHeavyChannelPt[iCut]);
fHistoMCHeavyChannelEta[iCut] = new TH1F("MC_HeavyChannel_Eta", "MC_HeavyChannel_Eta", 200, -2., 2.);
fHistoMCHeavyAllEta[iCut]->SetXTitle("#eta");
fHistoMCHeavyAllEta[iCut]->SetYTitle(Form("N_{%s}", NameNeutralMesonAnalyzedLatex.Data()));
fHistoMCHeavyAllEta[iCut]->Sumw2();
fMCList[iCut]->Add(fHistoMCHeavyChannelEta[iCut]);
fHistoMCHeavyChannelPhi[iCut] = new TH1F("MC_HeavyChannel_Phi", "MC_HeavyChannel_Phi", 200, 0., TMath::TwoPi());
fHistoMCHeavyChannelPhi[iCut]->SetXTitle("#phi{t} (GeV/c");
fHistoMCHeavyChannelPhi[iCut]->SetYTitle(Form("N_{%s}", NameNeutralMesonAnalyzedLatex.Data()));
fHistoMCHeavyChannelPhi[iCut]->Sumw2();
fMCList[iCut]->Add(fHistoMCHeavyChannelPhi[iCut]);
fHistMCChannelNDMFromHeavyPt[iCut] = new TH1F("MC_NDMFromHeavyChannel_Pt", "MC_NDMFromHeavyChannel_Pt", HistoNPtBins, HistoPtRange[0], HistoPtRange[1]);
fHistMCChannelNDMFromHeavyPt[iCut]->SetXTitle("p_{t} (GeV/c)");
fHistMCChannelNDMFromHeavyPt[iCut]->SetYTitle(Form("N_{%s}", NameNDMLatex.Data()));
fHistMCChannelNDMFromHeavyPt[iCut]->Sumw2();
fMCList[iCut]->Add(fHistMCChannelNDMFromHeavyPt[iCut]);
fHistMCChannelNDMFromHeavyEta[iCut] = new TH1F("MC_NDMFromHeavyChannel_Eta", "MC_NDMFromHeavyChannel_Eta", 200, -2., 2.);
fHistMCChannelNDMFromHeavyEta[iCut]->SetXTitle("#eta");
fHistMCChannelNDMFromHeavyEta[iCut]->SetYTitle(Form("N_{%s}", NameNDMLatex.Data()));
fHistMCChannelNDMFromHeavyEta[iCut]->Sumw2();
fMCList[iCut]->Add(fHistMCChannelNDMFromHeavyEta[iCut]);
fHistMCChannelNDMFromHeavyPhi[iCut] = new TH1F("MC_NDMFromHeavyChannel_Phi", "MC_NDMFromHeavyChannel_Phi", 200, 0., TMath::TwoPi());
fHistMCChannelNDMFromHeavyPhi[iCut]->SetXTitle("#phi");
fHistMCChannelNDMFromHeavyPhi[iCut]->SetYTitle(Form("N_{%s}", NameNDMLatex.Data()));
fHistMCChannelNDMFromHeavyPhi[iCut]->Sumw2();
fMCList[iCut]->Add(fHistMCChannelNDMFromHeavyPhi[iCut]);
fHistMCChannelPiPlusFromHeavyPt[iCut] = new TH1F("MC_PiPlusFromHeavyChannel_Pt", "MC_PiPlusFromHeavyChannel_Pt", HistoNPtBins, HistoPtRange[0], HistoPtRange[1]);
fHistMCChannelPiPlusFromHeavyPt[iCut]->SetXTitle("p_{t} (GeV/c)");
fHistMCChannelPiPlusFromHeavyPt[iCut]->SetYTitle("N_{#pi^{+}}");
fHistMCChannelPiPlusFromHeavyPt[iCut]->Sumw2();
fMCList[iCut]->Add(fHistMCChannelPiPlusFromHeavyPt[iCut]);
fHistMCChannelPiPlusFromHeavyEta[iCut] = new TH1F("MC_PiPlusFromHeavyChannel_Eta", "MC_PiPlusFromHeavyChannel_Eta", 200, -2., 2.);
fHistMCChannelPiPlusFromHeavyEta[iCut]->SetXTitle("#eta");
fHistMCChannelPiPlusFromHeavyEta[iCut]->SetYTitle("N_{#pi^{+}}");
fHistMCChannelPiPlusFromHeavyEta[iCut]->Sumw2();
fMCList[iCut]->Add(fHistMCChannelPiPlusFromHeavyEta[iCut]);
fHistMCChannelPiPlusFromHeavyPhi[iCut] = new TH1F("MC_PiPlusFromHeavyChannel_Phi", "MC_PiPlusFromHeavyChannel_Phi", 200, 0., TMath::TwoPi());
fHistMCChannelPiPlusFromHeavyPhi[iCut]->SetXTitle("#phi");
fHistMCChannelPiPlusFromHeavyPhi[iCut]->SetYTitle("N_{#pi^{+}}");
fHistMCChannelPiPlusFromHeavyPhi[iCut]->Sumw2();
fMCList[iCut]->Add(fHistMCChannelPiPlusFromHeavyPhi[iCut]);
fHistMCChannelPiMinusFromHeavyPt[iCut] = new TH1F("MC_PiMinusFromHeavyChannel_Pt", "MC_PiMinusFromHeavyChannel_Pt", HistoNPtBins, HistoPtRange[0], HistoPtRange[1]);
fHistMCChannelPiMinusFromHeavyPt[iCut]->SetXTitle("p_{t} (GeV/c)");
fHistMCChannelPiMinusFromHeavyPt[iCut]->SetYTitle("N_{#pi^{-}}");
fHistMCChannelPiMinusFromHeavyPt[iCut]->Sumw2();
fMCList[iCut]->Add(fHistMCChannelPiMinusFromHeavyPt[iCut]);
fHistMCChannelPiMinusFromHeavyEta[iCut] = new TH1F("MC_PiMinusFromHeavyChannel_Eta", "MC_PiMinusFromHeavyChannel_Eta", 200, -2., 2.);
fHistMCChannelPiMinusFromHeavyEta[iCut]->SetXTitle("#eta");
fHistMCChannelPiMinusFromHeavyEta[iCut]->SetYTitle("N_{#pi^{-}}");
fHistMCChannelPiMinusFromHeavyEta[iCut]->Sumw2();
fMCList[iCut]->Add(fHistMCChannelPiMinusFromHeavyEta[iCut]);
fHistMCChannelPiPMinusFromHeavyPhi[iCut] = new TH1F("MC_PiMinusFromHeavyChannel_Phi", "MC_PiMinusFromHeavyChannel_Phi", 200, 0., TMath::TwoPi());
fHistMCChannelPiPMinusFromHeavyPhi[iCut]->SetXTitle("#phi");
fHistMCChannelPiPMinusFromHeavyPhi[iCut]->SetYTitle("N_{#pi^{-}}");
fHistMCChannelPiPMinusFromHeavyPhi[iCut]->Sumw2();
fMCList[iCut]->Add(fHistMCChannelPiPMinusFromHeavyPhi[iCut]);
fHistMCChannelNDMPtHeavyPt[iCut] = new TH2F("MC_CorrPtNDMHeavyChannel", "MC_CorrPtNDMHeavyChannel", HistoNPtBins, HistoPtRange[0], HistoPtRange[1], HistoNPtBins, HistoPtRange[0], HistoPtRange[1]);
fHistMCChannelNDMPtHeavyPt[iCut]->SetXTitle(Form("p_{t, %s} (GeV/c)", NameNeutralMesonAnalyzedLatex.Data()));
fHistMCChannelNDMPtHeavyPt[iCut]->SetYTitle(Form("p_{t, %s} (GeV/c)", NameNDMLatex.Data()));
fHistMCChannelNDMPtHeavyPt[iCut]->SetZTitle(Form("N_{%s}", NameNeutralMesonAnalyzedLatex.Data()));
fHistMCChannelNDMPtHeavyPt[iCut]->Sumw2();
fMCList[iCut]->Add(fHistMCChannelNDMPtHeavyPt[iCut]);
fHistMCChannelPiPlusPtHeavyPt[iCut] = new TH2F("MC_CorrPtPiPlusHeavyChannel", "MC_CorrPtPiPlusHeavyChannel", HistoNPtBins, HistoPtRange[0], HistoPtRange[1], HistoNPtBins, HistoPtRange[0], HistoPtRange[1]);
fHistMCChannelPiPlusPtHeavyPt[iCut]->SetXTitle(Form("p_{t, %s} (GeV/c)", NameNeutralMesonAnalyzedLatex.Data()));
fHistMCChannelPiPlusPtHeavyPt[iCut]->SetYTitle("p_{t, #pi^{-}%s} (GeV/c)");
fHistMCChannelPiPlusPtHeavyPt[iCut]->SetZTitle(Form("N_{%s}", NameNeutralMesonAnalyzedLatex.Data()));
fHistMCChannelPiPlusPtHeavyPt[iCut]->Sumw2();
fMCList[iCut]->Add(fHistMCChannelPiPlusPtHeavyPt[iCut]);
fHistMCChannelPiMinusPtHeavyPt[iCut] = new TH2F("MC_CorrPtPiMinusHeavyChannel", "MC_CorrPtPiMinusHeavyChannel", HistoNPtBins, HistoPtRange[0], HistoPtRange[1], HistoNPtBins, HistoPtRange[0], HistoPtRange[1]);
fHistMCChannelPiMinusPtHeavyPt[iCut]->SetXTitle(Form("p_{t, %s} (GeV/c)", NameNeutralMesonAnalyzedLatex.Data()));
fHistMCChannelPiMinusPtHeavyPt[iCut]->SetYTitle("p_{t, #pi^{-}%s} (GeV/c)");
fHistMCChannelPiMinusPtHeavyPt[iCut]->SetZTitle(Form("N_{%s}", NameNeutralMesonAnalyzedLatex.Data()));
fHistMCChannelPiMinusPtHeavyPt[iCut]->Sumw2();
fMCList[iCut]->Add(fHistMCChannelPiMinusPtHeavyPt[iCut]);
fHistoMCHeavyReconstructiblePt[iCut] = new TH1F("MC_HeavyReconstructible_Pt", "MC_HeavyReconstructible_Pt", HistoNPtBins, HistoPtRange[0], HistoPtRange[1]);
fHistoMCHeavyReconstructiblePt[iCut]->SetXTitle("p_{t} (GeV/c)");
fHistoMCHeavyReconstructiblePt[iCut]->SetYTitle(Form("N_{%s}", NameNeutralMesonAnalyzedLatex.Data()));
fHistoMCHeavyReconstructiblePt[iCut]->Sumw2();
fMCList[iCut]->Add(fHistoMCHeavyReconstructiblePt[iCut]);
fHistoMCHeavyReconstructibleEta[iCut] = new TH1F("MC_HeavyReconstructible_Eta", "MC_HeavyReconstructible_Eta", 200, -2., 2.);
fHistoMCHeavyAllEta[iCut]->SetXTitle("#eta");
fHistoMCHeavyAllEta[iCut]->SetYTitle(Form("N_{%s}", NameNeutralMesonAnalyzedLatex.Data()));
fHistoMCHeavyAllEta[iCut]->Sumw2();
fMCList[iCut]->Add(fHistoMCHeavyReconstructibleEta[iCut]);
fHistoMCHeavyReconstructiblePhi[iCut] = new TH1F("MC_HeavyReconstructible_Phi", "MC_HeavyReconstructible_Phi", 200, 0., TMath::TwoPi());
fHistoMCHeavyReconstructiblePhi[iCut]->SetXTitle("#phi{t} (GeV/c");
fHistoMCHeavyReconstructiblePhi[iCut]->SetYTitle(Form("N_{%s}", NameNeutralMesonAnalyzedLatex.Data()));
fHistoMCHeavyReconstructiblePhi[iCut]->Sumw2();
fMCList[iCut]->Add(fHistoMCHeavyReconstructiblePhi[iCut]);
fHistMCReconstructibleNDMFromHeavyPt[iCut] = new TH1F("MC_NDMFromHeavyReconstructible_Pt", "MC_NDMFromHeavyReconstructible_Pt", HistoNPtBins, HistoPtRange[0], HistoPtRange[1]);
fHistMCReconstructibleNDMFromHeavyPt[iCut]->SetXTitle("p_{t} (GeV/c)");
fHistMCReconstructibleNDMFromHeavyPt[iCut]->SetYTitle(Form("N_{%s}", NameNDMLatex.Data()));
fHistMCReconstructibleNDMFromHeavyPt[iCut]->Sumw2();
fMCList[iCut]->Add(fHistMCReconstructibleNDMFromHeavyPt[iCut]);
fHistMCReconstructibleNDMFromHeavyEta[iCut] = new TH1F("MC_NDMFromHeavyReconstructible_Eta", "MC_NDMFromHeavyReconstructible_Eta", 200, -2., 2.);
fHistMCReconstructibleNDMFromHeavyEta[iCut]->SetXTitle("#eta");
fHistMCReconstructibleNDMFromHeavyEta[iCut]->SetYTitle(Form("N_{%s}", NameNDMLatex.Data()));
fHistMCReconstructibleNDMFromHeavyEta[iCut]->Sumw2();
fMCList[iCut]->Add(fHistMCReconstructibleNDMFromHeavyEta[iCut]);
fHistMCReconstructibleNDMFromHeavyPhi[iCut] = new TH1F("MC_NDMFromHeavyReconstructible_Phi", "MC_NDMFromHeavyReconstructible_Phi", 200, 0., TMath::TwoPi());
fHistMCReconstructibleNDMFromHeavyPhi[iCut]->SetXTitle("#phi");
fHistMCReconstructibleNDMFromHeavyPhi[iCut]->SetYTitle(Form("N_{%s}", NameNDMLatex.Data()));
fHistMCReconstructibleNDMFromHeavyPhi[iCut]->Sumw2();
fMCList[iCut]->Add(fHistMCReconstructibleNDMFromHeavyPhi[iCut]);
fHistMCReconstructiblePiPlusFromHeavyPt[iCut] = new TH1F("MC_PiPlusFromHeavyReconstructible_Pt", "MC_PiPlusFromHeavyReconstructible_Pt", HistoNPtBins, HistoPtRange[0], HistoPtRange[1]);
fHistMCReconstructiblePiPlusFromHeavyPt[iCut]->SetXTitle("p_{t} (GeV/c)");
fHistMCReconstructiblePiPlusFromHeavyPt[iCut]->SetYTitle("N_{#pi^{+}}");
fHistMCReconstructiblePiPlusFromHeavyPt[iCut]->Sumw2();
fMCList[iCut]->Add(fHistMCReconstructiblePiPlusFromHeavyPt[iCut]);
fHistMCReconstructiblePiPlusFromHeavyEta[iCut] = new TH1F("MC_PiPlusFromHeavyReconstructible_Eta", "MC_PiPlusFromHeavyReconstructible_Eta", 200, -2., 2.);
fHistMCReconstructiblePiPlusFromHeavyEta[iCut]->SetXTitle("#eta");
fHistMCReconstructiblePiPlusFromHeavyEta[iCut]->SetYTitle("N_{#pi^{+}}");
fHistMCReconstructiblePiPlusFromHeavyEta[iCut]->Sumw2();
fMCList[iCut]->Add(fHistMCReconstructiblePiPlusFromHeavyEta[iCut]);
fHistMCReconstructiblePiPlusFromHeavyPhi[iCut] = new TH1F("MC_PiPlusFromHeavyReconstructible_Phi", "MC_PiPlusFromHeavyReconstructible_Phi", 200, 0., TMath::TwoPi());
fHistMCReconstructiblePiPlusFromHeavyPhi[iCut]->SetXTitle("#phi");
fHistMCReconstructiblePiPlusFromHeavyPhi[iCut]->SetYTitle("N_{#pi^{+}}");
fHistMCReconstructiblePiPlusFromHeavyPhi[iCut]->Sumw2();
fMCList[iCut]->Add(fHistMCReconstructiblePiPlusFromHeavyPhi[iCut]);
fHistMCReconstructiblePiMinusFromHeavyPt[iCut] = new TH1F("MC_PiMinusFromHeavyReconstructible_Pt", "MC_PiMinusFromHeavyReconstructible_Pt", HistoNPtBins, HistoPtRange[0], HistoPtRange[1]);
fHistMCReconstructiblePiMinusFromHeavyPt[iCut]->SetXTitle("p_{t} (GeV/c)");
fHistMCReconstructiblePiMinusFromHeavyPt[iCut]->SetYTitle("N_{#pi^{-}}");
fHistMCReconstructiblePiMinusFromHeavyPt[iCut]->Sumw2();
fMCList[iCut]->Add(fHistMCReconstructiblePiMinusFromHeavyPt[iCut]);
fHistMCReconstructiblePiMinusFromHeavyEta[iCut] = new TH1F("MC_PiMinusFromHeavyReconstructible_Eta", "MC_PiMinusFromHeavyReconstructible_Eta", 200, -2., 2.);
fHistMCReconstructiblePiMinusFromHeavyEta[iCut]->SetXTitle("#eta");
fHistMCReconstructiblePiMinusFromHeavyEta[iCut]->SetYTitle("N_{#pi^{-}}");
fHistMCReconstructiblePiMinusFromHeavyEta[iCut]->Sumw2();
fMCList[iCut]->Add(fHistMCReconstructiblePiMinusFromHeavyEta[iCut]);
fHistMCReconstructiblePiPMinusFromHeavyPhi[iCut] = new TH1F("MC_PiMinusFromHeavyReconstructible_Phi", "MC_PiMinusFromHeavyReconstructible_Phi", 200, 0., TMath::TwoPi());
fHistMCReconstructiblePiPMinusFromHeavyPhi[iCut]->SetXTitle("#phi");
fHistMCReconstructiblePiPMinusFromHeavyPhi[iCut]->SetYTitle("N_{#pi^{-}}");
fHistMCReconstructiblePiPMinusFromHeavyPhi[iCut]->Sumw2();
fMCList[iCut]->Add(fHistMCReconstructiblePiPMinusFromHeavyPhi[iCut]);
fHistMCReconstructibleNDMPtHeavyPt[iCut] = new TH2F("MC_CorrPtNDMHeavyReconstructible", "MC_CorrPtNDMHeavyReconstructible", HistoNPtBins, HistoPtRange[0], HistoPtRange[1], HistoNPtBins, HistoPtRange[0], HistoPtRange[1]);
fHistMCReconstructibleNDMPtHeavyPt[iCut]->SetXTitle(Form("p_{t, %s} (GeV/c)", NameNeutralMesonAnalyzedLatex.Data()));
fHistMCReconstructibleNDMPtHeavyPt[iCut]->SetYTitle(Form("p_{t, %s} (GeV/c)", NameNDMLatex.Data()));
fHistMCReconstructibleNDMPtHeavyPt[iCut]->SetZTitle(Form("N_{%s}", NameNeutralMesonAnalyzedLatex.Data()));
fHistMCReconstructibleNDMPtHeavyPt[iCut]->Sumw2();
fMCList[iCut]->Add(fHistMCReconstructibleNDMPtHeavyPt[iCut]);
fHistMCReconstructiblePiPlusPtHeavyPt[iCut] = new TH2F("MC_CorrPtPiPlusHeavyReconstructible", "MC_CorrPtPiPlusHeavyReconstructible", HistoNPtBins, HistoPtRange[0], HistoPtRange[1], HistoNPtBins, HistoPtRange[0], HistoPtRange[1]);
fHistMCReconstructiblePiPlusPtHeavyPt[iCut]->SetXTitle(Form("p_{t, %s} (GeV/c)", NameNeutralMesonAnalyzedLatex.Data()));
fHistMCReconstructiblePiPlusPtHeavyPt[iCut]->SetYTitle("p_{t, #pi^{-}%s} (GeV/c)");
fHistMCReconstructiblePiPlusPtHeavyPt[iCut]->SetZTitle(Form("N_{%s}", NameNeutralMesonAnalyzedLatex.Data()));
fHistMCReconstructiblePiPlusPtHeavyPt[iCut]->Sumw2();
fMCList[iCut]->Add(fHistMCReconstructiblePiPlusPtHeavyPt[iCut]);
fHistMCReconstructiblePiMinusPtHeavyPt[iCut] = new TH2F("MC_CorrPtPiMinusHeavyReconstructible", "MC_CorrPtPiMinusHeavyReconstructible", HistoNPtBins, HistoPtRange[0], HistoPtRange[1], HistoNPtBins, HistoPtRange[0], HistoPtRange[1]);
fHistMCReconstructiblePiMinusPtHeavyPt[iCut]->SetXTitle(Form("p_{t, %s} (GeV/c)", NameNeutralMesonAnalyzedLatex.Data()));
fHistMCReconstructiblePiMinusPtHeavyPt[iCut]->SetYTitle("p_{t, #pi^{-}%s} (GeV/c)");
fHistMCReconstructiblePiMinusPtHeavyPt[iCut]->SetZTitle(Form("N_{%s}", NameNeutralMesonAnalyzedLatex.Data()));
fHistMCReconstructiblePiMinusPtHeavyPt[iCut]->Sumw2();
fMCList[iCut]->Add(fHistMCReconstructiblePiMinusPtHeavyPt[iCut]);
}
}
fHistoMCHNMPiPlPiMiNDMPt[iCut] = new TH1F("MC_HNM_Pt","MC_HNM_Pt",HistoNPtBins,HistoPtRange[0],HistoPtRange[1]);
fHistoMCHNMPiPlPiMiNDMPt[iCut]->GetXaxis()->SetTitle("p_{T} (GeV/c)");
fHistoMCHNMPiPlPiMiNDMPt[iCut]->GetYaxis()->SetTitle("N_{HNM}");
fHistoMCHNMPiPlPiMiNDMPt[iCut]->Sumw2();
fMCList[iCut]->Add(fHistoMCHNMPiPlPiMiNDMPt[iCut]);
fHistoMCHNMPiPlPiMiNDMInAccPt[iCut] = new TH1F("MC_HNMInAcc_Pt","MC_HNMInAcc_Pt",HistoNPtBins,HistoPtRange[0],HistoPtRange[1]);
fHistoMCHNMPiPlPiMiNDMInAccPt[iCut]->GetXaxis()->SetTitle("p_{T} (GeV/c)");
fHistoMCHNMPiPlPiMiNDMInAccPt[iCut]->GetYaxis()->SetTitle("A #times N_{HNM}");
fHistoMCHNMPiPlPiMiNDMInAccPt[iCut]->Sumw2();
fMCList[iCut]->Add(fHistoMCHNMPiPlPiMiNDMInAccPt[iCut]);
if(!fDoLightOutput){
fHistoMCHNMInAccVsNDMPt[iCut] = new TH2F("MC_HNMInAccVsNDMPt","MC_HNMInAccVsNDMPt",200,HistoPtRange[0],HistoPtRange[1],200,HistoPtRange[0],HistoPtRange[1]);
fHistoMCHNMInAccVsNDMPt[iCut]->GetXaxis()->SetTitle("p_{T} of HNM (GeV/c)");
fHistoMCHNMInAccVsNDMPt[iCut]->GetYaxis()->SetTitle("p_{T} of NDM (GeV/c)");
fHistoMCHNMInAccVsNDMPt[iCut]->Sumw2();
fMCList[iCut]->Add(fHistoMCHNMInAccVsNDMPt[iCut]);
fHistoMCHNMPiPlPiMiNDMEta[iCut] = new TH1F("MC_HNM_Eta","MC_HNM_Eta",200,-2,2);
fHistoMCHNMPiPlPiMiNDMEta[iCut]->GetXaxis()->SetTitle("#eta");
fHistoMCHNMPiPlPiMiNDMEta[iCut]->GetYaxis()->SetTitle("N_{HNM}");
fHistoMCHNMPiPlPiMiNDMEta[iCut]->Sumw2();
fMCList[iCut]->Add(fHistoMCHNMPiPlPiMiNDMEta[iCut]);
fHistoMCHNMPiPlPiMiNDMPhi[iCut] = new TH1F("MC_HNM_Phi","MC_HNM_Phi",200,0,2 * TMath::Pi());
fHistoMCHNMPiPlPiMiNDMPhi[iCut]->GetXaxis()->SetTitle("#phi");
fHistoMCHNMPiPlPiMiNDMPhi[iCut]->GetYaxis()->SetTitle("N_{HNM}");
fHistoMCHNMPiPlPiMiNDMPhi[iCut]->Sumw2();
fMCList[iCut]->Add(fHistoMCHNMPiPlPiMiNDMPhi[iCut]);
}
fTrueList[iCut] = new TList();
fTrueList[iCut]->SetName(nameTrueRecList.Data());
fTrueList[iCut]->SetOwner(kTRUE);
fCutFolder[iCut]->Add(fTrueList[iCut]);
if(!fDoLightOutput){
if (fNDMRecoMode < 2){
fHistoTrueConvGammaPt[iCut] = new TH1F("ESD_TrueConvGamma_Pt","ESD_TrueConvGamma_Pt",HistoNPtBins,HistoPtRange[0],HistoPtRange[1]);
fHistoTrueConvGammaPt[iCut]->GetXaxis()->SetTitle("p_{T} (GeV/c)");
fHistoTrueConvGammaPt[iCut]->GetYaxis()->SetTitle("N_{#gamma,conv}");
fHistoTrueConvGammaPt[iCut]->Sumw2();
fTrueList[iCut]->Add(fHistoTrueConvGammaPt[iCut]);
fHistoDoubleCountTrueConvGammaRPt[iCut] = new TH2F("ESD_TrueDoubleCountConvGamma_R_Pt","ESD_TrueDoubleCountConvGamma_R_Pt",800,0,200,HistoNPtBins,HistoPtRange[0],HistoPtRange[1]);
fHistoDoubleCountTrueConvGammaRPt[iCut]->GetXaxis()->SetTitle("R_{conv} (cm)");
fHistoDoubleCountTrueConvGammaRPt[iCut]->GetYaxis()->SetTitle("p_{T} (GeV/c)");
fHistoDoubleCountTrueConvGammaRPt[iCut]->Sumw2();
fTrueList[iCut]->Add(fHistoDoubleCountTrueConvGammaRPt[iCut]);
fHistoTrueConvGammaFromNeutralMesonPt[iCut] = new TH1F("ESD_TrueConvGammaFromNeutralMeson_Pt","ESD_TrueConvGammaFromNeutralMeson_Pt",HistoNPtBins,HistoPtRange[0],HistoPtRange[1]);
fHistoTrueConvGammaFromNeutralMesonPt[iCut]->GetXaxis()->SetTitle("p_{T} (GeV/c)");
fHistoTrueConvGammaFromNeutralMesonPt[iCut]->GetYaxis()->SetTitle("N_{#gamma,conv}");
fHistoTrueConvGammaFromNeutralMesonPt[iCut]->Sumw2();
fTrueList[iCut]->Add(fHistoTrueConvGammaFromNeutralMesonPt[iCut]);
}
if (fNDMRecoMode > 0){
fHistoTrueClusterGammaPt[iCut] = new TH1F("ESD_TrueClusterGamma_Pt","ESD_TrueClusterGamma_Pt",HistoNPtBins,HistoPtRange[0],HistoPtRange[1]);
fHistoTrueClusterGammaPt[iCut]->GetXaxis()->SetTitle("p_{T} (GeV/c)");
fHistoTrueClusterGammaPt[iCut]->GetYaxis()->SetTitle("N_{#gamma,cluster}");
fHistoTrueClusterGammaPt[iCut]->Sumw2();
fTrueList[iCut]->Add(fHistoTrueClusterGammaPt[iCut]);
fHistoTrueClusterGammaFromNeutralMesonPt[iCut] = new TH1F("ESD_TrueClusterGammaFromNeutralMeson_Pt","ESD_TrueClusterGammaFromNeutralMeson_Pt",HistoNPtBins,HistoPtRange[0],HistoPtRange[1]);
fHistoTrueClusterGammaFromNeutralMesonPt[iCut]->GetXaxis()->SetTitle("p_{T} (GeV/c)");
fHistoTrueClusterGammaFromNeutralMesonPt[iCut]->GetYaxis()->SetTitle("N_{#gamma,cluster}");
fHistoTrueClusterGammaFromNeutralMesonPt[iCut]->Sumw2();
fTrueList[iCut]->Add(fHistoTrueClusterGammaFromNeutralMesonPt[iCut]);
}
fHistoTruePosPionPt[iCut] = new TH1F("ESD_TruePosPion_Pt","ESD_TruePosPion_Pt",HistoNPtBins,HistoPtRange[0],HistoPtRange[1]);
fHistoTruePosPionPt[iCut]->GetXaxis()->SetTitle("p_{T} (GeV/c)");
fHistoTruePosPionPt[iCut]->GetYaxis()->SetTitle("N_{#pi^{+}}");
fHistoTruePosPionPt[iCut]->Sumw2();
fTrueList[iCut]->Add(fHistoTruePosPionPt[iCut]);
fHistoTrueNegPionPt[iCut] = new TH1F("ESD_TrueNegPion_Pt","ESD_TrueNegPion_Pt",HistoNPtBins,HistoPtRange[0],HistoPtRange[1]);
fHistoTrueNegPionPt[iCut]->GetXaxis()->SetTitle("p_{T} (GeV/c)");
fHistoTrueNegPionPt[iCut]->GetYaxis()->SetTitle("N_{#pi^{-}}");
fHistoTrueNegPionPt[iCut]->Sumw2();
fTrueList[iCut]->Add(fHistoTrueNegPionPt[iCut]);
fHistoTrueNegPionFromNeutralMesonPt[iCut] = new TH1F("ESD_TrueNegPionFromNeutralMeson_Pt","ESD_TrueNegPionFromNeutralMeson_Pt",HistoNPtBins,HistoPtRange[0],HistoPtRange[1]);
fHistoTrueNegPionFromNeutralMesonPt[iCut]->GetXaxis()->SetTitle("p_{T} (GeV/c)");
fHistoTrueNegPionFromNeutralMesonPt[iCut]->GetYaxis()->SetTitle("N_{#pi^{-}}");
fHistoTrueNegPionFromNeutralMesonPt[iCut]->Sumw2();
fTrueList[iCut]->Add(fHistoTrueNegPionFromNeutralMesonPt[iCut]);
fHistoTruePosPionFromNeutralMesonPt[iCut] = new TH1F("ESD_TruePosPionFromNeutralMeson_Pt","ESD_TruePosPionFromNeutralMeson_Pt",HistoNPtBins,HistoPtRange[0],HistoPtRange[1]);
fHistoTruePosPionFromNeutralMesonPt[iCut]->GetXaxis()->SetTitle("p_{T} (GeV/c)");
fHistoTruePosPionFromNeutralMesonPt[iCut]->GetYaxis()->SetTitle("N_{#pi^{+}}");
fHistoTruePosPionFromNeutralMesonPt[iCut]->Sumw2();
fTrueList[iCut]->Add(fHistoTruePosPionFromNeutralMesonPt[iCut]);
fHistoDoubleCountTruePi0InvMassPt[iCut] = new TH2F("ESD_TrueDoubleCountPi0_InvMass_Pt","ESD_TrueDoubleCountPi0_InvMass_Pt",800,0,0.8,HistoNPtBins,HistoPtRange[0],HistoPtRange[1]);
fHistoDoubleCountTruePi0InvMassPt[iCut]->GetXaxis()->SetTitle("M_{#gamma #gamma} (GeV/c^{2})");
fHistoDoubleCountTruePi0InvMassPt[iCut]->GetYaxis()->SetTitle("p_{T} (GeV/c)");
fHistoDoubleCountTruePi0InvMassPt[iCut]->Sumw2();
fTrueList[iCut]->Add(fHistoDoubleCountTruePi0InvMassPt[iCut]);
fHistoDoubleCountTrueHNMInvMassPt[iCut] = new TH2F("ESD_TrueDoubleCountHNM_InvMass_Pt","ESD_TrueDoubleCountHNM_InvMass_Pt",800,0,0.8,HistoNPtBins,HistoPtRange[0],HistoPtRange[1]);
fHistoDoubleCountTrueHNMInvMassPt[iCut]->GetXaxis()->SetTitle("M_{#eta} (GeV/c^{2})");
fHistoDoubleCountTrueHNMInvMassPt[iCut]->GetYaxis()->SetTitle("p_{T} (GeV/c)");
fHistoDoubleCountTrueHNMInvMassPt[iCut]->Sumw2();
fTrueList[iCut]->Add(fHistoDoubleCountTrueHNMInvMassPt[iCut]);
}
fHistoTrueMotherPiPlPiMiNDMInvMassPt[iCut] = new TH2F("ESD_TrueMotherPiPlPiMiNDM_InvMass_Pt","ESD_TrueMotherPiPlPiMiNDM_InvMass_Pt",HistoNMassBins,HistoMassRange[0],HistoMassRange[1],HistoNPtBins,HistoPtRange[0],HistoPtRange[1]);
fHistoTrueMotherPiPlPiMiNDMInvMassPt[iCut]->Sumw2();
fHistoTrueMotherPiPlPiMiNDMInvMassPt[iCut]->GetXaxis()->SetTitle(Form("M_{#pi^{+} #pi^{-} %s} (GeV/c^{2})",NameNDMLatex.Data()));
fHistoTrueMotherPiPlPiMiNDMInvMassPt[iCut]->GetYaxis()->SetTitle("p_{T} (GeV/c)");
fTrueList[iCut]->Add(fHistoTrueMotherPiPlPiMiNDMInvMassPt[iCut]);
fHistoTrueMotherPiPlPiMiNDMInvMassPtSubNDM[iCut] = new TH2F("ESD_TrueMotherPiPlPiMiNDM_InvMass_SubNDM_Pt","ESD_TrueMotherPiPlPiMiNDM_InvMass_SubNDM_Pt",HistoNMassBins,HistoMassRange[0],HistoMassRange[1],HistoNPtBins,HistoPtRange[0],HistoPtRange[1]);
fHistoTrueMotherPiPlPiMiNDMInvMassPtSubNDM[iCut]->Sumw2();
fHistoTrueMotherPiPlPiMiNDMInvMassPtSubNDM[iCut]->GetXaxis()->SetTitle(Form("M_{#pi^{+} #pi^{-} %s} (GeV/c^{2})",NameNDMLatex.Data()));
fHistoTrueMotherPiPlPiMiNDMInvMassPtSubNDM[iCut]->GetYaxis()->SetTitle("p_{T} (GeV/c)");
fTrueList[iCut]->Add(fHistoTrueMotherPiPlPiMiNDMInvMassPtSubNDM[iCut]);
fHistoTrueMotherPiPlPiMiNDMInvMassPtFixedPzNDM[iCut] = new TH2F("ESD_TrueMotherPiPlPiMiNDM_InvMass_FixedPzNDM_Pt","ESD_TrueMotherPiPlPiMiNDM_InvMass_FixedPzNDM_Pt",HistoNMassBins,HistoMassRange[0],HistoMassRange[1],HistoNPtBins,HistoPtRange[0],HistoPtRange[1]);
fHistoTrueMotherPiPlPiMiNDMInvMassPtFixedPzNDM[iCut]->Sumw2();
fHistoTrueMotherPiPlPiMiNDMInvMassPtFixedPzNDM[iCut]->GetXaxis()->SetTitle(Form("M_{#pi^{+} #pi^{-} %s} (GeV/c^{2})",NameNDMLatex.Data()));
fHistoTrueMotherPiPlPiMiNDMInvMassPtFixedPzNDM[iCut]->GetYaxis()->SetTitle("p_{T} (GeV/c)");
fTrueList[iCut]->Add(fHistoTrueMotherPiPlPiMiNDMInvMassPtFixedPzNDM[iCut]);
fHistoTrueMotherPiPlPiMiNDMInvMassPt_FromDifferent[iCut] = new TH2F("ESD_TrueMotherPiPlPiMiNDMInvMassPt_FromDifferent","ESD_TrueMotherPiPlPiMiNDMInvMassPt_FromDifferent",HistoNMassBins,HistoMassRange[0],HistoMassRange[1],HistoNPtBins,HistoPtRange[0],HistoPtRange[1]);
fHistoTrueMotherPiPlPiMiNDMInvMassPt_FromDifferent[iCut]->Sumw2();
fHistoTrueMotherPiPlPiMiNDMInvMassPt_FromDifferent[iCut]->GetXaxis()->SetTitle(Form("M_{#pi^{+} #pi^{-} %s} (GeV/c^{2})",NameNDMLatex.Data()));
fHistoTrueMotherPiPlPiMiNDMInvMassPt_FromDifferent[iCut]->GetYaxis()->SetTitle("p_{T} (GeV/c)");
fTrueList[iCut]->Add(fHistoTrueMotherPiPlPiMiNDMInvMassPt_FromDifferent[iCut]);
fHistoTruePiPlPiMiNDMCombinatoricalInvMassPt[iCut] = new TH2F("ESD_TruePiPlPiMiNDMCombinatorical_InvMassPt","ESD_TruePiPlPiMiNDMCombinatorical_InvMassPt",HistoNMassBins,HistoMassRange[0],HistoMassRange[1],HistoNPtBins,HistoPtRange[0],HistoPtRange[1]);
fHistoTruePiPlPiMiNDMCombinatoricalInvMassPt[iCut]->GetXaxis()->SetTitle(Form("M_{#pi^{+}#pi^{-}%s} (GeV/c^{2})",NameNDMLatex.Data()));
fHistoTruePiPlPiMiNDMCombinatoricalInvMassPt[iCut]->GetYaxis()->SetTitle("p_{T} (GeV/c)");
if (fIsMC>1) fHistoTruePiPlPiMiNDMCombinatoricalInvMassPt[iCut]->Sumw2();
fTrueList[iCut]->Add(fHistoTruePiPlPiMiNDMCombinatoricalInvMassPt[iCut]);
fHistoTruePiPlPiMiNDMContaminationInvMassPt[iCut] = new TH2F("ESD_TruePiPlPiMiNDMContamination_InvMassPt","ESD_TruePiPlPiMiNDMContamination_InvMassPt",HistoNMassBins,HistoMassRange[0],HistoMassRange[1],HistoNPtBins,HistoPtRange[0],HistoPtRange[1]);
fHistoTruePiPlPiMiNDMContaminationInvMassPt[iCut]->GetXaxis()->SetTitle(Form("M_{#pi^{+}#pi^{-}%s} (GeV/c^{2})",NameNDMLatex.Data()));
fHistoTruePiPlPiMiNDMContaminationInvMassPt[iCut]->GetYaxis()->SetTitle("p_{T} (GeV/c)");
if (fIsMC>1) fHistoTruePiPlPiMiNDMContaminationInvMassPt[iCut]->Sumw2();
fTrueList[iCut]->Add(fHistoTruePiPlPiMiNDMContaminationInvMassPt[iCut]);
if(!fDoLightOutput){
fHistoTrueMotherGammaGammaInvMassPt[iCut] = new TH2F("ESD_TrueMotherGG_InvMass_Pt","ESD_TrueMotherGG_InvMass_Pt",HistoNMassBinsDecayMeson,HistoMassRangeNDM[0],HistoMassRangeNDM[1],HistoNPtBins,HistoPtRange[0],HistoPtRange[1]);
fHistoTrueMotherGammaGammaInvMassPt[iCut]->GetXaxis()->SetTitle("M_{#gamma #gamma} (GeV/c^{2})");
fHistoTrueMotherGammaGammaInvMassPt[iCut]->GetYaxis()->SetTitle("p_{T} (GeV/c)");
fHistoTrueMotherGammaGammaInvMassPt[iCut]->Sumw2();
fTrueList[iCut]->Add(fHistoTrueMotherGammaGammaInvMassPt[iCut]);
fHistoTrueMotherGammaGammaFromHNMInvMassPt[iCut] = new TH2F("ESD_TrueMotherGGFromHNM_InvMass_Pt","ESD_TrueMotherGGFromHNM_InvMass_Pt",HistoNMassBinsDecayMeson,HistoMassRangeNDM[0],HistoMassRangeNDM[1],HistoNPtBins,HistoPtRange[0],HistoPtRange[1]);
fHistoTrueMotherGammaGammaFromHNMInvMassPt[iCut]->GetXaxis()->SetTitle("M_{#gamma #gamma} (GeV/c^{2})");
fHistoTrueMotherGammaGammaFromHNMInvMassPt[iCut]->GetYaxis()->SetTitle("p_{T} (GeV/c)");
fHistoTrueMotherGammaGammaFromHNMInvMassPt[iCut]->Sumw2();
fTrueList[iCut]->Add(fHistoTrueMotherGammaGammaFromHNMInvMassPt[iCut]);
fHistoTrueAngleSum[iCut] = new TH2F("ESD_TrueMother_AngleSum_Pt","ESD_TrueMother_AngleSum_Pt",HistoNPtBins,HistoPtRange[0],HistoPtRange[1],720,0,2*TMath::Pi());
fHistoTrueAngleSum[iCut]->GetXaxis()->SetTitle("#sum #angle");
fHistoTrueAngleSum[iCut]->GetYaxis()->SetTitle("p_{T} (GeV/c)");
fHistoTrueAngleSum[iCut]->Sumw2();
fTrueList[iCut]->Add(fHistoTrueAngleSum[iCut]);
fHistoTrueHNMesonPtvsNDMPt[iCut] = new TH2F("ESD_TrueMother_HNMesonPtvsNDMPt","ESD_TrueMother_HNMesonPtvsNDMPt",HistoNPtBins,HistoPtRange[0],HistoPtRange[1],HistoNPtBins,HistoPtRange[0],HistoPtRange[1]);
fHistoTrueHNMesonPtvsNDMPt[iCut]->GetXaxis()->SetTitle("p_{T} (GeV/c) of HNM");
fHistoTrueHNMesonPtvsNDMPt[iCut]->GetYaxis()->SetTitle("p_{T} (GeV/c) of NDM");
fHistoTrueHNMesonPtvsNDMPt[iCut]->Sumw2();
fTrueList[iCut]->Add(fHistoTrueHNMesonPtvsNDMPt[iCut]);
if (fDoMesonQA>0){
fHistoTruePionPionInvMassPt[iCut] = new TH2F("ESD_TruePiPlusPiNeg_InvMassPt","ESD_TruePiPlusPiNeg_InvMassPt",HistoNMassBinsPiPlusPiMinus,HistoMassRangePiPlusPiMinus[0],HistoMassRangePiPlusPiMinus[1],HistoNPtBins,HistoPtRange[0],HistoPtRange[1]);
fHistoTruePionPionInvMassPt[iCut]->GetXaxis()->SetTitle("M_{#pi^{+}#pi^{-}} (GeV/c^{2})");
fHistoTruePionPionInvMassPt[iCut]->GetYaxis()->SetTitle("p_{T} (GeV/c)");
fHistoTruePionPionInvMassPt[iCut]->Sumw2();
fTrueList[iCut]->Add(fHistoTruePionPionInvMassPt[iCut]);
fHistoTruePionPionFromSameMotherInvMassPt[iCut] = new TH2F("ESD_TruePiPlusPiNegFromSameMother_InvMassPt","ESD_TruePiPlusPiNegFromSameMother_InvMassPt",HistoNMassBinsPiPlusPiMinus,HistoMassRangePiPlusPiMinus[0],HistoMassRangePiPlusPiMinus[1],HistoNPtBins,HistoPtRange[0],HistoPtRange[1]);
fHistoTruePionPionFromSameMotherInvMassPt[iCut]->GetXaxis()->SetTitle("M_{#pi^{+}#pi^{-}} (GeV/c^{2})");
fHistoTruePionPionFromSameMotherInvMassPt[iCut]->GetYaxis()->SetTitle("p_{T} (GeV/c)");
fHistoTruePionPionFromSameMotherInvMassPt[iCut]->Sumw2();
fTrueList[iCut]->Add(fHistoTruePionPionFromSameMotherInvMassPt[iCut]);
fHistoTruePionPionFromHNMInvMassPt[iCut] = new TH2F("ESD_TruePiPlusPiNegFromHNM_InvMassPt","ESD_TruePiPlusPiNegFromHNM_InvMassPt",HistoNMassBinsPiPlusPiMinus,HistoMassRangePiPlusPiMinus[0],HistoMassRangePiPlusPiMinus[1],HistoNPtBins,HistoPtRange[0],HistoPtRange[1]);
fHistoTruePionPionFromHNMInvMassPt[iCut]->GetXaxis()->SetTitle("M_{#pi^{+}#pi^{-}} (GeV/c^{2})");
fHistoTruePionPionFromHNMInvMassPt[iCut]->GetYaxis()->SetTitle("p_{T} (GeV/c)");
fHistoTruePionPionFromHNMInvMassPt[iCut]->Sumw2();
fTrueList[iCut]->Add(fHistoTruePionPionFromHNMInvMassPt[iCut]);
fHistoTruevParticleChi2PerNDF[iCut] = new TH1F("fHistoTruevParticleChi2PerNDF","fHistoTruevParticleChi2PerNDF",300,0,300);
fHistoTruevParticleChi2PerNDF[iCut]->GetXaxis()->SetTitle("#chi^{2}/ndf");
fHistoTruevParticleChi2PerNDF[iCut]->Sumw2();
fTrueList[iCut]->Add(fHistoTruevParticleChi2PerNDF[iCut]);
fHistoTruevParticleFromSameMotherChi2PerNDF[iCut] = new TH1F("fHistoTruevParticleFromSameMotherChi2PerNDF","fHistoTruevParticleFromSameMotherChi2PerNDF",300,0,300);
fHistoTruevParticleFromSameMotherChi2PerNDF[iCut]->GetXaxis()->SetTitle("#chi^{2}/ndf");
fHistoTruevParticleFromSameMotherChi2PerNDF[iCut]->Sumw2();
fTrueList[iCut]->Add(fHistoTruevParticleFromSameMotherChi2PerNDF[iCut]);
fHistoTruevParticleFromHNMChi2PerNDF[iCut] = new TH1F("fHistoTruevParticleFromHNMChi2PerNDF","fHistoTruevParticleFromHNMChi2PerNDF",300,0,300);
fHistoTruevParticleFromHNMChi2PerNDF[iCut]->GetXaxis()->SetTitle("#chi^{2}/ndf");
fHistoTruevParticleFromHNMChi2PerNDF[iCut]->Sumw2();
fTrueList[iCut]->Add(fHistoTruevParticleFromHNMChi2PerNDF[iCut]);
fHistoTruevParticledS[iCut] = new TH1F("fHistoTruevParticledS","fHistoTruevParticledS",500,-4,4);
fHistoTruevParticledS[iCut]->GetXaxis()->SetTitle("dS");
fHistoTruevParticledS[iCut]->Sumw2();
fTrueList[iCut]->Add(fHistoTruevParticledS[iCut]);
fHistoTruevParticleFromSameMotherdS[iCut] = new TH1F("fHistoTruevParticleFromSameMotherdS","fHistoTruevParticleFromSameMotherdS",400,-4,4);
fHistoTruevParticleFromSameMotherdS[iCut]->GetXaxis()->SetTitle("dS");
fHistoTruevParticleFromSameMotherdS[iCut]->Sumw2();
fTrueList[iCut]->Add(fHistoTruevParticleFromSameMotherdS[iCut]);
fHistoTruevParticleFromHNMdS[iCut] = new TH1F("fHistoTruevParticleFromHNMdS","fHistoTruevParticleFromHNMdS",400,-4,4);
fHistoTruevParticleFromHNMdS[iCut]->GetXaxis()->SetTitle("dS");
fHistoTruevParticleFromHNMdS[iCut]->Sumw2();
fTrueList[iCut]->Add(fHistoTruevParticleFromHNMdS[iCut]);
fHistoTrueMesonFlags[iCut] = new TH1F("TrueMesonFlags","TrueMesonFlags",11,0.5,11.5);
fHistoTrueMesonFlags[iCut]->GetXaxis()->SetBinLabel(1, "All candidates");
fHistoTrueMesonFlags[iCut]->GetXaxis()->SetBinLabel(2, "Same mother");
fHistoTrueMesonFlags[iCut]->GetXaxis()->SetBinLabel(3, "True");
fHistoTrueMesonFlags[iCut]->GetXaxis()->SetBinLabel(4, "Not same mother");
fHistoTrueMesonFlags[iCut]->GetXaxis()->SetBinLabel(5, "Wrongly identified pions");
fHistoTrueMesonFlags[iCut]->GetXaxis()->SetBinLabel(6, "Wrongly identified pi0");
fHistoTrueMesonFlags[iCut]->GetXaxis()->SetBinLabel(7, "Wrongly identified pi+");
fHistoTrueMesonFlags[iCut]->GetXaxis()->SetBinLabel(8, "Wrongly identified pi-");
fHistoTrueMesonFlags[iCut]->GetXaxis()->SetBinLabel(9, "Wrongly identified multiple");
fHistoTrueMesonFlags[iCut]->GetXaxis()->SetBinLabel(10, "Problem with pi0 flag");
fHistoTrueMesonFlags[iCut]->GetXaxis()->SetBinLabel(11, "Problem with meson declaration flag");
fTrueList[iCut]->Add(fHistoTrueMesonFlags[iCut]);
TString TStr_MesonType_TrueMotherPiPlPiMiNDMInvMassPt_FromEtaOmega="Eta";
if (fSelectedHeavyNeutralMeson==0){
TStr_MesonType_TrueMotherPiPlPiMiNDMInvMassPt_FromEtaOmega="Omega";
}
fHistoTrueMotherPiPlPiMiNDMInvMassPt_FromEtaOmega[iCut] = new TH2F("ESD_TrueMotherPiPlPiMiNDMInvMassPt_FromEtaOmega", Form("ESD_TrueMotherPiPlPiMiNDMInvMassPt_From%s", TStr_MesonType_TrueMotherPiPlPiMiNDMInvMassPt_FromEtaOmega.Data()), HistoNMassBins, HistoMassRange[0], HistoMassRange[1], HistoNPtBins, HistoPtRange[0], HistoPtRange[1]);
fHistoTrueMotherPiPlPiMiNDMInvMassPt_FromEtaOmega[iCut]->GetXaxis()->SetTitle("M_{#pi^{+}#pi^{-}} (GeV/c^{2})");
fHistoTrueMotherPiPlPiMiNDMInvMassPt_FromEtaOmega[iCut]->GetYaxis()->SetTitle("p_{T} (GeV/c)");
if (fIsMC>1) fHistoTrueMotherPiPlPiMiNDMInvMassPt_FromEtaOmega[iCut]->Sumw2();
fTrueList[iCut]->Add(fHistoTrueMotherPiPlPiMiNDMInvMassPt_FromEtaOmega[iCut]);
fHistoTrueMotherPiPlPiMiNDMInvMassPt_FromRho[iCut] = new TH2F("ESD_TrueMotherPiPlPiMiNDMInvMassPt_FromRho","ESD_TrueMotherPiPlPiMiNDMInvMassPt_FromRho", HistoNMassBins, HistoMassRange[0], HistoMassRange[1], HistoNPtBins, HistoPtRange[0], HistoPtRange[1]);
fHistoTrueMotherPiPlPiMiNDMInvMassPt_FromRho[iCut]->GetXaxis()->SetTitle("M_{#pi^{+}#pi^{-}} (GeV/c^{2})");
fHistoTrueMotherPiPlPiMiNDMInvMassPt_FromRho[iCut]->GetYaxis()->SetTitle("p_{T} (GeV/c)");
if (fIsMC>1) fHistoTrueMotherPiPlPiMiNDMInvMassPt_FromRho[iCut]->Sumw2();
fTrueList[iCut]->Add(fHistoTrueMotherPiPlPiMiNDMInvMassPt_FromRho[iCut]);
fHistoTrueMotherPiPlPiMiNDMInvMassPt_FromK0s[iCut] = new TH2F("ESD_TrueMotherPiPlPiMiNDMInvMassPt_FromK0s","ESD_TrueMotherPiPlPiMiNDMInvMassPt_FromK0s", HistoNMassBins, HistoMassRange[0], HistoMassRange[1], HistoNPtBins, HistoPtRange[0], HistoPtRange[1]);
fHistoTrueMotherPiPlPiMiNDMInvMassPt_FromK0s[iCut]->GetXaxis()->SetTitle("M_{#pi^{+}#pi^{-}} (GeV/c^{2})");
fHistoTrueMotherPiPlPiMiNDMInvMassPt_FromK0s[iCut]->GetYaxis()->SetTitle("p_{T} (GeV/c)");
if (fIsMC>1) fHistoTrueMotherPiPlPiMiNDMInvMassPt_FromK0s[iCut]->Sumw2();
fTrueList[iCut]->Add(fHistoTrueMotherPiPlPiMiNDMInvMassPt_FromK0s[iCut]);
fHistoTrueMotherPiPlPiMiNDMInvMassPt_FromK0l[iCut] = new TH2F("ESD_TrueMotherPiPlPiMiNDMInvMassPt_FromK0l","ESD_TrueMotherPiPlPiMiNDMInvMassPt_FromK0l", HistoNMassBins, HistoMassRange[0], HistoMassRange[1], HistoNPtBins, HistoPtRange[0], HistoPtRange[1]);
fHistoTrueMotherPiPlPiMiNDMInvMassPt_FromK0l[iCut]->GetXaxis()->SetTitle("M_{#pi^{+}#pi^{-}} (GeV/c^{2})");
fHistoTrueMotherPiPlPiMiNDMInvMassPt_FromK0l[iCut]->GetYaxis()->SetTitle("p_{T} (GeV/c)");
if (fIsMC>1) fHistoTrueMotherPiPlPiMiNDMInvMassPt_FromK0l[iCut]->Sumw2();
fTrueList[iCut]->Add(fHistoTrueMotherPiPlPiMiNDMInvMassPt_FromK0l[iCut]);
fHistoTrueMotherPiPlPiMiNDMInvMassPt_FromEtaPrime[iCut] = new TH2F("ESD_TrueMotherPiPlPiMiNDMInvMassPt_FromEtaPrime","ESD_TrueMotherPiPlPiMiNDMInvMassPt_FromEtaPrime", HistoNMassBins, HistoMassRange[0], HistoMassRange[1], HistoNPtBins, HistoPtRange[0], HistoPtRange[1]);
fHistoTrueMotherPiPlPiMiNDMInvMassPt_FromEtaPrime[iCut]->GetXaxis()->SetTitle("M_{#pi^{+}#pi^{-}} (GeV/c^{2})");
fHistoTrueMotherPiPlPiMiNDMInvMassPt_FromEtaPrime[iCut]->GetYaxis()->SetTitle("p_{T} (GeV/c)");
if (fIsMC>1) fHistoTrueMotherPiPlPiMiNDMInvMassPt_FromEtaPrime[iCut]->Sumw2();
fTrueList[iCut]->Add(fHistoTrueMotherPiPlPiMiNDMInvMassPt_FromEtaPrime[iCut]);
fHistoTrueMotherPiPlPiMiNDMInvMassPt_FromOther[iCut] = new TH2F("ESD_TrueMotherPiPlPiMiNDMInvMassPt_FromOther","ESD_TrueMotherPiPlPiMiNDMInvMassPt_FromOther", HistoNMassBins, HistoMassRange[0], HistoMassRange[1], HistoNPtBins, HistoPtRange[0], HistoPtRange[1]);
fHistoTrueMotherPiPlPiMiNDMInvMassPt_FromOther[iCut]->GetXaxis()->SetTitle("M_{#pi^{+}#pi^{-}} (GeV/c^{2})");
fHistoTrueMotherPiPlPiMiNDMInvMassPt_FromOther[iCut]->GetYaxis()->SetTitle("p_{T} (GeV/c)");
if (fIsMC>1) fHistoTrueMotherPiPlPiMiNDMInvMassPt_FromOther[iCut]->Sumw2();
fTrueList[iCut]->Add(fHistoTrueMotherPiPlPiMiNDMInvMassPt_FromOther[iCut]);
fHistoTruePiPlPiMiSameMotherFromEtaInvMassPt[iCut] = new TH2F("ESD_TruePiPlPiMiSameMotherFromEta_InvMassPt","ESD_TruePiPlPiMiSameMotherFromEta_InvMassPt",HistoNMassBins,HistoMassRange[0],HistoMassRange[1],HistoNPtBins,HistoPtRange[0],HistoPtRange[1]);
fHistoTruePiPlPiMiSameMotherFromEtaInvMassPt[iCut]->GetXaxis()->SetTitle("M_{#pi^{+}#pi^{-}} (GeV/c^{2})");
fHistoTruePiPlPiMiSameMotherFromEtaInvMassPt[iCut]->GetYaxis()->SetTitle("p_{T} (GeV/c)");
if (fIsMC>1) fHistoTruePiPlPiMiSameMotherFromEtaInvMassPt[iCut]->Sumw2();
fTrueList[iCut]->Add(fHistoTruePiPlPiMiSameMotherFromEtaInvMassPt[iCut]);
fHistoTruePiPlPiMiSameMotherFromOmegaInvMassPt[iCut] = new TH2F("ESD_TruePiPlPiMiSameMotherFromOmega_InvMassPt","ESD_TruePiPlPiMiSameMotherFromOmega_InvMassPt",HistoNMassBins,HistoMassRange[0],HistoMassRange[1],HistoNPtBins,HistoPtRange[0],HistoPtRange[1]);
fHistoTruePiPlPiMiSameMotherFromOmegaInvMassPt[iCut]->GetXaxis()->SetTitle("M_{#pi^{+}#pi^{-}} (GeV/c^{2})");
fHistoTruePiPlPiMiSameMotherFromOmegaInvMassPt[iCut]->GetYaxis()->SetTitle("p_{T} (GeV/c)");
if (fIsMC>1) fHistoTruePiPlPiMiSameMotherFromOmegaInvMassPt[iCut]->Sumw2();
fTrueList[iCut]->Add(fHistoTruePiPlPiMiSameMotherFromOmegaInvMassPt[iCut]);
fHistoTruePiPlPiMiSameMotherFromRhoInvMassPt[iCut] = new TH2F("ESD_TruePiPlPiMiSameMotherFromRho_InvMassPt","ESD_TruePiPlPiMiSameMotherFromRho_InvMassPt",HistoNMassBins,HistoMassRange[0],HistoMassRange[1],HistoNPtBins,HistoPtRange[0],HistoPtRange[1]);
fHistoTruePiPlPiMiSameMotherFromRhoInvMassPt[iCut]->GetXaxis()->SetTitle("M_{#pi^{+}#pi^{-}} (GeV/c^{2})");
fHistoTruePiPlPiMiSameMotherFromRhoInvMassPt[iCut]->GetYaxis()->SetTitle("p_{T} (GeV/c)");
if (fIsMC>1) fHistoTruePiPlPiMiSameMotherFromRhoInvMassPt[iCut]->Sumw2();
fTrueList[iCut]->Add(fHistoTruePiPlPiMiSameMotherFromRhoInvMassPt[iCut]);
fHistoTruePiPlPiMiSameMotherFromEtaPrimeInvMassPt[iCut] = new TH2F("ESD_TruePiPlPiMiSameMotherFromEtaPrime_InvMassPt","ESD_TruePiPlPiMiSameMotherFromEtaPrime_InvMassPt",
HistoNMassBins,HistoMassRange[0],HistoMassRange[1],HistoNPtBins,HistoPtRange[0],HistoPtRange[1]);
fHistoTruePiPlPiMiSameMotherFromEtaPrimeInvMassPt[iCut]->GetXaxis()->SetTitle("M_{#pi^{+}#pi^{-}} (GeV/c^{2})");
fHistoTruePiPlPiMiSameMotherFromEtaPrimeInvMassPt[iCut]->GetYaxis()->SetTitle("p_{T} (GeV/c)");
if (fIsMC>1) fHistoTruePiPlPiMiSameMotherFromEtaPrimeInvMassPt[iCut]->Sumw2();
fTrueList[iCut]->Add(fHistoTruePiPlPiMiSameMotherFromEtaPrimeInvMassPt[iCut]);
fHistoTruePiPlPiMiSameMotherFromK0sInvMassPt[iCut] = new TH2F("ESD_TruePiPlPiMiSameMotherFromK0s_InvMassPt","ESD_TruePiPlPiMiSameMotherFromK0s_InvMassPt",HistoNMassBins,HistoMassRange[0],HistoMassRange[1],HistoNPtBins,HistoPtRange[0],HistoPtRange[1]);
fHistoTruePiPlPiMiSameMotherFromK0sInvMassPt[iCut]->GetXaxis()->SetTitle("M_{#pi^{+}#pi^{-}} (GeV/c^{2})");
fHistoTruePiPlPiMiSameMotherFromK0sInvMassPt[iCut]->GetYaxis()->SetTitle("p_{T} (GeV/c)");
if (fIsMC>1) fHistoTruePiPlPiMiSameMotherFromK0sInvMassPt[iCut]->Sumw2();
fTrueList[iCut]->Add(fHistoTruePiPlPiMiSameMotherFromK0sInvMassPt[iCut]);
fHistoTruePiPlPiMiSameMotherFromK0lInvMassPt[iCut] = new TH2F("ESD_TruePiPlPiMiSameMotherFromK0l_InvMassPt","ESD_TruePiPlPiMiSameMotherFromK0l_InvMassPt",HistoNMassBins,HistoMassRange[0],HistoMassRange[1],HistoNPtBins,HistoPtRange[0],HistoPtRange[1]);
fHistoTruePiPlPiMiSameMotherFromK0lInvMassPt[iCut]->GetXaxis()->SetTitle("M_{#pi^{+}#pi^{-}} (GeV/c^{2})");
fHistoTruePiPlPiMiSameMotherFromK0lInvMassPt[iCut]->GetYaxis()->SetTitle("p_{T} (GeV/c)");
if (fIsMC>1) fHistoTruePiPlPiMiSameMotherFromK0lInvMassPt[iCut]->Sumw2();
fTrueList[iCut]->Add(fHistoTruePiPlPiMiSameMotherFromK0lInvMassPt[iCut]);
fHistoTruePiPlPiMiSameMotherFromOtherlInvMassPt[iCut] = new TH2F("ESD_TruePiPlPiMiSameMotherFromOther_InvMassPt","ESD_TruePiPlPiMiSameMotherFromOther_InvMassPt",HistoNMassBins,HistoMassRange[0],HistoMassRange[1],HistoNPtBins,HistoPtRange[0],HistoPtRange[1]);
fHistoTruePiPlPiMiSameMotherFromOtherlInvMassPt[iCut]->GetXaxis()->SetTitle("M_{#pi^{+}#pi^{-}} (GeV/c^{2})");
fHistoTruePiPlPiMiSameMotherFromOtherlInvMassPt[iCut]->GetYaxis()->SetTitle("p_{T} (GeV/c)");
if (fIsMC>1) fHistoTruePiPlPiMiSameMotherFromOtherlInvMassPt[iCut]->Sumw2();
fTrueList[iCut]->Add(fHistoTruePiPlPiMiSameMotherFromOtherlInvMassPt[iCut]);
fHistoTruePiMiPiZeroSameMotherFromEtaInvMassPt[iCut] = new TH2F("ESD_TruePiMiPiZeroSameMotherFromEta_InvMassPt","ESD_TruePiMiPiZeroSameMotherFromEta_InvMassPt",HistoNMassBins,HistoMassRange[0],HistoMassRange[1],HistoNPtBins,HistoPtRange[0],HistoPtRange[1]);
fHistoTruePiMiPiZeroSameMotherFromEtaInvMassPt[iCut]->GetXaxis()->SetTitle(Form("M_{#pi^{-}%s} (GeV/c^{2})",NameNDMLatex.Data()));
fHistoTruePiMiPiZeroSameMotherFromEtaInvMassPt[iCut]->GetYaxis()->SetTitle("p_{T} (GeV/c)");
if (fIsMC>1) fHistoTruePiMiPiZeroSameMotherFromEtaInvMassPt[iCut]->Sumw2();
fTrueList[iCut]->Add(fHistoTruePiMiPiZeroSameMotherFromEtaInvMassPt[iCut]);
fHistoTruePiMiPiZeroSameMotherFromOmegaInvMassPt[iCut] = new TH2F("ESD_TruePiMiPiZeroSameMotherFromOmega_InvMassPt","ESD_TruePiMiPiZeroSameMotherFromOmega_InvMassPt",HistoNMassBins,HistoMassRange[0],HistoMassRange[1],HistoNPtBins,HistoPtRange[0],HistoPtRange[1]);
fHistoTruePiMiPiZeroSameMotherFromOmegaInvMassPt[iCut]->GetXaxis()->SetTitle(Form("M_{#pi^{-}%s} (GeV/c^{2})",NameNDMLatex.Data()));
fHistoTruePiMiPiZeroSameMotherFromOmegaInvMassPt[iCut]->GetYaxis()->SetTitle("p_{T} (GeV/c)");
if (fIsMC>1) fHistoTruePiMiPiZeroSameMotherFromOmegaInvMassPt[iCut]->Sumw2();
fTrueList[iCut]->Add(fHistoTruePiMiPiZeroSameMotherFromOmegaInvMassPt[iCut]);
fHistoTruePiMiPiZeroSameMotherFromRhoInvMassPt[iCut] = new TH2F("ESD_TruePiMiPiZeroSameMotherFromRho_InvMassPt","ESD_TruePiMiPiZeroSameMotherFromRho_InvMassPt",HistoNMassBins,HistoMassRange[0],HistoMassRange[1],HistoNPtBins,HistoPtRange[0],HistoPtRange[1]);
fHistoTruePiMiPiZeroSameMotherFromRhoInvMassPt[iCut]->GetXaxis()->SetTitle(Form("M_{#pi^{-}%s} (GeV/c^{2})",NameNDMLatex.Data()));
fHistoTruePiMiPiZeroSameMotherFromRhoInvMassPt[iCut]->GetYaxis()->SetTitle("p_{T} (GeV/c)");
if (fIsMC>1) fHistoTruePiMiPiZeroSameMotherFromRhoInvMassPt[iCut]->Sumw2();
fTrueList[iCut]->Add(fHistoTruePiMiPiZeroSameMotherFromRhoInvMassPt[iCut]);
fHistoTruePiMiPiZeroSameMotherFromK0lInvMassPt[iCut] = new TH2F("ESD_TruePiMiPiZeroSameMotherFromK0l_InvMassPt","ESD_TruePiMiPiZeroSameMotherFromK0l_InvMassPt",HistoNMassBins,HistoMassRange[0],HistoMassRange[1],HistoNPtBins,HistoPtRange[0],HistoPtRange[1]);
fHistoTruePiMiPiZeroSameMotherFromK0lInvMassPt[iCut]->GetXaxis()->SetTitle(Form("M_{#pi^{-}%s} (GeV/c^{2})",NameNDMLatex.Data()));
fHistoTruePiMiPiZeroSameMotherFromK0lInvMassPt[iCut]->GetYaxis()->SetTitle("p_{T} (GeV/c)");
if (fIsMC>1) fHistoTruePiMiPiZeroSameMotherFromK0lInvMassPt[iCut]->Sumw2();
fTrueList[iCut]->Add(fHistoTruePiMiPiZeroSameMotherFromK0lInvMassPt[iCut]);
fHistoTruePiMiPiZeroSameMotherFromOtherlInvMassPt[iCut] = new TH2F("ESD_TruePiMiPiZeroSameMotherFromOther_InvMassPt","ESD_TruePiMiPiZeroSameMotherFromOther_InvMassPt",HistoNMassBins,HistoMassRange[0],HistoMassRange[1],HistoNPtBins,HistoPtRange[0],HistoPtRange[1]);
fHistoTruePiMiPiZeroSameMotherFromOtherlInvMassPt[iCut]->GetXaxis()->SetTitle(Form("M_{#pi^{-}%s} (GeV/c^{2})",NameNDMLatex.Data()));
fHistoTruePiMiPiZeroSameMotherFromOtherlInvMassPt[iCut]->GetYaxis()->SetTitle("p_{T} (GeV/c)");
if (fIsMC>1) fHistoTruePiMiPiZeroSameMotherFromOtherlInvMassPt[iCut]->Sumw2();
fTrueList[iCut]->Add(fHistoTruePiMiPiZeroSameMotherFromOtherlInvMassPt[iCut]);
fHistoTruePiPlPiZeroSameMotherFromEtaInvMassPt[iCut] = new TH2F("ESD_TruePiPlPiZeroSameMotherFromEta_InvMassPt","ESD_TruePiPlPiZeroSameMotherFromEta_InvMassPt",HistoNMassBins,HistoMassRange[0],HistoMassRange[1],HistoNPtBins,HistoPtRange[0],HistoPtRange[1]);
fHistoTruePiPlPiZeroSameMotherFromEtaInvMassPt[iCut]->GetXaxis()->SetTitle(Form("M_{#pi^{+}%s} (GeV/c^{2})",NameNDMLatex.Data()));
fHistoTruePiPlPiZeroSameMotherFromEtaInvMassPt[iCut]->GetYaxis()->SetTitle("p_{T} (GeV/c)");
if (fIsMC>1) fHistoTruePiPlPiZeroSameMotherFromEtaInvMassPt[iCut]->Sumw2();
fTrueList[iCut]->Add(fHistoTruePiPlPiZeroSameMotherFromEtaInvMassPt[iCut]);
fHistoTruePiPlPiZeroSameMotherFromOmegaInvMassPt[iCut] = new TH2F("ESD_TruePiPlPiZeroSameMotherFromOmega_InvMassPt","ESD_TruePiPlPiZeroSameMotherFromOmega_InvMassPt",HistoNMassBins,HistoMassRange[0],HistoMassRange[1],HistoNPtBins,HistoPtRange[0],HistoPtRange[1]);
fHistoTruePiPlPiZeroSameMotherFromOmegaInvMassPt[iCut]->GetXaxis()->SetTitle(Form("M_{#pi^{+}%s} (GeV/c^{2})",NameNDMLatex.Data()));
fHistoTruePiPlPiZeroSameMotherFromOmegaInvMassPt[iCut]->GetYaxis()->SetTitle("p_{T} (GeV/c)");
if (fIsMC>1) fHistoTruePiPlPiZeroSameMotherFromOmegaInvMassPt[iCut]->Sumw2();
fTrueList[iCut]->Add(fHistoTruePiPlPiZeroSameMotherFromOmegaInvMassPt[iCut]);
fHistoTruePiPlPiZeroSameMotherFromRhoInvMassPt[iCut] = new TH2F("ESD_TruePiPlPiZeroSameMotherFromRho_InvMassPt","ESD_TruePiPlPiZeroSameMotherFromRho_InvMassPt",HistoNMassBins,HistoMassRange[0],HistoMassRange[1],HistoNPtBins,HistoPtRange[0],HistoPtRange[1]);
fHistoTruePiPlPiZeroSameMotherFromRhoInvMassPt[iCut]->GetXaxis()->SetTitle(Form("M_{#pi^{+}%s} (GeV/c^{2})",NameNDMLatex.Data()));
fHistoTruePiMiPiZeroSameMotherFromRhoInvMassPt[iCut]->GetYaxis()->SetTitle("p_{T} (GeV/c)");
if (fIsMC>1) fHistoTruePiMiPiZeroSameMotherFromRhoInvMassPt[iCut]->Sumw2();
fTrueList[iCut]->Add(fHistoTruePiPlPiZeroSameMotherFromRhoInvMassPt[iCut]);
fHistoTruePiPlPiZeroSameMotherFromK0lInvMassPt[iCut] = new TH2F("ESD_TruePiPlPiZeroSameMotherFromK0l_InvMassPt","ESD_TruePiPlPiZeroSameMotherFromK0l_InvMassPt",HistoNMassBins,HistoMassRange[0],HistoMassRange[1],HistoNPtBins,HistoPtRange[0],HistoPtRange[1]);
fHistoTruePiPlPiZeroSameMotherFromK0lInvMassPt[iCut]->GetXaxis()->SetTitle(Form("M_{#pi^{+}%s} (GeV/c^{2})",NameNDMLatex.Data()));
fHistoTruePiPlPiZeroSameMotherFromK0lInvMassPt[iCut]->GetYaxis()->SetTitle("p_{T} (GeV/c)");
if (fIsMC>1) fHistoTruePiPlPiZeroSameMotherFromK0lInvMassPt[iCut]->Sumw2();
fTrueList[iCut]->Add(fHistoTruePiPlPiZeroSameMotherFromK0lInvMassPt[iCut]);
fHistoTruePiPlPiZeroSameMotherFromOtherInvMassPt[iCut] = new TH2F("ESD_TruePiPlPiZeroSameMotherFromOther_InvMassPt","ESD_TruePiPlPiZeroSameMotherFromOther_InvMassPt",HistoNMassBins,HistoMassRange[0],HistoMassRange[1],HistoNPtBins,HistoPtRange[0],HistoPtRange[1]);
fHistoTruePiPlPiZeroSameMotherFromOtherInvMassPt[iCut]->GetXaxis()->SetTitle(Form("M_{#pi^{+}%s} (GeV/c^{2})",NameNDMLatex.Data()));
fHistoTruePiPlPiZeroSameMotherFromOtherInvMassPt[iCut]->GetYaxis()->SetTitle("p_{T} (GeV/c)");
if (fIsMC>1) fHistoTruePiPlPiZeroSameMotherFromOtherInvMassPt[iCut]->Sumw2();
fTrueList[iCut]->Add(fHistoTruePiPlPiZeroSameMotherFromOtherInvMassPt[iCut]);
fHistoTruePiPlPiMiNDMPureCombinatoricalInvMassPt[iCut] = new TH2F("ESD_TruePiPlPiMiNDMPureCombinatorical_InvMassPt","ESD_TruePiPlPiMiNDMPureCombinatorical_InvMassPt",HistoNMassBins,HistoMassRange[0],HistoMassRange[1],HistoNPtBins,HistoPtRange[0],HistoPtRange[1]);
fHistoTruePiPlPiMiNDMPureCombinatoricalInvMassPt[iCut]->GetXaxis()->SetTitle(Form("M_{#pi^{+}#pi^{-}%s} (GeV/c^{2})",NameNDMLatex.Data()));
fHistoTruePiPlPiMiNDMPureCombinatoricalInvMassPt[iCut]->GetYaxis()->SetTitle("p_{T} (GeV/c)");
if (fIsMC>1) fHistoTruePiPlPiMiNDMPureCombinatoricalInvMassPt[iCut]->Sumw2();
fTrueList[iCut]->Add(fHistoTruePiPlPiMiNDMPureCombinatoricalInvMassPt[iCut]);
fHistoTruePiPlPiMiNDMContamination_Pi0_InvMassPt[iCut] = new TH2F("ESD_TruePiPlPiMiNDMContamination_Pi0_InvMassPt","ESD_TruePiPlPiMiNDMContamination_Pi0_InvMassPt",HistoNMassBins,HistoMassRange[0],HistoMassRange[1],HistoNPtBins,HistoPtRange[0],HistoPtRange[1]);
fHistoTruePiPlPiMiNDMContamination_Pi0_InvMassPt[iCut]->GetXaxis()->SetTitle(Form("M_{#pi^{+}#pi^{-}%s} (GeV/c^{2})",NameNDMLatex.Data()));
fHistoTruePiPlPiMiNDMContamination_Pi0_InvMassPt[iCut]->GetYaxis()->SetTitle("p_{T} (GeV/c)");
if (fIsMC>1) fHistoTruePiPlPiMiNDMContamination_Pi0_InvMassPt[iCut]->Sumw2();
fTrueList[iCut]->Add(fHistoTruePiPlPiMiNDMContamination_Pi0_InvMassPt[iCut]);
fHistoTruePiPlPiMiNDMContamination_PiPl_InvMassPt[iCut] = new TH2F("ESD_TruePiPlPiMiNDMContamination_PiPl_InvMassPt","ESD_TruePiPlPiMiNDMContamination_PiPl_InvMassPt",HistoNMassBins,HistoMassRange[0],HistoMassRange[1],HistoNPtBins,HistoPtRange[0],HistoPtRange[1]);
fHistoTruePiPlPiMiNDMContamination_PiPl_InvMassPt[iCut]->GetXaxis()->SetTitle(Form("M_{#pi^{+}#pi^{-}%s} (GeV/c^{2})",NameNDMLatex.Data()));
fHistoTruePiPlPiMiNDMContamination_PiPl_InvMassPt[iCut]->GetYaxis()->SetTitle("p_{T} (GeV/c)");
if (fIsMC>1) fHistoTruePiPlPiMiNDMContamination_PiPl_InvMassPt[iCut]->Sumw2();
fTrueList[iCut]->Add(fHistoTruePiPlPiMiNDMContamination_PiPl_InvMassPt[iCut]);
fHistoTruePiPlPiMiNDMContamination_PiMi_InvMassPt[iCut] = new TH2F("ESD_TruePiPlPiMiNDMContamination_PiMi_InvMassPt","ESD_TruePiPlPiMiNDMContamination_PiMi_InvMassPt",HistoNMassBins,HistoMassRange[0],HistoMassRange[1],HistoNPtBins,HistoPtRange[0],HistoPtRange[1]);
fHistoTruePiPlPiMiNDMContamination_PiMi_InvMassPt[iCut]->GetXaxis()->SetTitle(Form("M_{#pi^{+}#pi^{-}%s} (GeV/c^{2})",NameNDMLatex.Data()));
fHistoTruePiPlPiMiNDMContamination_PiMi_InvMassPt[iCut]->GetYaxis()->SetTitle("p_{T} (GeV/c)");
if (fIsMC>1) fHistoTruePiPlPiMiNDMContamination_PiMi_InvMassPt[iCut]->Sumw2();
fTrueList[iCut]->Add(fHistoTruePiPlPiMiNDMContamination_PiMi_InvMassPt[iCut]);
fHistoTruePiPlPiMiNDMContamination_Crosscheck_InvMassPt[iCut] = new TH2F("ESD_TruePiPlPiMiNDMContamination_Crosscheck_InvMassPt","ESD_TruePiPlPiMiNDMContamination_Crosscheck_InvMassPt",HistoNMassBins,HistoMassRange[0],HistoMassRange[1],HistoNPtBins,HistoPtRange[0],HistoPtRange[1]);
fHistoTruePiPlPiMiNDMContamination_Crosscheck_InvMassPt[iCut]->GetXaxis()->SetTitle(Form("M_{#pi^{+}#pi^{-}%s} (GeV/c^{2})",NameNDMLatex.Data()));
fHistoTruePiPlPiMiNDMContamination_Crosscheck_InvMassPt[iCut]->GetYaxis()->SetTitle("p_{T} (GeV/c)");
if (fIsMC>1) fHistoTruePiPlPiMiNDMContamination_Crosscheck_InvMassPt[iCut]->Sumw2();
fTrueList[iCut]->Add(fHistoTruePiPlPiMiNDMContamination_Crosscheck_InvMassPt[iCut]);
fHistoTruePiPlPiMiNDMContamination_multipel_InvMassPt[iCut] = new TH2F("ESD_TruePiPlPiMiNDMContamination_multipel_InvMassPt","ESD_TruePiPlPiMiNDMContamination_multipel_InvMassPt",HistoNMassBins,HistoMassRange[0],HistoMassRange[1],HistoNPtBins,HistoPtRange[0],HistoPtRange[1]);
fHistoTruePiPlPiMiNDMContamination_multipel_InvMassPt[iCut]->GetXaxis()->SetTitle(Form("M_{#pi^{+}#pi^{-}%s} (GeV/c^{2})",NameNDMLatex.Data()));
fHistoTruePiPlPiMiNDMContamination_multipel_InvMassPt[iCut]->GetYaxis()->SetTitle("p_{T} (GeV/c)");
if (fIsMC>1) fHistoTruePiPlPiMiNDMContamination_multipel_InvMassPt[iCut]->Sumw2();
fTrueList[iCut]->Add(fHistoTruePiPlPiMiNDMContamination_multipel_InvMassPt[iCut]);
//---------------------------------------
//Dalitz All Pt
if (enableDalitzAllPt){
fHistoTrueMotherPiPlPiMiNDMDalitzPlotPosFixedPzNDM[iCut] = new TH2F("ESD_TrueMotherPiPlPiMiNDM_DalitzPlot_FixedPzNDM_Pos","ESD_TrueMotherPiPlPiMiNDM_DalitzPlot_FixedPzNDM_Pos", HistoNMassBins, HistoMassRangeDalitzMin, HistoMassRangeDalitz, HistoNMassBins, HistoMassRangeDalitzMin, HistoMassRangeDalitz);
fHistoTrueMotherPiPlPiMiNDMDalitzPlotPosFixedPzNDM[iCut]->Sumw2();
fHistoTrueMotherPiPlPiMiNDMDalitzPlotPosFixedPzNDM[iCut]->GetXaxis()->SetTitle("M_{#pi^{+} #pi^{-}} (GeV/c^{2})");
fHistoTrueMotherPiPlPiMiNDMDalitzPlotPosFixedPzNDM[iCut]->GetYaxis()->SetTitle(Form("M_{#pi^{+} %s} (GeV/c^{2})", NameNDMLatex.Data()));
fTrueList[iCut]->Add(fHistoTrueMotherPiPlPiMiNDMDalitzPlotPosFixedPzNDM[iCut]);
fHistoTrueMotherPiPlPiMiNDMDalitzPlotNegFixedPzNDM[iCut] = new TH2F("ESD_TrueMotherPiPlPiMiNDM_DalitzPlot_FixedPzNDM_Neg","ESD_TrueMotherPiPlPiMiNDM_DalitzPlot_FixedPzNDM_Neg", HistoNMassBins, HistoMassRangeDalitzMin, HistoMassRangeDalitz, HistoNMassBins, HistoMassRangeDalitzMin, HistoMassRangeDalitz);
fHistoTrueMotherPiPlPiMiNDMDalitzPlotNegFixedPzNDM[iCut]->Sumw2();
fHistoTrueMotherPiPlPiMiNDMDalitzPlotNegFixedPzNDM[iCut]->GetXaxis()->SetTitle("M_{#pi^{+} #pi^{-}} (GeV/c^{2})");
fHistoTrueMotherPiPlPiMiNDMDalitzPlotNegFixedPzNDM[iCut]->GetYaxis()->SetTitle(Form("M_{#pi^{-} %s} (GeV/c^{2})", NameNDMLatex.Data()));
fTrueList[iCut]->Add(fHistoTrueMotherPiPlPiMiNDMDalitzPlotNegFixedPzNDM[iCut]);
fHistoTrueMotherPiPlPiMiNDMDalitzPlotPosSubNDM[iCut] = new TH2F("ESD_TrueMotherPiPlPiMiNDM_DalitzPlot_SubNDM_Pos","ESD_TrueMotherPiPlPiMiNDM_DalitzPlot_SubNDM_Pos", HistoNMassBins, HistoMassRangeDalitzMin, HistoMassRangeDalitz, HistoNMassBins, HistoMassRangeDalitzMin, HistoMassRangeDalitz);
fHistoTrueMotherPiPlPiMiNDMDalitzPlotPosSubNDM[iCut]->Sumw2();
fHistoTrueMotherPiPlPiMiNDMDalitzPlotPosSubNDM[iCut]->GetXaxis()->SetTitle("M_{#pi^{+} #pi^{-}} (GeV/c^{2})");
fHistoTrueMotherPiPlPiMiNDMDalitzPlotPosSubNDM[iCut]->GetYaxis()->SetTitle(Form("M_{#pi^{+} %s} (GeV/c^{2})", NameNDMLatex.Data()));
fTrueList[iCut]->Add(fHistoTrueMotherPiPlPiMiNDMDalitzPlotPosSubNDM[iCut]);
fHistoTrueMotherPiPlPiMiNDMDalitzPlotNegSubNDM[iCut] = new TH2F("ESD_TrueMotherPiPlPiMiNDM_DalitzPlot_SubNDM_Neg","ESD_TrueMotherPiPlPiMiNDM_DalitzPlot_SubNDM_Neg", HistoNMassBins, HistoMassRangeDalitzMin, HistoMassRangeDalitz, HistoNMassBins, HistoMassRangeDalitzMin, HistoMassRangeDalitz);
fHistoTrueMotherPiPlPiMiNDMDalitzPlotNegSubNDM[iCut]->Sumw2();
fHistoTrueMotherPiPlPiMiNDMDalitzPlotNegSubNDM[iCut]->GetXaxis()->SetTitle("M_{#pi^{+} #pi^{-}} (GeV/c^{2})");
fHistoTrueMotherPiPlPiMiNDMDalitzPlotNegSubNDM[iCut]->GetYaxis()->SetTitle(Form("M_{#pi^{-} %s} (GeV/c^{2})", NameNDMLatex.Data()));
fTrueList[iCut]->Add(fHistoTrueMotherPiPlPiMiNDMDalitzPlotNegSubNDM[iCut]);
}
//---------------------------------------
//Dalitz Low Pt
if (enableDalitzLowPt){
fHistoTrueMotherPiPlPiMiNDMDalitzPlotPosFixedPzNDM_LowPt[iCut] = new TH2F("ESD_TrueMotherPiPlPiMiNDM_DalitzPlot_FixedPzNDM_Pos_LowPt", Form("ESD_TrueMotherPiPlPiMiNDM_DalitzPlot_FixedPzNDM_Pos_LowPt (%3.1f to %3.1f)Gev/c", HistoDalitzPtRangeMin_LowPt, HistoDalitzPtRangeMax_LowPt), HistoNMassBins, HistoMassRangeDalitzMin, HistoMassRangeDalitz, HistoNMassBins, HistoMassRangeDalitzMin, HistoMassRangeDalitz);
fHistoTrueMotherPiPlPiMiNDMDalitzPlotPosFixedPzNDM_LowPt[iCut]->Sumw2();
fHistoTrueMotherPiPlPiMiNDMDalitzPlotPosFixedPzNDM_LowPt[iCut]->GetXaxis()->SetTitle("M_{#pi^{+} #pi^{-}} (GeV/c^{2})");
fHistoTrueMotherPiPlPiMiNDMDalitzPlotPosFixedPzNDM_LowPt[iCut]->GetYaxis()->SetTitle(Form("M_{#pi^{+} %s} (GeV/c^{2})", NameNDMLatex.Data()));
fTrueList[iCut]->Add(fHistoTrueMotherPiPlPiMiNDMDalitzPlotPosFixedPzNDM_LowPt[iCut]);
fHistoTrueMotherPiPlPiMiNDMDalitzPlotNegFixedPzNDM_LowPt[iCut] = new TH2F("ESD_TrueMotherPiPlPiMiNDM_DalitzPlot_FixedPzNDM_Neg_LowPt", Form("ESD_TrueMotherPiPlPiMiNDM_DalitzPlot_FixedPzNDM_Neg_LowPt (%3.1f to %3.1f)Gev/c", HistoDalitzPtRangeMin_LowPt, HistoDalitzPtRangeMax_LowPt), HistoNMassBins, HistoMassRangeDalitzMin, HistoMassRangeDalitz, HistoNMassBins, HistoMassRangeDalitzMin, HistoMassRangeDalitz);
fHistoTrueMotherPiPlPiMiNDMDalitzPlotNegFixedPzNDM_LowPt[iCut]->Sumw2();
fHistoTrueMotherPiPlPiMiNDMDalitzPlotNegFixedPzNDM_LowPt[iCut]->GetXaxis()->SetTitle("M_{#pi^{+} #pi^{-}} (GeV/c^{2})");
fHistoTrueMotherPiPlPiMiNDMDalitzPlotNegFixedPzNDM_LowPt[iCut]->GetYaxis()->SetTitle(Form("M_{#pi^{-} %s} (GeV/c^{2})", NameNDMLatex.Data()));
fTrueList[iCut]->Add(fHistoTrueMotherPiPlPiMiNDMDalitzPlotNegFixedPzNDM_LowPt[iCut]);
fHistoTrueMotherPiPlPiMiNDMDalitzPlotPosSubNDM_LowPt[iCut] = new TH2F("ESD_TrueMotherPiPlPiMiNDM_DalitzPlot_SubNDM_Pos_LowPt", Form("ESD_TrueMotherPiPlPiMiNDM_DalitzPlot_SubNDM_Pos_LowPt (%3.1f to %3.1f)Gev/c", HistoDalitzPtRangeMin_LowPt, HistoDalitzPtRangeMax_LowPt), HistoNMassBins, HistoMassRangeDalitzMin, HistoMassRangeDalitz, HistoNMassBins, HistoMassRangeDalitzMin, HistoMassRangeDalitz);
fHistoTrueMotherPiPlPiMiNDMDalitzPlotPosSubNDM_LowPt[iCut]->Sumw2();
fHistoTrueMotherPiPlPiMiNDMDalitzPlotPosSubNDM_LowPt[iCut]->GetXaxis()->SetTitle("M_{#pi^{+} #pi^{-}} (GeV/c^{2})");
fHistoTrueMotherPiPlPiMiNDMDalitzPlotPosSubNDM_LowPt[iCut]->GetYaxis()->SetTitle(Form("M_{#pi^{+} %s} (GeV/c^{2})", NameNDMLatex.Data()));
fTrueList[iCut]->Add(fHistoTrueMotherPiPlPiMiNDMDalitzPlotPosSubNDM_LowPt[iCut]);
fHistoTrueMotherPiPlPiMiNDMDalitzPlotNegSubNDM_LowPt[iCut] = new TH2F("ESD_TrueMotherPiPlPiMiNDM_DalitzPlot_SubNDM_Neg_LowPt", Form("ESD_TrueMotherPiPlPiMiNDM_DalitzPlot_SubNDM_Neg_LowPt (%3.1f to %3.1f)Gev/c", HistoDalitzPtRangeMin_LowPt, HistoDalitzPtRangeMax_LowPt), HistoNMassBins, HistoMassRangeDalitzMin, HistoMassRangeDalitz, HistoNMassBins, HistoMassRangeDalitzMin, HistoMassRangeDalitz);
fHistoTrueMotherPiPlPiMiNDMDalitzPlotNegSubNDM_LowPt[iCut]->Sumw2();
fHistoTrueMotherPiPlPiMiNDMDalitzPlotNegSubNDM_LowPt[iCut]->GetXaxis()->SetTitle("M_{#pi^{+} #pi^{-}} (GeV/c^{2})");
fHistoTrueMotherPiPlPiMiNDMDalitzPlotNegSubNDM_LowPt[iCut]->GetYaxis()->SetTitle(Form("M_{#pi^{-} %s} (GeV/c^{2})", NameNDMLatex.Data()));
fTrueList[iCut]->Add(fHistoTrueMotherPiPlPiMiNDMDalitzPlotNegSubNDM_LowPt[iCut]);
}
//---------------------------------------
//Dalitz Mid Pt
if (enableDalitzMidPt){
fHistoTrueMotherPiPlPiMiNDMDalitzPlotPosFixedPzNDM_MidPt[iCut] = new TH2F("ESD_TrueMotherPiPlPiMiNDM_DalitzPlot_FixedPzNDM_Pos_MidPt", Form("ESD_TrueMotherPiPlPiMiNDM_DalitzPlot_FixedPzNDM_Pos_MidPt (%3.1f to %3.1f)Gev/c", HistoDalitzPtRangeMin_MidPt, HistoDalitzPtRangeMax_MidPt), HistoNMassBins, HistoMassRangeDalitzMin, HistoMassRangeDalitz, HistoNMassBins, HistoMassRangeDalitzMin, HistoMassRangeDalitz);
fHistoTrueMotherPiPlPiMiNDMDalitzPlotPosFixedPzNDM_MidPt[iCut]->Sumw2();
fHistoTrueMotherPiPlPiMiNDMDalitzPlotPosFixedPzNDM_MidPt[iCut]->GetXaxis()->SetTitle("M_{#pi^{+} #pi^{-}} (GeV/c^{2})");
fHistoTrueMotherPiPlPiMiNDMDalitzPlotPosFixedPzNDM_MidPt[iCut]->GetYaxis()->SetTitle(Form("M_{#pi^{+} %s} (GeV/c^{2})", NameNDMLatex.Data()));
fTrueList[iCut]->Add(fHistoTrueMotherPiPlPiMiNDMDalitzPlotPosFixedPzNDM_MidPt[iCut]);
fHistoTrueMotherPiPlPiMiNDMDalitzPlotNegFixedPzNDM_MidPt[iCut] = new TH2F("ESD_TrueMotherPiPlPiMiNDM_DalitzPlot_FixedPzNDM_Neg_MidPt", Form("ESD_TrueMotherPiPlPiMiNDM_DalitzPlot_FixedPzNDM_Neg_MidPt (%3.1f to %3.1f)Gev/c", HistoDalitzPtRangeMin_MidPt, HistoDalitzPtRangeMax_MidPt), HistoNMassBins, HistoMassRangeDalitzMin, HistoMassRangeDalitz, HistoNMassBins, HistoMassRangeDalitzMin, HistoMassRangeDalitz);
fHistoTrueMotherPiPlPiMiNDMDalitzPlotNegFixedPzNDM_MidPt[iCut]->Sumw2();
fHistoTrueMotherPiPlPiMiNDMDalitzPlotNegFixedPzNDM_MidPt[iCut]->GetXaxis()->SetTitle("M_{#pi^{+} #pi^{-}} (GeV/c^{2})");
fHistoTrueMotherPiPlPiMiNDMDalitzPlotNegFixedPzNDM_MidPt[iCut]->GetYaxis()->SetTitle(Form("M_{#pi^{-} %s} (GeV/c^{2})", NameNDMLatex.Data()));
fTrueList[iCut]->Add(fHistoTrueMotherPiPlPiMiNDMDalitzPlotNegFixedPzNDM_MidPt[iCut]);
fHistoTrueMotherPiPlPiMiNDMDalitzPlotPosSubNDM_MidPt[iCut] = new TH2F("ESD_TrueMotherPiPlPiMiNDM_DalitzPlot_SubNDM_Pos_MidPt", Form("ESD_TrueMotherPiPlPiMiNDM_DalitzPlot_SubNDM_Pos_MidPt (%3.1f to %3.1f)Gev/c", HistoDalitzPtRangeMin_MidPt, HistoDalitzPtRangeMax_MidPt), HistoNMassBins, HistoMassRangeDalitzMin, HistoMassRangeDalitz, HistoNMassBins, HistoMassRangeDalitzMin, HistoMassRangeDalitz);
fHistoTrueMotherPiPlPiMiNDMDalitzPlotPosSubNDM_MidPt[iCut]->Sumw2();
fHistoTrueMotherPiPlPiMiNDMDalitzPlotPosSubNDM_MidPt[iCut]->GetXaxis()->SetTitle("M_{#pi^{+} #pi^{-}} (GeV/c^{2})");
fHistoTrueMotherPiPlPiMiNDMDalitzPlotPosSubNDM_MidPt[iCut]->GetYaxis()->SetTitle(Form("M_{#pi^{+} %s} (GeV/c^{2})", NameNDMLatex.Data()));
fTrueList[iCut]->Add(fHistoTrueMotherPiPlPiMiNDMDalitzPlotPosSubNDM_MidPt[iCut]);
fHistoTrueMotherPiPlPiMiNDMDalitzPlotNegSubNDM_MidPt[iCut] = new TH2F("ESD_TrueMotherPiPlPiMiNDM_DalitzPlot_SubNDM_Neg_MidPt", Form("ESD_TrueMotherPiPlPiMiNDM_DalitzPlot_SubNDM_Neg_MidPt (%3.1f to %3.1f)Gev/c", HistoDalitzPtRangeMin_MidPt, HistoDalitzPtRangeMax_MidPt), HistoNMassBins, HistoMassRangeDalitzMin, HistoMassRangeDalitz, HistoNMassBins, HistoMassRangeDalitzMin, HistoMassRangeDalitz);
fHistoTrueMotherPiPlPiMiNDMDalitzPlotNegSubNDM_MidPt[iCut]->Sumw2();
fHistoTrueMotherPiPlPiMiNDMDalitzPlotNegSubNDM_MidPt[iCut]->GetXaxis()->SetTitle("M_{#pi^{+} #pi^{-}} (GeV/c^{2})");
fHistoTrueMotherPiPlPiMiNDMDalitzPlotNegSubNDM_MidPt[iCut]->GetYaxis()->SetTitle(Form("M_{#pi^{-} %s} (GeV/c^{2})", NameNDMLatex.Data()));
fTrueList[iCut]->Add(fHistoTrueMotherPiPlPiMiNDMDalitzPlotNegSubNDM_MidPt[iCut]);
}
//---------------------------------------
//Dalitz High Pt
if (enableDalitzHighPt){
fHistoTrueMotherPiPlPiMiNDMDalitzPlotPosFixedPzNDM_HighPt[iCut] = new TH2F("ESD_TrueMotherPiPlPiMiNDM_DalitzPlot_FixedPzNDM_Pos_HighPt", Form("ESD_TrueMotherPiPlPiMiNDM_DalitzPlot_FixedPzNDM_Pos_HighPt (%3.1f to %3.1f)Gev/c", HistoDalitzPtRangeMin_HighPt, HistoDalitzPtRangeMax_HighPt), HistoNMassBins, HistoMassRangeDalitzMin, HistoMassRangeDalitz, HistoNMassBins, HistoMassRangeDalitzMin, HistoMassRangeDalitz);
fHistoTrueMotherPiPlPiMiNDMDalitzPlotPosFixedPzNDM_HighPt[iCut]->Sumw2();
fHistoTrueMotherPiPlPiMiNDMDalitzPlotPosFixedPzNDM_HighPt[iCut]->GetXaxis()->SetTitle("M_{#pi^{+} #pi^{-}} (GeV/c^{2})");
fHistoTrueMotherPiPlPiMiNDMDalitzPlotPosFixedPzNDM_HighPt[iCut]->GetYaxis()->SetTitle(Form("M_{#pi^{+} %s} (GeV/c^{2})", NameNDMLatex.Data()));
fTrueList[iCut]->Add(fHistoTrueMotherPiPlPiMiNDMDalitzPlotPosFixedPzNDM_HighPt[iCut]);
fHistoTrueMotherPiPlPiMiNDMDalitzPlotNegFixedPzNDM_HighPt[iCut] = new TH2F("ESD_TrueMotherPiPlPiMiNDM_DalitzPlot_FixedPzNDM_Neg_HighPt", Form("ESD_TrueMotherPiPlPiMiNDM_DalitzPlot_FixedPzNDM_Neg_HighPt (%3.1f to %3.1f)Gev/c", HistoDalitzPtRangeMin_HighPt, HistoDalitzPtRangeMax_HighPt), HistoNMassBins, HistoMassRangeDalitzMin, HistoMassRangeDalitz, HistoNMassBins, HistoMassRangeDalitzMin, HistoMassRangeDalitz);
fHistoTrueMotherPiPlPiMiNDMDalitzPlotNegFixedPzNDM_HighPt[iCut]->Sumw2();
fHistoTrueMotherPiPlPiMiNDMDalitzPlotNegFixedPzNDM_HighPt[iCut]->GetXaxis()->SetTitle("M_{#pi^{+} #pi^{-}} (GeV/c^{2})");
fHistoTrueMotherPiPlPiMiNDMDalitzPlotNegFixedPzNDM_HighPt[iCut]->GetYaxis()->SetTitle(Form("M_{#pi^{-} %s} (GeV/c^{2})", NameNDMLatex.Data()));
fTrueList[iCut]->Add(fHistoTrueMotherPiPlPiMiNDMDalitzPlotNegFixedPzNDM_HighPt[iCut]);
fHistoTrueMotherPiPlPiMiNDMDalitzPlotPosSubNDM_HighPt[iCut] = new TH2F("ESD_TrueMotherPiPlPiMiNDM_DalitzPlot_SubNDM_Pos_HighPt", Form("ESD_TrueMotherPiPlPiMiNDM_DalitzPlot_SubNDM_Pos_HighPt (%3.1f to %3.1f)Gev/c", HistoDalitzPtRangeMin_HighPt, HistoDalitzPtRangeMax_HighPt), HistoNMassBins, HistoMassRangeDalitzMin, HistoMassRangeDalitz, HistoNMassBins, HistoMassRangeDalitzMin, HistoMassRangeDalitz);
fHistoTrueMotherPiPlPiMiNDMDalitzPlotPosSubNDM_HighPt[iCut]->Sumw2();
fHistoTrueMotherPiPlPiMiNDMDalitzPlotPosSubNDM_HighPt[iCut]->GetXaxis()->SetTitle("M_{#pi^{+} #pi^{-}} (GeV/c^{2})");
fHistoTrueMotherPiPlPiMiNDMDalitzPlotPosSubNDM_HighPt[iCut]->GetYaxis()->SetTitle(Form("M_{#pi^{+} %s} (GeV/c^{2})", NameNDMLatex.Data()));
fTrueList[iCut]->Add(fHistoTrueMotherPiPlPiMiNDMDalitzPlotPosSubNDM_HighPt[iCut]);
fHistoTrueMotherPiPlPiMiNDMDalitzPlotNegSubNDM_HighPt[iCut] = new TH2F("ESD_TrueMotherPiPlPiMiNDM_DalitzPlot_SubNDM_Neg_HighPt", Form("ESD_TrueMotherPiPlPiMiNDM_DalitzPlot_SubNDM_Neg_HighPt (%3.1f to %3.1f)Gev/c", HistoDalitzPtRangeMin_HighPt, HistoDalitzPtRangeMax_HighPt), HistoNMassBins, HistoMassRangeDalitzMin, HistoMassRangeDalitz, HistoNMassBins, HistoMassRangeDalitzMin, HistoMassRangeDalitz);
fHistoTrueMotherPiPlPiMiNDMDalitzPlotNegSubNDM_HighPt[iCut]->Sumw2();
fHistoTrueMotherPiPlPiMiNDMDalitzPlotNegSubNDM_HighPt[iCut]->GetXaxis()->SetTitle("M_{#pi^{+} #pi^{-}} (GeV/c^{2})");
fHistoTrueMotherPiPlPiMiNDMDalitzPlotNegSubNDM_HighPt[iCut]->GetYaxis()->SetTitle(Form("M_{#pi^{-} %s} (GeV/c^{2})", NameNDMLatex.Data()));
fTrueList[iCut]->Add(fHistoTrueMotherPiPlPiMiNDMDalitzPlotNegSubNDM_HighPt[iCut]);
}
if(fDoMesonQA>1){
fTrueTreeList[iCut] = new TList();
fTrueTreeList[iCut]->SetName(nameTrueRecTTreeList.Data());
fTrueTreeList[iCut]->SetOwner(kTRUE);
fCutFolder[iCut]->Add(fTrueTreeList[iCut]);
fTreePiPiSameMother[iCut] = new TTree("TreePiPiSameMother","TreePiPiSameMother");
fTreePiPiSameMother[iCut]->Branch("fCasePiPi", &fCasePiPi, "fCasePiPi/S");
fTreePiPiSameMother[iCut]->Branch("fSamePiPiMotherID", &fSamePiPiMotherID, "fSamePiPiMotherID/F");
fTreePiPiSameMother[iCut]->Branch("fSamePiPiMotherInvMass", &fSamePiPiMotherInvMass, "fSamePiPiMotherInvMass/F");
fTreePiPiSameMother[iCut]->Branch("fSamePiPiMotherPt", &fSamePiPiMotherPt, "fSamePiPiMotherPt/F");
fTrueTreeList[iCut]->Add(fTreePiPiSameMother[iCut]);
fTreePiPiPiSameMother[iCut] = new TTree("TreePiPiPiSameMother","TreePiPiPiSameMother");
fTreePiPiPiSameMother[iCut]->Branch("fSamePiPiPiMotherID", &fSamePiPiPiMotherID, "fSamePiPiPiMotherID/F");
fTreePiPiPiSameMother[iCut]->Branch("fSamePiPiPiMotherInvMass", &fSamePiPiPiMotherInvMass, "fSamePiPiPiMotherInvMass/F");
fTreePiPiPiSameMother[iCut]->Branch("fSamePiPiPiMotherPt", &fSamePiPiPiMotherPt, "fSamePiPiPiMotherPt/F");
fTrueTreeList[iCut]->Add(fTreePiPiPiSameMother[iCut]);
fTreeEventInfoHNM[iCut] = new TTree("TreeEventInfoHNM","TreeEventInfoHNM");
fTreeEventInfoHNM[iCut]->Branch("fV0MultiplicityHNMEvent", &fV0MultiplicityHNMEvent, "fV0MultiplicityHNMEvent/F");
fTreeEventInfoHNM[iCut]->Branch("fTrackMultiplicityHNMEvent", &fTrackMultiplicityHNMEvent, "fTrackMultiplicityHNMEvent/F");
fTreeEventInfoHNM[iCut]->Branch("fZVertexHNMEvent", &fZVertexHNMEvent, "fZVertexHNMEvent/F");
fTreeEventInfoHNM[iCut]->Branch("fPtHNM", &fPtHNM, "fPtHNM/F");
fTrueTreeList[iCut]->Add(fTreeEventInfoHNM[iCut]);
}
}
}
}
}
fVectorDoubleCountTruePi0s.clear();
fVectorDoubleCountTrueHNMs.clear();
fVectorDoubleCountTrueConvGammas.clear();
InitBack(); // Init Background Handler
fV0Reader=(AliV0ReaderV1*)AliAnalysisManager::GetAnalysisManager()->GetTask(fV0ReaderName.Data());
if(!fV0Reader){printf("Error: No V0 Reader");return;} // GetV0Reader
if(fV0Reader){
if((AliConvEventCuts*)fV0Reader->GetEventCuts()){
if(((AliConvEventCuts*)fV0Reader->GetEventCuts())->GetCutHistograms()){
fOutputContainer->Add(((AliConvEventCuts*)fV0Reader->GetEventCuts())->GetCutHistograms());
}
}
if((AliConversionPhotonCuts*)fV0Reader->GetConversionCuts()){
if(((AliConversionPhotonCuts*)fV0Reader->GetConversionCuts())->GetCutHistograms()){
fOutputContainer->Add(((AliConversionPhotonCuts*)fV0Reader->GetConversionCuts())->GetCutHistograms());
}
}
}
for(Int_t iMatcherTask = 0; iMatcherTask < 3; iMatcherTask++){
AliCaloTrackMatcher* temp = (AliCaloTrackMatcher*) (AliAnalysisManager::GetAnalysisManager()->GetTask(Form("CaloTrackMatcher_%i_%i",iMatcherTask,fTrackMatcherRunningMode)));
if(temp && (!fDoLightOutput)) fOutputContainer->Add(temp->GetCaloTrackMatcherHistograms());
}
fPionSelector=(AliPrimaryPionSelector*)AliAnalysisManager::GetAnalysisManager()->GetTask(fPionSelectorName.Data());
if(!fPionSelector){printf("Error: No PionSelector");return;} // GetV0Reader
if( fPionSelector && (!fDoLightOutput)){
if ( ((AliPrimaryPionCuts*)fPionSelector->GetPrimaryPionCuts())->GetCutHistograms() ){
fOutputContainer->Add( ((AliPrimaryPionCuts*)fPionSelector->GetPrimaryPionCuts())->GetCutHistograms() );
}
}
for(Int_t iCut = 0; iCut<fnCuts;iCut++){
if( fEventCutArray) {
if( ((AliConvEventCuts*)fEventCutArray->At(iCut))->GetCutHistograms() ) {
fCutFolder[iCut]->Add( ((AliConvEventCuts*)fEventCutArray->At(iCut))->GetCutHistograms());
}
}
if( fPionCutArray){
if( ((AliPrimaryPionCuts*)fPionCutArray->At(iCut))->GetCutHistograms() ) {
fCutFolder[iCut]->Add( ((AliPrimaryPionCuts*)fPionCutArray->At(iCut))->GetCutHistograms() );
}
}
if (fNDMRecoMode < 2){
if( fGammaCutArray ) {
if( ((AliConversionPhotonCuts*)fGammaCutArray->At(iCut))->GetCutHistograms() ) {
fCutFolder[iCut]->Add( ((AliConversionPhotonCuts*)fGammaCutArray->At(iCut))->GetCutHistograms() );
}
}
}
if (fNDMRecoMode > 0){
if( fClusterCutArray ) {
if( ((AliCaloPhotonCuts*)fClusterCutArray->At(iCut))->GetCutHistograms() ) {
fCutFolder[iCut]->Add( ((AliCaloPhotonCuts*)fClusterCutArray->At(iCut))->GetCutHistograms() );
}
}
}
if( fNeutralDecayMesonCutArray ) {
if( ((AliConversionMesonCuts*)fNeutralDecayMesonCutArray->At(iCut))->GetCutHistograms() ) {
fCutFolder[iCut]->Add( ((AliConversionMesonCuts*)fNeutralDecayMesonCutArray->At(iCut))->GetCutHistograms());
}
}
if( fMesonCutArray ) {
if( ((AliConversionMesonCuts*)fMesonCutArray->At(iCut))->GetCutHistograms() ) {
fCutFolder[iCut]->Add( ((AliConversionMesonCuts*)fMesonCutArray->At(iCut))->GetCutHistograms());
}
}
}
PostData(1, fOutputContainer);
}
//______________________________________________________________________
void AliAnalysisTaskNeutralMesonToPiPlPiMiNeutralMeson::UserExec(Option_t *){
//
// Execute analysis for current event
//
fV0Reader=(AliV0ReaderV1*)AliAnalysisManager::GetAnalysisManager()->GetTask(fV0ReaderName.Data());
if(!fV0Reader){printf("Error: No V0 Reader");return;} // GetV0Reader
Int_t eventQuality = ((AliConvEventCuts*)fV0Reader->GetEventCuts())->GetEventQuality();
if(InputEvent()->IsIncompleteDAQ()==kTRUE) eventQuality = 2; // incomplete event
if(eventQuality == 2 || eventQuality == 3){// Event Not Accepted due to MC event missing or wrong trigger for V0ReaderV1 or because it is incomplete
for(Int_t iCut = 0; iCut<fnCuts; iCut++){
fHistoNEvents[iCut]->Fill(eventQuality);
if (fIsMC>1) fHistoNEventsWOWeight[iCut]->Fill(eventQuality);
}
return;
}
fPionSelector=(AliPrimaryPionSelector*)AliAnalysisManager::GetAnalysisManager()->GetTask(fPionSelectorName.Data());
if(!fPionSelector){printf("Error: No PionSelector");return;} // GetV0Reader
if(fIsMC) fMCEvent = MCEvent();
fInputEvent = InputEvent();
fReaderGammas = fV0Reader->GetReconstructedGammas(); // Gammas from default Cut
fSelectorNegPionIndex = fPionSelector->GetReconstructedNegPionIndex(); // Electrons from default Cut
fSelectorPosPionIndex = fPionSelector->GetReconstructedPosPionIndex(); // Positrons from default Cut
fNumberOfESDTracks = fV0Reader->GetNumberOfPrimaryTracks();
//AddTaskContainers(); //Add conatiner
if(fIsMC && fInputEvent->IsA()==AliAODEvent::Class() && !(fV0Reader->AreAODsRelabeled())){
RelabelAODPhotonCandidates(kTRUE); // In case of AODMC relabeling MC
fV0Reader->RelabelAODs(kTRUE);
}
for(Int_t iCut = 0; iCut<fnCuts; iCut++){
fiCut = iCut;
Bool_t isRunningEMCALrelAna = kFALSE;
if (fNDMRecoMode > 0){
if (((AliCaloPhotonCuts*)fClusterCutArray->At(fiCut))->GetClusterType() == 1) isRunningEMCALrelAna = kTRUE;
}
Int_t eventNotAccepted = ((AliConvEventCuts*)fEventCutArray->At(iCut))->IsEventAcceptedByCut(fV0Reader->GetEventCuts(),fInputEvent,fMCEvent,fIsHeavyIon, isRunningEMCALrelAna);
if(fIsMC==2){
Float_t xsection = -1.;
Float_t ntrials = -1.;
((AliConvEventCuts*)fEventCutArray->At(iCut))->GetXSectionAndNTrials(fMCEvent,xsection,ntrials, fInputEvent );
if((xsection==-1.) || (ntrials==-1.)) AliFatal(Form("ERROR: GetXSectionAndNTrials returned invalid xsection/ntrials, periodName from V0Reader: '%s'",fV0Reader->GetPeriodName().Data()));
fProfileJetJetXSection[iCut]->Fill(0.,xsection);
fHistoJetJetNTrials[iCut]->Fill("#sum{NTrials}", ntrials);
}
if (fIsMC > 1){
fWeightJetJetMC = 1;
Float_t maxjetpt = -1.;
Float_t pthard = -1;
if(((AliConvEventCuts*)fEventCutArray->At(fiCut))->GetUseJetFinderForOutliers()) maxjetpt = fOutlierJetReader->GetMaxJetPt();
Bool_t isMCJet = ((AliConvEventCuts*)fEventCutArray->At(iCut))->IsJetJetMCEventAccepted( fMCEvent, fWeightJetJetMC ,pthard, fInputEvent, maxjetpt);
if (fIsMC == 3){
Double_t weightMult = ((AliConvEventCuts*)fEventCutArray->At(iCut))->GetWeightForMultiplicity(fV0Reader->GetNumberOfPrimaryTracks());
fWeightJetJetMC = fWeightJetJetMC*weightMult;
}
if (!isMCJet){
fHistoNEvents[iCut]->Fill(10,fWeightJetJetMC);
if (fIsMC>1) fHistoNEventsWOWeight[iCut]->Fill(10);
continue;
}
}
Bool_t triggered = kTRUE;
if(eventNotAccepted!=0){
// cout << "event rejected due to wrong trigger: " <<eventNotAccepted << endl;
fHistoNEvents[iCut]->Fill(eventNotAccepted,fWeightJetJetMC); // Check Centrality, PileUp, SDD and V0AND --> Not Accepted => eventQuality = 1
if (fIsMC>1) fHistoNEventsWOWeight[iCut]->Fill(eventNotAccepted);
if (eventNotAccepted==3 && fIsMC > 0){
triggered = kFALSE;
}else {
continue;
}
}
if(eventQuality != 0 && triggered== kTRUE){// Event Not Accepted
//cout << "event rejected due to: " <<eventQuality << endl;
fHistoNEvents[iCut]->Fill(eventQuality, fWeightJetJetMC);
if (fIsMC>1) fHistoNEventsWOWeight[iCut]->Fill(eventQuality); // Should be 0 here
continue;
}
if (triggered == kTRUE) {
fHistoNEvents[iCut]->Fill(eventQuality,fWeightJetJetMC);
if (fIsMC>1) fHistoNEventsWOWeight[iCut]->Fill(eventQuality); // Should be 0 here
fHistoNGoodESDTracks[iCut]->Fill(fNumberOfESDTracks,fWeightJetJetMC);
if(!fDoLightOutput){
fHistoSPDClusterTrackletBackground[iCut]->Fill(fInputEvent->GetMultiplicity()->GetNumberOfTracklets(),(fInputEvent->GetNumberOfITSClusters(0)+fInputEvent->GetNumberOfITSClusters(1)),fWeightJetJetMC);
}
}
if(fIsMC> 0){ // Process MC Particle
if(((AliConvEventCuts*)fEventCutArray->At(iCut))->GetSignalRejection() != 0){
if(fInputEvent->IsA()==AliESDEvent::Class()){
((AliConvEventCuts*)fEventCutArray->At(iCut))->GetNotRejectedParticles(((AliConvEventCuts*)fEventCutArray->At(iCut))->GetSignalRejection(),
((AliConvEventCuts*)fEventCutArray->At(iCut))->GetAcceptedHeader(),
fMCEvent);
} else if(fInputEvent->IsA()==AliAODEvent::Class()){
((AliConvEventCuts*)fEventCutArray->At(iCut))->GetNotRejectedParticles(((AliConvEventCuts*)fEventCutArray->At(iCut))->GetSignalRejection(),
((AliConvEventCuts*)fEventCutArray->At(iCut))->GetAcceptedHeader(),
fInputEvent);
}
}
if(fInputEvent->IsA()==AliESDEvent::Class()) ProcessMCParticles();
if(fInputEvent->IsA()==AliAODEvent::Class()) ProcessAODMCParticles();
}
// continue is called after processing of MC particle to get correct acceptance
// and include trigger efficiency in efficiency (relevant when mimicking)
if (triggered==kFALSE) continue;
if (fNDMRecoMode < 2){
ProcessConversionPhotonCandidates(); // Process this cuts conversion gammas
}
if (fNDMRecoMode > 0){
ProcessCaloPhotonCandidates(); // Process this cuts calo gammas
}
if (fNDMRecoMode == 0 ){
ProcessNeutralDecayMesonCandidatesPureConversions(); // Process neutral pion candidates purely from conversions
}
if (fNDMRecoMode == 1){
ProcessNeutralPionCandidatesMixedConvCalo(); // Process neutral pion candidates mixed conv and calo
}
if (fNDMRecoMode == 2){
ProcessNeutralPionCandidatesPureCalo(); // Process neutral pion candidates purely from calo
}
if(fInputEvent->IsA()==AliESDEvent::Class()) ProcessPionCandidates(); // Process this cuts gammas
if(fInputEvent->IsA()==AliAODEvent::Class()) ProcessPionCandidatesAOD();
//CalculateMesonCandidates();
if(((AliConversionMesonCuts*)fMesonCutArray->At(iCut))->DoBGCalculation()){
if(((AliConversionMesonCuts*)fMesonCutArray->At(iCut))->UseLikeSignMixing()){
CalculateBackground(5);
} else{
CalculateBackground(((AliConversionMesonCuts*)fMesonCutArray->At(iCut))->GetBackgroundMode());
}
}
UpdateEventByEventData();
fVectorDoubleCountTruePi0s.clear();
fVectorDoubleCountTrueHNMs.clear();
fVectorDoubleCountTrueConvGammas.clear();
fGoodConvGammas->Clear();
fClusterCandidates->Clear();
fNeutralDecayParticleCandidates->Clear();
if(fNeutralDecayParticleSidebandCandidates) fNeutralDecayParticleSidebandCandidates->Clear();
fPosPionCandidates->Clear();
fNegPionCandidates->Clear();
}
fSelectorNegPionIndex.clear();
fSelectorPosPionIndex.clear();
if( fIsMC && fInputEvent->IsA()==AliAODEvent::Class() && !(fV0Reader->AreAODsRelabeled())){
RelabelAODPhotonCandidates(kFALSE); // Back to ESDMC Label
fV0Reader->RelabelAODs(kFALSE);
}
PostData( 1, fOutputContainer );
}
//________________________________________________________________________
Bool_t AliAnalysisTaskNeutralMesonToPiPlPiMiNeutralMeson::Notify(){
for(Int_t iCut = 0; iCut<fnCuts;iCut++){
if (((AliConvEventCuts*)fEventCutArray->At(iCut))->GetPeriodEnum() == AliConvEventCuts::kNoPeriod && ((AliConvEventCuts*)fV0Reader->GetEventCuts())->GetPeriodEnum() != AliConvEventCuts::kNoPeriod){
((AliConvEventCuts*)fEventCutArray->At(iCut))->SetPeriodEnumExplicit(((AliConvEventCuts*)fV0Reader->GetEventCuts())->GetPeriodEnum());
} else if (((AliConvEventCuts*)fEventCutArray->At(iCut))->GetPeriodEnum() == AliConvEventCuts::kNoPeriod ){
((AliConvEventCuts*)fEventCutArray->At(iCut))->SetPeriodEnum(fV0Reader->GetPeriodName());
}
if( !((AliConvEventCuts*)fEventCutArray->At(iCut))->GetDoEtaShift() ){
if(!fDoLightOutput){
fProfileEtaShift[iCut]->Fill(0.,0.);
}
continue; // No Eta Shift requested, continue
}
if( ((AliConvEventCuts*)fEventCutArray->At(iCut))->GetEtaShift() == 0.0){ // Eta Shift requested but not set, get shift automatically
((AliConvEventCuts*)fEventCutArray->At(iCut))->GetCorrectEtaShiftFromPeriod();
((AliConvEventCuts*)fEventCutArray->At(iCut))->DoEtaShift(kFALSE); // Eta Shift Set, make sure that it is called only once
((AliPrimaryPionCuts*)fPionCutArray->At(iCut))->SetEtaShift( ((AliConvEventCuts*)fEventCutArray->At(iCut))->GetEtaShift() );
if(!fDoLightOutput){
fProfileEtaShift[iCut]->Fill(0.,(((AliConvEventCuts*)fEventCutArray->At(iCut))->GetEtaShift()));
}
continue;
} else {
printf(" Eta t PiPlusPiMinus Gamma Task %s :: Eta Shift Manually Set to %f \n\n",
(((AliConvEventCuts*)fEventCutArray->At(iCut))->GetCutNumber()).Data(),((AliConvEventCuts*)fEventCutArray->At(iCut))->GetEtaShift());
((AliConvEventCuts*)fEventCutArray->At(iCut))->DoEtaShift(kFALSE); // Eta Shift Set, make sure that it is called only once
((AliPrimaryPionCuts*)fPionCutArray->At(iCut))->SetEtaShift( ((AliConvEventCuts*)fEventCutArray->At(iCut))->GetEtaShift() );
if(!fDoLightOutput){
fProfileEtaShift[iCut]->Fill(0.,(((AliConvEventCuts*)fEventCutArray->At(iCut))->GetEtaShift()));
}
}
}
return kTRUE;
}
void AliAnalysisTaskNeutralMesonToPiPlPiMiNeutralMeson::Terminate(const Option_t *){
///Grid
}
//________________________________________________________________________
void AliAnalysisTaskNeutralMesonToPiPlPiMiNeutralMeson::ProcessCaloPhotonCandidates()
{
Int_t nclus = 0;
nclus = fInputEvent->GetNumberOfCaloClusters();
// cout << nclus << endl;
if(nclus == 0) return;
// plotting histograms on cell/tower level, only if extendedMatchAndQA > 1
((AliCaloPhotonCuts*)fClusterCutArray->At(fiCut))->FillHistogramsExtendedQA(fInputEvent,fIsMC);
// match tracks to clusters
((AliCaloPhotonCuts*)fClusterCutArray->At(fiCut))->MatchTracksToClusters(fInputEvent,fWeightJetJetMC,kTRUE, fMCEvent);
// vertex
Double_t vertex[3] = {0};
InputEvent()->GetPrimaryVertex()->GetXYZ(vertex);
// Loop over EMCal clusters
for(Long_t i = 0; i < nclus; i++){
Double_t tempClusterWeight = fWeightJetJetMC;
Double_t tempPhotonWeight = fWeightJetJetMC;
std::unique_ptr<AliVCluster> clus;
if(fInputEvent->IsA()==AliESDEvent::Class()) clus = std::unique_ptr<AliVCluster>(new AliESDCaloCluster(*(AliESDCaloCluster*)fInputEvent->GetCaloCluster(i)));
else if(fInputEvent->IsA()==AliAODEvent::Class()) clus = std::unique_ptr<AliVCluster>(new AliAODCaloCluster(*(AliAODCaloCluster*)fInputEvent->GetCaloCluster(i)));
if (!clus) continue;
// Set the jetjet weight to 1 in case the cluster orignated from the minimum bias header
if (fIsMC>0 && ((AliConvEventCuts*)fEventCutArray->At(fiCut))->GetSignalRejection() == 4){
if( ((AliConvEventCuts*)fEventCutArray->At(fiCut))->IsParticleFromBGEvent(clus->GetLabelAt(0), fMCEvent, fInputEvent) == 2)
tempClusterWeight = 1;
}
if(!((AliCaloPhotonCuts*)fClusterCutArray->At(fiCut))->ClusterIsSelected(clus.get(),fInputEvent,fMCEvent,fIsMC, tempClusterWeight,i)){
continue;
}
// TLorentzvector with cluster
TLorentzVector clusterVector;
clus->GetMomentum(clusterVector,vertex);
TLorentzVector tmpvec;
tmpvec.SetPxPyPzE(clusterVector.Px(),clusterVector.Py(),clusterVector.Pz(),clusterVector.E());
// convert to AODConversionPhoton
AliAODConversionPhoton *PhotonCandidate=new AliAODConversionPhoton(&tmpvec);
if(!PhotonCandidate){ continue;}
// Flag Photon as CaloPhoton
PhotonCandidate->SetIsCaloPhoton(((AliCaloPhotonCuts*)fClusterCutArray->At(fiCut))->GetClusterType());
PhotonCandidate->SetCaloClusterRef(i);
// get MC label
if(fIsMC>0){
Int_t* mclabelsCluster = clus->GetLabels();
PhotonCandidate->SetNCaloPhotonMCLabels(clus->GetNLabels());
// cout << clus->GetNLabels() << endl;
if (clus->GetNLabels()>0){
for (Int_t k =0; k< (Int_t)clus->GetNLabels(); k++){
PhotonCandidate->SetCaloPhotonMCLabel(k,mclabelsCluster[k]);
// Int_t pdgCode = fMCEvent->Particle(mclabelsCluster[k])->GetPdgCode();
// cout << "label " << k << "\t" << mclabelsCluster[k] << " pdg code: " << pdgCode << endl;
}
}
}
fIsFromDesiredHeader = kTRUE;
fIsOverlappingWithOtherHeader = kFALSE;
//TString periodName = fV0Reader->GetPeriodName();
// test whether largest contribution to cluster orginates in added signals
if (fIsMC>0 && ((AliConvEventCuts*)fEventCutArray->At(fiCut))->GetSignalRejection() > 0){
if (((AliConvEventCuts*)fEventCutArray->At(fiCut))->IsParticleFromBGEvent(PhotonCandidate->GetCaloPhotonMCLabel(0), fMCEvent, fInputEvent) == 0){
fIsFromDesiredHeader = kFALSE;
}
if (clus->GetNLabels()>1){
Int_t* mclabelsCluster = clus->GetLabels();
for (Int_t l = 1; l < (Int_t)clus->GetNLabels(); l++ ){
if (((AliConvEventCuts*)fEventCutArray->At(fiCut))->IsParticleFromBGEvent(mclabelsCluster[l], fMCEvent, fInputEvent) == 0){
fIsOverlappingWithOtherHeader = kTRUE;
}
}
}
}
if ( (fIsFromDesiredHeader && !fIsOverlappingWithOtherHeader && !fAllowOverlapHeaders) || (fIsFromDesiredHeader && fAllowOverlapHeaders)){
fHistoClusterGammaPt[fiCut]->Fill(PhotonCandidate->Pt(),tempPhotonWeight);
fHistoClusterGammaEta[fiCut]->Fill(PhotonCandidate->Eta(),tempPhotonWeight);
fHistoClusterGammaE[fiCut]->Fill(PhotonCandidate->E(),tempPhotonWeight);
if(fIsMC>0){
if(fInputEvent->IsA()==AliESDEvent::Class()){
ProcessTrueCaloPhotonCandidates(PhotonCandidate);
}else {
ProcessTrueCaloPhotonCandidatesAOD(PhotonCandidate);
}
}
fClusterCandidates->Add(PhotonCandidate); // if no second loop is required add to events good gammas
} else{
delete PhotonCandidate;
}
}
}
//________________________________________________________________________
void AliAnalysisTaskNeutralMesonToPiPlPiMiNeutralMeson::ProcessTrueCaloPhotonCandidates(AliAODConversionPhoton *TruePhotonCandidate)
{
TParticle *Photon = nullptr;
if (TruePhotonCandidate->GetIsCaloPhoton() == 0) AliFatal("CaloPhotonFlag has not been set task will abort");
// fHistoTrueNLabelsInClus[fiCut]->Fill(TruePhotonCandidate->GetNCaloPhotonMCLabels());
const AliVVertex* primVtxMC = fMCEvent->GetPrimaryVertex();
Double_t mcProdVtxX = primVtxMC->GetX();
Double_t mcProdVtxY = primVtxMC->GetY();
Double_t mcProdVtxZ = primVtxMC->GetZ();
if (TruePhotonCandidate->GetNCaloPhotonMCLabels()>0)Photon = fMCEvent->Particle(TruePhotonCandidate->GetCaloPhotonMCLabel(0));
else return;
if(Photon == nullptr){
// cout << "no photon" << endl;
return;
}
// Int_t pdgCodeParticle = Photon->GetPdgCode();
TruePhotonCandidate->SetCaloPhotonMCFlags(fMCEvent, kFALSE);
// True Photon
if(!fDoLightOutput){
Bool_t isPrimary = ((AliConvEventCuts*)fEventCutArray->At(fiCut))->IsConversionPrimaryESD( fMCEvent, TruePhotonCandidate->GetCaloPhotonMCLabel(0), mcProdVtxX, mcProdVtxY, mcProdVtxZ);
if(isPrimary){
if (TruePhotonCandidate->IsLargestComponentPhoton()){
fHistoTrueClusterGammaPt[fiCut]->Fill(TruePhotonCandidate->Pt(), fWeightJetJetMC);
if (GammaIsNeutralMesonPiPlPiMiNDMDaughter(TruePhotonCandidate->GetCaloPhotonMCLabel(0))){
fHistoTrueClusterGammaFromNeutralMesonPt[fiCut]->Fill(TruePhotonCandidate->Pt(), fWeightJetJetMC);
}
}
if (TruePhotonCandidate->IsLargestComponentElectron() && TruePhotonCandidate->IsConversion()){
fHistoTrueClusterGammaPt[fiCut]->Fill(TruePhotonCandidate->Pt(), fWeightJetJetMC);
if (GammaIsNeutralMesonPiPlPiMiNDMDaughter(TruePhotonCandidate->GetCaloPhotonMCLabel(0))){
fHistoTrueClusterGammaFromNeutralMesonPt[fiCut]->Fill(TruePhotonCandidate->Pt(), fWeightJetJetMC);
}
}
}
}
return;
}
//________________________________________________________________________
void AliAnalysisTaskNeutralMesonToPiPlPiMiNeutralMeson::ProcessTrueCaloPhotonCandidatesAOD(AliAODConversionPhoton *TruePhotonCandidate)
{
AliAODMCParticle *Photon = NULL;
TClonesArray *AODMCTrackArray = dynamic_cast<TClonesArray*>(fInputEvent->FindListObject(AliAODMCParticle::StdBranchName()));
if (AODMCTrackArray){
if (TruePhotonCandidate->GetIsCaloPhoton() == 0) AliFatal("CaloPhotonFlag has not been set task will abort");
}else{
AliInfo("AODMCTrackArray could not be loaded");
return;
}
// fHistoTrueNLabelsInClus[fiCut]->Fill(TruePhotonCandidate->GetNCaloPhotonMCLabels());
const AliVVertex* primVtxMC = fMCEvent->GetPrimaryVertex();
Double_t mcProdVtxX = primVtxMC->GetX();
Double_t mcProdVtxY = primVtxMC->GetY();
Double_t mcProdVtxZ = primVtxMC->GetZ();
if (TruePhotonCandidate->GetNCaloPhotonMCLabels()>0)Photon = (AliAODMCParticle*) AODMCTrackArray->At(TruePhotonCandidate->GetCaloPhotonMCLabel(0));
else return;
if(Photon == NULL){
return;
}
// Int_t pdgCodeParticle = Photon->GetPdgCode();
TruePhotonCandidate->SetCaloPhotonMCFlagsAOD(AODMCTrackArray, kFALSE);
// True Photon
if(!fDoLightOutput){
Bool_t isPrimary = ((AliConvEventCuts*)fEventCutArray->At(fiCut))->IsConversionPrimaryAOD( fInputEvent, Photon, mcProdVtxX, mcProdVtxY, mcProdVtxZ);
if(isPrimary){
if (TruePhotonCandidate->IsLargestComponentPhoton()){
fHistoTrueClusterGammaPt[fiCut]->Fill(TruePhotonCandidate->Pt(), fWeightJetJetMC);
if (GammaIsNeutralMesonPiPlPiMiNDMDaughterAOD(AODMCTrackArray,TruePhotonCandidate->GetCaloPhotonMCLabel(0))){
fHistoTrueClusterGammaFromNeutralMesonPt[fiCut]->Fill(TruePhotonCandidate->Pt(), fWeightJetJetMC);
}
}
if (TruePhotonCandidate->IsLargestComponentElectron() && TruePhotonCandidate->IsConversion()){
fHistoTrueClusterGammaPt[fiCut]->Fill(TruePhotonCandidate->Pt(), fWeightJetJetMC);
if (GammaIsNeutralMesonPiPlPiMiNDMDaughterAOD(AODMCTrackArray,TruePhotonCandidate->GetCaloPhotonMCLabel(0))){
fHistoTrueClusterGammaFromNeutralMesonPt[fiCut]->Fill(TruePhotonCandidate->Pt(), fWeightJetJetMC);
}
}
}
}
return;
}
//________________________________________________________________________
void AliAnalysisTaskNeutralMesonToPiPlPiMiNeutralMeson::ProcessConversionPhotonCandidates(){
Int_t nV0 = 0;
TList GoodGammasStepOne;
TList GoodGammasStepTwo;
// Loop over Photon Candidates allocated by ReaderV1
for(Int_t i = 0; i < fReaderGammas->GetEntriesFast(); i++){
AliAODConversionPhoton* PhotonCandidate = (AliAODConversionPhoton*) fReaderGammas->At(i);
if(!PhotonCandidate) continue;
fIsFromMBHeader = kTRUE;
if( fMCEvent && ((AliConvEventCuts*)fEventCutArray->At(fiCut))->GetSignalRejection() != 0 ){
Int_t isPosFromMBHeader
= ((AliConvEventCuts*)fEventCutArray->At(fiCut))->IsParticleFromBGEvent(PhotonCandidate->GetMCLabelPositive(), fMCEvent, fInputEvent);
if(isPosFromMBHeader == 0 && ((AliConvEventCuts*)fEventCutArray->At(fiCut))->GetSignalRejection() != 3) continue;
Int_t isNegFromMBHeader
= ((AliConvEventCuts*)fEventCutArray->At(fiCut))->IsParticleFromBGEvent(PhotonCandidate->GetMCLabelNegative(), fMCEvent,fInputEvent);
if(isNegFromMBHeader == 0 && ((AliConvEventCuts*)fEventCutArray->At(fiCut))->GetSignalRejection() != 3) continue;
if( (isNegFromMBHeader+isPosFromMBHeader) != 4) fIsFromMBHeader = kFALSE;
}
if(!((AliConversionPhotonCuts*)fGammaCutArray->At(fiCut))->PhotonIsSelected(PhotonCandidate,fInputEvent)) continue;
if(!((AliConversionPhotonCuts*)fGammaCutArray->At(fiCut))->UseElecSharingCut() &&
!((AliConversionPhotonCuts*)fGammaCutArray->At(fiCut))->UseToCloseV0sCut()){ // if no post reader loop is required add to events good gammas
fGoodConvGammas->Add(PhotonCandidate);
if(fIsFromMBHeader && (!fDoLightOutput)){
fHistoConvGammaPt[fiCut]->Fill(PhotonCandidate->Pt(), fWeightJetJetMC);
fHistoConvGammaEta[fiCut]->Fill(PhotonCandidate->Eta(), fWeightJetJetMC);
}
if(fMCEvent){
if(fInputEvent->IsA()==AliESDEvent::Class())
ProcessTrueConversionPhotonCandidates(PhotonCandidate);
if(fInputEvent->IsA()==AliAODEvent::Class())
ProcessTrueConversionPhotonCandidatesAOD(PhotonCandidate);
}
} else if(((AliConversionPhotonCuts*)fGammaCutArray->At(fiCut))->UseElecSharingCut()){ // if Shared Electron cut is enabled, Fill array, add to step one
((AliConversionPhotonCuts*)fGammaCutArray->At(fiCut))->FillElectonLabelArray(PhotonCandidate,nV0);
nV0++;
GoodGammasStepOne.Add(PhotonCandidate);
} else if(!((AliConversionPhotonCuts*)fGammaCutArray->At(fiCut))->UseElecSharingCut() &&
((AliConversionPhotonCuts*)fGammaCutArray->At(fiCut))->UseToCloseV0sCut()){ // shared electron is disabled, step one not needed -> step two
GoodGammasStepTwo.Add(PhotonCandidate);
}
}
if(((AliConversionPhotonCuts*)fGammaCutArray->At(fiCut))->UseElecSharingCut()){
for(Int_t i = 0;i<GoodGammasStepOne.GetEntries();i++){
AliAODConversionPhoton *PhotonCandidate= (AliAODConversionPhoton*) GoodGammasStepOne.At(i);
if(!PhotonCandidate) continue;
fIsFromMBHeader = kTRUE;
if(fMCEvent && ((AliConvEventCuts*)fEventCutArray->At(fiCut))->GetSignalRejection() != 0){
Int_t isPosFromMBHeader
= ((AliConvEventCuts*)fEventCutArray->At(fiCut))->IsParticleFromBGEvent(PhotonCandidate->GetMCLabelPositive(), fMCEvent,fInputEvent);
Int_t isNegFromMBHeader
= ((AliConvEventCuts*)fEventCutArray->At(fiCut))->IsParticleFromBGEvent(PhotonCandidate->GetMCLabelNegative(), fMCEvent,fInputEvent);
if( (isNegFromMBHeader+isPosFromMBHeader) != 4) fIsFromMBHeader = kFALSE;
}
if(!((AliConversionPhotonCuts*)fGammaCutArray->At(fiCut))->RejectSharedElectronV0s(PhotonCandidate,i,GoodGammasStepOne.GetEntries())) continue;
if(!((AliConversionPhotonCuts*)fGammaCutArray->At(fiCut))->UseToCloseV0sCut()){ // To Colse v0s cut diabled, step two not needed
fGoodConvGammas->Add(PhotonCandidate);
if(fIsFromMBHeader && (!fDoLightOutput)){
fHistoConvGammaPt[fiCut]->Fill(PhotonCandidate->Pt(), fWeightJetJetMC);
fHistoConvGammaEta[fiCut]->Fill(PhotonCandidate->Eta(), fWeightJetJetMC);
}
if(fMCEvent){
if(fInputEvent->IsA()==AliESDEvent::Class())
ProcessTrueConversionPhotonCandidates(PhotonCandidate);
if(fInputEvent->IsA()==AliAODEvent::Class())
ProcessTrueConversionPhotonCandidatesAOD(PhotonCandidate);
}
}
else GoodGammasStepTwo.Add(PhotonCandidate); // Close v0s cut enabled -> add to list two
}
}
if(((AliConversionPhotonCuts*)fGammaCutArray->At(fiCut))->UseToCloseV0sCut()){
for(Int_t i = 0;i<GoodGammasStepTwo.GetEntries();i++){
AliAODConversionPhoton* PhotonCandidate = (AliAODConversionPhoton*) GoodGammasStepTwo.At(i);
if(!PhotonCandidate) continue;
if(fMCEvent && ((AliConvEventCuts*)fEventCutArray->At(fiCut))->GetSignalRejection() != 0){
Int_t isPosFromMBHeader
= ((AliConvEventCuts*)fEventCutArray->At(fiCut))->IsParticleFromBGEvent(PhotonCandidate->GetMCLabelPositive(), fMCEvent,fInputEvent);
Int_t isNegFromMBHeader
= ((AliConvEventCuts*)fEventCutArray->At(fiCut))->IsParticleFromBGEvent(PhotonCandidate->GetMCLabelNegative(), fMCEvent,fInputEvent);
if( (isNegFromMBHeader+isPosFromMBHeader) != 4) fIsFromMBHeader = kFALSE;
}
if(!((AliConversionPhotonCuts*)fGammaCutArray->At(fiCut))->RejectToCloseV0s(PhotonCandidate,&GoodGammasStepTwo,i)) continue;
fGoodConvGammas->Add(PhotonCandidate); // Add gamma to current cut TList
if(fIsFromMBHeader && (!fDoLightOutput)){
fHistoConvGammaPt[fiCut]->Fill(PhotonCandidate->Pt(), fWeightJetJetMC); // Differences to old V0Reader in p_t due to conversion KF->TLorentzVector
fHistoConvGammaEta[fiCut]->Fill(PhotonCandidate->Eta(), fWeightJetJetMC);
}
if(fMCEvent){
if(fInputEvent->IsA()==AliESDEvent::Class())
ProcessTrueConversionPhotonCandidates(PhotonCandidate);
if(fInputEvent->IsA()==AliAODEvent::Class())
ProcessTrueConversionPhotonCandidatesAOD(PhotonCandidate);
}
}
}
}
//________________________________________________________________________
void AliAnalysisTaskNeutralMesonToPiPlPiMiNeutralMeson::ProcessTrueConversionPhotonCandidates(AliAODConversionPhoton *TruePhotonCandidate)
{
// Process True Photons
TParticle *posDaughter = TruePhotonCandidate->GetPositiveMCDaughter(fMCEvent);
TParticle *negDaughter = TruePhotonCandidate->GetNegativeMCDaughter(fMCEvent);
const AliVVertex* primVtxMC = fMCEvent->GetPrimaryVertex();
Double_t mcProdVtxX = primVtxMC->GetX();
Double_t mcProdVtxY = primVtxMC->GetY();
Double_t mcProdVtxZ = primVtxMC->GetZ();
if(posDaughter == NULL || negDaughter == NULL){
return; // One particle does not exist
}
if(posDaughter->GetMother(0) != negDaughter->GetMother(0)){ // Not Same Mother == Combinatorial Bck
return;
}
else if (posDaughter->GetMother(0) == -1){
return;
}
if(TMath::Abs(posDaughter->GetPdgCode())!=11 || TMath::Abs(negDaughter->GetPdgCode())!=11){
return; //One Particle is not electron
}
if(posDaughter->GetPdgCode()==negDaughter->GetPdgCode()){
return; // Same Charge
}
if(posDaughter->GetUniqueID() != 5 || negDaughter->GetUniqueID() !=5){
return;// check if the daughters come from a conversion
}
TParticle *Photon = TruePhotonCandidate->GetMCParticle(fMCEvent);
if(Photon->GetPdgCode() != 22){
return; // Mother is no Photon
}
// True Photon
if (CheckVectorForDoubleCount(fVectorDoubleCountTrueConvGammas,posDaughter->GetMother(0)) && (!fDoLightOutput)) fHistoDoubleCountTrueConvGammaRPt[fiCut]->Fill(TruePhotonCandidate->GetConversionRadius(),TruePhotonCandidate->Pt());
Int_t labelGamma = TruePhotonCandidate->GetMCParticleLabel(fMCEvent);
Bool_t gammaIsPrimary = ((AliConvEventCuts*)fEventCutArray->At(fiCut))->IsConversionPrimaryESD( fMCEvent, labelGamma, mcProdVtxX, mcProdVtxY, mcProdVtxZ);
if( gammaIsPrimary ){
if( fIsFromMBHeader && (!fDoLightOutput) ){
fHistoTrueConvGammaPt[fiCut]->Fill(TruePhotonCandidate->Pt(),fWeightJetJetMC);
if (GammaIsNeutralMesonPiPlPiMiNDMDaughter(labelGamma)){
fHistoTrueConvGammaFromNeutralMesonPt[fiCut]->Fill(TruePhotonCandidate->Pt(), fWeightJetJetMC);
}
}
}
}
//________________________________________________________________________
void AliAnalysisTaskNeutralMesonToPiPlPiMiNeutralMeson::ProcessTrueConversionPhotonCandidatesAOD(AliAODConversionPhoton *TruePhotonCandidate)
{
// Process True Photons
TClonesArray *AODMCTrackArray = dynamic_cast<TClonesArray*>(fInputEvent->FindListObject(AliAODMCParticle::StdBranchName()));
if (AODMCTrackArray == NULL || TruePhotonCandidate == NULL){
return;
}
AliAODMCParticle *posDaughter = (AliAODMCParticle*) AODMCTrackArray->At(TruePhotonCandidate->GetMCLabelPositive());
AliAODMCParticle *negDaughter = (AliAODMCParticle*) AODMCTrackArray->At(TruePhotonCandidate->GetMCLabelNegative());
const AliVVertex* primVtxMC = fMCEvent->GetPrimaryVertex();
Double_t mcProdVtxX = primVtxMC->GetX();
Double_t mcProdVtxY = primVtxMC->GetY();
Double_t mcProdVtxZ = primVtxMC->GetZ();
if(posDaughter == NULL || negDaughter == NULL) {
return; // One particle does not exist
}
if(posDaughter->GetMother() != negDaughter->GetMother()){ // Not Same Mother == Combinatorial Bck
return;
}
else if (posDaughter->GetMother() == -1){
return;
}
if(TMath::Abs(posDaughter->GetPdgCode())!=11 || TMath::Abs(negDaughter->GetPdgCode())!=11){
return; //One Particle is not electron
}
if(posDaughter->GetPdgCode()==negDaughter->GetPdgCode()){
return; // Same Charge
}
if(posDaughter->GetMCProcessCode() != 5 || negDaughter->GetMCProcessCode() !=5){
return;// check if the daughters come from a conversion
}
AliAODMCParticle *Photon = (AliAODMCParticle*) AODMCTrackArray->At(posDaughter->GetMother());
if(Photon->GetPdgCode() != 22){
return; // Mother is no Photon
}
// True Photon
if (CheckVectorForDoubleCount(fVectorDoubleCountTrueConvGammas,posDaughter->GetMother()) && (!fDoLightOutput)) fHistoDoubleCountTrueConvGammaRPt[fiCut]->Fill(TruePhotonCandidate->GetConversionRadius(),TruePhotonCandidate->Pt());
// for AOD you have to ask electron for mother to get label
Int_t labelGamma = posDaughter->GetMother();
Bool_t gammaIsPrimary = ((AliConvEventCuts*)fEventCutArray->At(fiCut))->IsConversionPrimaryAOD( fInputEvent, Photon, mcProdVtxX, mcProdVtxY, mcProdVtxZ);
if( gammaIsPrimary ){
if( fIsFromMBHeader && (!fDoLightOutput) ){
fHistoTrueConvGammaPt[fiCut]->Fill(TruePhotonCandidate->Pt(), fWeightJetJetMC);
if (GammaIsNeutralMesonPiPlPiMiNDMDaughterAOD(AODMCTrackArray, labelGamma)){
fHistoTrueConvGammaFromNeutralMesonPt[fiCut]->Fill(TruePhotonCandidate->Pt(), fWeightJetJetMC);
}
}
}
}
//________________________________________________________________________
void AliAnalysisTaskNeutralMesonToPiPlPiMiNeutralMeson::ProcessNeutralDecayMesonCandidatesPureConversions(){
// Conversion Gammas
if(fGoodConvGammas->GetEntries()>1){
for(Int_t firstGammaIndex=0;firstGammaIndex<fGoodConvGammas->GetEntries()-1;firstGammaIndex++){
AliAODConversionPhoton *gamma0=dynamic_cast<AliAODConversionPhoton*>(fGoodConvGammas->At(firstGammaIndex));
if (gamma0==nullptr) continue;
for(Int_t secondGammaIndex=firstGammaIndex+1;secondGammaIndex<fGoodConvGammas->GetEntries();secondGammaIndex++){
AliAODConversionPhoton *gamma1=dynamic_cast<AliAODConversionPhoton*>(fGoodConvGammas->At(secondGammaIndex));
//Check for same Electron ID
if (gamma1==nullptr) continue;
if(gamma0->GetTrackLabelPositive() == gamma1->GetTrackLabelPositive() ||
gamma0->GetTrackLabelNegative() == gamma1->GetTrackLabelNegative() ||
gamma0->GetTrackLabelNegative() == gamma1->GetTrackLabelPositive() ||
gamma0->GetTrackLabelPositive() == gamma1->GetTrackLabelNegative() ) continue;
AliAODConversionMother *NDMcand = new AliAODConversionMother(gamma0,gamma1);
NDMcand->SetLabels(firstGammaIndex,secondGammaIndex);
NDMcand->CalculateDistanceOfClossetApproachToPrimVtx(fInputEvent->GetPrimaryVertex());
if(!fDoLightOutput){
fHistoGammaGammaInvMassPtBeforeCuts[fiCut]->Fill(NDMcand->M(),NDMcand->Pt(), fWeightJetJetMC);
}
if( ((AliConversionMesonCuts*)fNeutralDecayMesonCutArray->At(fiCut))->DoGammaMinEnergyCut() ){
Int_t minDaughters = ((AliConversionMesonCuts*)fNeutralDecayMesonCutArray->At(fiCut))->GetNDaughterEnergyCut();
Float_t minDaughterEnergy = ((AliConversionMesonCuts*)fNeutralDecayMesonCutArray->At(fiCut))->GetSingleDaughterMinE();
if(minDaughters==1){ // at least one over threshold
if( (gamma0->E() < minDaughterEnergy) && (gamma1->E() < minDaughterEnergy)) continue;
} else if (minDaughters==2){ // both over threshold
if( (gamma0->E() < minDaughterEnergy) || (gamma1->E() < minDaughterEnergy)) continue;
}
}
if((((AliConversionMesonCuts*)fNeutralDecayMesonCutArray->At(fiCut))->MesonIsSelected(NDMcand,kTRUE,((AliConvEventCuts*)fEventCutArray->At(fiCut))->GetEtaShift()))){
if(fIsMC){
if(fInputEvent->IsA()==AliESDEvent::Class())
ProcessTrueNeutralPionCandidatesPureConversions(NDMcand,gamma0,gamma1);
if(fInputEvent->IsA()==AliAODEvent::Class())
ProcessTrueNeutralPionCandidatesPureConversionsAOD(NDMcand,gamma0,gamma1);
}
if (((AliConversionMesonCuts*)fNeutralDecayMesonCutArray->At(fiCut))->MesonIsSelectedByMassCut(NDMcand, 0)){
fNeutralDecayParticleCandidates->Add(NDMcand);
if(!fDoLightOutput){
fHistoGammaGammaInvMassPt[fiCut]->Fill(NDMcand->M(),NDMcand->Pt(), fWeightJetJetMC);
}
} else if((((AliConversionMesonCuts*)fMesonCutArray->At(fiCut))->UseSidebandMixing()) &&
(((AliConversionMesonCuts*)fMesonCutArray->At(fiCut))->MesonIsSelectedByMassCut(NDMcand, 1))){
fNeutralDecayParticleSidebandCandidates->Add(NDMcand);
if(!fDoLightOutput){
fHistoGammaGammaInvMassPt[fiCut]->Fill(NDMcand->M(),NDMcand->Pt(), fWeightJetJetMC);
}
} else if((((AliConversionMesonCuts*)fMesonCutArray->At(fiCut))->UseSidebandMixingBothSides()) &&
((((AliConversionMesonCuts*)fMesonCutArray->At(fiCut))->MesonIsSelectedByMassCut(NDMcand, 2)) ||
((((AliConversionMesonCuts*)fMesonCutArray->At(fiCut))->MesonIsSelectedByMassCut(NDMcand, 3))))){
fNeutralDecayParticleSidebandCandidates->Add(NDMcand);
if(!fDoLightOutput){
fHistoGammaGammaInvMassPt[fiCut]->Fill(NDMcand->M(),NDMcand->Pt(), fWeightJetJetMC);
}
} else{
delete NDMcand;
}
} else{
delete NDMcand;
}
}
}
}
}
//________________________________________________________________________
void AliAnalysisTaskNeutralMesonToPiPlPiMiNeutralMeson::ProcessNeutralPionCandidatesPureCalo(){
// Conversion Gammas
if(fClusterCandidates->GetEntries()>0){
// vertex
Double_t vertex[3] = {0};
InputEvent()->GetPrimaryVertex()->GetXYZ(vertex);
for(Int_t firstGammaIndex=0;firstGammaIndex<fClusterCandidates->GetEntries();firstGammaIndex++){
AliAODConversionPhoton *gamma0=dynamic_cast<AliAODConversionPhoton*>(fClusterCandidates->At(firstGammaIndex));
if (gamma0==nullptr) continue;
for(Int_t secondGammaIndex=0;secondGammaIndex<fClusterCandidates->GetEntries();secondGammaIndex++){
if (firstGammaIndex == secondGammaIndex) continue;
AliAODConversionPhoton *gamma1=dynamic_cast<AliAODConversionPhoton*>(fClusterCandidates->At(secondGammaIndex));
if (gamma1==nullptr) continue;
AliAODConversionMother *NDMcand = new AliAODConversionMother(gamma0,gamma1);
NDMcand->SetLabels(firstGammaIndex,secondGammaIndex);
if(!fDoLightOutput){
fHistoGammaGammaInvMassPtBeforeCuts[fiCut]->Fill(NDMcand->M(),NDMcand->Pt(), fWeightJetJetMC);
}
if( ((AliConversionMesonCuts*)fNeutralDecayMesonCutArray->At(fiCut))->DoGammaMinEnergyCut() ){
Int_t minDaughters = ((AliConversionMesonCuts*)fNeutralDecayMesonCutArray->At(fiCut))->GetNDaughterEnergyCut();
Float_t minDaughterEnergy = ((AliConversionMesonCuts*)fNeutralDecayMesonCutArray->At(fiCut))->GetSingleDaughterMinE();
if(minDaughters==1){ // at least one over threshold
if( (gamma0->E() < minDaughterEnergy) && (gamma1->E() < minDaughterEnergy)) continue;
} else if (minDaughters==2){ // both over threshold
if( (gamma0->E() < minDaughterEnergy) || (gamma1->E() < minDaughterEnergy)) continue;
}
}
if((((AliConversionMesonCuts*)fNeutralDecayMesonCutArray->At(fiCut))->MesonIsSelected(NDMcand,kTRUE,((AliConvEventCuts*)fEventCutArray->At(fiCut))->GetEtaShift()))){
if(fIsMC){
if(fInputEvent->IsA()==AliESDEvent::Class())
ProcessTrueNeutralPionCandidatesPureCalo(NDMcand,gamma0,gamma1);
if(fInputEvent->IsA()==AliAODEvent::Class())
ProcessTrueNeutralPionCandidatesPureCaloAOD(NDMcand,gamma0,gamma1);
}
if (((AliConversionMesonCuts*)fNeutralDecayMesonCutArray->At(fiCut))->MesonIsSelectedByMassCut(NDMcand, 0)){
fNeutralDecayParticleCandidates->Add(NDMcand);
if(!fDoLightOutput){
fHistoGammaGammaInvMassPt[fiCut]->Fill(NDMcand->M(),NDMcand->Pt(), fWeightJetJetMC);
}
} else if((((AliConversionMesonCuts*)fMesonCutArray->At(fiCut))->UseSidebandMixing()) &&
(((AliConversionMesonCuts*)fMesonCutArray->At(fiCut))->MesonIsSelectedByMassCut(NDMcand, 1))){
fNeutralDecayParticleSidebandCandidates->Add(NDMcand);
if(!fDoLightOutput){
fHistoGammaGammaInvMassPt[fiCut]->Fill(NDMcand->M(),NDMcand->Pt(), fWeightJetJetMC);
}
} else if((((AliConversionMesonCuts*)fMesonCutArray->At(fiCut))->UseSidebandMixingBothSides()) &&
((((AliConversionMesonCuts*)fMesonCutArray->At(fiCut))->MesonIsSelectedByMassCut(NDMcand, 2)) ||
((((AliConversionMesonCuts*)fMesonCutArray->At(fiCut))->MesonIsSelectedByMassCut(NDMcand, 3))))){
fNeutralDecayParticleSidebandCandidates->Add(NDMcand);
if(!fDoLightOutput){
fHistoGammaGammaInvMassPt[fiCut]->Fill(NDMcand->M(),NDMcand->Pt(), fWeightJetJetMC);
}
}else {
delete NDMcand;
}
} else{
delete NDMcand;
}
}
}
}
}
//______________________________________________________________________
void AliAnalysisTaskNeutralMesonToPiPlPiMiNeutralMeson::ProcessTrueNeutralPionCandidatesPureCalo( AliAODConversionMother *Pi0Candidate, AliAODConversionPhoton *TrueGammaCandidate0, AliAODConversionPhoton *TrueGammaCandidate1)
{
// Process True Mesons
Bool_t isTrueNDM = kFALSE;
Int_t gamma0MCLabel = TrueGammaCandidate0->GetCaloPhotonMCLabel(0); // get most probable MC label
Int_t gamma0MotherLabel = -1;
if(gamma0MCLabel != -1){ // Gamma is Combinatorial; MC Particles don't belong to the same Mother
TParticle * gammaMC0 = (TParticle*)fMCEvent->Particle(gamma0MCLabel);
if (TrueGammaCandidate0->IsLargestComponentPhoton() || TrueGammaCandidate0->IsLargestComponentElectron()){ // largest component is electro magnetic
// get mother of interest (pi0 or eta)
if (TrueGammaCandidate0->IsLargestComponentPhoton()){ // for photons its the direct mother
gamma0MotherLabel=gammaMC0->GetMother(0);
} else if (TrueGammaCandidate0->IsLargestComponentElectron()){ // for electrons its either the direct mother or for conversions the grandmother
if (TrueGammaCandidate0->IsConversion() && gammaMC0->GetMother(0)>-1){
gamma0MotherLabel=fMCEvent->Particle(gammaMC0->GetMother(0))->GetMother(0);
} else {
gamma0MotherLabel=gammaMC0->GetMother(0);
}
}
}
}
if (TrueGammaCandidate1->GetIsCaloPhoton() == 0) AliFatal("CaloPhotonFlag has not been set. Aborting");
Int_t gamma1MCLabel = TrueGammaCandidate1->GetCaloPhotonMCLabel(0); // get most probable MC label
Int_t gamma1MotherLabel = -1;
// check if
if(gamma1MCLabel != -1){ // Gamma is Combinatorial; MC Particles don't belong to the same Mother
// Daughters Gamma 1
TParticle * gammaMC1 = (TParticle*)fMCEvent->Particle(gamma1MCLabel);
if (TrueGammaCandidate1->IsLargestComponentPhoton() || TrueGammaCandidate1->IsLargestComponentElectron()){ // largest component is electro magnetic
// get mother of interest (pi0 or eta)
if (TrueGammaCandidate1->IsLargestComponentPhoton()){ // for photons its the direct mother
gamma1MotherLabel=gammaMC1->GetMother(0);
} else if (TrueGammaCandidate1->IsLargestComponentElectron()){ // for electrons its either the direct mother or for conversions the grandmother
if (TrueGammaCandidate1->IsConversion() && gammaMC1->GetMother(0)>-1) gamma1MotherLabel=fMCEvent->Particle(gammaMC1->GetMother(0))->GetMother(0);
else gamma1MotherLabel=gammaMC1->GetMother(0);
}
}
}
if(gamma0MotherLabel>=0 && gamma0MotherLabel==gamma1MotherLabel){
if(((TParticle*)fMCEvent->Particle(gamma1MotherLabel))->GetPdgCode() == fPDGCodeNDM){
isTrueNDM=kTRUE;
if (CheckVectorForDoubleCount(fVectorDoubleCountTruePi0s,gamma0MotherLabel) && (!fDoLightOutput)) fHistoDoubleCountTruePi0InvMassPt[fiCut]->Fill(Pi0Candidate->M(),Pi0Candidate->Pt());
}
}
if(isTrueNDM){// True Pion
Pi0Candidate->SetTrueMesonValue(1);
Pi0Candidate->SetMCLabel(gamma0MotherLabel);
if(!fDoLightOutput){
fHistoTrueMotherGammaGammaInvMassPt[fiCut]->Fill(Pi0Candidate->M(),Pi0Candidate->Pt(), fWeightJetJetMC);
switch( fSelectedHeavyNeutralMeson ) {
case 0: // ETA MESON
if( IsEtaPiPlPiMiPiZeroDaughter(gamma0MotherLabel) )
fHistoTrueMotherGammaGammaFromHNMInvMassPt[fiCut]->Fill(Pi0Candidate->M(),Pi0Candidate->Pt(), fWeightJetJetMC);
break;
case 1: // OMEGA MESON
if( IsOmegaPiPlPiMiPiZeroDaughter(gamma0MotherLabel) )
fHistoTrueMotherGammaGammaFromHNMInvMassPt[fiCut]->Fill(Pi0Candidate->M(),Pi0Candidate->Pt(), fWeightJetJetMC);
break;
case 2: // ETA PRIME MESON
if( IsEtaPrimePiPlPiMiEtaDaughter(gamma0MotherLabel) )
fHistoTrueMotherGammaGammaFromHNMInvMassPt[fiCut]->Fill(Pi0Candidate->M(),Pi0Candidate->Pt(), fWeightJetJetMC);
break;
case 3: // D0 MESON
if( IsD0PiPlPiMiPiZeroDaughter(gamma0MotherLabel) )
fHistoTrueMotherGammaGammaFromHNMInvMassPt[fiCut]->Fill(Pi0Candidate->M(),Pi0Candidate->Pt(), fWeightJetJetMC);
break;
default:
AliError(Form("Heavy neutral meson not correctly selected (only 0,1,2,3 valid)... selected: %d",fSelectedHeavyNeutralMeson));
}
}
}
}
//______________________________________________________________________
void AliAnalysisTaskNeutralMesonToPiPlPiMiNeutralMeson::ProcessTrueNeutralPionCandidatesPureCaloAOD( AliAODConversionMother *Pi0Candidate, AliAODConversionPhoton *TrueGammaCandidate0, AliAODConversionPhoton *TrueGammaCandidate1)
{
// Process True Mesons
// Process True Mesons
TClonesArray *AODMCTrackArray = dynamic_cast<TClonesArray*>(fInputEvent->FindListObject(AliAODMCParticle::StdBranchName()));
if (AODMCTrackArray == NULL) return;
Bool_t isTrueNDM = kFALSE;
Int_t gamma0MCLabel = TrueGammaCandidate0->GetCaloPhotonMCLabel(0); // get most probable MC label
Int_t gamma0MotherLabel = -1;
if(gamma0MCLabel != -1){ // Gamma is Combinatorial; MC Particles don't belong to the same Mother
AliAODMCParticle * gammaMC0 = static_cast<AliAODMCParticle*>(AODMCTrackArray->At(gamma0MCLabel));
if (TrueGammaCandidate0->IsLargestComponentPhoton() || TrueGammaCandidate0->IsLargestComponentElectron()){ // largest component is electro magnetic
// get mother of interest (pi0 or eta)
if (TrueGammaCandidate0->IsLargestComponentPhoton()){ // for photons its the direct mother
gamma0MotherLabel=gammaMC0->GetMother();
} else if (TrueGammaCandidate0->IsLargestComponentElectron()){ // for electrons its either the direct mother or for conversions the grandmother
if (TrueGammaCandidate0->IsConversion() && gammaMC0->GetMother()>-1){
AliAODMCParticle * gammaGrandMotherMC0 = static_cast<AliAODMCParticle*>(AODMCTrackArray->At(gammaMC0->GetMother()));
gamma0MotherLabel=gammaGrandMotherMC0->GetMother();
} else {
gamma0MotherLabel=gammaMC0->GetMother();
}
}
}
}
if (TrueGammaCandidate1->GetIsCaloPhoton() == 0) AliFatal("CaloPhotonFlag has not been set. Aborting");
Int_t gamma1MCLabel = TrueGammaCandidate1->GetCaloPhotonMCLabel(0); // get most probable MC label
Int_t gamma1MotherLabel = -1;
// check if
if(gamma1MCLabel != -1){ // Gamma is Combinatorial; MC Particles don't belong to the same Mother
// Daughters Gamma 1
AliAODMCParticle * gammaMC1 = static_cast<AliAODMCParticle*>(AODMCTrackArray->At(gamma1MCLabel));
if (TrueGammaCandidate1->IsLargestComponentPhoton() || TrueGammaCandidate1->IsLargestComponentElectron()){ // largest component is electro magnetic
// get mother of interest (pi0 or eta)
if (TrueGammaCandidate1->IsLargestComponentPhoton()){ // for photons its the direct mother
gamma1MotherLabel=gammaMC1->GetMother();
} else if (TrueGammaCandidate1->IsLargestComponentElectron()){ // for electrons its either the direct mother or for conversions the grandmother
if (TrueGammaCandidate1->IsConversion() && gammaMC1->GetMother()>-1){
AliAODMCParticle * gammaGrandMotherMC1 = static_cast<AliAODMCParticle*>(AODMCTrackArray->At(gammaMC1->GetMother()));
gamma1MotherLabel=gammaGrandMotherMC1->GetMother();
}else gamma1MotherLabel=gammaMC1->GetMother();
}
}
}
if(gamma0MotherLabel>=0 && gamma0MotherLabel==gamma1MotherLabel){
if(((AliAODMCParticle*)AODMCTrackArray->At(gamma1MotherLabel))->GetPdgCode() == fPDGCodeNDM){
isTrueNDM=kTRUE;
if (CheckVectorForDoubleCount(fVectorDoubleCountTruePi0s,gamma0MotherLabel) && (!fDoLightOutput)) fHistoDoubleCountTruePi0InvMassPt[fiCut]->Fill(Pi0Candidate->M(),Pi0Candidate->Pt(), fWeightJetJetMC);
}
}
if(isTrueNDM){// True Pion
Pi0Candidate->SetTrueMesonValue(1);
Pi0Candidate->SetMCLabel(gamma0MotherLabel);
if(!fDoLightOutput){
fHistoTrueMotherGammaGammaInvMassPt[fiCut]->Fill(Pi0Candidate->M(),Pi0Candidate->Pt(), fWeightJetJetMC);
switch( fSelectedHeavyNeutralMeson ) {
case 0: // ETA MESON
if( IsEtaPiPlPiMiPiZeroDaughterAOD(AODMCTrackArray,gamma0MotherLabel) )
fHistoTrueMotherGammaGammaFromHNMInvMassPt[fiCut]->Fill(Pi0Candidate->M(),Pi0Candidate->Pt(), fWeightJetJetMC);
break;
case 1: // OMEGA MESON
if( IsOmegaPiPlPiMiPiZeroDaughterAOD(AODMCTrackArray,gamma0MotherLabel) )
fHistoTrueMotherGammaGammaFromHNMInvMassPt[fiCut]->Fill(Pi0Candidate->M(),Pi0Candidate->Pt(), fWeightJetJetMC);
break;
case 2: // ETA PRIME MESON
if( IsEtaPrimePiPlPiMiEtaDaughterAOD(AODMCTrackArray,gamma0MotherLabel) )
fHistoTrueMotherGammaGammaFromHNMInvMassPt[fiCut]->Fill(Pi0Candidate->M(),Pi0Candidate->Pt(), fWeightJetJetMC);
break;
case 3: // D0 MESON
if( IsD0PiPlPiMiPiZeroDaughterAOD(AODMCTrackArray,gamma0MotherLabel) )
fHistoTrueMotherGammaGammaFromHNMInvMassPt[fiCut]->Fill(Pi0Candidate->M(),Pi0Candidate->Pt(), fWeightJetJetMC);
break;
default:
AliError(Form("Heavy neutral meson not correctly selected (only 0,1,2,3 valid)... selected: %d",fSelectedHeavyNeutralMeson));
}
}
}
}
//______________________________________________________________________
void AliAnalysisTaskNeutralMesonToPiPlPiMiNeutralMeson::ProcessTrueNeutralPionCandidatesPureConversions(AliAODConversionMother *Pi0Candidate, AliAODConversionPhoton *TrueGammaCandidate0, AliAODConversionPhoton *TrueGammaCandidate1)
{
// Process True Mesons
if(TrueGammaCandidate0->GetV0Index()<fInputEvent->GetNumberOfV0s()){
Bool_t isTrueNDM = kFALSE;
Bool_t isTruePi0Dalitz = kFALSE;
Bool_t gamma0DalitzCand = kFALSE;
Bool_t gamma1DalitzCand = kFALSE;
Int_t gamma0MCLabel = TrueGammaCandidate0->GetMCParticleLabel(fMCEvent);
Int_t gamma0MotherLabel = -1;
Int_t motherRealLabel = -1;
if(gamma0MCLabel != -1){ // Gamma is Combinatorial; MC Particles don't belong to the same Mother
// Daughters Gamma 0
TParticle * negativeMC = (TParticle*)TrueGammaCandidate0->GetNegativeMCDaughter(fMCEvent);
TParticle * positiveMC = (TParticle*)TrueGammaCandidate0->GetPositiveMCDaughter(fMCEvent);
TParticle * gammaMC0 = (TParticle*)fMCEvent->Particle(gamma0MCLabel);
if(TMath::Abs(negativeMC->GetPdgCode())==11 && TMath::Abs(positiveMC->GetPdgCode())==11){ // Electrons ...
if(negativeMC->GetUniqueID() == 5 && positiveMC->GetUniqueID() ==5){ // ... From Conversion ...
if(gammaMC0->GetPdgCode() == 22){ // ... with Gamma Mother
gamma0MotherLabel=gammaMC0->GetFirstMother();
motherRealLabel=gammaMC0->GetFirstMother();
}
}
if(gammaMC0->GetPdgCode() ==111){ // Dalitz candidate
gamma0DalitzCand = kTRUE;
gamma0MotherLabel=-111;
motherRealLabel=gamma0MCLabel;
}
}
}
if(TrueGammaCandidate1->GetV0Index()<fInputEvent->GetNumberOfV0s()){
Int_t gamma1MCLabel = TrueGammaCandidate1->GetMCParticleLabel(fMCEvent);
Int_t gamma1MotherLabel = -1;
if(gamma1MCLabel != -1){ // Gamma is Combinatorial; MC Particles don't belong to the same Mother
// Daughters Gamma 1
TParticle * negativeMC = (TParticle*)TrueGammaCandidate1->GetNegativeMCDaughter(fMCEvent);
TParticle * positiveMC = (TParticle*)TrueGammaCandidate1->GetPositiveMCDaughter(fMCEvent);
TParticle * gammaMC1 = (TParticle*)fMCEvent->Particle(gamma1MCLabel);
if(TMath::Abs(negativeMC->GetPdgCode())==11 && TMath::Abs(positiveMC->GetPdgCode())==11){ // Electrons ...
if(negativeMC->GetUniqueID() == 5 && positiveMC->GetUniqueID() ==5){ // ... From Conversion ...
if(gammaMC1->GetPdgCode() == 22){ // ... with Gamma Mother
gamma1MotherLabel=gammaMC1->GetFirstMother();
}
}
if(gammaMC1->GetPdgCode() ==111 ){ // Dalitz candidate
gamma1DalitzCand = kTRUE;
gamma1MotherLabel=-111;
}
}
}
if(gamma0MotherLabel>=0 && gamma0MotherLabel==gamma1MotherLabel){
if(((TParticle*)fMCEvent->Particle(gamma1MotherLabel))->GetPdgCode() == fPDGCodeNDM){
isTrueNDM=kTRUE;
if (CheckVectorForDoubleCount(fVectorDoubleCountTruePi0s,gamma0MotherLabel) && (!fDoLightOutput)) fHistoDoubleCountTruePi0InvMassPt[fiCut]->Fill(Pi0Candidate->M(),Pi0Candidate->Pt(), fWeightJetJetMC);
}
}
//Identify Dalitz candidate
if (gamma1DalitzCand || gamma0DalitzCand){
if (gamma0DalitzCand && gamma0MCLabel >=0 && gamma0MCLabel==gamma1MotherLabel){
if (gamma0MotherLabel == -111) isTruePi0Dalitz = kTRUE;
}
if (gamma1DalitzCand && gamma1MCLabel >=0 && gamma1MCLabel==gamma0MotherLabel){
if (gamma1MotherLabel == -111) isTruePi0Dalitz = kTRUE;
}
}
if(isTrueNDM || isTruePi0Dalitz){// True Pion
Pi0Candidate->SetTrueMesonValue(1);
Pi0Candidate->SetMCLabel(motherRealLabel);
if(!fDoLightOutput){
fHistoTrueMotherGammaGammaInvMassPt[fiCut]->Fill(Pi0Candidate->M(),Pi0Candidate->Pt(), fWeightJetJetMC);
switch( fSelectedHeavyNeutralMeson ) {
case 0: // ETA MESON
if( IsEtaPiPlPiMiPiZeroDaughter(motherRealLabel) )
fHistoTrueMotherGammaGammaFromHNMInvMassPt[fiCut]->Fill(Pi0Candidate->M(),Pi0Candidate->Pt(), fWeightJetJetMC);
break;
case 1: // OMEGA MESON
if( IsOmegaPiPlPiMiPiZeroDaughter(motherRealLabel) )
fHistoTrueMotherGammaGammaFromHNMInvMassPt[fiCut]->Fill(Pi0Candidate->M(),Pi0Candidate->Pt(), fWeightJetJetMC);
break;
case 2: // ETA PRIME MESON
if( IsEtaPrimePiPlPiMiEtaDaughter(motherRealLabel) )
fHistoTrueMotherGammaGammaFromHNMInvMassPt[fiCut]->Fill(Pi0Candidate->M(),Pi0Candidate->Pt(), fWeightJetJetMC);
break;
case 3: // D0 MESON
if( IsD0PiPlPiMiPiZeroDaughter(motherRealLabel) )
fHistoTrueMotherGammaGammaFromHNMInvMassPt[fiCut]->Fill(Pi0Candidate->M(),Pi0Candidate->Pt(), fWeightJetJetMC);
break;
default:
AliError(Form("Heavy neutral meson not correctly selected (only 0,1,2,3 valid)... selected: %d",fSelectedHeavyNeutralMeson));
}
}
}
}
}
}
//______________________________________________________________________
void AliAnalysisTaskNeutralMesonToPiPlPiMiNeutralMeson::ProcessTrueNeutralPionCandidatesPureConversionsAOD(AliAODConversionMother *Pi0Candidate, AliAODConversionPhoton *TrueGammaCandidate0, AliAODConversionPhoton *TrueGammaCandidate1)
{
// Process True Mesons
TClonesArray *AODMCTrackArray = dynamic_cast<TClonesArray*>(fInputEvent->FindListObject(AliAODMCParticle::StdBranchName()));
Bool_t isTruePi0 = kFALSE;
Bool_t isTruePi0Dalitz = kFALSE;
Bool_t gamma0DalitzCand = kFALSE;
Bool_t gamma1DalitzCand = kFALSE;
Int_t motherRealLabel = -1;
if (AODMCTrackArray!=nullptr && TrueGammaCandidate0 != nullptr){
AliAODMCParticle *positiveMC = static_cast<AliAODMCParticle*>(AODMCTrackArray->At(TrueGammaCandidate0->GetMCLabelPositive()));
AliAODMCParticle *negativeMC = static_cast<AliAODMCParticle*>(AODMCTrackArray->At(TrueGammaCandidate0->GetMCLabelNegative()));
Int_t gamma0MCLabel = -1;
Int_t gamma0MotherLabel = -1;
if(!positiveMC||!negativeMC)
return;
if(positiveMC->GetMother()>-1&&(negativeMC->GetMother() == positiveMC->GetMother())){
gamma0MCLabel = positiveMC->GetMother();
}
if(gamma0MCLabel != -1){ // Gamma is Combinatorial; MC Particles don't belong to the same Mother
// Daughters Gamma 0
AliAODMCParticle * gammaMC0 = static_cast<AliAODMCParticle*>(AODMCTrackArray->At(gamma0MCLabel));
if(TMath::Abs(negativeMC->GetPdgCode())==11 && TMath::Abs(positiveMC->GetPdgCode())==11){ // Electrons ...
if(((positiveMC->GetMCProcessCode())) == 5 && ((negativeMC->GetMCProcessCode())) == 5){ // ... From Conversion ...
if(gammaMC0->GetPdgCode() == 22){ // ... with Gamma Mother
gamma0MotherLabel=gammaMC0->GetMother();
motherRealLabel=gammaMC0->GetMother();
}
}
if(gammaMC0->GetPdgCode() ==111){ // Dalitz candidate
gamma0DalitzCand = kTRUE;
gamma0MotherLabel=-111;
motherRealLabel=gamma0MCLabel;
}
}
}
positiveMC = static_cast<AliAODMCParticle*>(AODMCTrackArray->At(TrueGammaCandidate1->GetMCLabelPositive()));
negativeMC = static_cast<AliAODMCParticle*>(AODMCTrackArray->At(TrueGammaCandidate1->GetMCLabelNegative()));
Int_t gamma1MCLabel = -1;
Int_t gamma1MotherLabel = -1;
if(!positiveMC||!negativeMC)
return;
if(positiveMC->GetMother()>-1&&(negativeMC->GetMother() == positiveMC->GetMother())){
gamma1MCLabel = positiveMC->GetMother();
}
if(gamma1MCLabel != -1){ // Gamma is Combinatorial; MC Particles don't belong to the same Mother
// Daughters Gamma 1
AliAODMCParticle * gammaMC1 = static_cast<AliAODMCParticle*>(AODMCTrackArray->At(gamma1MCLabel));
if(TMath::Abs(negativeMC->GetPdgCode())==11 && TMath::Abs(positiveMC->GetPdgCode())==11){ // Electrons ...
if(((positiveMC->GetMCProcessCode())) == 5 && ((negativeMC->GetMCProcessCode())) == 5){ // ... From Conversion ...
if(gammaMC1->GetPdgCode() == 22){ // ... with Gamma Mother
gamma1MotherLabel=gammaMC1->GetMother();
}
}
if(gammaMC1->GetPdgCode() ==111 ){ // Dalitz candidate
gamma1DalitzCand = kTRUE;
gamma1MotherLabel=-111;
}
}
}
if(gamma0MotherLabel>=0 && gamma0MotherLabel==gamma1MotherLabel){
if(static_cast<AliAODMCParticle*>(AODMCTrackArray->At(gamma1MotherLabel))->GetPdgCode() == fPDGCodeNDM){
isTruePi0=kTRUE;
if (CheckVectorForDoubleCount(fVectorDoubleCountTruePi0s,gamma0MotherLabel) &&(!fDoLightOutput)) fHistoDoubleCountTruePi0InvMassPt[fiCut]->Fill(Pi0Candidate->M(),Pi0Candidate->Pt(), fWeightJetJetMC);
}
}
//Identify Dalitz candidate
if (gamma1DalitzCand || gamma0DalitzCand){
if (gamma0DalitzCand && gamma0MCLabel >=0 && gamma0MCLabel==gamma1MotherLabel){
if (gamma0MotherLabel == -111) isTruePi0Dalitz = kTRUE;
}
if (gamma1DalitzCand && gamma1MCLabel >=0 && gamma1MCLabel==gamma0MotherLabel){
if (gamma1MotherLabel == -111) isTruePi0Dalitz = kTRUE;
}
}
if(isTruePi0 || isTruePi0Dalitz){// True Pion
Pi0Candidate->SetTrueMesonValue(1);
Pi0Candidate->SetMCLabel(motherRealLabel);
if(!fDoLightOutput){
fHistoTrueMotherGammaGammaInvMassPt[fiCut]->Fill(Pi0Candidate->M(),Pi0Candidate->Pt(), fWeightJetJetMC);
switch( fSelectedHeavyNeutralMeson ) {
case 0: // ETA MESON
if( IsEtaPiPlPiMiPiZeroDaughterAOD(AODMCTrackArray,motherRealLabel) )
fHistoTrueMotherGammaGammaFromHNMInvMassPt[fiCut]->Fill(Pi0Candidate->M(),Pi0Candidate->Pt(), fWeightJetJetMC);
break;
case 1: // OMEGA MESON
if( IsOmegaPiPlPiMiPiZeroDaughterAOD(AODMCTrackArray,motherRealLabel) )
fHistoTrueMotherGammaGammaFromHNMInvMassPt[fiCut]->Fill(Pi0Candidate->M(),Pi0Candidate->Pt(), fWeightJetJetMC);
break;
case 2: // ETA PRIME MESON
if( IsEtaPrimePiPlPiMiEtaDaughterAOD(AODMCTrackArray, motherRealLabel) )
fHistoTrueMotherGammaGammaFromHNMInvMassPt[fiCut]->Fill(Pi0Candidate->M(),Pi0Candidate->Pt(), fWeightJetJetMC);
break;
case 3: // D0 MESON
if( IsD0PiPlPiMiPiZeroDaughterAOD(AODMCTrackArray, motherRealLabel) )
fHistoTrueMotherGammaGammaFromHNMInvMassPt[fiCut]->Fill(Pi0Candidate->M(),Pi0Candidate->Pt(), fWeightJetJetMC);
break;
default:
AliError(Form("Heavy neutral meson not correctly selected (only 0,1,2,3 valid)... selected: %d",fSelectedHeavyNeutralMeson));
}
}
}
}
return;
}
//________________________________________________________________________
void AliAnalysisTaskNeutralMesonToPiPlPiMiNeutralMeson::ProcessNeutralPionCandidatesMixedConvCalo(){
// Conversion Gammas
if(fGoodConvGammas->GetEntries()>0){
// vertex
Double_t vertex[3] = {0};
InputEvent()->GetPrimaryVertex()->GetXYZ(vertex);
for(Int_t firstGammaIndex=0;firstGammaIndex<fGoodConvGammas->GetEntries();firstGammaIndex++){
AliAODConversionPhoton *gamma0=dynamic_cast<AliAODConversionPhoton*>(fGoodConvGammas->At(firstGammaIndex));
if (gamma0==nullptr) continue;
for(Int_t secondGammaIndex=0;secondGammaIndex<fClusterCandidates->GetEntries();secondGammaIndex++){
Bool_t matched = kFALSE;
AliAODConversionPhoton *gamma1=dynamic_cast<AliAODConversionPhoton*>(fClusterCandidates->At(secondGammaIndex));
if (gamma1==nullptr) continue;
if (gamma1->GetIsCaloPhoton() > 0){
AliVCluster* cluster = fInputEvent->GetCaloCluster(gamma1->GetCaloClusterRef());
matched = ((AliCaloPhotonCuts*)fClusterCutArray->At(fiCut))->MatchConvPhotonToCluster(gamma0,cluster, fInputEvent );
}
AliAODConversionMother *NDMcand = new AliAODConversionMother(gamma0,gamma1);
NDMcand->SetLabels(firstGammaIndex,secondGammaIndex);
if(!fDoLightOutput){
fHistoGammaGammaInvMassPtBeforeCuts[fiCut]->Fill(NDMcand->M(),NDMcand->Pt(), fWeightJetJetMC);
}
if( ((AliConversionMesonCuts*)fNeutralDecayMesonCutArray->At(fiCut))->DoGammaMinEnergyCut() ){
Int_t minDaughters = ((AliConversionMesonCuts*)fNeutralDecayMesonCutArray->At(fiCut))->GetNDaughterEnergyCut();
Float_t minDaughterEnergy = ((AliConversionMesonCuts*)fNeutralDecayMesonCutArray->At(fiCut))->GetSingleDaughterMinE();
if(minDaughters==1){ // at least one over threshold
if( (gamma0->E() < minDaughterEnergy) && (gamma1->E() < minDaughterEnergy)) continue;
} else if (minDaughters==2){ // both over threshold
if( (gamma0->E() < minDaughterEnergy) || (gamma1->E() < minDaughterEnergy)) continue;
}
}
if((((AliConversionMesonCuts*)fNeutralDecayMesonCutArray->At(fiCut))->MesonIsSelected(NDMcand,kTRUE,((AliConvEventCuts*)fEventCutArray->At(fiCut))->GetEtaShift()))){
if (!matched){
if(fIsMC){
if(fInputEvent->IsA()==AliESDEvent::Class())
ProcessTrueNeutralPionCandidatesMixedConvCalo(NDMcand,gamma0,gamma1);
if(fInputEvent->IsA()==AliAODEvent::Class())
ProcessTrueNeutralPionCandidatesMixedConvCaloAOD(NDMcand,gamma0,gamma1);
}
if (((AliConversionMesonCuts*)fNeutralDecayMesonCutArray->At(fiCut))->MesonIsSelectedByMassCut(NDMcand, 0)){
fNeutralDecayParticleCandidates->Add(NDMcand);
if(!fDoLightOutput){
fHistoGammaGammaInvMassPt[fiCut]->Fill(NDMcand->M(),NDMcand->Pt(), fWeightJetJetMC);
}
} else if((((AliConversionMesonCuts*)fMesonCutArray->At(fiCut))->UseSidebandMixing()) &&
(((AliConversionMesonCuts*)fMesonCutArray->At(fiCut))->MesonIsSelectedByMassCut(NDMcand, 1))){
fNeutralDecayParticleSidebandCandidates->Add(NDMcand);
if(!fDoLightOutput){
fHistoGammaGammaInvMassPt[fiCut]->Fill(NDMcand->M(),NDMcand->Pt(), fWeightJetJetMC);
}
} else if((((AliConversionMesonCuts*)fMesonCutArray->At(fiCut))->UseSidebandMixingBothSides()) &&
((((AliConversionMesonCuts*)fMesonCutArray->At(fiCut))->MesonIsSelectedByMassCut(NDMcand, 2)) ||
((((AliConversionMesonCuts*)fMesonCutArray->At(fiCut))->MesonIsSelectedByMassCut(NDMcand, 3))))){
fNeutralDecayParticleSidebandCandidates->Add(NDMcand);
if(!fDoLightOutput){
fHistoGammaGammaInvMassPt[fiCut]->Fill(NDMcand->M(),NDMcand->Pt(), fWeightJetJetMC);
}
} else{
delete NDMcand;
NDMcand=0x0;
}
}else{
delete NDMcand;
NDMcand=0x0;
}
}else{
delete NDMcand;
NDMcand=0x0;
}
}
}
}
}
//______________________________________________________________________
void AliAnalysisTaskNeutralMesonToPiPlPiMiNeutralMeson::ProcessTrueNeutralPionCandidatesMixedConvCalo( AliAODConversionMother *Pi0Candidate, AliAODConversionPhoton *TrueGammaCandidate0, AliAODConversionPhoton *TrueGammaCandidate1)
{
// Process True Mesons
if(TrueGammaCandidate0->GetV0Index()<fInputEvent->GetNumberOfV0s()){
Bool_t isTruePi0 = kFALSE;
Bool_t isTruePi0Dalitz = kFALSE;
Bool_t gamma0DalitzCand = kFALSE;
Int_t gamma0MCLabel = TrueGammaCandidate0->GetMCParticleLabel(fMCEvent);
Int_t gamma0MotherLabel = -1;
Int_t motherRealLabel = -1;
if(gamma0MCLabel != -1){ // Gamma is Combinatorial; MC Particles don't belong to the same Mother
// Daughters Gamma 0
TParticle * negativeMC = (TParticle*)TrueGammaCandidate0->GetNegativeMCDaughter(fMCEvent);
TParticle * positiveMC = (TParticle*)TrueGammaCandidate0->GetPositiveMCDaughter(fMCEvent);
TParticle * gammaMC0 = (TParticle*)fMCEvent->Particle(gamma0MCLabel);
if(TMath::Abs(negativeMC->GetPdgCode())==11 && TMath::Abs(positiveMC->GetPdgCode())==11){ // Electrons ...
if(negativeMC->GetUniqueID() == 5 && positiveMC->GetUniqueID() ==5){ // ... From Conversion ...
if(gammaMC0->GetPdgCode() == 22){ // ... with Gamma Mother
gamma0MotherLabel=gammaMC0->GetFirstMother();
motherRealLabel=gammaMC0->GetFirstMother();
}
}
if(gammaMC0->GetPdgCode() ==111){ // Dalitz candidate
gamma0DalitzCand = kTRUE;
gamma0MotherLabel=-111;
motherRealLabel=gamma0MCLabel;
}
}
}
if (TrueGammaCandidate1->GetIsCaloPhoton() == 0) AliFatal("CaloPhotonFlag has not been set. Aborting");
Int_t gamma1MCLabel = TrueGammaCandidate1->GetCaloPhotonMCLabel(0); // get most probable MC label
Int_t gamma1MotherLabel = -1;
// check if
if(gamma1MCLabel != -1){ // Gamma is Combinatorial; MC Particles don't belong to the same Mother
// Daughters Gamma 1
TParticle * gammaMC1 = (TParticle*)fMCEvent->Particle(gamma1MCLabel);
if (TrueGammaCandidate1->IsLargestComponentPhoton() || TrueGammaCandidate1->IsLargestComponentElectron()){ // largest component is electro magnetic
// get mother of interest (pi0 or eta)
if (TrueGammaCandidate1->IsLargestComponentPhoton()){ // for photons its the direct mother
gamma1MotherLabel=gammaMC1->GetMother(0);
} else if (TrueGammaCandidate1->IsLargestComponentElectron()){ // for electrons its either the direct mother or for conversions the grandmother
if (TrueGammaCandidate1->IsConversion() && gammaMC1->GetMother(0)>-1) gamma1MotherLabel=fMCEvent->Particle(gammaMC1->GetMother(0))->GetMother(0);
else gamma1MotherLabel=gammaMC1->GetMother(0);
}
}
}
if(gamma0MotherLabel>=0 && gamma0MotherLabel==gamma1MotherLabel){
if(((TParticle*)fMCEvent->Particle(gamma1MotherLabel))->GetPdgCode() == fPDGCodeNDM){
isTruePi0=kTRUE;
if (CheckVectorForDoubleCount(fVectorDoubleCountTruePi0s,gamma0MotherLabel) && (!fDoLightOutput)) fHistoDoubleCountTruePi0InvMassPt[fiCut]->Fill(Pi0Candidate->M(),Pi0Candidate->Pt(), fWeightJetJetMC);
}
}
if (gamma0DalitzCand ){
if (gamma0DalitzCand && gamma0MCLabel >=0 && gamma0MCLabel==gamma1MotherLabel){
if (gamma0MotherLabel == -111) isTruePi0Dalitz = kTRUE;
}
}
if(isTruePi0 || isTruePi0Dalitz ){
Pi0Candidate->SetTrueMesonValue(1);
Pi0Candidate->SetMCLabel(motherRealLabel);
if(!fDoLightOutput){
fHistoTrueMotherGammaGammaInvMassPt[fiCut]->Fill(Pi0Candidate->M(),Pi0Candidate->Pt(), fWeightJetJetMC);
switch( fSelectedHeavyNeutralMeson ) {
case 0: // ETA MESON
if( IsEtaPiPlPiMiPiZeroDaughter(motherRealLabel) )
fHistoTrueMotherGammaGammaFromHNMInvMassPt[fiCut]->Fill(Pi0Candidate->M(),Pi0Candidate->Pt(), fWeightJetJetMC);
break;
case 1: // OMEGA MESON
if( IsOmegaPiPlPiMiPiZeroDaughter(motherRealLabel) )
fHistoTrueMotherGammaGammaFromHNMInvMassPt[fiCut]->Fill(Pi0Candidate->M(),Pi0Candidate->Pt(), fWeightJetJetMC);
break;
case 2: // ETA PRIME MESON
if( IsEtaPrimePiPlPiMiEtaDaughter(motherRealLabel) )
fHistoTrueMotherGammaGammaFromHNMInvMassPt[fiCut]->Fill(Pi0Candidate->M(),Pi0Candidate->Pt(), fWeightJetJetMC);
break;
case 3: // D0 MESON
if( IsD0PiPlPiMiPiZeroDaughter(motherRealLabel) )
fHistoTrueMotherGammaGammaFromHNMInvMassPt[fiCut]->Fill(Pi0Candidate->M(),Pi0Candidate->Pt(), fWeightJetJetMC);
break;
default:
AliError(Form("Heavy neutral meson not correctly selected (only 0,1,2,3 valid)... selected: %d",fSelectedHeavyNeutralMeson));
}
}
}
}
}
//______________________________________________________________________
void AliAnalysisTaskNeutralMesonToPiPlPiMiNeutralMeson::ProcessTrueNeutralPionCandidatesMixedConvCaloAOD( AliAODConversionMother *Pi0Candidate, AliAODConversionPhoton *TrueGammaCandidate0, AliAODConversionPhoton *TrueGammaCandidate1)
{
// Process True Mesons
TClonesArray *AODMCTrackArray = dynamic_cast<TClonesArray*>(fInputEvent->FindListObject(AliAODMCParticle::StdBranchName()));
if (AODMCTrackArray == NULL) return;
AliAODMCParticle * negativeMC = static_cast<AliAODMCParticle*>(AODMCTrackArray->At(TrueGammaCandidate0->GetMCLabelNegative()));
AliAODMCParticle * positiveMC = static_cast<AliAODMCParticle*>(AODMCTrackArray->At(TrueGammaCandidate0->GetMCLabelPositive()));
if(TrueGammaCandidate0->GetV0Index()<fInputEvent->GetNumberOfV0s()){
Bool_t isTruePi0 = kFALSE;
Bool_t isTruePi0Dalitz = kFALSE;
Bool_t gamma0DalitzCand = kFALSE;
Int_t gamma0MCLabel = positiveMC->GetMother();// check that this always works
Int_t gamma0MotherLabel = -1;
Int_t motherRealLabel = -1;
if(gamma0MCLabel != -1){ // Gamma is Combinatorial; MC Particles don't belong to the same Mother
// Daughters Gamma 0
AliAODMCParticle * gammaMC0 = static_cast<AliAODMCParticle*>(AODMCTrackArray->At(gamma0MCLabel));
if(TMath::Abs(negativeMC->GetPdgCode())==11 && TMath::Abs(positiveMC->GetPdgCode())==11){ // Electrons ...
if(negativeMC->GetMCProcessCode() == 5 && positiveMC->GetMCProcessCode() ==5){ // ... From Conversion ...
if(gammaMC0->GetPdgCode() == 22){ // ... with Gamma Mother
gamma0MotherLabel=gammaMC0->GetMother();
motherRealLabel=gammaMC0->GetMother();
}
}
if(gammaMC0->GetPdgCode() ==111){ // Dalitz candidate
gamma0DalitzCand = kTRUE;
gamma0MotherLabel=-111;
motherRealLabel=gamma0MCLabel;
}
}
}
if (TrueGammaCandidate1->GetIsCaloPhoton() == 0) AliFatal("CaloPhotonFlag has not been set. Aborting");
Int_t gamma1MCLabel = TrueGammaCandidate1->GetCaloPhotonMCLabel(0); // get most probable MC label
Int_t gamma1MotherLabel = -1;
// check if
if(gamma1MCLabel != -1){ // Gamma is Combinatorial; MC Particles don't belong to the same Mother
// Daughters Gamma 1
AliAODMCParticle *gammaMC1 = static_cast<AliAODMCParticle*>(AODMCTrackArray->At(gamma1MCLabel));
if (TrueGammaCandidate1->IsLargestComponentPhoton() || TrueGammaCandidate1->IsLargestComponentElectron()){ // largest component is electro magnetic
// get mother of interest (pi0 or eta)
if (TrueGammaCandidate1->IsLargestComponentPhoton()){ // for photons its the direct mother
gamma1MotherLabel=gammaMC1->GetMother();
} else if (TrueGammaCandidate1->IsLargestComponentElectron()){ // for electrons its either the direct mother or for conversions the grandmother
if (TrueGammaCandidate1->IsConversion() && gammaMC1->GetMother()>-1) gamma1MotherLabel= (static_cast<AliAODMCParticle*>(AODMCTrackArray->At(gammaMC1->GetMother())))->GetMother();
else gamma1MotherLabel=gammaMC1->GetMother();
}
}
}
if(gamma0MotherLabel>=0 && gamma0MotherLabel==gamma1MotherLabel){
if((static_cast<AliAODMCParticle*>(AODMCTrackArray->At(gamma1MotherLabel)))->GetPdgCode() == fPDGCodeNDM){
isTruePi0=kTRUE;
if (CheckVectorForDoubleCount(fVectorDoubleCountTruePi0s,gamma0MotherLabel) && (!fDoLightOutput)) fHistoDoubleCountTruePi0InvMassPt[fiCut]->Fill(Pi0Candidate->M(),Pi0Candidate->Pt(), fWeightJetJetMC);
}
}
if (gamma0DalitzCand ){
if (gamma0DalitzCand && gamma0MCLabel >=0 && gamma0MCLabel==gamma1MotherLabel){
if (gamma0MotherLabel == -111) isTruePi0Dalitz = kTRUE;
}
}
if(isTruePi0 || isTruePi0Dalitz ){
Pi0Candidate->SetTrueMesonValue(1);
Pi0Candidate->SetMCLabel(motherRealLabel);
if(!fDoLightOutput){
fHistoTrueMotherGammaGammaInvMassPt[fiCut]->Fill(Pi0Candidate->M(),Pi0Candidate->Pt(), fWeightJetJetMC);
switch( fSelectedHeavyNeutralMeson ) {
case 0: // ETA MESON
if( IsEtaPiPlPiMiPiZeroDaughterAOD(AODMCTrackArray,motherRealLabel) )
fHistoTrueMotherGammaGammaFromHNMInvMassPt[fiCut]->Fill(Pi0Candidate->M(),Pi0Candidate->Pt(), fWeightJetJetMC);
break;
case 1: // OMEGA MESON
if( IsOmegaPiPlPiMiPiZeroDaughterAOD(AODMCTrackArray, motherRealLabel) )
fHistoTrueMotherGammaGammaFromHNMInvMassPt[fiCut]->Fill(Pi0Candidate->M(),Pi0Candidate->Pt(), fWeightJetJetMC);
break;
case 2: // ETA PRIME MESON
if( IsEtaPrimePiPlPiMiEtaDaughterAOD(AODMCTrackArray, motherRealLabel) )
fHistoTrueMotherGammaGammaFromHNMInvMassPt[fiCut]->Fill(Pi0Candidate->M(),Pi0Candidate->Pt(), fWeightJetJetMC);
break;
case 3: // D0 MESON
if( IsD0PiPlPiMiPiZeroDaughterAOD(AODMCTrackArray, motherRealLabel) )
fHistoTrueMotherGammaGammaFromHNMInvMassPt[fiCut]->Fill(Pi0Candidate->M(),Pi0Candidate->Pt(), fWeightJetJetMC);
break;
default:
AliError(Form("Heavy neutral meson not correctly selected (only 0,1,2,3 valid)... selected: %d",fSelectedHeavyNeutralMeson));
}
}
}
}
}
//________________________________________________________________________
void AliAnalysisTaskNeutralMesonToPiPlPiMiNeutralMeson::ProcessPionCandidates(){
Bool_t use4vecformass = ((AliPrimaryPionCuts*)fPionCutArray->At(fiCut))->Use4VecForMass();
Double_t magField = fInputEvent->GetMagneticField();
if( magField < 0.0 ){
magField = 1.0;
} else {
magField = -1.0;
}
vector<Int_t> lGoodNegPionIndexPrev(0);
vector<Int_t> lGoodPosPionIndexPrev(0);
for(UInt_t i = 0; i < fSelectorNegPionIndex.size(); i++){
AliESDtrack* negPionCandidate =dynamic_cast<AliESDtrack*>(fInputEvent->GetTrack(fSelectorNegPionIndex[i]));
if(! ((AliPrimaryPionCuts*)fPionCutArray->At(fiCut))->PionIsSelected(negPionCandidate) ) continue;
lGoodNegPionIndexPrev.push_back( fSelectorNegPionIndex[i] );
TLorentzVector* negPionforHandler = new TLorentzVector();
negPionforHandler->SetPxPyPzE(negPionCandidate->Px(), negPionCandidate->Py(), negPionCandidate->Pz(), negPionCandidate->E());
FixPzVecToMatchPDGInvMass(negPionforHandler);
AliAODConversionPhoton *negPionHandler = new AliAODConversionPhoton(negPionforHandler);
delete negPionforHandler;
fNegPionCandidates->Add(negPionHandler);
if(!fDoLightOutput){
fHistoNegPionPt[fiCut]->Fill(negPionCandidate->Pt(), fWeightJetJetMC);
fHistoNegPionPhi[fiCut]->Fill(negPionCandidate->Phi(), fWeightJetJetMC);
}
if( fMCEvent ) {
const AliVVertex* primVtxMC = fMCEvent->GetPrimaryVertex();
Double_t mcProdVtxX = primVtxMC->GetX();
Double_t mcProdVtxY = primVtxMC->GetY();
Double_t mcProdVtxZ = primVtxMC->GetZ();
Int_t labelNegPion = TMath::Abs( negPionCandidate->GetLabel() );
Bool_t negPionIsPrimary = ((AliConvEventCuts*)fEventCutArray->At(fiCut))->IsConversionPrimaryESD( fMCEvent, labelNegPion, mcProdVtxX, mcProdVtxY, mcProdVtxZ);
if( labelNegPion>-1 && labelNegPion < fMCEvent->GetNumberOfTracks() ){
TParticle* negPion = fMCEvent->Particle(labelNegPion);
if( negPion->GetPdgCode() == -211 ){
if(!fDoLightOutput){
if( negPionIsPrimary ){
fHistoTrueNegPionPt[fiCut]->Fill(negPionCandidate->Pt(), fWeightJetJetMC); //primary negPion
}
switch( fSelectedHeavyNeutralMeson ) {
case 0: // ETA MESON
if( IsEtaPiPlPiMiPiZeroDaughter(labelNegPion) && negPionIsPrimary )
fHistoTrueNegPionFromNeutralMesonPt[fiCut]->Fill(negPionCandidate->Pt(), fWeightJetJetMC);
break;
case 1: // OMEGA MESON
if( IsOmegaPiPlPiMiPiZeroDaughter(labelNegPion) && negPionIsPrimary)
fHistoTrueNegPionFromNeutralMesonPt[fiCut]->Fill(negPionCandidate->Pt(), fWeightJetJetMC);
break;
case 2: // ETA PRIME MESON
if( IsEtaPrimePiPlPiMiEtaDaughter(labelNegPion) && negPionIsPrimary)
fHistoTrueNegPionFromNeutralMesonPt[fiCut]->Fill(negPionCandidate->Pt(), fWeightJetJetMC);
break;
case 3: // D0 MESON
if( IsD0PiPlPiMiPiZeroDaughter(labelNegPion)& negPionIsPrimary)
fHistoTrueNegPionFromNeutralMesonPt[fiCut]->Fill(negPionCandidate->Pt(), fWeightJetJetMC);
break;
default:
AliError(Form("Heavy neutral meson not correctly selected (only 0,1,2,3 valid)... selected: %d",fSelectedHeavyNeutralMeson));
}
}
}
}
}
}
for(UInt_t i = 0; i < fSelectorPosPionIndex.size(); i++){
AliESDtrack* posPionCandidate = dynamic_cast<AliESDtrack*>(fInputEvent->GetTrack(fSelectorPosPionIndex[i]));
if(! ((AliPrimaryPionCuts*)fPionCutArray->At(fiCut))->PionIsSelected(posPionCandidate) ) continue;
lGoodPosPionIndexPrev.push_back( fSelectorPosPionIndex[i] );
TLorentzVector* posPionforHandler = new TLorentzVector();
posPionforHandler->SetPxPyPzE(posPionCandidate->Px(), posPionCandidate->Py(), posPionCandidate->Pz(), posPionCandidate->E());
FixPzVecToMatchPDGInvMass(posPionforHandler);
AliAODConversionPhoton *posPionHandler = new AliAODConversionPhoton(posPionforHandler);
delete posPionforHandler;
fPosPionCandidates->Add(posPionHandler);
if(!fDoLightOutput){
fHistoPosPionPt[fiCut]->Fill(posPionCandidate->Pt(), fWeightJetJetMC);
fHistoPosPionPhi[fiCut]->Fill(posPionCandidate->Phi(), fWeightJetJetMC);
}
if( fMCEvent ) {
const AliVVertex* primVtxMC = fMCEvent->GetPrimaryVertex();
Double_t mcProdVtxX = primVtxMC->GetX();
Double_t mcProdVtxY = primVtxMC->GetY();
Double_t mcProdVtxZ = primVtxMC->GetZ();
Int_t labelPosPion = TMath::Abs( posPionCandidate->GetLabel() );
Bool_t posPionIsPrimary = ((AliConvEventCuts*)fEventCutArray->At(fiCut))->IsConversionPrimaryESD( fMCEvent, labelPosPion, mcProdVtxX, mcProdVtxY, mcProdVtxZ);
if( labelPosPion>-1 && labelPosPion < fMCEvent->GetNumberOfTracks() ) {
TParticle* posPion = fMCEvent->Particle(labelPosPion);
if( posPion->GetPdgCode() == 211 ){
if(!fDoLightOutput){
if( posPionIsPrimary ){
fHistoTruePosPionPt[fiCut]->Fill(posPionCandidate->Pt(), fWeightJetJetMC);
}
switch( fSelectedHeavyNeutralMeson ) {
case 0: // ETA MESON
if( IsEtaPiPlPiMiPiZeroDaughter(labelPosPion) && posPionIsPrimary )
fHistoTruePosPionFromNeutralMesonPt[fiCut]->Fill(posPionCandidate->Pt(), fWeightJetJetMC);
break;
case 1: // OMEGA MESON
if( IsOmegaPiPlPiMiPiZeroDaughter(labelPosPion) && posPionIsPrimary)
fHistoTruePosPionFromNeutralMesonPt[fiCut]->Fill(posPionCandidate->Pt(), fWeightJetJetMC);
break;
case 2: // ETA PRIME MESON
if( IsEtaPrimePiPlPiMiEtaDaughter(labelPosPion) && posPionIsPrimary)
fHistoTruePosPionFromNeutralMesonPt[fiCut]->Fill(posPionCandidate->Pt(), fWeightJetJetMC);
break;
case 3: // D0 MESON
if( IsD0PiPlPiMiPiZeroDaughter(labelPosPion) && posPionIsPrimary )
fHistoTruePosPionFromNeutralMesonPt[fiCut]->Fill(posPionCandidate->Pt(), fWeightJetJetMC);
break;
default:
AliError(Form("Heavy neutral meson not correctly selected (only 0,1,2,3 valid)... selected: %d",fSelectedHeavyNeutralMeson));
}
}
}
}
}
}
// AliInfo(Form("Number of good neg pions: %i \t pos pions = %i", lGoodNegPionIndexPrev.size(), lGoodPosPionIndexPrev.size()));
for(UInt_t i = 0; i < lGoodNegPionIndexPrev.size(); i++){
AliVTrack* negPionCandidate = dynamic_cast<AliVTrack*>(fInputEvent->GetTrack(lGoodNegPionIndexPrev[i]));
//AliKFParticle negPionCandidateKF( *negPionCandidate->GetConstrainedParam(), 211 );
AliKFParticle negPionCandidateKF( *negPionCandidate, 211 );
for(UInt_t j = 0; j < lGoodPosPionIndexPrev.size(); j++){
AliVTrack *posPionCandidate = dynamic_cast<AliVTrack*>(fInputEvent->GetTrack(lGoodPosPionIndexPrev[j]));
//AliKFParticle posPionCandidateKF( *posPionCandidate->GetConstrainedParam(), 211 );
AliKFParticle posPionCandidateKF( *posPionCandidate, 211 );
// AliInfo(Form("virtualPhoton distance before pi+ pi- = %f", negPionCandidateKF.GetDistanceFromParticle(posPionCandidateKF)));
AliKFConversionPhoton virtualPhoton(negPionCandidateKF,posPionCandidateKF);
// AliInfo(Form(" GetPrimaryVertex() x=%f y=%f z=%f",primx,primy,primz));
// virtualPhoton->SetProductionVertex(primaryVertex);
virtualPhoton.SetTrackLabels( lGoodPosPionIndexPrev[j], lGoodNegPionIndexPrev[i]);
TLorentzVector posPionVec4;
TLorentzVector negPionVec4;
TLorentzVector virtPionVec4;
TLorentzVector posKFPionVec4;
TLorentzVector negKFPionVec4;
TLorentzVector virtKFPionVec4;
if(use4vecformass){
posKFPionVec4.SetPxPyPzE(posPionCandidateKF.Px(),posPionCandidateKF.Py(),posPionCandidateKF.Pz(),posPionCandidateKF.E());
negKFPionVec4.SetPxPyPzE(negPionCandidateKF.Px(),negPionCandidateKF.Py(),negPionCandidateKF.Pz(),negPionCandidateKF.E());
virtKFPionVec4 = posKFPionVec4 + negKFPionVec4;
}
Int_t labeln=0;
Int_t labelp=0;
Int_t motherlabelp = 0;
Int_t motherlabeln = 0;
TParticle *fNegativeMCParticle =nullptr;
TParticle *fPositiveMCParticle =nullptr;
if( fMCEvent ) {
labeln=TMath::Abs(negPionCandidate->GetLabel());
labelp=TMath::Abs(posPionCandidate->GetLabel());
if(labeln>-1) fNegativeMCParticle = fMCEvent->Particle(labeln);
if(labelp>-1) fPositiveMCParticle = fMCEvent->Particle(labelp);
// check whether MC particles exist, else abort
if (fNegativeMCParticle == nullptr || fPositiveMCParticle == nullptr) return;
motherlabeln = fNegativeMCParticle->GetMother(0);
motherlabelp = fPositiveMCParticle->GetMother(0);
virtualPhoton.SetMCLabelPositive(labelp);
virtualPhoton.SetMCLabelNegative(labeln);
}
AliAODConversionPhoton *vParticle = new AliAODConversionPhoton(&virtualPhoton); //To apply mass 2 pion mass cut
if(use4vecformass){
vParticle->SetPxPyPzE(virtKFPionVec4.Px(),virtKFPionVec4.Py(),virtKFPionVec4.Pz(),virtKFPionVec4.E());
// set mass to one calculated from four vector, not from parameters
vParticle->SetMass(vParticle->M());
}
if(!fDoLightOutput){
Double_t ds,dsp;
posPionCandidateKF.GetDStoParticle(negPionCandidateKF,ds,dsp);
Float_t chi2 = virtualPhoton.GetChi2perNDF();
if(chi2>299) chi2 = 299; // to illustrate overflow bin
fHistovParticleChi2PerNDF[fiCut]->Fill(chi2,fWeightJetJetMC);
fHistovParticledS[fiCut]->Fill(ds,fWeightJetJetMC);
if (fMCEvent &&(fDoMesonQA>0)){
if (fPositiveMCParticle && fNegativeMCParticle ) {
if (((AliPrimaryPionCuts*)fPionCutArray->At(fiCut))->DoMassCut()){
if (vParticle->GetMass() < ((AliPrimaryPionCuts*)fPionCutArray->At(fiCut))->GetMassCut()){
if(TMath::Abs(fNegativeMCParticle->GetPdgCode())==211 && TMath::Abs(fPositiveMCParticle->GetPdgCode())==211){ // Pions ...
fHistoTruePionPionInvMassPt[fiCut]->Fill(vParticle->GetMass(),vParticle->Pt(), fWeightJetJetMC);
fHistoTruevParticleChi2PerNDF[fiCut]->Fill(chi2,fWeightJetJetMC);
fHistoTruevParticledS[fiCut]->Fill(ds,fWeightJetJetMC);
if (motherlabeln == motherlabelp){
fHistoTruePionPionFromSameMotherInvMassPt[fiCut]->Fill(vParticle->GetMass(),vParticle->Pt(), fWeightJetJetMC);
fHistoTruevParticleFromSameMotherChi2PerNDF[fiCut]->Fill(chi2,fWeightJetJetMC);
fHistoTruevParticleFromSameMotherdS[fiCut]->Fill(ds,fWeightJetJetMC);
switch( fSelectedHeavyNeutralMeson ) {
case 0: // ETA MESON
if( IsEtaPiPlPiMiPiZeroDaughter(labeln) ){
fHistoTruePionPionFromHNMInvMassPt[fiCut]->Fill(vParticle->GetMass(),vParticle->Pt(), fWeightJetJetMC);
fHistoTruevParticleFromHNMChi2PerNDF[fiCut]->Fill(chi2,fWeightJetJetMC);
fHistoTruevParticleFromHNMdS[fiCut]->Fill(ds,fWeightJetJetMC);
}
break;
case 1: // OMEGA MESON
if( IsOmegaPiPlPiMiPiZeroDaughter(labeln) ){
fHistoTruePionPionFromHNMInvMassPt[fiCut]->Fill(vParticle->GetMass(),vParticle->Pt(), fWeightJetJetMC);
fHistoTruevParticleFromHNMChi2PerNDF[fiCut]->Fill(chi2,fWeightJetJetMC);
fHistoTruevParticleFromHNMdS[fiCut]->Fill(ds,fWeightJetJetMC);
}
break;
case 2: // ETA PRIME MESON
if( IsEtaPrimePiPlPiMiEtaDaughter(labeln) ){
fHistoTruePionPionFromHNMInvMassPt[fiCut]->Fill(vParticle->GetMass(),vParticle->Pt(), fWeightJetJetMC);
fHistoTruevParticleFromHNMChi2PerNDF[fiCut]->Fill(chi2,fWeightJetJetMC);
fHistoTruevParticleFromHNMdS[fiCut]->Fill(ds,fWeightJetJetMC);
}
break;
case 3: // D0 MESON
if( IsD0PiPlPiMiPiZeroDaughter(labeln) ){
fHistoTruePionPionFromHNMInvMassPt[fiCut]->Fill(vParticle->GetMass(),vParticle->Pt(), fWeightJetJetMC);
fHistoTruevParticleFromHNMChi2PerNDF[fiCut]->Fill(chi2,fWeightJetJetMC);
fHistoTruevParticleFromHNMdS[fiCut]->Fill(ds,fWeightJetJetMC);
}
break;
default:
AliError(Form("Heavy neutral meson not correctly selected (only 0,1,2,3 valid)... selected: %d",fSelectedHeavyNeutralMeson));
}
}
}
}
} else {
if(TMath::Abs(fNegativeMCParticle->GetPdgCode())==211 && TMath::Abs(fPositiveMCParticle->GetPdgCode())==211){ // Pions ...
fHistoTruePionPionInvMassPt[fiCut]->Fill(vParticle->GetMass(),vParticle->Pt(), fWeightJetJetMC);
fHistoTruevParticleChi2PerNDF[fiCut]->Fill(chi2,fWeightJetJetMC);
fHistoTruevParticledS[fiCut]->Fill(ds,fWeightJetJetMC);
if (motherlabeln == motherlabelp){
fHistoTruePionPionFromSameMotherInvMassPt[fiCut]->Fill(vParticle->GetMass(),vParticle->Pt(), fWeightJetJetMC);
fHistoTruevParticleFromSameMotherChi2PerNDF[fiCut]->Fill(chi2,fWeightJetJetMC);
fHistoTruevParticleFromSameMotherdS[fiCut]->Fill(ds,fWeightJetJetMC);
switch( fSelectedHeavyNeutralMeson ) {
case 0: // ETA MESON
if( IsEtaPiPlPiMiPiZeroDaughter(labeln) ){
fHistoTruePionPionFromHNMInvMassPt[fiCut]->Fill(vParticle->GetMass(),vParticle->Pt(), fWeightJetJetMC);
fHistoTruevParticleFromHNMChi2PerNDF[fiCut]->Fill(chi2,fWeightJetJetMC);
fHistoTruevParticleFromHNMdS[fiCut]->Fill(ds,fWeightJetJetMC);
}
break;
case 1: // OMEGA MESON
if( IsOmegaPiPlPiMiPiZeroDaughter(labeln) ){
fHistoTruePionPionFromHNMInvMassPt[fiCut]->Fill(vParticle->GetMass(),vParticle->Pt(), fWeightJetJetMC);
fHistoTruevParticleFromHNMChi2PerNDF[fiCut]->Fill(chi2,fWeightJetJetMC);
fHistoTruevParticleFromHNMdS[fiCut]->Fill(ds,fWeightJetJetMC);
}
break;
case 2: // ETA PRIME MESON
if( IsEtaPrimePiPlPiMiEtaDaughter(labeln) ){
fHistoTruePionPionFromHNMInvMassPt[fiCut]->Fill(vParticle->GetMass(),vParticle->Pt(), fWeightJetJetMC);
fHistoTruevParticleFromHNMChi2PerNDF[fiCut]->Fill(chi2,fWeightJetJetMC);
fHistoTruevParticleFromHNMdS[fiCut]->Fill(ds,fWeightJetJetMC);
}
break;
case 3: // D0 MESON
if( IsD0PiPlPiMiPiZeroDaughter(labeln) ){
fHistoTruePionPionFromHNMInvMassPt[fiCut]->Fill(vParticle->GetMass(),vParticle->Pt(), fWeightJetJetMC);
fHistoTruevParticleFromHNMChi2PerNDF[fiCut]->Fill(chi2,fWeightJetJetMC);
fHistoTruevParticleFromHNMdS[fiCut]->Fill(ds,fWeightJetJetMC);
}
break;
default:
AliError(Form("Heavy neutral meson not correctly selected (only 0,1,2,3 valid)... selected: %d",fSelectedHeavyNeutralMeson));
}
}
}
}
}
}
}
Bool_t survivesMassCut = kFALSE;
if (((AliPrimaryPionCuts*)fPionCutArray->At(fiCut))->DoMassCut()){
if (vParticle->GetMass() < ((AliPrimaryPionCuts*)fPionCutArray->At(fiCut))->GetMassCut()){
survivesMassCut = kTRUE;
}
} else{
survivesMassCut = kTRUE;
}
if(survivesMassCut){
//fGoodVirtualParticles->Add( vParticle );
if(!fDoLightOutput){
fHistoPionPionInvMassPt[fiCut]->Fill( vParticle->GetMass(),vParticle->Pt(), fWeightJetJetMC);
}
CalculateMesonCandidates(vParticle);
delete vParticle;
vParticle=0x0;
}else{
delete vParticle;
vParticle=0x0;
}
}
}
Double_t clsToFPos = -1.0;
Double_t clsToFNeg = -1.0;
Float_t dcaToVertexXYPos = -1.0;
Float_t dcaToVertexZPos = -1.0;
Float_t dcaToVertexXYNeg = -1.0;
Float_t dcaToVertexZNeg = -1.0;
if ( fDoMesonQA>0 ) {
for(UInt_t i = 0; i < lGoodNegPionIndexPrev.size(); i++){
AliVTrack* negPionCandidate = dynamic_cast<AliVTrack*>(fInputEvent->GetTrack(lGoodNegPionIndexPrev[i]));
clsToFNeg = ((AliPrimaryPionCuts*)fPionCutArray->At(fiCut))->GetNFindableClustersTPC(negPionCandidate);
Float_t bNeg[2];
Float_t bCovNeg[3];
negPionCandidate->GetImpactParameters(bNeg,bCovNeg);
if (bCovNeg[0]<=0 || bCovNeg[2]<=0) {
AliDebug(1, "Estimated b resolution lower or equal zero!");
bCovNeg[0]=0; bCovNeg[2]=0;
}
dcaToVertexXYNeg = bNeg[0];
dcaToVertexZNeg = bNeg[1];
if(!fDoLightOutput){
fHistoNegPionEta[fiCut]->Fill(negPionCandidate->Eta(), fWeightJetJetMC);
fHistoNegPionClsTPC[fiCut]->Fill(clsToFNeg,negPionCandidate->Pt(), fWeightJetJetMC);
fHistoPionDCAxy[fiCut]->Fill( dcaToVertexXYNeg, negPionCandidate->Pt(), fWeightJetJetMC );
fHistoPionDCAz[fiCut]->Fill( dcaToVertexZNeg, negPionCandidate->Pt(), fWeightJetJetMC );
fHistoPionTPCdEdxNSigma[fiCut]->Fill( negPionCandidate->P(),((AliPrimaryPionCuts*)fPionCutArray->At(fiCut))->GetPIDResponse()->NumberOfSigmasTPC(negPionCandidate, AliPID::kPion), fWeightJetJetMC );
fHistoPionTPCdEdx[fiCut]->Fill(negPionCandidate->P(), TMath::Abs(negPionCandidate->GetTPCsignal()), fWeightJetJetMC);
}
}
for(UInt_t i = 0; i < lGoodPosPionIndexPrev.size(); i++){
AliVTrack* posPionCandidate = dynamic_cast<AliVTrack*>(fInputEvent->GetTrack(lGoodPosPionIndexPrev[i]));
clsToFPos = ((AliPrimaryPionCuts*)fPionCutArray->At(fiCut))->GetNFindableClustersTPC(posPionCandidate);
Float_t bPos[2];
Float_t bCovPos[3];
posPionCandidate->GetImpactParameters(bPos,bCovPos);
if (bCovPos[0]<=0 || bCovPos[2]<=0) {
AliDebug(1, "Estimated b resolution lower or equal zero!");
bCovPos[0]=0; bCovPos[2]=0;
}
dcaToVertexXYPos = bPos[0];
dcaToVertexZPos = bPos[1];
if(!fDoLightOutput){
fHistoPosPionEta[fiCut]->Fill(posPionCandidate->Eta(), fWeightJetJetMC);
fHistoPosPionClsTPC[fiCut]->Fill(clsToFPos,posPionCandidate->Pt(), fWeightJetJetMC);
fHistoPionDCAxy[fiCut]->Fill( dcaToVertexXYPos, posPionCandidate->Pt(), fWeightJetJetMC );
fHistoPionDCAz[fiCut]->Fill( dcaToVertexZPos, posPionCandidate->Pt(), fWeightJetJetMC );
fHistoPionTPCdEdxNSigma[fiCut]->Fill( posPionCandidate->P(),((AliPrimaryPionCuts*)fPionCutArray->At(fiCut))->GetPIDResponse()->NumberOfSigmasTPC(posPionCandidate, AliPID::kPion), fWeightJetJetMC );
fHistoPionTPCdEdx[fiCut]->Fill(posPionCandidate->P(), TMath::Abs(posPionCandidate->GetTPCsignal()), fWeightJetJetMC);
}
}
}
}
//________________________________________________________________________
void AliAnalysisTaskNeutralMesonToPiPlPiMiNeutralMeson::ProcessPionCandidatesAOD(){
Bool_t use4vecformass = ((AliPrimaryPionCuts*)fPionCutArray->At(fiCut))->Use4VecForMass();
Double_t magField = fInputEvent->GetMagneticField();
if( magField < 0.0 ){
magField = 1.0;
} else {
magField = -1.0;
}
vector<Int_t> lGoodNegPionIndexPrev(0);
vector<Int_t> lGoodPosPionIndexPrev(0);
TClonesArray *AODMCTrackArray = NULL;
if(fMCEvent){
AODMCTrackArray = dynamic_cast<TClonesArray*>(fInputEvent->FindListObject(AliAODMCParticle::StdBranchName()));
}
for(UInt_t i = 0; i < fSelectorNegPionIndex.size(); i++){
AliAODTrack* negPionCandidate =dynamic_cast<AliAODTrack*>(fInputEvent->GetTrack(fSelectorNegPionIndex[i]));
if(! ((AliPrimaryPionCuts*)fPionCutArray->At(fiCut))->PionIsSelectedAOD(negPionCandidate) ) continue;
lGoodNegPionIndexPrev.push_back( fSelectorNegPionIndex[i] );
TLorentzVector* negPionforHandler = new TLorentzVector();
negPionforHandler->SetPxPyPzE(negPionCandidate->Px(), negPionCandidate->Py(), negPionCandidate->Pz(), negPionCandidate->E());
FixPzVecToMatchPDGInvMass(negPionforHandler);
AliAODConversionPhoton *negPionHandler = new AliAODConversionPhoton(negPionforHandler);
delete negPionforHandler;
fNegPionCandidates->Add(negPionHandler);
if(!fDoLightOutput){
fHistoNegPionPt[fiCut]->Fill(negPionCandidate->Pt(), fWeightJetJetMC);
fHistoNegPionPhi[fiCut]->Fill(negPionCandidate->Phi(), fWeightJetJetMC);
}
if( fMCEvent ) {
const AliVVertex* primVtxMC = fMCEvent->GetPrimaryVertex();
Double_t mcProdVtxX = primVtxMC->GetX();
Double_t mcProdVtxY = primVtxMC->GetY();
Double_t mcProdVtxZ = primVtxMC->GetZ();
Int_t labelNegPion = TMath::Abs( negPionCandidate->GetLabel() );
if( labelNegPion>-1 && labelNegPion < AODMCTrackArray->GetEntriesFast() ){
AliAODMCParticle* negPion = static_cast<AliAODMCParticle*>(AODMCTrackArray->At(labelNegPion));
Bool_t negPionIsPrimary = ((AliConvEventCuts*)fEventCutArray->At(fiCut))->IsConversionPrimaryAOD( fInputEvent, negPion, mcProdVtxX, mcProdVtxY, mcProdVtxZ);
if( negPion->GetPdgCode() == -211 ){
if(!fDoLightOutput){
if( negPionIsPrimary ){
fHistoTrueNegPionPt[fiCut]->Fill(negPionCandidate->Pt(), fWeightJetJetMC); //primary negPion
}
switch( fSelectedHeavyNeutralMeson ) {
case 0: // ETA MESON
if( IsEtaPiPlPiMiPiZeroDaughterAOD(AODMCTrackArray, labelNegPion) && negPionIsPrimary )
fHistoTrueNegPionFromNeutralMesonPt[fiCut]->Fill(negPionCandidate->Pt(), fWeightJetJetMC);
break;
case 1: // OMEGA MESON
if( IsOmegaPiPlPiMiPiZeroDaughterAOD(AODMCTrackArray, labelNegPion) && negPionIsPrimary)
fHistoTrueNegPionFromNeutralMesonPt[fiCut]->Fill(negPionCandidate->Pt(), fWeightJetJetMC);
break;
case 2: // ETA PRIME MESON
if( IsEtaPrimePiPlPiMiEtaDaughterAOD(AODMCTrackArray,labelNegPion) && negPionIsPrimary)
fHistoTrueNegPionFromNeutralMesonPt[fiCut]->Fill(negPionCandidate->Pt(), fWeightJetJetMC);
break;
case 3: // D0 MESON
if( IsD0PiPlPiMiPiZeroDaughterAOD(AODMCTrackArray,labelNegPion)&& negPionIsPrimary)
fHistoTrueNegPionFromNeutralMesonPt[fiCut]->Fill(negPionCandidate->Pt(), fWeightJetJetMC);
break;
default:
AliError(Form("Heavy neutral meson not correctly selected (only 0,1,2,3 valid)... selected: %d",fSelectedHeavyNeutralMeson));
}
}
}
}
}
}
for(UInt_t i = 0; i < fSelectorPosPionIndex.size(); i++){
AliAODTrack* posPionCandidate = dynamic_cast<AliAODTrack*>(fInputEvent->GetTrack(fSelectorPosPionIndex[i]));
if(! ((AliPrimaryPionCuts*)fPionCutArray->At(fiCut))->PionIsSelectedAOD(posPionCandidate) ) continue;
lGoodPosPionIndexPrev.push_back( fSelectorPosPionIndex[i] );
TLorentzVector* posPionforHandler = new TLorentzVector();
posPionforHandler->SetPxPyPzE(posPionCandidate->Px(), posPionCandidate->Py(), posPionCandidate->Pz(), posPionCandidate->E());
FixPzVecToMatchPDGInvMass(posPionforHandler);
AliAODConversionPhoton *posPionHandler = new AliAODConversionPhoton(posPionforHandler);
delete posPionforHandler;
fPosPionCandidates->Add(posPionHandler);
if(!fDoLightOutput){
fHistoPosPionPt[fiCut]->Fill( posPionCandidate->Pt(), fWeightJetJetMC );
fHistoPosPionPhi[fiCut]->Fill( posPionCandidate->Phi(), fWeightJetJetMC );
}
if( fMCEvent ) {
const AliVVertex* primVtxMC = fMCEvent->GetPrimaryVertex();
Double_t mcProdVtxX = primVtxMC->GetX();
Double_t mcProdVtxY = primVtxMC->GetY();
Double_t mcProdVtxZ = primVtxMC->GetZ();
Int_t labelPosPion = TMath::Abs( posPionCandidate->GetLabel() );
if( labelPosPion>-1 && labelPosPion < fMCEvent->GetNumberOfTracks() ) {
AliAODMCParticle* posPion = static_cast<AliAODMCParticle*>(AODMCTrackArray->At(labelPosPion));
Bool_t posPionIsPrimary = ((AliConvEventCuts*)fEventCutArray->At(fiCut))->IsConversionPrimaryAOD( fInputEvent, posPion, mcProdVtxX, mcProdVtxY, mcProdVtxZ);
if( posPion->GetPdgCode() == 211 ){
if(!fDoLightOutput){
if( posPionIsPrimary ){
fHistoTruePosPionPt[fiCut]->Fill(posPionCandidate->Pt(), fWeightJetJetMC);
}
switch( fSelectedHeavyNeutralMeson ) {
case 0: // ETA MESON
if( IsEtaPiPlPiMiPiZeroDaughterAOD(AODMCTrackArray,labelPosPion) && posPionIsPrimary )
fHistoTruePosPionFromNeutralMesonPt[fiCut]->Fill(posPionCandidate->Pt(), fWeightJetJetMC);
break;
case 1: // OMEGA MESON
if( IsOmegaPiPlPiMiPiZeroDaughterAOD(AODMCTrackArray, labelPosPion) && posPionIsPrimary)
fHistoTruePosPionFromNeutralMesonPt[fiCut]->Fill(posPionCandidate->Pt(), fWeightJetJetMC);
break;
case 2: // ETA PRIME MESON
if( IsEtaPrimePiPlPiMiEtaDaughterAOD(AODMCTrackArray, labelPosPion) && posPionIsPrimary)
fHistoTruePosPionFromNeutralMesonPt[fiCut]->Fill(posPionCandidate->Pt(), fWeightJetJetMC);
break;
case 3: // D0 MESON
if( IsD0PiPlPiMiPiZeroDaughterAOD(AODMCTrackArray,labelPosPion) && posPionIsPrimary )
fHistoTruePosPionFromNeutralMesonPt[fiCut]->Fill(posPionCandidate->Pt(), fWeightJetJetMC);
break;
default:
AliError(Form("Heavy neutral meson not correctly selected (only 0,1,2,3 valid)... selected: %d",fSelectedHeavyNeutralMeson));
}
}
}
}
}
}
//AliInfo(Form("Number of good neg pions: %i \t pos pions = %i", lGoodNegPionIndexPrev.size(), lGoodPosPionIndexPrev.size()));
for(UInt_t i = 0; i < lGoodNegPionIndexPrev.size(); i++){
AliVTrack* negPionCandidate = dynamic_cast<AliVTrack*>(fInputEvent->GetTrack(lGoodNegPionIndexPrev[i]));
AliAODTrack* negPionCandidateAOD = dynamic_cast<AliAODTrack*>(fInputEvent->GetTrack(lGoodNegPionIndexPrev[i]));
AliKFParticle negPionCandidateKF( *negPionCandidate, 211 );
for(UInt_t j = 0; j < lGoodPosPionIndexPrev.size(); j++){
AliVTrack *posPionCandidate = dynamic_cast<AliVTrack*>(fInputEvent->GetTrack(lGoodPosPionIndexPrev[j]));
AliAODTrack* posPionCandidateAOD = dynamic_cast<AliAODTrack*>(fInputEvent->GetTrack(lGoodPosPionIndexPrev[j]));
AliKFParticle posPionCandidateKF( *posPionCandidate, 211 );
AliKFConversionPhoton* virtualPhoton = NULL;
virtualPhoton = new AliKFConversionPhoton(negPionCandidateKF,posPionCandidateKF);
//AliKFVertex primaryVertex(*fInputEvent->GetPrimaryVertex());
// primaryVertexImproved+=*virtualPhoton;
// virtualPhoton->SetProductionVertex(primaryVertex);
virtualPhoton->SetTrackLabels( lGoodPosPionIndexPrev[j], lGoodNegPionIndexPrev[i]);
TLorentzVector posPionVec4;
TLorentzVector negPionVec4;
TLorentzVector virtPionVec4;
TLorentzVector posKFPionVec4;
TLorentzVector negKFPionVec4;
TLorentzVector virtKFPionVec4;
if(use4vecformass){
posKFPionVec4.SetPxPyPzE(posPionCandidateKF.Px(),posPionCandidateKF.Py(),posPionCandidateKF.Pz(),posPionCandidateKF.E());
negKFPionVec4.SetPxPyPzE(negPionCandidateKF.Px(),negPionCandidateKF.Py(),negPionCandidateKF.Pz(),negPionCandidateKF.E());
virtKFPionVec4 = posKFPionVec4 + negKFPionVec4;
}
Int_t labeln=0;
Int_t labelp=0;
Int_t motherlabelp = 0;
Int_t motherlabeln = 0;
AliAODMCParticle *fNegativeMCParticle =NULL;
AliAODMCParticle *fPositiveMCParticle =NULL;
if( fMCEvent ) {
labeln=TMath::Abs(negPionCandidate->GetLabel());
labelp=TMath::Abs(posPionCandidate->GetLabel());
if(labeln>-1) fNegativeMCParticle = static_cast<AliAODMCParticle*>(AODMCTrackArray->At(labeln));
if(labelp>-1) fPositiveMCParticle = static_cast<AliAODMCParticle*>(AODMCTrackArray->At(labelp));
// check whether MC particles exist, else abort
if (fNegativeMCParticle == NULL || fPositiveMCParticle == NULL) return;
motherlabeln = fNegativeMCParticle->GetMother();
motherlabelp = fPositiveMCParticle->GetMother();
virtualPhoton->SetMCLabelPositive(labelp);
virtualPhoton->SetMCLabelNegative(labeln);
}
// AliInfo(Form("virtualPhoton chi2 = %f", virtualPhoton->GetChi2perNDF()));
//AliInfo(Form("virtualPhoton distance pi+ pi- = %f", negPionCandidateKF.GetDeviationFromParticle(posPionCandidateKF)));
AliAODConversionPhoton *vParticle = new AliAODConversionPhoton(virtualPhoton); //To apply mass 2 pion mass cut
if(use4vecformass){
vParticle->SetPxPyPzE(virtKFPionVec4.Px(),virtKFPionVec4.Py(),virtKFPionVec4.Pz(),virtKFPionVec4.E());
vParticle->SetMass(vParticle->M());
}
if(!fDoLightOutput){
Bool_t isPiMiGlobalC = negPionCandidateAOD->IsGlobalConstrained();
Bool_t isPiPlGlobalC = posPionCandidateAOD->IsGlobalConstrained();
Double_t ds,dsp;
posPionCandidateKF.GetDStoParticle(negPionCandidateKF,ds,dsp);
//AliInfo(Form("ds = %f dsp = %f", ds,dsp));
//AliInfo(Form("Is pi+ constrained = %i Is pi- constrained = %i",isPiPlGlobalC,isPiMiGlobalC));
Float_t chi2 = virtualPhoton->GetChi2perNDF();
if(chi2>299) chi2 = 299; // to illustrate overflow bin
fHistovParticleChi2PerNDF[fiCut]->Fill(chi2);
fHistovParticledS[fiCut]->Fill(ds);
if(isPiMiGlobalC == isPiPlGlobalC){
fHistovParticleChi2PerNDFBothConstrained[fiCut]->Fill(chi2);
fHistovParticledSBothConstrained[fiCut]->Fill(ds);
} else{
fHistovParticleChi2PerNDFOneConstrained[fiCut]->Fill(chi2);
fHistovParticledSOneConstrained[fiCut]->Fill(ds);
}
if (fMCEvent &&(fDoMesonQA>0)){
if (fPositiveMCParticle && fNegativeMCParticle ) {
if (((AliPrimaryPionCuts*)fPionCutArray->At(fiCut))->DoMassCut()){
if (vParticle->GetMass() < ((AliPrimaryPionCuts*)fPionCutArray->At(fiCut))->GetMassCut()){
if(TMath::Abs(fNegativeMCParticle->GetPdgCode())==211 && TMath::Abs(fPositiveMCParticle->GetPdgCode())==211){ // Pions ...
fHistoTruePionPionInvMassPt[fiCut]->Fill(vParticle->GetMass(),vParticle->Pt(), fWeightJetJetMC);
fHistoTruevParticleChi2PerNDF[fiCut]->Fill(chi2);
fHistoTruevParticledS[fiCut]->Fill(ds);
if (motherlabeln == motherlabelp){
fHistoTruePionPionFromSameMotherInvMassPt[fiCut]->Fill(vParticle->GetMass(),vParticle->Pt(), fWeightJetJetMC);
fHistoTruevParticleFromSameMotherChi2PerNDF[fiCut]->Fill(chi2);
fHistoTruevParticleFromSameMotherdS[fiCut]->Fill(ds);
switch( fSelectedHeavyNeutralMeson ) {
case 0: // ETA MESON
if( IsEtaPiPlPiMiPiZeroDaughterAOD(AODMCTrackArray,labeln) ){
fHistoTruePionPionFromHNMInvMassPt[fiCut]->Fill(vParticle->GetMass(),vParticle->Pt(), fWeightJetJetMC);
fHistoTruevParticleFromHNMChi2PerNDF[fiCut]->Fill(chi2);
fHistoTruevParticleFromHNMdS[fiCut]->Fill(ds);
}
break;
case 1: // OMEGA MESON
if( IsOmegaPiPlPiMiPiZeroDaughterAOD(AODMCTrackArray,labeln) ){
fHistoTruePionPionFromHNMInvMassPt[fiCut]->Fill(vParticle->GetMass(),vParticle->Pt(), fWeightJetJetMC);
fHistoTruevParticleFromHNMChi2PerNDF[fiCut]->Fill(chi2);
fHistoTruevParticleFromHNMdS[fiCut]->Fill(ds);
}
break;
case 2: // ETA PRIME MESON
if( IsEtaPrimePiPlPiMiEtaDaughterAOD(AODMCTrackArray,labeln) ){
fHistoTruePionPionFromHNMInvMassPt[fiCut]->Fill(vParticle->GetMass(),vParticle->Pt(), fWeightJetJetMC);
fHistoTruevParticleFromHNMChi2PerNDF[fiCut]->Fill(chi2);
fHistoTruevParticleFromHNMdS[fiCut]->Fill(ds);
}
break;
case 3: // D0 MESON
if( IsD0PiPlPiMiPiZeroDaughterAOD(AODMCTrackArray,labeln) ){
fHistoTruePionPionFromHNMInvMassPt[fiCut]->Fill(vParticle->GetMass(),vParticle->Pt(), fWeightJetJetMC);
fHistoTruevParticleFromHNMChi2PerNDF[fiCut]->Fill(chi2);
fHistoTruevParticleFromHNMdS[fiCut]->Fill(ds);
}
break;
default:
AliError(Form("Heavy neutral meson not correctly selected (only 0,1,2,3 valid)... selected: %d",fSelectedHeavyNeutralMeson));
}
}
}
}
} else {
if(TMath::Abs(fNegativeMCParticle->GetPdgCode())==211 && TMath::Abs(fPositiveMCParticle->GetPdgCode())==211){ // Pions ...
fHistoTruePionPionInvMassPt[fiCut]->Fill(vParticle->GetMass(),vParticle->Pt(), fWeightJetJetMC);
fHistoTruevParticleChi2PerNDF[fiCut]->Fill(chi2);
fHistoTruevParticledS[fiCut]->Fill(ds);
if (motherlabeln == motherlabelp){
fHistoTruePionPionFromSameMotherInvMassPt[fiCut]->Fill(vParticle->GetMass(),vParticle->Pt(), fWeightJetJetMC);
fHistoTruevParticleFromSameMotherChi2PerNDF[fiCut]->Fill(chi2);
fHistoTruevParticleFromSameMotherdS[fiCut]->Fill(ds);
switch( fSelectedHeavyNeutralMeson ) {
case 0: // ETA MESON
if( IsEtaPiPlPiMiPiZeroDaughterAOD(AODMCTrackArray,labeln) ){
fHistoTruePionPionFromHNMInvMassPt[fiCut]->Fill(vParticle->GetMass(),vParticle->Pt(), fWeightJetJetMC);
fHistoTruevParticleFromHNMChi2PerNDF[fiCut]->Fill(chi2);
fHistoTruevParticleFromHNMdS[fiCut]->Fill(ds);
}
break;
case 1: // OMEGA MESON
if( IsOmegaPiPlPiMiPiZeroDaughterAOD(AODMCTrackArray,labeln) ){
fHistoTruePionPionFromHNMInvMassPt[fiCut]->Fill(vParticle->GetMass(),vParticle->Pt(), fWeightJetJetMC);
fHistoTruevParticleFromHNMChi2PerNDF[fiCut]->Fill(chi2);
fHistoTruevParticleFromHNMdS[fiCut]->Fill(ds);
}
break;
case 2: // ETA PRIME MESON
if( IsEtaPrimePiPlPiMiEtaDaughterAOD(AODMCTrackArray,labeln) ){
fHistoTruePionPionFromHNMInvMassPt[fiCut]->Fill(vParticle->GetMass(),vParticle->Pt(), fWeightJetJetMC);
fHistoTruevParticleFromHNMChi2PerNDF[fiCut]->Fill(chi2);
fHistoTruevParticleFromHNMdS[fiCut]->Fill(ds);
}
break;
case 3: // D0 MESON
if( IsD0PiPlPiMiPiZeroDaughterAOD(AODMCTrackArray,labeln) ){
fHistoTruePionPionFromHNMInvMassPt[fiCut]->Fill(vParticle->GetMass(),vParticle->Pt(), fWeightJetJetMC);
fHistoTruevParticleFromHNMChi2PerNDF[fiCut]->Fill(chi2);
fHistoTruevParticleFromHNMdS[fiCut]->Fill(ds);
}
break;
default:
AliError(Form("Heavy neutral meson not correctly selected (only 0,1,2,3 valid)... selected: %d",fSelectedHeavyNeutralMeson));
}
}
}
}
}
}
}
Bool_t survivesMassCut = kFALSE;
if (((AliPrimaryPionCuts*)fPionCutArray->At(fiCut))->DoMassCut()){
if (vParticle->GetMass() < ((AliPrimaryPionCuts*)fPionCutArray->At(fiCut))->GetMassCut()){
survivesMassCut = kTRUE;
}
} else{
survivesMassCut = kTRUE;
}
if(survivesMassCut){
if(!fDoLightOutput){
fHistoPionPionInvMassPt[fiCut]->Fill( vParticle->GetMass(),vParticle->Pt(), fWeightJetJetMC);
}
CalculateMesonCandidates(vParticle);
delete vParticle;
vParticle=0x0;
}else{
delete vParticle;
vParticle=0x0;
}
delete virtualPhoton;
virtualPhoton=0x0;
}
}
Double_t clsToFPos = -1.0;
Double_t clsToFNeg = -1.0;
Float_t dcaToVertexXYPos = -1.0;
Float_t dcaToVertexZPos = -1.0;
Float_t dcaToVertexXYNeg = -1.0;
Float_t dcaToVertexZNeg = -1.0;
if ( fDoMesonQA>0 ) {
for(UInt_t i = 0; i < lGoodNegPionIndexPrev.size(); i++){
AliVTrack* negPionCandidate = dynamic_cast<AliVTrack*>(fInputEvent->GetTrack(lGoodNegPionIndexPrev[i]));
clsToFNeg = ((AliPrimaryPionCuts*)fPionCutArray->At(fiCut))->GetNFindableClustersTPC(negPionCandidate);
Float_t bNeg[2];
Float_t bCovNeg[3];
negPionCandidate->GetImpactParameters(bNeg,bCovNeg);
if (bCovNeg[0]<=0 || bCovNeg[2]<=0) {
AliDebug(1, "Estimated b resolution lower or equal zero!");
bCovNeg[0]=0; bCovNeg[2]=0;
}
dcaToVertexXYNeg = bNeg[0];
dcaToVertexZNeg = bNeg[1];
if(!fDoLightOutput){
fHistoNegPionEta[fiCut]->Fill(negPionCandidate->Eta(), fWeightJetJetMC);
fHistoNegPionClsTPC[fiCut]->Fill(clsToFNeg,negPionCandidate->Pt(), fWeightJetJetMC);
fHistoPionDCAxy[fiCut]->Fill( dcaToVertexXYNeg, negPionCandidate->Pt(), fWeightJetJetMC );
fHistoPionDCAz[fiCut]->Fill( dcaToVertexZNeg, negPionCandidate->Pt(), fWeightJetJetMC );
fHistoPionTPCdEdxNSigma[fiCut]->Fill( negPionCandidate->P(),((AliPrimaryPionCuts*)fPionCutArray->At(fiCut))->GetPIDResponse()->NumberOfSigmasTPC(negPionCandidate, AliPID::kPion), fWeightJetJetMC );
fHistoPionTPCdEdx[fiCut]->Fill(negPionCandidate->P(), TMath::Abs(negPionCandidate->GetTPCsignal()), fWeightJetJetMC);
}
}
for(UInt_t i = 0; i < lGoodPosPionIndexPrev.size(); i++){
AliVTrack* posPionCandidate = dynamic_cast<AliVTrack*>(fInputEvent->GetTrack(lGoodPosPionIndexPrev[i]));
clsToFPos = ((AliPrimaryPionCuts*)fPionCutArray->At(fiCut))->GetNFindableClustersTPC(posPionCandidate);
Float_t bPos[2];
Float_t bCovPos[3];
posPionCandidate->GetImpactParameters(bPos,bCovPos);
if (bCovPos[0]<=0 || bCovPos[2]<=0) {
AliDebug(1, "Estimated b resolution lower or equal zero!");
bCovPos[0]=0; bCovPos[2]=0;
}
dcaToVertexXYPos = bPos[0];
dcaToVertexZPos = bPos[1];
if(!fDoLightOutput){
fHistoPosPionEta[fiCut]->Fill(posPionCandidate->Eta(), fWeightJetJetMC);
fHistoPosPionClsTPC[fiCut]->Fill(clsToFPos,posPionCandidate->Pt(), fWeightJetJetMC);
fHistoPionDCAxy[fiCut]->Fill( dcaToVertexXYPos, posPionCandidate->Pt(), fWeightJetJetMC );
fHistoPionDCAz[fiCut]->Fill( dcaToVertexZPos, posPionCandidate->Pt(), fWeightJetJetMC );
fHistoPionTPCdEdxNSigma[fiCut]->Fill( posPionCandidate->P(),((AliPrimaryPionCuts*)fPionCutArray->At(fiCut))->GetPIDResponse()->NumberOfSigmasTPC(posPionCandidate, AliPID::kPion), fWeightJetJetMC );
fHistoPionTPCdEdx[fiCut]->Fill(posPionCandidate->P(), TMath::Abs(posPionCandidate->GetTPCsignal()), fWeightJetJetMC);
}
}
}
}
//_____________________________________________________________________________
void AliAnalysisTaskNeutralMesonToPiPlPiMiNeutralMeson::ProcessMCParticles(){
// Loop over all primary MC particle
const AliVVertex* primVtxMC = fMCEvent->GetPrimaryVertex();
Double_t mcProdVtxX = primVtxMC->GetX();
Double_t mcProdVtxY = primVtxMC->GetY();
Double_t mcProdVtxZ = primVtxMC->GetZ();
for(Int_t i = 0; i < fMCEvent->GetNumberOfTracks(); i++) {
if (((AliConvEventCuts*)fEventCutArray->At(fiCut))->IsConversionPrimaryESD( fMCEvent, i, mcProdVtxX, mcProdVtxY, mcProdVtxZ)){
Double_t tempParticleWeight = fWeightJetJetMC;
TParticle* particle = (TParticle *)fMCEvent->Particle(i);
if (!particle) continue;
Int_t isMCFromMBHeader = -1;
if(((AliConvEventCuts*)fEventCutArray->At(fiCut))->GetSignalRejection() != 0){
isMCFromMBHeader
= ((AliConvEventCuts*)fEventCutArray->At(fiCut))->IsParticleFromBGEvent(i, fMCEvent, fInputEvent);
if(isMCFromMBHeader == 0 && ((AliConvEventCuts*)fEventCutArray->At(fiCut))->GetSignalRejection() != 3) continue;
// Set the jetjet weight to 1 in case the particle orignated from the minimum bias header
if(isMCFromMBHeader == 2 && ((AliConvEventCuts*)fEventCutArray->At(fiCut))->GetSignalRejection() == 4) tempParticleWeight = 1;
}
if(!fDoLightOutput){
if(fDoMesonQA > 0){
// Fill kinematics for heavy particle
// This also contains not-reconstructed particles
if(TMath::Abs(particle->GetPdgCode()) == fPDGCodeAnalyzedMeson){
fHistoMCHeavyAllPt[fiCut]->Fill(particle->Pt(), tempParticleWeight);
fHistoMCHeavyAllEta[fiCut]->Fill(particle->Eta(), tempParticleWeight);
fHistoMCHeavyAllPhi[fiCut]->Fill(TVector2::Phi_0_2pi(particle->Phi()), tempParticleWeight);
// check for Decay kinematics
if(particle->GetNDaughters() == 3){
AliVParticle *neutralMeson(nullptr), *piplus(nullptr), *piminus(nullptr);
Int_t indexpiplus(-1), indexpiminus(-1);
for(int idaug = particle->GetFirstDaughter(); idaug <= particle->GetLastDaughter(); idaug++) {
AliVParticle *daughter = fMCEvent->GetTrack(idaug);
if(daughter->PdgCode() == kPiPlus){
piplus = daughter;
indexpiplus = idaug;
} else if(daughter->PdgCode() == kPiMinus) {
piminus = daughter;
indexpiminus = idaug;
} else if(TMath::Abs(daughter->PdgCode()) == fPDGCodeNDM){
neutralMeson = daughter;
}
}
if(neutralMeson && piplus && piminus) {
fHistoMCHeavyChannelPt[fiCut]->Fill(particle->Pt(), tempParticleWeight);
fHistoMCHeavyChannelEta[fiCut]->Fill(particle->Eta(), tempParticleWeight);
fHistoMCHeavyChannelPhi[fiCut]->Fill(TVector2::Phi_0_2pi(particle->Phi()), tempParticleWeight);
// Fill kinematics for daughter particles
fHistMCChannelNDMFromHeavyPt[fiCut]->Fill(neutralMeson->Pt(), tempParticleWeight);
fHistMCChannelNDMFromHeavyEta[fiCut]->Fill(neutralMeson->Eta(), tempParticleWeight);
fHistMCChannelNDMFromHeavyPhi[fiCut]->Fill(TVector2::Phi_0_2pi(neutralMeson->Phi()), tempParticleWeight);
fHistMCChannelPiPlusFromHeavyPt[fiCut]->Fill(piplus->Pt(), tempParticleWeight);
fHistMCChannelPiPlusFromHeavyEta[fiCut]->Fill(piplus->Eta(), tempParticleWeight);
fHistMCChannelPiPlusFromHeavyPhi[fiCut]->Fill(TVector2::Phi_0_2pi(piplus->Phi()), tempParticleWeight);
fHistMCChannelPiMinusFromHeavyPt[fiCut]->Fill(piminus->Pt(), tempParticleWeight);
fHistMCChannelPiMinusFromHeavyEta[fiCut]->Fill(piminus->Eta(), tempParticleWeight);
fHistMCChannelPiPMinusFromHeavyPhi[fiCut]->Fill(TVector2::Phi_0_2pi(piminus->Phi()), tempParticleWeight);
fHistMCChannelNDMPtHeavyPt[fiCut]->Fill(particle->Pt(), neutralMeson->Pt(), tempParticleWeight);
fHistMCChannelPiPlusPtHeavyPt[fiCut]->Fill(particle->Pt(), piplus->Pt(), tempParticleWeight);
fHistMCChannelPiMinusPtHeavyPt[fiCut]->Fill(particle->Pt(), piminus->Pt(), tempParticleWeight);
// check if particle is reconstructible
bool reconstructible(true);
if(!((AliPrimaryPionCuts*)fPionCutArray->At(fiCut))->PionIsSelectedMC(indexpiminus,fMCEvent)) reconstructible = false;
if(!((AliPrimaryPionCuts*)fPionCutArray->At(fiCut))->PionIsSelectedMC(indexpiplus,fMCEvent)) reconstructible = false;
if(neutralMeson->GetNDaughters() == 3) {
// exclude Dalitz-decays
reconstructible = false;
} else {
AliVParticle *photon1 = fMCEvent->GetTrack(neutralMeson->GetDaughterFirst()), *photon2 = fMCEvent->GetTrack(neutralMeson->GetDaughterLast());
if(!(photon1 && photon2)) reconstructible = false;
else {
switch(fNDMRecoMode) {
case 0 : {
if(!((AliConversionPhotonCuts*)fGammaCutArray->At(fiCut))->PhotonIsSelectedMC(photon1->Particle(),fMCEvent,kFALSE)) reconstructible = false;
if(!((AliConversionPhotonCuts*)fGammaCutArray->At(fiCut))->PhotonIsSelectedMC(photon2->Particle(),fMCEvent,kFALSE)) reconstructible = false;
break;
}
case 1: {
if(!(((AliConversionPhotonCuts*)fGammaCutArray->At(fiCut))->PhotonIsSelectedMC(photon1->Particle(),fMCEvent,kFALSE) &&
((AliCaloPhotonCuts*)fClusterCutArray->At(fiCut))->ClusterIsSelectedMC(photon1->Particle(),fMCEvent)) ||
!(((AliConversionPhotonCuts*)fGammaCutArray->At(fiCut))->PhotonIsSelectedMC(photon2->Particle(),fMCEvent,kFALSE) &&
((AliCaloPhotonCuts*)fClusterCutArray->At(fiCut))->ClusterIsSelectedMC(photon1->Particle(),fMCEvent))
) reconstructible = false;
break;
}
case 2: {
if(!((AliCaloPhotonCuts*)fClusterCutArray->At(fiCut))->ClusterIsSelectedMC(photon1->Particle(),fMCEvent)) reconstructible = false;
if(!((AliCaloPhotonCuts*)fClusterCutArray->At(fiCut))->ClusterIsSelectedMC(photon1->Particle(),fMCEvent)) reconstructible = false;
break;
}
};
}
}
if(reconstructible) {
fHistoMCHeavyReconstructiblePt[fiCut]->Fill(particle->Pt(), tempParticleWeight);
fHistoMCHeavyReconstructibleEta[fiCut]->Fill(particle->Eta(), tempParticleWeight);
fHistoMCHeavyReconstructiblePhi[fiCut]->Fill(TVector2::Phi_0_2pi(particle->Phi()), tempParticleWeight);
// Fill kinematics for daughter particles
fHistMCReconstructibleNDMFromHeavyPt[fiCut]->Fill(neutralMeson->Pt(), tempParticleWeight);
fHistMCReconstructibleNDMFromHeavyEta[fiCut]->Fill(neutralMeson->Eta(), tempParticleWeight);
fHistMCReconstructibleNDMFromHeavyPhi[fiCut]->Fill(TVector2::Phi_0_2pi(neutralMeson->Phi()), tempParticleWeight);
fHistMCReconstructiblePiPlusFromHeavyPt[fiCut]->Fill(piplus->Pt(), tempParticleWeight);
fHistMCReconstructiblePiPlusFromHeavyEta[fiCut]->Fill(piplus->Eta(), tempParticleWeight);
fHistMCReconstructiblePiPlusFromHeavyPhi[fiCut]->Fill(TVector2::Phi_0_2pi(piplus->Phi()), tempParticleWeight);
fHistMCReconstructiblePiMinusFromHeavyPt[fiCut]->Fill(piminus->Pt(), tempParticleWeight);
fHistMCReconstructiblePiMinusFromHeavyEta[fiCut]->Fill(piminus->Eta(), tempParticleWeight);
fHistMCReconstructiblePiPMinusFromHeavyPhi[fiCut]->Fill(TVector2::Phi_0_2pi(piminus->Phi()), tempParticleWeight);
fHistMCReconstructibleNDMPtHeavyPt[fiCut]->Fill(particle->Pt(), neutralMeson->Pt(), tempParticleWeight);
fHistMCReconstructiblePiPlusPtHeavyPt[fiCut]->Fill(particle->Pt(), piplus->Pt(), tempParticleWeight);
fHistMCReconstructiblePiMinusPtHeavyPt[fiCut]->Fill(particle->Pt(), piminus->Pt(), tempParticleWeight);
}
}
}
}
}
if(((AliConvEventCuts*)fEventCutArray->At(fiCut))->IsParticleFromBGEvent(i, fMCEvent,fInputEvent)){
// find MC photons
if (fNDMRecoMode < 2 ){
if(((AliConversionPhotonCuts*)fGammaCutArray->At(fiCut))->PhotonIsSelectedMC(particle,fMCEvent,kFALSE)){
fHistoMCAllGammaPt[fiCut]->Fill(particle->Pt(), tempParticleWeight); // All MC Gamma
if(particle->GetMother(0) >-1){
if (fMCEvent->Particle(particle->GetMother(0))->GetPdgCode() ==fPDGCodeNDM){
TParticle *particleNDM = fMCEvent->Particle(particle->GetMother(0));
if(fDoMesonQA){
fHistoMCAllMesonPt[fiCut]->Fill(particleNDM->Pt(), tempParticleWeight);
fHistoMCAllMesonEta[fiCut]->Fill(particleNDM->Eta(), tempParticleWeight);
fHistoMCAllMesonPhi[fiCut]->Fill(TVector2::Phi_0_2pi(particleNDM->Phi()), tempParticleWeight);
}
if (fMCEvent->Particle(particle->GetMother(0))->GetMother(0) > -1){
if ( fMCEvent->Particle((fMCEvent->Particle(particle->GetMother(0)))->GetMother(0))->GetPdgCode() == fPDGCodeAnalyzedMeson ){
if ( fMCEvent->Particle((fMCEvent->Particle(particle->GetMother(0)))->GetMother(0))->GetNDaughters()==3 ){
fHistoMCGammaFromNeutralMesonPt[fiCut]->Fill(particle->Pt(), tempParticleWeight); // All photons from eta or omega via pi0
if(fDoMesonQA > 0) {
fHistoMCMesonFromNeutralMesonPt[fiCut]->Fill(particleNDM->Pt(), tempParticleWeight); // ALl meson mothers (pi0/eta) from analyzed heavy meson
fHistoMCMesonFromNeutralMesonEta[fiCut]->Fill(particleNDM->Eta(), tempParticleWeight); // All meson mothers (pi0/eta) from analyzed heavy meson
fHistoMCMesonFromNeutralMesonPhi[fiCut]->Fill(TVector2::Phi_0_2pi(particleNDM->Phi()), tempParticleWeight); // All meson mothers (pi0/eta) from analyzed heavy meson
}
}
}
}
}
}
}
} else if (fNDMRecoMode == 2){
if(((AliCaloPhotonCuts*)fClusterCutArray->At(fiCut))->ClusterIsSelectedMC(particle,fMCEvent)){
fHistoMCAllGammaPt[fiCut]->Fill(particle->Pt(), tempParticleWeight); // All MC Gamma
if(particle->GetMother(0) >-1){
if (fMCEvent->Particle(particle->GetMother(0))->GetPdgCode() ==fPDGCodeNDM){
TParticle *particleNDM = fMCEvent->Particle(particle->GetMother(0));
if(fDoMesonQA > 0){
fHistoMCAllMesonPt[fiCut]->Fill(particleNDM->Pt(), tempParticleWeight);
fHistoMCAllMesonEta[fiCut]->Fill(particleNDM->Eta(), tempParticleWeight);
fHistoMCAllMesonPhi[fiCut]->Fill(TVector2::Phi_0_2pi(particleNDM->Phi()), tempParticleWeight);
}
if (fMCEvent->Particle(particle->GetMother(0))->GetMother(0) > -1){
if ( fMCEvent->Particle((fMCEvent->Particle(particle->GetMother(0)))->GetMother(0))->GetPdgCode() == fPDGCodeAnalyzedMeson ){
if ( fMCEvent->Particle((fMCEvent->Particle(particle->GetMother(0)))->GetMother(0))->GetNDaughters()==3 ){
fHistoMCGammaFromNeutralMesonPt[fiCut]->Fill(particle->Pt(), tempParticleWeight); // All photons from analyzed meson via pi0 or eta from decay
if(fDoMesonQA > 0){
fHistoMCMesonFromNeutralMesonPt[fiCut]->Fill(particleNDM->Pt(), tempParticleWeight); // All meson mothers (pi0/eta) from analyzed heavy meson
fHistoMCMesonFromNeutralMesonEta[fiCut]->Fill(particleNDM->Eta(), tempParticleWeight); // All meson mothers (pi0/eta) from analyzed heavy meson
fHistoMCMesonFromNeutralMesonPhi[fiCut]->Fill(TVector2::Phi_0_2pi(particleNDM->Phi()), tempParticleWeight); // All meson mothers (pi0/eta) from analyzed heavy meson
}
}
}
}
}
}
}
}
if (fNDMRecoMode < 2){
if (((AliConversionPhotonCuts*)fGammaCutArray->At(fiCut))->PhotonIsSelectedMC(particle,fMCEvent,kTRUE)){
fHistoMCConvGammaPt[fiCut]->Fill(particle->Pt(), tempParticleWeight);
} // Converted MC Gamma
}
if(((AliPrimaryPionCuts*)fPionCutArray->At(fiCut))->PionIsSelectedMC(i,fMCEvent)){
if( particle->GetPdgCode() == 211){
fHistoMCAllPosPionsPt[fiCut]->Fill(particle->Pt(), tempParticleWeight); // All pos pions
if(fDoMesonQA > 0){
fHistoMCAllPosPionsEta[fiCut]->Fill(particle->Eta(), tempParticleWeight); // All pos pions
fHistoMCAllPosPionsPhi[fiCut]->Fill(TVector2::Phi_0_2pi(particle->Phi()), tempParticleWeight); // All pos pions
}
if(particle->GetMother(0) >-1){
if (fMCEvent->Particle(particle->GetMother(0))->GetPdgCode() ==fPDGCodeAnalyzedMeson){
fHistoMCPosPionsFromNeutralMesonPt[fiCut]->Fill(particle->Pt(), tempParticleWeight); // All pos from neutral heavy meson (omega, eta OR eta prime)
if(fDoMesonQA > 0){
fHistoMCPosPionsFromNeutralMesonEta[fiCut]->Fill(particle->Eta(), tempParticleWeight); // All pos from neutral heavy meson (omega, eta OR eta prime)
fHistoMCPosPionsFromNeutralMesonPhi[fiCut]->Fill(TVector2::Phi_0_2pi(particle->Phi()), tempParticleWeight); // All pos from neutral heavy meson (omega, eta OR eta prime)
}
}
}
}
if( particle->GetPdgCode() == -211){
fHistoMCAllNegPionsPt[fiCut]->Fill(particle->Pt(), tempParticleWeight); // All neg pions
if(fDoMesonQA > 0) {
fHistoMCAllNegPionsEta[fiCut]->Fill(particle->Eta(), tempParticleWeight); // All neg pions
fHistoMCAllNegPionsPhi[fiCut]->Fill(TVector2::Phi_0_2pi(particle->Phi()), tempParticleWeight); // All neg pions
}
if(particle->GetMother(0) >-1){
if (fMCEvent->Particle(particle->GetMother(0))->GetPdgCode() ==fPDGCodeAnalyzedMeson){
fHistoMCNegPionsFromNeutralMesonPt[fiCut]->Fill(particle->Pt(), tempParticleWeight); // All pos from neutral heavy meson (omega, eta OR eta prime)
if(fDoMesonQA > 0){
fHistoMCNegPionsFromNeutralMesonEta[fiCut]->Fill(particle->Eta(), tempParticleWeight); // All pos from neutral heavy meson (omega, eta OR eta prime)
fHistoMCNegPionsFromNeutralMesonPhi[fiCut]->Fill(TVector2::Phi_0_2pi(particle->Phi()), tempParticleWeight); // All pos from neutral heavy meson (omega, eta OR eta prime)
}
}
}
}
}
}
}
// \eta -> pi+ pi- \gamma
Int_t labelNDM = -1;
Int_t labelNegPion = -1;
Int_t labelPosPion = -1;
if( ((AliConversionMesonCuts*)fMesonCutArray->At(fiCut))->MesonIsSelectedMCPiPlPiMiPiZero(particle,fMCEvent,labelNegPion,labelPosPion,labelNDM,((AliConvEventCuts*)fEventCutArray->At(fiCut))->GetEtaShift()) || ((AliConversionMesonCuts*)fMesonCutArray->At(fiCut))->MesonIsSelectedMCPiPlPiMiEta(particle,fMCEvent,labelNegPion,labelPosPion,labelNDM,((AliConvEventCuts*)fEventCutArray->At(fiCut))->GetEtaShift())){
Float_t weighted= 1.;
if( ((AliPrimaryPionCuts*) fPionCutArray->At(fiCut))->DoWeights() ) {
if(((AliConvEventCuts*)fEventCutArray->At(fiCut))->IsParticleFromBGEvent(i, fMCEvent,fInputEvent)){
if (particle->Pt()>0.005){
weighted= ((AliConvEventCuts*)fEventCutArray->At(fiCut))->GetWeightForMeson(i, fMCEvent,fInputEvent);
}
}
}
if(particle->GetPdgCode() == fPDGCodeAnalyzedMeson){
fHistoMCHNMPiPlPiMiNDMPt[fiCut]->Fill(particle->Pt(), weighted* tempParticleWeight); // All MC eta, omega OR eta prime in respective decay channel
if(!fDoLightOutput){
fHistoMCHNMPiPlPiMiNDMEta[fiCut]->Fill(particle->Eta(),weighted* tempParticleWeight);
fHistoMCHNMPiPlPiMiNDMPhi[fiCut]->Fill(particle->Phi(),weighted* tempParticleWeight);
}
}
if(labelNDM>-1){
TParticle *particleNDM = fMCEvent->Particle(labelNDM);
if(particleNDM->GetDaughter(0)>-1 && particleNDM->GetDaughter(1)>-1){
TParticle *gamma1 = fMCEvent->Particle(particleNDM->GetDaughter(0));
TParticle *gamma2 = fMCEvent->Particle(particleNDM->GetDaughter(1));
Bool_t kDaughter0IsPrim = ((AliConvEventCuts*)fEventCutArray->At(fiCut))->IsConversionPrimaryESD( fMCEvent, particleNDM->GetDaughter(0), mcProdVtxX, mcProdVtxY, mcProdVtxZ);
Bool_t kDaughter1IsPrim = ((AliConvEventCuts*)fEventCutArray->At(fiCut))->IsConversionPrimaryESD( fMCEvent, particleNDM->GetDaughter(1), mcProdVtxX, mcProdVtxY, mcProdVtxZ);
Bool_t kNegPionIsPrim = ((AliConvEventCuts*)fEventCutArray->At(fiCut))->IsConversionPrimaryESD( fMCEvent, labelNegPion, mcProdVtxX, mcProdVtxY, mcProdVtxZ);
Bool_t kPosPionIsPrim = ((AliConvEventCuts*)fEventCutArray->At(fiCut))->IsConversionPrimaryESD( fMCEvent, labelPosPion, mcProdVtxX, mcProdVtxY, mcProdVtxZ);
if (fNDMRecoMode == 0){
if( kDaughter0IsPrim && kDaughter1IsPrim && kNegPionIsPrim && kPosPionIsPrim &&
((AliConversionPhotonCuts*)fGammaCutArray->At(fiCut))->PhotonIsSelectedMC(gamma1,fMCEvent,kFALSE) && // test first daugther of pi0
((AliConversionPhotonCuts*)fGammaCutArray->At(fiCut))->PhotonIsSelectedMC(gamma2,fMCEvent,kFALSE) && // test second daughter of pi0
((AliPrimaryPionCuts*)fPionCutArray->At(fiCut))->PionIsSelectedMC(labelNegPion,fMCEvent) && // test negative pion
((AliPrimaryPionCuts*)fPionCutArray->At(fiCut))->PionIsSelectedMC(labelPosPion,fMCEvent) // test positive pion
) {
if(particle->GetPdgCode() == fPDGCodeAnalyzedMeson){
fHistoMCHNMPiPlPiMiNDMInAccPt[fiCut]->Fill(particle->Pt(), weighted* tempParticleWeight ); // MC Eta, omega or eta prime with pi+ pi- pi0 with gamma's and e+e- in acc
// check relation between HNM pt and NDM, while respecting pT cutoff for NDM
if(!fDoLightOutput){
if(particleNDM->Pt() >= fNDMMinPtPossible) fHistoMCHNMInAccVsNDMPt[fiCut]->Fill(particle->Pt(),particleNDM->Pt(),weighted* tempParticleWeight);
}
}
}
} else if (fNDMRecoMode == 1){ // mixed mode
// check acceptamce of pions firs
if( kDaughter0IsPrim && kDaughter1IsPrim && kNegPionIsPrim && kPosPionIsPrim &&
((AliPrimaryPionCuts*)fPionCutArray->At(fiCut))->PionIsSelectedMC(labelNegPion,fMCEvent) && // test negative pion
((AliPrimaryPionCuts*)fPionCutArray->At(fiCut))->PionIsSelectedMC(labelPosPion,fMCEvent) // test positive pion
) {
// check acceptance of clusters and PCM photons
if((((AliConversionPhotonCuts*)fGammaCutArray->At(fiCut))->PhotonIsSelectedMC(gamma1,fMCEvent,kFALSE) &&
((AliCaloPhotonCuts*)fClusterCutArray->At(fiCut))->ClusterIsSelectedMC(gamma2,fMCEvent)) ||
(((AliConversionPhotonCuts*)fGammaCutArray->At(fiCut))->PhotonIsSelectedMC(gamma2,fMCEvent,kFALSE) &&
((AliCaloPhotonCuts*)fClusterCutArray->At(fiCut))->ClusterIsSelectedMC(gamma1,fMCEvent))
){
if(particle->GetPdgCode() == fPDGCodeAnalyzedMeson){
fHistoMCHNMPiPlPiMiNDMInAccPt[fiCut]->Fill(particle->Pt(), weighted* tempParticleWeight ); // MC Eta, omega or eta prime with pi+ pi- pi0 with gamma's and e+e- in acc
// check relation between HNM pt and NDM, while respecting pT cutoff for NDM
if(!fDoLightOutput){
if(particleNDM->Pt() >= fNDMMinPtPossible) fHistoMCHNMInAccVsNDMPt[fiCut]->Fill(particle->Pt(),particleNDM->Pt(),weighted* tempParticleWeight );
}
}
}
}
} else if (fNDMRecoMode == 2){
if( kDaughter0IsPrim && kDaughter1IsPrim && kNegPionIsPrim && kPosPionIsPrim &&
((AliCaloPhotonCuts*)fClusterCutArray->At(fiCut))->ClusterIsSelectedMC(gamma1,fMCEvent) && // test first daugther of pi0
((AliCaloPhotonCuts*)fClusterCutArray->At(fiCut))->ClusterIsSelectedMC(gamma2,fMCEvent) && // test second daughter of pi0
((AliPrimaryPionCuts*)fPionCutArray->At(fiCut))->PionIsSelectedMC(labelNegPion,fMCEvent) && // test negative pion
((AliPrimaryPionCuts*)fPionCutArray->At(fiCut))->PionIsSelectedMC(labelPosPion,fMCEvent) // test positive pion
) {
if(particle->GetPdgCode() == fPDGCodeAnalyzedMeson){
fHistoMCHNMPiPlPiMiNDMInAccPt[fiCut]->Fill(particle->Pt(), weighted* tempParticleWeight ); // MC Eta pi+ pi- pi0 with gamma's and e+e- in acc
// check relation between HNM pt and NDM, while respecting pT cutoff for NDM
if(!fDoLightOutput){
if(particleNDM->Pt() >= fNDMMinPtPossible) fHistoMCHNMInAccVsNDMPt[fiCut]->Fill(particle->Pt(),particleNDM->Pt(),weighted* tempParticleWeight );
}
}
}
}
}
}
}
}
}
}
//_____________________________________________________________________________
void AliAnalysisTaskNeutralMesonToPiPlPiMiNeutralMeson::ProcessAODMCParticles(){
// Loop over all primary MC particle
const AliVVertex* primVtxMC = fMCEvent->GetPrimaryVertex();
Double_t mcProdVtxX = primVtxMC->GetX();
Double_t mcProdVtxY = primVtxMC->GetY();
Double_t mcProdVtxZ = primVtxMC->GetZ();
TClonesArray *AODMCTrackArray = dynamic_cast<TClonesArray*>(fInputEvent->FindListObject(AliAODMCParticle::StdBranchName()));
if (AODMCTrackArray){
for(Int_t i = 0; i < AODMCTrackArray->GetEntriesFast(); i++) {
Double_t tempParticleWeight = fWeightJetJetMC;
AliAODMCParticle* particle = static_cast<AliAODMCParticle*>(AODMCTrackArray->At(i));
if (!particle) continue;
if (((AliConvEventCuts*)fEventCutArray->At(fiCut))->IsConversionPrimaryAOD( fInputEvent, particle, mcProdVtxX, mcProdVtxY, mcProdVtxZ)){
Int_t isMCFromMBHeader = -1;
if(((AliConvEventCuts*)fEventCutArray->At(fiCut))->GetSignalRejection() != 0){
isMCFromMBHeader
= ((AliConvEventCuts*)fEventCutArray->At(fiCut))->IsParticleFromBGEvent(i, fMCEvent, fInputEvent);
if(isMCFromMBHeader == 0 && ((AliConvEventCuts*)fEventCutArray->At(fiCut))->GetSignalRejection() != 3) continue;
// Set the jetjet weight to 1 in case the particle orignated from the minimum bias header
if(isMCFromMBHeader == 2 && ((AliConvEventCuts*)fEventCutArray->At(fiCut))->GetSignalRejection() == 4) tempParticleWeight = 1;
}
if(!fDoLightOutput){
// Fill kinematics for heavy particle
// This also contains not-reconstructed particles
if(fDoMesonQA > 0){
if(TMath::Abs(particle->GetPdgCode()) == fPDGCodeAnalyzedMeson){
fHistoMCHeavyAllPt[fiCut]->Fill(particle->Pt(), tempParticleWeight);
fHistoMCHeavyAllEta[fiCut]->Fill(particle->Eta(), tempParticleWeight);
fHistoMCHeavyAllPhi[fiCut]->Fill(TVector2::Phi_0_2pi(particle->Phi()), fWeightJetJetMC);
// check for Decay kinematics
if(particle->GetNDaughters() == 3){
AliAODMCParticle *neutralMeson(nullptr), *piplus(nullptr), *piminus(nullptr);
Int_t indexpiplus(-1), indexpiminus(-1);
for(int idaug = particle->GetDaughterFirst(); idaug <= particle->GetDaughterLast(); idaug++) {
AliAODMCParticle *daughter = static_cast<AliAODMCParticle *>(AODMCTrackArray->At(idaug));
if(daughter->PdgCode() == kPiPlus){
piplus = daughter;
indexpiplus = idaug;
} else if(daughter->PdgCode() == kPiMinus) {
piminus = daughter;
indexpiminus = idaug;
} else if(TMath::Abs(daughter->PdgCode()) == fPDGCodeNDM){
neutralMeson = daughter;
}
}
if(neutralMeson && piplus && piminus) {
// Meson is in the expected channel
fHistoMCHeavyChannelPt[fiCut]->Fill(particle->Pt(), fWeightJetJetMC);
fHistoMCHeavyChannelEta[fiCut]->Fill(particle->Eta(), fWeightJetJetMC);
fHistoMCHeavyChannelPhi[fiCut]->Fill(TVector2::Phi_0_2pi(particle->Phi()), fWeightJetJetMC);
// Fill kinematics for daughter particles
fHistMCChannelNDMFromHeavyPt[fiCut]->Fill(neutralMeson->Pt(), fWeightJetJetMC);
fHistMCChannelNDMFromHeavyEta[fiCut]->Fill(neutralMeson->Eta(), fWeightJetJetMC);
fHistMCChannelNDMFromHeavyPhi[fiCut]->Fill(TVector2::Phi_0_2pi(neutralMeson->Phi()), fWeightJetJetMC);
fHistMCChannelPiPlusFromHeavyPt[fiCut]->Fill(piplus->Pt(), fWeightJetJetMC);
fHistMCChannelPiPlusFromHeavyEta[fiCut]->Fill(piplus->Eta(), fWeightJetJetMC);
fHistMCChannelPiPlusFromHeavyPhi[fiCut]->Fill(TVector2::Phi_0_2pi(piplus->Phi()), fWeightJetJetMC);
fHistMCChannelPiMinusFromHeavyPt[fiCut]->Fill(piminus->Pt(), fWeightJetJetMC);
fHistMCChannelPiMinusFromHeavyEta[fiCut]->Fill(piminus->Eta(), fWeightJetJetMC);
fHistMCChannelPiPMinusFromHeavyPhi[fiCut]->Fill(TVector2::Phi_0_2pi(piminus->Phi()), fWeightJetJetMC);
fHistMCChannelNDMPtHeavyPt[fiCut]->Fill(particle->Pt(), neutralMeson->Pt(), fWeightJetJetMC);
fHistMCChannelPiPlusPtHeavyPt[fiCut]->Fill(particle->Pt(), piplus->Pt(), fWeightJetJetMC);
fHistMCChannelPiMinusPtHeavyPt[fiCut]->Fill(particle->Pt(), piminus->Pt(), fWeightJetJetMC);
// check if particle is reconstructible
bool reconstructible(true);
if(!((AliPrimaryPionCuts*)fPionCutArray->At(fiCut))->PionIsSelectedAODMC(indexpiminus,AODMCTrackArray)) reconstructible = false;
if(!((AliPrimaryPionCuts*)fPionCutArray->At(fiCut))->PionIsSelectedAODMC(indexpiplus,AODMCTrackArray)) reconstructible = false;
if(neutralMeson->GetNDaughters() == 3) {
// exclude Dalitz-decays
reconstructible = false;
} else {
AliAODMCParticle *photon1 = static_cast<AliAODMCParticle *>(AODMCTrackArray->At(neutralMeson->GetDaughterFirst())),
*photon2 = static_cast<AliAODMCParticle *>(AODMCTrackArray->At(neutralMeson->GetDaughterLast()));
if(!(photon1 && photon2)) reconstructible = false;
else {
switch(fNDMRecoMode) {
case 0 : {
if(!((AliConversionPhotonCuts*)fGammaCutArray->At(fiCut))->PhotonIsSelectedAODMC(photon1, AODMCTrackArray, kFALSE)) reconstructible = false;
if(!((AliConversionPhotonCuts*)fGammaCutArray->At(fiCut))->PhotonIsSelectedAODMC(photon2, AODMCTrackArray, kFALSE)) reconstructible = false;
break;
}
case 1: {
if(!(((AliConversionPhotonCuts*)fGammaCutArray->At(fiCut))->PhotonIsSelectedAODMC(photon1, AODMCTrackArray, kFALSE) &&
((AliCaloPhotonCuts*)fClusterCutArray->At(fiCut))->ClusterIsSelectedAODMC(photon1, AODMCTrackArray)) ||
!(((AliConversionPhotonCuts*)fGammaCutArray->At(fiCut))->PhotonIsSelectedAODMC(photon2, AODMCTrackArray, kFALSE) &&
((AliCaloPhotonCuts*)fClusterCutArray->At(fiCut))->ClusterIsSelectedAODMC(photon1, AODMCTrackArray))
) reconstructible = false;
break;
}
case 2: {
if(!((AliCaloPhotonCuts*)fClusterCutArray->At(fiCut))->ClusterIsSelectedAODMC(photon1, AODMCTrackArray)) reconstructible = false;
if(!((AliCaloPhotonCuts*)fClusterCutArray->At(fiCut))->ClusterIsSelectedAODMC(photon1, AODMCTrackArray)) reconstructible = false;
break;
}
};
}
}
if(reconstructible) {
fHistoMCHeavyReconstructiblePt[fiCut]->Fill(particle->Pt(), fWeightJetJetMC);
fHistoMCHeavyReconstructibleEta[fiCut]->Fill(particle->Eta(), fWeightJetJetMC);
fHistoMCHeavyReconstructiblePhi[fiCut]->Fill(TVector2::Phi_0_2pi(particle->Phi()), fWeightJetJetMC);
// Fill kinematics for daughter particles
fHistMCReconstructibleNDMFromHeavyPt[fiCut]->Fill(neutralMeson->Pt(), fWeightJetJetMC);
fHistMCReconstructibleNDMFromHeavyEta[fiCut]->Fill(neutralMeson->Eta(), fWeightJetJetMC);
fHistMCReconstructibleNDMFromHeavyPhi[fiCut]->Fill(TVector2::Phi_0_2pi(neutralMeson->Phi()), fWeightJetJetMC);
fHistMCReconstructiblePiPlusFromHeavyPt[fiCut]->Fill(piplus->Pt(), fWeightJetJetMC);
fHistMCReconstructiblePiPlusFromHeavyEta[fiCut]->Fill(piplus->Eta(), fWeightJetJetMC);
fHistMCReconstructiblePiPlusFromHeavyPhi[fiCut]->Fill(TVector2::Phi_0_2pi(piplus->Phi()), fWeightJetJetMC);
fHistMCReconstructiblePiMinusFromHeavyPt[fiCut]->Fill(piminus->Pt(), fWeightJetJetMC);
fHistMCReconstructiblePiMinusFromHeavyEta[fiCut]->Fill(piminus->Eta(), fWeightJetJetMC);
fHistMCReconstructiblePiPMinusFromHeavyPhi[fiCut]->Fill(TVector2::Phi_0_2pi(piminus->Phi()), fWeightJetJetMC);
fHistMCReconstructibleNDMPtHeavyPt[fiCut]->Fill(particle->Pt(), neutralMeson->Pt(), fWeightJetJetMC);
fHistMCReconstructiblePiPlusPtHeavyPt[fiCut]->Fill(particle->Pt(), piplus->Pt(), fWeightJetJetMC);
fHistMCReconstructiblePiMinusPtHeavyPt[fiCut]->Fill(particle->Pt(), piminus->Pt(), fWeightJetJetMC);
}
}
}
}
}
// find MC photons
if (fNDMRecoMode < 2 ){
if(((AliConversionPhotonCuts*)fGammaCutArray->At(fiCut))->PhotonIsSelectedAODMC(particle,AODMCTrackArray,kFALSE)){
fHistoMCAllGammaPt[fiCut]->Fill(particle->Pt(), fWeightJetJetMC); // All MC Gamma
if(particle->GetMother() >-1){
if ((static_cast<AliAODMCParticle*>(AODMCTrackArray->At(particle->GetMother())))->GetPdgCode() ==fPDGCodeNDM){
AliAODMCParticle *particleNDM = static_cast<AliAODMCParticle *>(AODMCTrackArray->At(particle->GetMother()));
if (fDoMesonQA>0){
fHistoMCAllMesonPt[fiCut]->Fill(particleNDM->Pt(), fWeightJetJetMC);
fHistoMCAllMesonEta[fiCut]->Fill(particleNDM->Eta(), fWeightJetJetMC);
fHistoMCAllMesonPhi[fiCut]->Fill(TVector2::Phi_0_2pi(particleNDM->Phi()), fWeightJetJetMC);
}
if ((static_cast<AliAODMCParticle*>(AODMCTrackArray->At(particle->GetMother())))->GetMother() > -1){
if ( (static_cast<AliAODMCParticle*>(AODMCTrackArray->At( (static_cast<AliAODMCParticle*>(AODMCTrackArray->At(particle->GetMother())))->GetMother() )))->GetPdgCode() == fPDGCodeAnalyzedMeson ){
if ( (static_cast<AliAODMCParticle*>(AODMCTrackArray->At( (static_cast<AliAODMCParticle*>(AODMCTrackArray->At(particle->GetMother())))->GetMother() )))->GetNDaughters() ==3 ) {
fHistoMCGammaFromNeutralMesonPt[fiCut]->Fill(particle->Pt(), fWeightJetJetMC); // All photons from eta or omega via pi0
if(fDoMesonQA > 0) {
fHistoMCMesonFromNeutralMesonPt[fiCut]->Fill(particleNDM->Pt(), fWeightJetJetMC); // ALl meson mothers (pi0/eta) from analyzed heavy meson
fHistoMCMesonFromNeutralMesonEta[fiCut]->Fill(particleNDM->Eta(), fWeightJetJetMC); // All meson mothers (pi0/eta) from analyzed heavy meson
fHistoMCMesonFromNeutralMesonPhi[fiCut]->Fill(TVector2::Phi_0_2pi(particleNDM->Phi()), fWeightJetJetMC); // All meson mothers (pi0/eta) from analyzed heavy meson
}
}
}
}
}
}
}
} else if (fNDMRecoMode == 2){
if(((AliCaloPhotonCuts*)fClusterCutArray->At(fiCut))->ClusterIsSelectedAODMC(particle,AODMCTrackArray)){
fHistoMCAllGammaPt[fiCut]->Fill(particle->Pt(), fWeightJetJetMC); // All MC Gamma
if(particle->GetMother() >-1){
if ( (static_cast<AliAODMCParticle*>(AODMCTrackArray->At(particle->GetMother())))->GetPdgCode() == fPDGCodeNDM){
AliAODMCParticle *particleNDM = static_cast<AliAODMCParticle *>(AODMCTrackArray->At(particle->GetMother()));
if(fDoMesonQA > 0){
fHistoMCAllMesonPt[fiCut]->Fill(particleNDM->Pt(), fWeightJetJetMC);
fHistoMCAllMesonEta[fiCut]->Fill(particleNDM->Eta(), fWeightJetJetMC);
fHistoMCAllMesonPhi[fiCut]->Fill(TVector2::Phi_0_2pi(particleNDM->Phi()), fWeightJetJetMC);
}
if ((static_cast<AliAODMCParticle*>(AODMCTrackArray->At(particle->GetMother())))->GetMother() > -1){
if ( (static_cast<AliAODMCParticle*>(AODMCTrackArray->At( (static_cast<AliAODMCParticle*>(AODMCTrackArray->At(particle->GetMother())))->GetMother() )))->GetPdgCode() == fPDGCodeAnalyzedMeson ){
if ( (static_cast<AliAODMCParticle*>(AODMCTrackArray->At( (static_cast<AliAODMCParticle*>(AODMCTrackArray->At(particle->GetMother())))->GetMother() )))->GetNDaughters() ==3 ) {
fHistoMCGammaFromNeutralMesonPt[fiCut]->Fill(particle->Pt(), fWeightJetJetMC); // All photons from analyzed meson via pi0 or eta from decay
if(fDoMesonQA > 0){
fHistoMCMesonFromNeutralMesonPt[fiCut]->Fill(particleNDM->Pt(), fWeightJetJetMC); // All meson mothers (pi0/eta) from analyzed heavy meson
fHistoMCMesonFromNeutralMesonEta[fiCut]->Fill(particleNDM->Eta(), fWeightJetJetMC); // All meson mothers (pi0/eta) from analyzed heavy meson
fHistoMCMesonFromNeutralMesonPhi[fiCut]->Fill(TVector2::Phi_0_2pi(particleNDM->Phi()), fWeightJetJetMC); // All meson mothers (pi0/eta) from analyzed heavy meson
}
}
}
}
}
}
}
}
if (fNDMRecoMode < 2){
if (((AliConversionPhotonCuts*)fGammaCutArray->At(fiCut))->PhotonIsSelectedAODMC(particle,AODMCTrackArray,kTRUE)){
fHistoMCConvGammaPt[fiCut]->Fill(particle->Pt(), fWeightJetJetMC);
} // Converted MC Gamma
}
if(((AliPrimaryPionCuts*)fPionCutArray->At(fiCut))->PionIsSelectedAODMC(i,AODMCTrackArray)){
if( particle->GetPdgCode() == 211){
fHistoMCAllPosPionsPt[fiCut]->Fill(particle->Pt(), fWeightJetJetMC); // All pos pions
if(fDoMesonQA > 0){
fHistoMCAllPosPionsEta[fiCut]->Fill(particle->Eta(), fWeightJetJetMC); // All pos pions
fHistoMCAllPosPionsPhi[fiCut]->Fill(TVector2::Phi_0_2pi(particle->Phi()), fWeightJetJetMC); // All pos pions
}
if(particle->GetMother() >-1){
if ( (static_cast<AliAODMCParticle*>(AODMCTrackArray->At(particle->GetMother())))->GetPdgCode() ==fPDGCodeAnalyzedMeson){
fHistoMCPosPionsFromNeutralMesonPt[fiCut]->Fill(particle->Pt(), fWeightJetJetMC); // All pos from neutral heavy meson (omega, eta OR eta prime)
if(fDoMesonQA > 0){
fHistoMCPosPionsFromNeutralMesonEta[fiCut]->Fill(particle->Eta(), fWeightJetJetMC); // All pos from neutral heavy meson (omega, eta OR eta prime)
fHistoMCPosPionsFromNeutralMesonPhi[fiCut]->Fill(TVector2::Phi_0_2pi(particle->Phi()), fWeightJetJetMC); // All pos from neutral heavy meson (omega, eta OR eta prime)
}
}
}
}
if( particle->GetPdgCode() == -211){
fHistoMCAllNegPionsPt[fiCut]->Fill(particle->Pt(), fWeightJetJetMC); // All neg pions
if(fDoMesonQA){
fHistoMCAllNegPionsEta[fiCut]->Fill(particle->Eta(), fWeightJetJetMC); // All neg pions
fHistoMCAllNegPionsPhi[fiCut]->Fill(TVector2::Phi_0_2pi(particle->Phi()), fWeightJetJetMC); // All neg pions
}
if(particle->GetMother() >-1){
if ((static_cast<AliAODMCParticle*>(AODMCTrackArray->At(particle->GetMother())))->GetPdgCode() ==fPDGCodeAnalyzedMeson) {
fHistoMCNegPionsFromNeutralMesonPt[fiCut]->Fill(particle->Pt(), fWeightJetJetMC); // All pos from neutral heavy meson (omega, eta OR eta prime)
if(fDoMesonQA > 0) {
fHistoMCNegPionsFromNeutralMesonEta[fiCut]->Fill(particle->Eta(), fWeightJetJetMC); // All pos from neutral heavy meson (omega, eta OR eta prime)
fHistoMCNegPionsFromNeutralMesonPhi[fiCut]->Fill(TVector2::Phi_0_2pi(particle->Phi()), fWeightJetJetMC); // All pos from neutral heavy meson (omega, eta OR eta prime)
}
}
}
}
}
}
// \eta -> pi+ pi- \gamma
Int_t labelNDM = -1;
Int_t labelNegPion = -1;
Int_t labelPosPion = -1;
if( ((AliConversionMesonCuts*)fMesonCutArray->At(fiCut))->MesonIsSelectedAODMCPiPlPiMiPiZero(particle,AODMCTrackArray,labelNegPion,labelPosPion,labelNDM,((AliConvEventCuts*)fEventCutArray->At(fiCut))->GetEtaShift()) || ((AliConversionMesonCuts*)fMesonCutArray->At(fiCut))->MesonIsSelectedAODMCPiPlPiMiEta(particle,AODMCTrackArray,labelNegPion,labelPosPion,labelNDM,((AliConvEventCuts*)fEventCutArray->At(fiCut))->GetEtaShift())){
Float_t weighted= 1.;
if( ((AliPrimaryPionCuts*) fPionCutArray->At(fiCut))->DoWeights() ) {
if(((AliConvEventCuts*)fEventCutArray->At(fiCut))->IsParticleFromBGEvent(i, fMCEvent,fInputEvent)){
if (particle->Pt()>0.005){
weighted= ((AliConvEventCuts*)fEventCutArray->At(fiCut))->GetWeightForMeson(i, 0x0,fInputEvent);
}
}
}
if(particle->GetPdgCode() == fPDGCodeAnalyzedMeson)fHistoMCHNMPiPlPiMiNDMPt[fiCut]->Fill(particle->Pt(), tempParticleWeight); // All MC eta, omega OR eta prime in respective decay channel
if(!fDoLightOutput){
fHistoMCHNMPiPlPiMiNDMEta[fiCut]->Fill(particle->Eta(),tempParticleWeight);
fHistoMCHNMPiPlPiMiNDMPhi[fiCut]->Fill(particle->Phi(),tempParticleWeight);
}
if(labelNDM>-1){
AliAODMCParticle* particleNDM = static_cast<AliAODMCParticle*>(AODMCTrackArray->At(labelNDM));
if(particleNDM->GetDaughterLabel(0)>-1 && particleNDM->GetDaughterLabel(1)>-1){
AliAODMCParticle *gamma1 = static_cast<AliAODMCParticle*>(AODMCTrackArray->At(particleNDM->GetDaughterLabel(0)));
AliAODMCParticle *gamma2 = static_cast<AliAODMCParticle*>(AODMCTrackArray->At(particleNDM->GetDaughterLabel(1)));
AliAODMCParticle *negpion = static_cast<AliAODMCParticle*>(AODMCTrackArray->At(labelNegPion));
AliAODMCParticle *pospion = static_cast<AliAODMCParticle*>(AODMCTrackArray->At(labelPosPion));
Bool_t kDaughter0IsPrim = ((AliConvEventCuts*)fEventCutArray->At(fiCut))->IsConversionPrimaryAOD( fInputEvent, gamma1, mcProdVtxX, mcProdVtxY, mcProdVtxZ);
Bool_t kDaughter1IsPrim = ((AliConvEventCuts*)fEventCutArray->At(fiCut))->IsConversionPrimaryAOD( fInputEvent, gamma2, mcProdVtxX, mcProdVtxY, mcProdVtxZ);
Bool_t kNegPionIsPrim = ((AliConvEventCuts*)fEventCutArray->At(fiCut))->IsConversionPrimaryAOD( fInputEvent, negpion, mcProdVtxX, mcProdVtxY, mcProdVtxZ);
Bool_t kPosPionIsPrim = ((AliConvEventCuts*)fEventCutArray->At(fiCut))->IsConversionPrimaryAOD( fInputEvent, pospion, mcProdVtxX, mcProdVtxY, mcProdVtxZ);
if (fNDMRecoMode == 0){
if( kDaughter0IsPrim && kDaughter1IsPrim && kNegPionIsPrim && kPosPionIsPrim &&
((AliConversionPhotonCuts*)fGammaCutArray->At(fiCut))->PhotonIsSelectedAODMC(gamma1,AODMCTrackArray,kFALSE) && // test first daugther of pi0
((AliConversionPhotonCuts*)fGammaCutArray->At(fiCut))->PhotonIsSelectedAODMC(gamma2,AODMCTrackArray,kFALSE) && // test second daughter of pi0
((AliPrimaryPionCuts*)fPionCutArray->At(fiCut))->PionIsSelectedAODMC(labelNegPion,AODMCTrackArray) && // test negative pion
((AliPrimaryPionCuts*)fPionCutArray->At(fiCut))->PionIsSelectedAODMC(labelPosPion,AODMCTrackArray) // test positive pion
) {
if(particle->GetPdgCode() == fPDGCodeAnalyzedMeson) {
fHistoMCHNMPiPlPiMiNDMInAccPt[fiCut]->Fill(particle->Pt(), tempParticleWeight ); // MC Eta, omega or eta prime with pi+ pi- pi0 with gamma's and e+e- in acc
// check relation between HNM pt and NDM, while respecting pT cutoff for NDM
if(!fDoLightOutput){
if(particleNDM->Pt() >= fNDMMinPtPossible) fHistoMCHNMInAccVsNDMPt[fiCut]->Fill(particle->Pt(),particleNDM->Pt(),tempParticleWeight);
}
}
}
} else if (fNDMRecoMode == 1){ // mixed mode
// check if within PCM acceptance first
if( kDaughter0IsPrim && kDaughter1IsPrim && kNegPionIsPrim && kPosPionIsPrim &&
((AliConversionPhotonCuts*)fGammaCutArray->At(fiCut))->PhotonIsSelectedAODMC(gamma1,AODMCTrackArray,kFALSE) && // test first daugther of pi0
((AliConversionPhotonCuts*)fGammaCutArray->At(fiCut))->PhotonIsSelectedAODMC(gamma2,AODMCTrackArray,kFALSE) && // test second daughter of pi0
((AliPrimaryPionCuts*)fPionCutArray->At(fiCut))->PionIsSelectedAODMC(labelNegPion,AODMCTrackArray) && // test negative pion
((AliPrimaryPionCuts*)fPionCutArray->At(fiCut))->PionIsSelectedAODMC(labelPosPion,AODMCTrackArray) // test positive pion
) {
// check acceptance of clusters as well, true if one of them points into the Calo acceptance
if (((AliCaloPhotonCuts*)fClusterCutArray->At(fiCut))->ClusterIsSelectedAODMC(gamma1,AODMCTrackArray) ||
((AliCaloPhotonCuts*)fClusterCutArray->At(fiCut))->ClusterIsSelectedAODMC(gamma2,AODMCTrackArray) ){
if(particle->GetPdgCode() == fPDGCodeAnalyzedMeson){
fHistoMCHNMPiPlPiMiNDMInAccPt[fiCut]->Fill(particle->Pt(), weighted* tempParticleWeight ); // MC Eta, omega or eta prime with pi+ pi- pi0 with gamma's and e+e- in acc
// check relation between HNM pt and NDM, while respecting pT cutoff for NDM
if(!fDoLightOutput){
if(particleNDM->Pt() >= fNDMMinPtPossible) fHistoMCHNMInAccVsNDMPt[fiCut]->Fill(particle->Pt(),particleNDM->Pt(),weighted* tempParticleWeight);
}
}
}
}
} else if (fNDMRecoMode == 2){
if( kDaughter0IsPrim && kDaughter1IsPrim && kNegPionIsPrim && kPosPionIsPrim &&
((AliCaloPhotonCuts*)fClusterCutArray->At(fiCut))->ClusterIsSelectedAODMC(gamma1,AODMCTrackArray) && // test first daugther of pi0
((AliCaloPhotonCuts*)fClusterCutArray->At(fiCut))->ClusterIsSelectedAODMC(gamma2,AODMCTrackArray) && // test second daughter of pi0
((AliPrimaryPionCuts*)fPionCutArray->At(fiCut))->PionIsSelectedAODMC(labelNegPion,AODMCTrackArray) && // test negative pion
((AliPrimaryPionCuts*)fPionCutArray->At(fiCut))->PionIsSelectedAODMC(labelPosPion,AODMCTrackArray) // test positive pion
) {
if(particle->GetPdgCode() == fPDGCodeAnalyzedMeson){
fHistoMCHNMPiPlPiMiNDMInAccPt[fiCut]->Fill(particle->Pt(), weighted* tempParticleWeight ); // MC Eta pi+ pi- pi0 with gamma's and e+e- in acc
// check relation between HNM pt and NDM, while respecting pT cutoff for NDM
if(!fDoLightOutput){
if(particleNDM->Pt() >= fNDMMinPtPossible) fHistoMCHNMInAccVsNDMPt[fiCut]->Fill(particle->Pt(),particleNDM->Pt(),weighted* tempParticleWeight);
}
}
}
}
}
}
}
}
}
}
}
//________________________________________________________________________
void AliAnalysisTaskNeutralMesonToPiPlPiMiNeutralMeson::CalculateMesonCandidates(AliAODConversionPhoton *vParticle){
// Conversion Gammas
if( fNeutralDecayParticleCandidates->GetEntries() > 0){
for(Int_t mesonIndex=0; mesonIndex<fNeutralDecayParticleCandidates->GetEntries(); mesonIndex++){
AliAODConversionMother *neutralDecayMeson= (AliAODConversionMother*) fNeutralDecayParticleCandidates->At(mesonIndex);
if (neutralDecayMeson==nullptr) continue;
if (vParticle==nullptr) continue;
//Check for same Electron ID
AliAODConversionMother* mesoncand = new AliAODConversionMother(neutralDecayMeson,vParticle);
//mesoncand->SetLabels(mesonIndex,virtualParticleIndex);
if( ((AliConversionMesonCuts*)fMesonCutArray->At(fiCut))->MesonIsSelected(mesoncand,kTRUE,((AliConvEventCuts*)fEventCutArray->At(fiCut))->GetEtaShift())){
AliVTrack *negPionCandidatetmp = dynamic_cast<AliVTrack*>(fInputEvent->GetTrack(vParticle->GetTrackLabel(1)));
AliVTrack *posPionCandidatetmp = dynamic_cast<AliVTrack*>(fInputEvent->GetTrack(vParticle->GetTrackLabel(0)));
if(!(negPionCandidatetmp || posPionCandidatetmp)) continue;
AliAODConversionMother NegPiontmp, PosPiontmp;
NegPiontmp.SetPxPyPzE(negPionCandidatetmp->Px(), negPionCandidatetmp->Py(), negPionCandidatetmp->Pz(), negPionCandidatetmp->E());
PosPiontmp.SetPxPyPzE(posPionCandidatetmp->Px(), posPionCandidatetmp->Py(), posPionCandidatetmp->Pz(), posPionCandidatetmp->E());
// Fix Pz of pi0 candidate to match pi0 PDG mass
AliAODConversionMother NDMtmp;
NDMtmp.SetPxPyPzE(neutralDecayMeson->Px(), neutralDecayMeson->Py(), neutralDecayMeson->Pz(), neutralDecayMeson->Energy());
FixPzToMatchPDGInvMassNDM(&NDMtmp);
//Variables for Dalitz plot and Pi0 Pi+- Mass Cut
AliKFParticle PosPionKFtmp( *posPionCandidatetmp, 211 );
AliKFParticle NegPionKFtmp( *negPionCandidatetmp, 211 );
TLorentzVector PosPionTLVtmp;
TLorentzVector NegPionTLVtmp;
TLorentzVector PosNegPionTLVtmp;
PosPionTLVtmp.SetPxPyPzE (PosPionKFtmp.Px(), PosPionKFtmp.Py(), PosPionKFtmp.Pz(), PosPionKFtmp.E() );
NegPionTLVtmp.SetPxPyPzE (NegPionKFtmp.Px(), NegPionKFtmp.Py(), NegPionKFtmp.Pz(), NegPionKFtmp.E() );
PosNegPionTLVtmp = PosPionTLVtmp + NegPionTLVtmp;
TLorentzVector NDMTLVtmp;
TLorentzVector NDMSubTLVtmp;
TLorentzVector PosPionNDMTLVtmp;
TLorentzVector NegPionNDMTLVtmp;
TLorentzVector PosPionNDMSubTLVtmp;
TLorentzVector NegPionNDMSubTLVtmp;
NDMTLVtmp.SetPxPyPzE( NDMtmp.Px(), NDMtmp.Py(), NDMtmp.Pz(), NDMtmp.E() ); //Fixed Pz
NDMSubTLVtmp.SetPxPyPzE (neutralDecayMeson->Px(), neutralDecayMeson->Py(), neutralDecayMeson->Pz(), neutralDecayMeson->Energy());
PosPionNDMTLVtmp = PosPionTLVtmp + NDMTLVtmp;
NegPionNDMTLVtmp = NegPionTLVtmp + NDMTLVtmp;
PosPionNDMSubTLVtmp = PosPionTLVtmp + NDMSubTLVtmp;
NegPionNDMSubTLVtmp = NegPionTLVtmp + NDMSubTLVtmp;
//Double_t Mass_PiPl_NDM_FixPz = PosPionNDMTLVtmp.M(); //Outcommented as currently not needed
//Double_t Mass_PiMi_NDM_FixPz = NegPionNDMTLVtmp.M(); //Outcommented as currently not needed
Double_t Mass_PiPl_NDM_Sub = PosPionNDMSubTLVtmp.M() - (NDMSubTLVtmp.M() - fPDGMassNDM);
Double_t Mass_PiMi_NDM_Sub = NegPionNDMSubTLVtmp.M() - (NDMSubTLVtmp.M() - fPDGMassNDM);
Double_t MassCutValue_PiPlMi_NDM = ((AliPrimaryPionCuts*)fPionCutArray->At(fiCut))->GetMassCut_WithNDM();
Bool_t useMassCut_WithNDM = ((AliPrimaryPionCuts*)fPionCutArray->At(fiCut))->DoMassCut_WithNDM();
if ((!useMassCut_WithNDM)||
((useMassCut_WithNDM)
&&(Mass_PiPl_NDM_Sub<MassCutValue_PiPlMi_NDM)
&&(Mass_PiMi_NDM_Sub<MassCutValue_PiPlMi_NDM)
)){
if(KinematicCut(&NegPiontmp, &PosPiontmp, neutralDecayMeson, mesoncand)){
if(!fDoLightOutput){
fHistoAngleHNMesonNDM[fiCut]->Fill(mesoncand->Pt(),neutralDecayMeson->Angle(mesoncand->Vect()), fWeightJetJetMC);
fHistoAngleHNMesonPiPl[fiCut]->Fill(mesoncand->Pt(),PosPiontmp.Angle(mesoncand->Vect()), fWeightJetJetMC);
fHistoAngleHNMesonPiMi[fiCut]->Fill(mesoncand->Pt(),NegPiontmp.Angle(mesoncand->Vect()), fWeightJetJetMC);
fHistoAngleNDMPiMi[fiCut]->Fill(mesoncand->Pt(),NegPiontmp.Angle(neutralDecayMeson->Vect()), fWeightJetJetMC);
fHistoAnglePiPlPiMi[fiCut]->Fill(mesoncand->Pt(),NegPiontmp.Angle(PosPiontmp.Vect()), fWeightJetJetMC);
fHistoAnglePiPlNDM[fiCut]->Fill(mesoncand->Pt(),PosPiontmp.Angle(neutralDecayMeson->Vect()), fWeightJetJetMC);
fHistoAngleHNMesonPiPlPiMi[fiCut]->Fill(mesoncand->Pt(),vParticle->Angle(mesoncand->Vect()), fWeightJetJetMC);
fHistoAngleSum[fiCut]->Fill(mesoncand->Pt(),((PosPiontmp.Angle(mesoncand->Vect()))+(NegPiontmp.Angle(PosPiontmp.Vect()))+(PosPiontmp.Angle(neutralDecayMeson->Vect()))), fWeightJetJetMC);
}
// Subtract mass of used pi0 candidate and then add PDG mass to get to right range again
fHistoMotherInvMassSubNDM[fiCut]->Fill(mesoncand->M()-(neutralDecayMeson->M()-fPDGMassNDM),mesoncand->Pt(), fWeightJetJetMC);
AliAODConversionMother mesontmp(&NDMtmp,vParticle);
fHistoMotherInvMassFixedPzNDM[fiCut]->Fill(mesontmp.M(),mesontmp.Pt(), fWeightJetJetMC);
fHistoMotherInvMassPt[fiCut]->Fill(mesoncand->M(),mesoncand->Pt(), fWeightJetJetMC);
if(fDoMesonQA>0){
//Dalitz All Pt
if (enableDalitzAllPt){
fHistoDalitzPlotPosFixedPzNDM[fiCut]->Fill(PosNegPionTLVtmp.M(), PosPionNDMTLVtmp.M() );
fHistoDalitzPlotNegFixedPzNDM[fiCut]->Fill(PosNegPionTLVtmp.M(), NegPionNDMTLVtmp.M() );
fHistoDalitzPlotPosSubNDM[fiCut]->Fill( PosNegPionTLVtmp.M(), PosPionNDMSubTLVtmp.M() - (NDMSubTLVtmp.M() - fPDGMassNDM));
fHistoDalitzPlotNegSubNDM[fiCut]->Fill( PosNegPionTLVtmp.M(), NegPionNDMSubTLVtmp.M() - (NDMSubTLVtmp.M() - fPDGMassNDM));
}
//Dalitz Low Pt
if (enableDalitzLowPt){
if ((mesoncand->Pt()>HistoDalitzPtRangeMin_LowPt)&&(mesoncand->Pt()<HistoDalitzPtRangeMax_LowPt)){
fHistoDalitzPlotPosFixedPzNDM_LowPt[fiCut]->Fill(PosNegPionTLVtmp.M(), PosPionNDMTLVtmp.M() );
fHistoDalitzPlotNegFixedPzNDM_LowPt[fiCut]->Fill(PosNegPionTLVtmp.M(), NegPionNDMTLVtmp.M() );
fHistoDalitzPlotPosSubNDM_LowPt[fiCut]->Fill( PosNegPionTLVtmp.M(), PosPionNDMSubTLVtmp.M() - (NDMSubTLVtmp.M() - fPDGMassNDM));
fHistoDalitzPlotNegSubNDM_LowPt[fiCut]->Fill( PosNegPionTLVtmp.M(), NegPionNDMSubTLVtmp.M() - (NDMSubTLVtmp.M() - fPDGMassNDM));
}
}
//Dalitz Mid Pt
if (enableDalitzMidPt){
if ((mesoncand->Pt()>HistoDalitzPtRangeMin_MidPt)&&(mesoncand->Pt()<HistoDalitzPtRangeMax_MidPt)){
fHistoDalitzPlotPosFixedPzNDM_MidPt[fiCut]->Fill(PosNegPionTLVtmp.M(), PosPionNDMTLVtmp.M() );
fHistoDalitzPlotNegFixedPzNDM_MidPt[fiCut]->Fill(PosNegPionTLVtmp.M(), NegPionNDMTLVtmp.M() );
fHistoDalitzPlotPosSubNDM_MidPt[fiCut]->Fill( PosNegPionTLVtmp.M(), PosPionNDMSubTLVtmp.M() - (NDMSubTLVtmp.M() - fPDGMassNDM));
fHistoDalitzPlotNegSubNDM_MidPt[fiCut]->Fill( PosNegPionTLVtmp.M(), NegPionNDMSubTLVtmp.M() - (NDMSubTLVtmp.M() - fPDGMassNDM));
}
}
//Dalitz High Pt
if (enableDalitzHighPt){
if ((mesoncand->Pt()>HistoDalitzPtRangeMin_HighPt)&&(mesoncand->Pt()<HistoDalitzPtRangeMax_HighPt)){
fHistoDalitzPlotPosFixedPzNDM_HighPt[fiCut]->Fill(PosNegPionTLVtmp.M(), PosPionNDMTLVtmp.M() );
fHistoDalitzPlotNegFixedPzNDM_HighPt[fiCut]->Fill(PosNegPionTLVtmp.M(), NegPionNDMTLVtmp.M() );
fHistoDalitzPlotPosSubNDM_HighPt[fiCut]->Fill( PosNegPionTLVtmp.M(), PosPionNDMSubTLVtmp.M() - (NDMSubTLVtmp.M() - fPDGMassNDM));
fHistoDalitzPlotNegSubNDM_HighPt[fiCut]->Fill( PosNegPionTLVtmp.M(), NegPionNDMSubTLVtmp.M() - (NDMSubTLVtmp.M() - fPDGMassNDM));
}
}
} //end fDoMesonQA>0
if(fMCEvent){
if(fInputEvent->IsA()==AliESDEvent::Class())
ProcessTrueMesonCandidates(mesoncand,neutralDecayMeson,vParticle);
if(fInputEvent->IsA()==AliAODEvent::Class())
ProcessTrueMesonCandidatesAOD(mesoncand,neutralDecayMeson,vParticle);
}
}else{ //else KinematicCut
if(!fDoLightOutput){
fHistoMotherInvMassPtRejectedKinematic[fiCut]->Fill(mesoncand->M(),mesoncand->Pt(), fWeightJetJetMC);
}
} //end KinematicCut
}
} //end MesonIsSelected
delete mesoncand;
mesoncand=0x0;
}
}
}
//________________________________________________________________________
void AliAnalysisTaskNeutralMesonToPiPlPiMiNeutralMeson::CalculateBackground(Int_t mode = 4){
/*
* Mode 1 => pi+ and pi- from same event
* Mode 2 => pi+ and pi0 from same event
* Mode 3 => pi- and pi0 from same event
* Mode 4 => no pions from same event (default)
* Mode 5 => Ligesign mixing
*/
// Get multiplicity and zbin from fBGHandler
Int_t zbin = fBGHandlerPiMi[fiCut]->GetZBinIndex(fInputEvent->GetPrimaryVertex()->GetZ());
Int_t mbin = 0;
// Multiplicity can be determined either by number of cluster candidates or track mulitiplicity
if (((AliConversionMesonCuts *)fMesonCutArray->At(fiCut))->UseTrackMultiplicity()) {
mbin = fBGHandlerPiMi[fiCut]->GetMultiplicityBinIndex(fNumberOfESDTracks);
} else {
if (fNDMRecoMode < 2)
mbin = fBGHandlerPiMi[fiCut]->GetMultiplicityBinIndex(fGoodConvGammas->GetEntries());
else
mbin = fBGHandlerPiMi[fiCut]->GetMultiplicityBinIndex(fClusterCandidates->GetEntries());
}
AliGammaConversionAODBGHandler::GammaConversionVertex *bgEventVertexPl = nullptr;
AliGammaConversionAODBGHandler::GammaConversionVertex *bgEventVertexMi = nullptr;
// Get N of Pi0 according to chosen mix mode
Int_t NNDMCandidates = 0;
if ((((AliConversionMesonCuts *)fMesonCutArray->At(fiCut))->UseSidebandMixing()) || (((AliConversionMesonCuts *)fMesonCutArray->At(fiCut))->UseSidebandMixingBothSides())) {
NNDMCandidates = fNeutralDecayParticleSidebandCandidates->GetEntries();
} else {
NNDMCandidates = fNeutralDecayParticleCandidates->GetEntries();
}
//
// ─── LOOP OVER ALL NDM FROM CURRENT EVENT ───────────────────────────────────────
//
for (Int_t iCurrentNDM = 0; iCurrentNDM < NNDMCandidates; iCurrentNDM++) {
AliAODConversionMother *EventNDMGoodMeson;
if ((((AliConversionMesonCuts *)fMesonCutArray->At(fiCut))->UseSidebandMixing()) || (((AliConversionMesonCuts *)fMesonCutArray->At(fiCut))->UseSidebandMixingBothSides())) {
EventNDMGoodMeson = (AliAODConversionMother *)(fNeutralDecayParticleSidebandCandidates->At(iCurrentNDM));
} else {
EventNDMGoodMeson = (AliAODConversionMother *)(fNeutralDecayParticleCandidates->At(iCurrentNDM));
}
//
// ─── Pi+ PI- from same event───
//
if(mode==1){
// Begin loop over BG events for Pi+
for (Int_t nEventsInBGPl = 0; nEventsInBGPl < fBGHandlerPiPl[fiCut]->GetNBGEvents(); nEventsInBGPl++) {
// Store all Pi+ of current event in right binning in vector
AliGammaConversionMotherAODVector *EventPiPlMeson = fBGHandlerPiPl[fiCut]->GetBGGoodMesons(zbin, mbin, nEventsInBGPl);
if(!EventPiPlMeson) continue;
// Begin loop over BG events for Pi-
for (Int_t nEventsInBGMi = 0; nEventsInBGMi < fBGHandlerPiMi[fiCut]->GetNBGEvents(); nEventsInBGMi++) {
AliGammaConversionMotherAODVector *EventPiMiMeson = fBGHandlerPiMi[fiCut]->GetBGGoodMesons(zbin, mbin, nEventsInBGMi);
// If one of the events isn't found skip to next one
if(!EventPiMiMeson) continue;
// If events are unequal, skip:
if (nEventsInBGMi != nEventsInBGPl) continue;
// Determine Background event vertex
if (fMoveParticleAccordingToVertex == kTRUE) {
bgEventVertexPl = fBGHandlerPiPl[fiCut]->GetBGEventVertex(zbin, mbin, nEventsInBGPl);
bgEventVertexMi = fBGHandlerPiMi[fiCut]->GetBGEventVertex(zbin, mbin, nEventsInBGMi);
}
// Loop over all Pi+
for (UInt_t iCurrentPiPl = 0; iCurrentPiPl < EventPiPlMeson->size(); iCurrentPiPl++) {
AliAODConversionMother EventPiPlGoodMeson = (AliAODConversionMother)(*(EventPiPlMeson->at(iCurrentPiPl)));
// Move Vertex
if (fMoveParticleAccordingToVertex == kTRUE) {
MoveParticleAccordingToVertex(&EventPiPlGoodMeson, bgEventVertexPl);
}
for (UInt_t iCurrentPiMi = 0; iCurrentPiMi < EventPiMiMeson->size(); iCurrentPiMi++) {
AliAODConversionMother EventPiMiGoodMeson = (AliAODConversionMother)(*(EventPiMiMeson->at(iCurrentPiMi)));
// Move Vertex
if (fMoveParticleAccordingToVertex == kTRUE) {
MoveParticleAccordingToVertex(&EventPiMiGoodMeson, bgEventVertexMi);
}
// create momentum vector for all three particles
TLorentzVector vec4PiPlus, vec4PiMinus, vec4NDM;
vec4PiPlus.SetPxPyPzE(EventPiPlGoodMeson.Px(),EventPiPlGoodMeson.Py(),EventPiPlGoodMeson.Pz(),EventPiPlGoodMeson.Energy());
vec4PiMinus.SetPxPyPzE(EventPiMiGoodMeson.Px(),EventPiMiGoodMeson.Py(),EventPiMiGoodMeson.Pz(),EventPiMiGoodMeson.Energy());
vec4NDM.SetPxPyPzE(EventNDMGoodMeson->Px(),EventNDMGoodMeson->Py(),EventNDMGoodMeson->Pz(),EventNDMGoodMeson->Energy());
// Mass cut (pi+pi-)
if (((AliPrimaryPionCuts *)fPionCutArray->At(fiCut))->DoMassCut()) {
TLorentzVector vec4PiPlusPiMinus = vec4PiPlus + vec4PiMinus;
if (vec4PiPlusPiMinus.M() >= ((AliPrimaryPionCuts *)fPionCutArray->At(fiCut))->GetMassCut()) {
continue;
}
}
// Mass cut (pi0pi+-)
if (((AliPrimaryPionCuts *)fPionCutArray->At(fiCut))->DoMassCut_WithNDM()) {
TLorentzVector vec4PiPlusPiZero = vec4PiPlus + vec4NDM;
TLorentzVector vec4PiMinusPiZero = vec4PiMinus + vec4NDM;
Double_t Mass_PiPlus_PiZero_Sub = vec4PiPlusPiZero.M() - (vec4NDM.M() - fPDGMassNDM);
Double_t Mass_PiMinus_PiZero_Sub = vec4PiMinusPiZero.M() - (vec4NDM.M() - fPDGMassNDM);
if ((Mass_PiPlus_PiZero_Sub >= ((AliPrimaryPionCuts *)fPionCutArray->At(fiCut))->GetMassCut_WithNDM())||
(Mass_PiMinus_PiZero_Sub >= ((AliPrimaryPionCuts *)fPionCutArray->At(fiCut))->GetMassCut_WithNDM())
) {
continue;
}
}
// Create Pi+Pi- pair (only at this stage after cuts were applied to save time, before only vectors)
AliAODConversionMother backPiPlPiMiCandidate(&EventPiPlGoodMeson, &EventPiMiGoodMeson);
AliAODConversionMother PiPlPiMiNDMBackgroundCandidate(&backPiPlPiMiCandidate, EventNDMGoodMeson);
// Check if candidate survives meson cut
if (((AliConversionMesonCuts *)fMesonCutArray->At(fiCut))->MesonIsSelected(&PiPlPiMiNDMBackgroundCandidate, kFALSE, ((AliConvEventCuts *)fEventCutArray->At(fiCut))->GetEtaShift())) {
// Check if candidate survives kinematic cut
if (KinematicCut(&EventPiMiGoodMeson, &EventPiPlGoodMeson, EventNDMGoodMeson, &PiPlPiMiNDMBackgroundCandidate)) {
// Create temporary mesons to be able to fix pz
AliAODConversionMother NDMtmp;
NDMtmp.SetPxPyPzE(EventNDMGoodMeson->Px(), EventNDMGoodMeson->Py(), EventNDMGoodMeson->Pz(), EventNDMGoodMeson->Energy());
FixPzToMatchPDGInvMassNDM(&NDMtmp);
AliAODConversionMother PiMiNDMtmp(&EventPiMiGoodMeson, &NDMtmp);
AliAODConversionMother PiPlPiMiNDMtmp(&EventPiPlGoodMeson, &PiMiNDMtmp); // Must be two separate lines since second instance depends on first and execution order is not guaranteed
// Pi+ and Pi- don't come from the same event (but different than pi0 event)
// Fill histograms
fHistoBackInvMassPt[fiCut]->Fill(PiPlPiMiNDMBackgroundCandidate.M(), PiPlPiMiNDMBackgroundCandidate.Pt(), fWeightJetJetMC);
fHistoBackInvMassPtSubNDM[fiCut]->Fill(PiPlPiMiNDMBackgroundCandidate.M() - (EventNDMGoodMeson->M() - fPDGMassNDM), PiPlPiMiNDMBackgroundCandidate.Pt(), fWeightJetJetMC);
fHistoBackInvMassPtFixedPzNDM[fiCut]->Fill(PiPlPiMiNDMtmp.M(), PiPlPiMiNDMtmp.Pt(), fWeightJetJetMC);
}
}
} // end pi- loop
} // end pi+ loop
} // end loop over all pi- event
} // end loop over pi+ events
//
// ─── NO PIONS FROM SAME EVENT ───
//
} else if(mode==4){
// Begin loop over BG events for Pi+
for (Int_t nEventsInBGPl = 0; nEventsInBGPl < fBGHandlerPiPl[fiCut]->GetNBGEvents(); nEventsInBGPl++) {
// Store all Pi+ of current event in right binning in vector
AliGammaConversionMotherAODVector *EventPiPlMeson = fBGHandlerPiPl[fiCut]->GetBGGoodMesons(zbin, mbin, nEventsInBGPl);
if(!EventPiPlMeson) continue;
// Begin loop over BG events for Pi-
for (Int_t nEventsInBGMi = 0; nEventsInBGMi < fBGHandlerPiMi[fiCut]->GetNBGEvents(); nEventsInBGMi++) {
AliGammaConversionMotherAODVector *EventPiMiMeson = fBGHandlerPiMi[fiCut]->GetBGGoodMesons(zbin, mbin, nEventsInBGMi);
// If one of the events isn't found skip to next one
if(!EventPiMiMeson) continue;
// If events are equal, skip:
if (nEventsInBGMi == nEventsInBGPl) continue;
// Determine Background event vertex
if (fMoveParticleAccordingToVertex == kTRUE) {
bgEventVertexPl = fBGHandlerPiPl[fiCut]->GetBGEventVertex(zbin, mbin, nEventsInBGPl);
bgEventVertexMi = fBGHandlerPiMi[fiCut]->GetBGEventVertex(zbin, mbin, nEventsInBGMi);
}
// Loop over all Pi+
for (UInt_t iCurrentPiPl = 0; iCurrentPiPl < EventPiPlMeson->size(); iCurrentPiPl++) {
AliAODConversionMother EventPiPlGoodMeson = (AliAODConversionMother)(*(EventPiPlMeson->at(iCurrentPiPl)));
// Move Vertex
if (fMoveParticleAccordingToVertex == kTRUE) {
MoveParticleAccordingToVertex(&EventPiPlGoodMeson, bgEventVertexPl);
}
for (UInt_t iCurrentPiMi = 0; iCurrentPiMi < EventPiMiMeson->size(); iCurrentPiMi++) {
AliAODConversionMother EventPiMiGoodMeson = (AliAODConversionMother)(*(EventPiMiMeson->at(iCurrentPiMi)));
// Move Vertex
if (fMoveParticleAccordingToVertex == kTRUE) {
MoveParticleAccordingToVertex(&EventPiMiGoodMeson, bgEventVertexMi);
}
// create momentum vector for all three particles
TLorentzVector vec4PiPlus, vec4PiMinus, vec4NDM;
vec4PiPlus.SetPxPyPzE(EventPiPlGoodMeson.Px(),EventPiPlGoodMeson.Py(),EventPiPlGoodMeson.Pz(),EventPiPlGoodMeson.Energy());
vec4PiMinus.SetPxPyPzE(EventPiMiGoodMeson.Px(),EventPiMiGoodMeson.Py(),EventPiMiGoodMeson.Pz(),EventPiMiGoodMeson.Energy());
vec4NDM.SetPxPyPzE(EventNDMGoodMeson->Px(),EventNDMGoodMeson->Py(),EventNDMGoodMeson->Pz(),EventNDMGoodMeson->Energy());
// Mass cut (pi+pi-)
if (((AliPrimaryPionCuts *)fPionCutArray->At(fiCut))->DoMassCut()) {
TLorentzVector vec4PiPlusPiMinus = vec4PiPlus + vec4PiMinus;
if (vec4PiPlusPiMinus.M() >= ((AliPrimaryPionCuts *)fPionCutArray->At(fiCut))->GetMassCut()) {
continue;
}
}
// Mass cut (pi0pi+-)
if (((AliPrimaryPionCuts *)fPionCutArray->At(fiCut))->DoMassCut_WithNDM()) {
TLorentzVector vec4PiPlusPiZero = vec4PiPlus + vec4NDM;
TLorentzVector vec4PiMinusPiZero = vec4PiMinus + vec4NDM;
Double_t Mass_PiPlus_PiZero_Sub = vec4PiPlusPiZero.M() - (vec4NDM.M() - fPDGMassNDM);
Double_t Mass_PiMinus_PiZero_Sub = vec4PiMinusPiZero.M() - (vec4NDM.M() - fPDGMassNDM);
if ((Mass_PiPlus_PiZero_Sub >= ((AliPrimaryPionCuts *)fPionCutArray->At(fiCut))->GetMassCut_WithNDM())||
(Mass_PiMinus_PiZero_Sub >= ((AliPrimaryPionCuts *)fPionCutArray->At(fiCut))->GetMassCut_WithNDM())
) {
continue;
}
}
// Create Pi+Pi- pair (only at this stage after cuts were applied to save time, before only vectors)
AliAODConversionMother backPiPlPiMiCandidate(&EventPiPlGoodMeson, &EventPiMiGoodMeson);
AliAODConversionMother PiPlPiMiNDMBackgroundCandidate(&backPiPlPiMiCandidate, EventNDMGoodMeson);
// Check if candidate survives meson cut
if (((AliConversionMesonCuts *)fMesonCutArray->At(fiCut))->MesonIsSelected(&PiPlPiMiNDMBackgroundCandidate, kFALSE, ((AliConvEventCuts *)fEventCutArray->At(fiCut))->GetEtaShift())) {
// Check if candidate survives kinematic cut
if (KinematicCut(&EventPiMiGoodMeson, &EventPiPlGoodMeson, EventNDMGoodMeson, &PiPlPiMiNDMBackgroundCandidate)) {
// Create temporary mesons to be able to fix pz
AliAODConversionMother NDMtmp;
NDMtmp.SetPxPyPzE(EventNDMGoodMeson->Px(), EventNDMGoodMeson->Py(), EventNDMGoodMeson->Pz(), EventNDMGoodMeson->Energy());
FixPzToMatchPDGInvMassNDM(&NDMtmp);
AliAODConversionMother PiMiNDMtmp(&EventPiMiGoodMeson, &NDMtmp);
AliAODConversionMother PiPlPiMiNDMtmp(&EventPiPlGoodMeson, &PiMiNDMtmp); // Must be two separate lines since second instance depends on first and execution order is not guaranteed
// Pi+ and Pi- don't come from the same event (but different than pi0 event)
// Fill histograms
fHistoBackInvMassPt[fiCut]->Fill(PiPlPiMiNDMBackgroundCandidate.M(), PiPlPiMiNDMBackgroundCandidate.Pt(), fWeightJetJetMC);
fHistoBackInvMassPtSubNDM[fiCut]->Fill(PiPlPiMiNDMBackgroundCandidate.M() - (EventNDMGoodMeson->M() - fPDGMassNDM), PiPlPiMiNDMBackgroundCandidate.Pt(), fWeightJetJetMC);
fHistoBackInvMassPtFixedPzNDM[fiCut]->Fill(PiPlPiMiNDMtmp.M(), PiPlPiMiNDMtmp.Pt(), fWeightJetJetMC);
}
}
} // end pi- loop
} // end pi+ loop
} // end loop over all pi- event
} // end loop over pi+ events
//
// ─── PIPL AND PIZERO FROM SAME EVENT ─────────────────────────────
//
} else if(mode==2){
// Loop over PiPl from current event
for (Int_t iCurrentPiPl = 0; iCurrentPiPl < fPosPionCandidates->GetEntries(); iCurrentPiPl++) {
AliAODConversionMother EventPiPlGoodMeson = *(AliAODConversionMother *)(fPosPionCandidates->At(iCurrentPiPl));
// Begin loop over BG events for Pi-
for (Int_t nEventsInBGMi = 0; nEventsInBGMi < fBGHandlerPiMi[fiCut]->GetNBGEvents(); nEventsInBGMi++) {
AliGammaConversionMotherAODVector *EventPiMiMeson = fBGHandlerPiMi[fiCut]->GetBGGoodMesons(zbin, mbin, nEventsInBGMi);
// If one of the events isn't found skip to next one
if(!EventPiMiMeson) continue;
// Determine Background event vertex
if (fMoveParticleAccordingToVertex == kTRUE) {
bgEventVertexMi = fBGHandlerPiMi[fiCut]->GetBGEventVertex(zbin, mbin, nEventsInBGMi);
}
for (UInt_t iCurrentPiMi = 0; iCurrentPiMi < EventPiMiMeson->size(); iCurrentPiMi++) {
AliAODConversionMother EventPiMiGoodMeson = (AliAODConversionMother)(*(EventPiMiMeson->at(iCurrentPiMi)));
// Move Vertex
if (fMoveParticleAccordingToVertex == kTRUE) {
MoveParticleAccordingToVertex(&EventPiMiGoodMeson, bgEventVertexMi);
}
// create momentum vector for all three particles
TLorentzVector vec4PiPlus, vec4PiMinus, vec4NDM;
vec4PiPlus.SetPxPyPzE(EventPiPlGoodMeson.Px(),EventPiPlGoodMeson.Py(),EventPiPlGoodMeson.Pz(),EventPiPlGoodMeson.Energy());
vec4PiMinus.SetPxPyPzE(EventPiMiGoodMeson.Px(),EventPiMiGoodMeson.Py(),EventPiMiGoodMeson.Pz(),EventPiMiGoodMeson.Energy());
vec4NDM.SetPxPyPzE(EventNDMGoodMeson->Px(),EventNDMGoodMeson->Py(),EventNDMGoodMeson->Pz(),EventNDMGoodMeson->Energy());
// Mass cut (pi+pi-)
if (((AliPrimaryPionCuts *)fPionCutArray->At(fiCut))->DoMassCut()) {
TLorentzVector vec4PiPlusPiMinus = vec4PiPlus + vec4PiMinus;
if (vec4PiPlusPiMinus.M() >= ((AliPrimaryPionCuts *)fPionCutArray->At(fiCut))->GetMassCut()) {
continue;
}
}
// Mass cut (pi0pi+-)
if (((AliPrimaryPionCuts *)fPionCutArray->At(fiCut))->DoMassCut_WithNDM()) {
TLorentzVector vec4PiPlusPiZero = vec4PiPlus + vec4NDM;
TLorentzVector vec4PiMinusPiZero = vec4PiMinus + vec4NDM;
Double_t Mass_PiPlus_PiZero_Sub = vec4PiPlusPiZero.M() - (vec4NDM.M() - fPDGMassNDM);
Double_t Mass_PiMinus_PiZero_Sub = vec4PiMinusPiZero.M() - (vec4NDM.M() - fPDGMassNDM);
if ((Mass_PiPlus_PiZero_Sub >= ((AliPrimaryPionCuts *)fPionCutArray->At(fiCut))->GetMassCut_WithNDM())||
(Mass_PiMinus_PiZero_Sub >= ((AliPrimaryPionCuts *)fPionCutArray->At(fiCut))->GetMassCut_WithNDM())
) {
continue;
}
}
// Create Pi+Pi- pair (only at this stage after cuts were applied to save time, before only vectors)
AliAODConversionMother backPiPlPiMiCandidate(&EventPiPlGoodMeson, &EventPiMiGoodMeson);
AliAODConversionMother PiPlPiMiNDMBackgroundCandidate(&backPiPlPiMiCandidate, EventNDMGoodMeson);
// Check if candidate survives meson cut
if (((AliConversionMesonCuts *)fMesonCutArray->At(fiCut))->MesonIsSelected(&PiPlPiMiNDMBackgroundCandidate, kFALSE, ((AliConvEventCuts *)fEventCutArray->At(fiCut))->GetEtaShift())) {
// Check if candidate survives kinematic cut
if (KinematicCut(&EventPiMiGoodMeson, &EventPiPlGoodMeson, EventNDMGoodMeson, &PiPlPiMiNDMBackgroundCandidate)) {
// Create temporary mesons to be able to fix pz
AliAODConversionMother NDMtmp;
NDMtmp.SetPxPyPzE(EventNDMGoodMeson->Px(), EventNDMGoodMeson->Py(), EventNDMGoodMeson->Pz(), EventNDMGoodMeson->Energy());
FixPzToMatchPDGInvMassNDM(&NDMtmp);
AliAODConversionMother PiMiNDMtmp(&EventPiMiGoodMeson, &NDMtmp);
AliAODConversionMother PiPlPiMiNDMtmp(&EventPiPlGoodMeson, &PiMiNDMtmp); // Must be two separate lines since second instance depends on first and execution order is not guaranteed
// Pi+ and Pi- don't come from the same event (but different than pi0 event)
// Fill histograms
fHistoBackInvMassPt[fiCut]->Fill(PiPlPiMiNDMBackgroundCandidate.M(), PiPlPiMiNDMBackgroundCandidate.Pt(), fWeightJetJetMC);
fHistoBackInvMassPtSubNDM[fiCut]->Fill(PiPlPiMiNDMBackgroundCandidate.M() - (EventNDMGoodMeson->M() - fPDGMassNDM), PiPlPiMiNDMBackgroundCandidate.Pt(), fWeightJetJetMC);
fHistoBackInvMassPtFixedPzNDM[fiCut]->Fill(PiPlPiMiNDMtmp.M(), PiPlPiMiNDMtmp.Pt(), fWeightJetJetMC);
}
}
} // end pi- loop
} // end loop over all pi- event
}
} else if(mode==3){
// Loop over PiMi from current event
for (Int_t iCurrentPiMi = 0; iCurrentPiMi < fNegPionCandidates->GetEntries(); iCurrentPiMi++) {
AliAODConversionMother EventPiMiGoodMeson = *(AliAODConversionMother *)(fNegPionCandidates->At(iCurrentPiMi));
// Begin loop over BG events for Pi+
for (Int_t nEventsInBGPl = 0; nEventsInBGPl < fBGHandlerPiPl[fiCut]->GetNBGEvents(); nEventsInBGPl++) {
AliGammaConversionMotherAODVector *EventPiPlMeson = fBGHandlerPiPl[fiCut]->GetBGGoodMesons(zbin, mbin, nEventsInBGPl);
// If one of the events isn't found skip to next one
if(!EventPiPlMeson) continue;
// Determine Background event vertex
if (fMoveParticleAccordingToVertex == kTRUE) {
bgEventVertexPl = fBGHandlerPiPl[fiCut]->GetBGEventVertex(zbin, mbin, nEventsInBGPl);
}
for (UInt_t iCurrentPiPl = 0; iCurrentPiPl < EventPiPlMeson->size(); iCurrentPiPl++) {
AliAODConversionMother EventPiPlGoodMeson = (AliAODConversionMother)(*(EventPiPlMeson->at(iCurrentPiPl)));
// Move Vertex
if (fMoveParticleAccordingToVertex == kTRUE) {
MoveParticleAccordingToVertex(&EventPiPlGoodMeson, bgEventVertexPl);
}
// create momentum vector for all three particles
TLorentzVector vec4PiPlus, vec4PiMinus, vec4NDM;
vec4PiPlus.SetPxPyPzE(EventPiPlGoodMeson.Px(),EventPiPlGoodMeson.Py(),EventPiPlGoodMeson.Pz(),EventPiPlGoodMeson.Energy());
vec4PiMinus.SetPxPyPzE(EventPiMiGoodMeson.Px(),EventPiMiGoodMeson.Py(),EventPiMiGoodMeson.Pz(),EventPiMiGoodMeson.Energy());
vec4NDM.SetPxPyPzE(EventNDMGoodMeson->Px(),EventNDMGoodMeson->Py(),EventNDMGoodMeson->Pz(),EventNDMGoodMeson->Energy());
// Mass cut (pi+pi-)
if (((AliPrimaryPionCuts *)fPionCutArray->At(fiCut))->DoMassCut()) {
TLorentzVector vec4PiPlusPiMinus = vec4PiPlus + vec4PiMinus;
if (vec4PiPlusPiMinus.M() >= ((AliPrimaryPionCuts *)fPionCutArray->At(fiCut))->GetMassCut()) {
continue;
}
}
// Mass cut (pi0pi+-)
if (((AliPrimaryPionCuts *)fPionCutArray->At(fiCut))->DoMassCut_WithNDM()) {
TLorentzVector vec4PiPlusPiZero = vec4PiPlus + vec4NDM;
TLorentzVector vec4PiMinusPiZero = vec4PiMinus + vec4NDM;
Double_t Mass_PiPlus_PiZero_Sub = vec4PiPlusPiZero.M() - (vec4NDM.M() - fPDGMassNDM);
Double_t Mass_PiMinus_PiZero_Sub = vec4PiMinusPiZero.M() - (vec4NDM.M() - fPDGMassNDM);
if ((Mass_PiPlus_PiZero_Sub >= ((AliPrimaryPionCuts *)fPionCutArray->At(fiCut))->GetMassCut_WithNDM())||
(Mass_PiMinus_PiZero_Sub >= ((AliPrimaryPionCuts *)fPionCutArray->At(fiCut))->GetMassCut_WithNDM())
) {
continue;
}
}
// Create Pi+Pi- pair (only at this stage after cuts were applied to save time, before only vectors)
AliAODConversionMother backPiPlPiMiCandidate(&EventPiPlGoodMeson, &EventPiMiGoodMeson);
AliAODConversionMother PiPlPiMiNDMBackgroundCandidate(&backPiPlPiMiCandidate, EventNDMGoodMeson);
// Check if candidate survives meson cut
if (((AliConversionMesonCuts *)fMesonCutArray->At(fiCut))->MesonIsSelected(&PiPlPiMiNDMBackgroundCandidate, kFALSE, ((AliConvEventCuts *)fEventCutArray->At(fiCut))->GetEtaShift())) {
// Check if candidate survives kinematic cut
if (KinematicCut(&EventPiMiGoodMeson, &EventPiPlGoodMeson, EventNDMGoodMeson, &PiPlPiMiNDMBackgroundCandidate)) {
// Create temporary mesons to be able to fix pz
AliAODConversionMother NDMtmp;
NDMtmp.SetPxPyPzE(EventNDMGoodMeson->Px(), EventNDMGoodMeson->Py(), EventNDMGoodMeson->Pz(), EventNDMGoodMeson->Energy());
FixPzToMatchPDGInvMassNDM(&NDMtmp);
AliAODConversionMother PiMiNDMtmp(&EventPiMiGoodMeson, &NDMtmp);
AliAODConversionMother PiPlPiMiNDMtmp(&EventPiPlGoodMeson, &PiMiNDMtmp); // Must be two separate lines since second instance depends on first and execution order is not guaranteed
// Pi+ and Pi- don't come from the same event (but different than pi0 event)
// Fill histograms
fHistoBackInvMassPt[fiCut]->Fill(PiPlPiMiNDMBackgroundCandidate.M(), PiPlPiMiNDMBackgroundCandidate.Pt(), fWeightJetJetMC);
fHistoBackInvMassPtSubNDM[fiCut]->Fill(PiPlPiMiNDMBackgroundCandidate.M() - (EventNDMGoodMeson->M() - fPDGMassNDM), PiPlPiMiNDMBackgroundCandidate.Pt(), fWeightJetJetMC);
fHistoBackInvMassPtFixedPzNDM[fiCut]->Fill(PiPlPiMiNDMtmp.M(), PiPlPiMiNDMtmp.Pt(), fWeightJetJetMC);
}
}
} // end pi- loop
} // end loop over all pi- event
}
//
// ─── LIKESIGN MIXING ─────────────────────────────────────────────
//
} else if (mode == 5){
// Loops for Pi0Pi+Pi+ LikeSign mixing
for (Int_t iCurrentPiPl = 0; iCurrentPiPl < fPosPionCandidates->GetEntries(); iCurrentPiPl++) {
AliAODConversionMother EventPiPlGoodMeson = *(AliAODConversionMother *)(fPosPionCandidates->At(iCurrentPiPl));
for (Int_t iCurrentPiPl2 = iCurrentPiPl; iCurrentPiPl2 < fPosPionCandidates->GetEntries(); iCurrentPiPl2++) {
if (iCurrentPiPl == iCurrentPiPl2) continue;
AliAODConversionMother EventPiPlGoodMeson2 = *(AliAODConversionMother *)(fPosPionCandidates->At(iCurrentPiPl2));
// Mass cut on pi+pi+
if (((AliPrimaryPionCuts *)fPionCutArray->At(fiCut))->DoMassCut()) {
AliAODConversionMother backPiPlPiPlCandidate(&EventPiPlGoodMeson, &EventPiPlGoodMeson2);
if (backPiPlPiPlCandidate.M() >= ((AliPrimaryPionCuts *)fPionCutArray->At(fiCut))->GetMassCut()) {
continue;
}
}
// Combine Pi+ and Pi0
AliAODConversionMother PiPlNDMBackgroundCandidate(&EventPiPlGoodMeson, EventNDMGoodMeson);
// Mass cut (pi0pi+-)
if (((AliPrimaryPionCuts *)fPionCutArray->At(fiCut))->DoMassCut_WithNDM()) {
AliAODConversionMother PiPlNDMBackgroundCandidate2(&EventPiPlGoodMeson2, EventNDMGoodMeson);
Double_t Mass_PiPlus_PiZero_Sub = PiPlNDMBackgroundCandidate.M() - (EventNDMGoodMeson->M() - fPDGMassNDM);
Double_t Mass_PiPlus2_PiZero_Sub = PiPlNDMBackgroundCandidate2.M() - (EventNDMGoodMeson->M() - fPDGMassNDM);
if ((Mass_PiPlus_PiZero_Sub >= ((AliPrimaryPionCuts *)fPionCutArray->At(fiCut))->GetMassCut_WithNDM())||
(Mass_PiPlus2_PiZero_Sub >= ((AliPrimaryPionCuts *)fPionCutArray->At(fiCut))->GetMassCut_WithNDM())
) {
continue;
}
}
// Create (final) Candidate
AliAODConversionMother PiPlPiPlNDMBackgroundCandidate(&PiPlNDMBackgroundCandidate, &EventPiPlGoodMeson2);
// Check if candidate survives meson cut
if (((AliConversionMesonCuts *)fMesonCutArray->At(fiCut))->MesonIsSelected(&PiPlNDMBackgroundCandidate, kFALSE, ((AliConvEventCuts *)fEventCutArray->At(fiCut))->GetEtaShift())) {
// Check if candidate survives kinematic cut
if (KinematicCut(&EventPiPlGoodMeson, &EventPiPlGoodMeson2, EventNDMGoodMeson, &PiPlPiPlNDMBackgroundCandidate)) {
// Create temporary mesons to be able to fix pz
AliAODConversionMother NDMtmp;
NDMtmp.SetPxPyPzE(EventNDMGoodMeson->Px(), EventNDMGoodMeson->Py(), EventNDMGoodMeson->Pz(), EventNDMGoodMeson->Energy());
FixPzToMatchPDGInvMassNDM(&NDMtmp);
AliAODConversionMother PiPlNDMtmp(&EventPiPlGoodMeson, &NDMtmp);
AliAODConversionMother PiPlPiPlNDMtmp(&EventPiPlGoodMeson2, &PiPlNDMtmp); // Must be two separate lines since second instance depends on first and execution order is not guaranteed
// Fill histograms (likesign)
fHistoMotherLikeSignBackInvMassPt[fiCut]->Fill(PiPlPiPlNDMBackgroundCandidate.M(), PiPlPiPlNDMBackgroundCandidate.Pt(), fWeightJetJetMC);
fHistoMotherLikeSignBackInvMassSubNDMPt[fiCut]->Fill(PiPlPiPlNDMBackgroundCandidate.M() - (EventNDMGoodMeson->M() - fPDGMassNDM), PiPlPiPlNDMBackgroundCandidate.Pt(), fWeightJetJetMC);
fHistoMotherLikeSignBackInvMassFixedPzNDMPt[fiCut]->Fill(PiPlPiPlNDMtmp.M(), PiPlPiPlNDMtmp.Pt(), fWeightJetJetMC);
}
}
} // end of iCurrentPiPl2
} // end of iCurrenPiPl
// Loops for Pi0Pi-Pi- LikeSign mixing
for (Int_t iCurrentPiMi = 0; iCurrentPiMi < fNegPionCandidates->GetEntries(); iCurrentPiMi++) {
AliAODConversionMother EventPiMiGoodMeson = *(AliAODConversionMother *)(fNegPionCandidates->At(iCurrentPiMi));
for (Int_t iCurrentPiMi2 = iCurrentPiMi; iCurrentPiMi2 < fNegPionCandidates->GetEntries(); iCurrentPiMi2++){
if (iCurrentPiMi == iCurrentPiMi2) continue;
AliAODConversionMother EventPiMiGoodMeson2 = *(AliAODConversionMother *)(fNegPionCandidates->At(iCurrentPiMi2));
// Mass cut on pi-pi-
if (((AliPrimaryPionCuts *)fPionCutArray->At(fiCut))->DoMassCut()) {
AliAODConversionMother backPiMiPiMiCandidate(&EventPiMiGoodMeson, &EventPiMiGoodMeson2);
if (backPiMiPiMiCandidate.M() >= ((AliPrimaryPionCuts *)fPionCutArray->At(fiCut))->GetMassCut()) {
continue;
}
}
// Combine Pi- and Pi0
AliAODConversionMother PiMiNDMBackgroundCandidate(&EventPiMiGoodMeson, EventNDMGoodMeson);
// Mass cut (pi0pi+-)
if (((AliPrimaryPionCuts *)fPionCutArray->At(fiCut))->DoMassCut_WithNDM()) {
AliAODConversionMother PiMiNDMBackgroundCandidate2(&EventPiMiGoodMeson2, EventNDMGoodMeson);
Double_t Mass_PiMinus_PiZero_Sub = PiMiNDMBackgroundCandidate.M() - (EventNDMGoodMeson->M() - fPDGMassNDM);
Double_t Mass_PiMinus2_PiZero_Sub = PiMiNDMBackgroundCandidate2.M() - (EventNDMGoodMeson->M() - fPDGMassNDM);
if ((Mass_PiMinus_PiZero_Sub >= ((AliPrimaryPionCuts *)fPionCutArray->At(fiCut))->GetMassCut_WithNDM())||
(Mass_PiMinus2_PiZero_Sub >= ((AliPrimaryPionCuts *)fPionCutArray->At(fiCut))->GetMassCut_WithNDM())
) {
continue;
}
}
// Create (final) Candidate
AliAODConversionMother PiMiPiMiNDMBackgroundCandidate(&PiMiNDMBackgroundCandidate, &EventPiMiGoodMeson2);
// Check if candidate survives meson cut
if (((AliConversionMesonCuts *)fMesonCutArray->At(fiCut))->MesonIsSelected(&PiMiPiMiNDMBackgroundCandidate, kFALSE, ((AliConvEventCuts *)fEventCutArray->At(fiCut))->GetEtaShift())) {
// Check if candidate survives kinematic cut
if (KinematicCut(&EventPiMiGoodMeson, &EventPiMiGoodMeson2, EventNDMGoodMeson, &PiMiPiMiNDMBackgroundCandidate)) {
// Create temporary mesons to be able to fix pz
AliAODConversionMother NDMtmp;
NDMtmp.SetPxPyPzE(EventNDMGoodMeson->Px(), EventNDMGoodMeson->Py(), EventNDMGoodMeson->Pz(), EventNDMGoodMeson->Energy());
FixPzToMatchPDGInvMassNDM(&NDMtmp);
AliAODConversionMother PiMiNDMtmp(&EventPiMiGoodMeson, &NDMtmp);
AliAODConversionMother PiMiPiMiNDMtmp(&EventPiMiGoodMeson2, &PiMiNDMtmp); // Must be two separate lines since second instance depends on first and execution order is not guaranteed
// Fill histograms (likesign)
fHistoMotherLikeSignBackInvMassPt[fiCut]->Fill(PiMiPiMiNDMBackgroundCandidate.M(), PiMiPiMiNDMBackgroundCandidate.Pt(), fWeightJetJetMC);
fHistoMotherLikeSignBackInvMassSubNDMPt[fiCut]->Fill(PiMiPiMiNDMBackgroundCandidate.M() - (EventNDMGoodMeson->M() - fPDGMassNDM), PiMiPiMiNDMBackgroundCandidate.Pt(), fWeightJetJetMC);
fHistoMotherLikeSignBackInvMassFixedPzNDMPt[fiCut]->Fill(PiMiPiMiNDMtmp.M(), PiMiPiMiNDMtmp.Pt(), fWeightJetJetMC);
}
}
} // end of iCurrentPiMi2
} // end of iCurrenPiMi
} else if (mode == 6){
// Loops for Pi0Pi+Pi- Sideband mixing
for (Int_t iCurrentPiPl = 0; iCurrentPiPl < fPosPionCandidates->GetEntries(); iCurrentPiPl++) {
AliAODConversionMother EventPiPlGoodMeson = *(AliAODConversionMother *)(fPosPionCandidates->At(iCurrentPiPl));
for (Int_t iCurrentPiMi = 0; iCurrentPiMi < fNegPionCandidates->GetEntries(); iCurrentPiMi++) {
AliAODConversionMother EventPiMiGoodMeson = *(AliAODConversionMother *)(fNegPionCandidates->At(iCurrentPiMi));
// Mass cut on pi+pi-
if (((AliPrimaryPionCuts *)fPionCutArray->At(fiCut))->DoMassCut()) {
AliAODConversionMother backPiPlPiMiCandidate(&EventPiPlGoodMeson, &EventPiMiGoodMeson);
if (backPiPlPiMiCandidate.M() >= ((AliPrimaryPionCuts *)fPionCutArray->At(fiCut))->GetMassCut()) {
continue;
}
}
// Combine Pi+ and Pi0
AliAODConversionMother PiPlNDMBackgroundCandidate(&EventPiPlGoodMeson, EventNDMGoodMeson);
// Mass cut (pi0pi+-)
if (((AliPrimaryPionCuts *)fPionCutArray->At(fiCut))->DoMassCut_WithNDM()) {
AliAODConversionMother PiPlNDMBackgroundCandidate2(&EventPiMiGoodMeson, EventNDMGoodMeson);
Double_t Mass_PiPlus_PiZero_Sub = PiPlNDMBackgroundCandidate.M() - (EventNDMGoodMeson->M() - fPDGMassNDM);
Double_t Mass_PiPlus2_PiZero_Sub = PiPlNDMBackgroundCandidate2.M() - (EventNDMGoodMeson->M() - fPDGMassNDM);
if ((Mass_PiPlus_PiZero_Sub >= ((AliPrimaryPionCuts *)fPionCutArray->At(fiCut))->GetMassCut_WithNDM())||
(Mass_PiPlus2_PiZero_Sub >= ((AliPrimaryPionCuts *)fPionCutArray->At(fiCut))->GetMassCut_WithNDM())
) {
continue;
}
}
// Create (final) Candidate
AliAODConversionMother PiPlPiMiNDMBackgroundCandidate(&PiPlNDMBackgroundCandidate, &EventPiMiGoodMeson);
// Check if candidate survives meson cut
if (((AliConversionMesonCuts *)fMesonCutArray->At(fiCut))->MesonIsSelected(&PiPlPiMiNDMBackgroundCandidate, kFALSE, ((AliConvEventCuts *)fEventCutArray->At(fiCut))->GetEtaShift())) {
// Check if candidate survives kinematic cut
if (KinematicCut(&EventPiPlGoodMeson, &EventPiMiGoodMeson, EventNDMGoodMeson, &PiPlPiMiNDMBackgroundCandidate)) {
// Create temporary mesons to be able to fix pz
AliAODConversionMother NDMtmp;
NDMtmp.SetPxPyPzE(EventNDMGoodMeson->Px(), EventNDMGoodMeson->Py(), EventNDMGoodMeson->Pz(), EventNDMGoodMeson->Energy());
FixPzToMatchPDGInvMassNDM(&NDMtmp);
AliAODConversionMother PiPlNDMtmp(&EventPiPlGoodMeson, &NDMtmp);
AliAODConversionMother PiPlPiMiNDMtmp(&EventPiMiGoodMeson, &PiPlNDMtmp); // Must be two separate lines since second instance depends on first and execution order is not guaranteed
// Fill histograms
fHistoBackInvMassPt[fiCut]->Fill(PiPlPiMiNDMBackgroundCandidate.M(), PiPlPiMiNDMBackgroundCandidate.Pt(), fWeightJetJetMC);
fHistoBackInvMassPtSubNDM[fiCut]->Fill(PiPlPiMiNDMBackgroundCandidate.M() - (EventNDMGoodMeson->M() - fPDGMassNDM), PiPlPiMiNDMBackgroundCandidate.Pt(), fWeightJetJetMC);
fHistoBackInvMassPtFixedPzNDM[fiCut]->Fill(PiPlPiMiNDMtmp.M(), PiPlPiMiNDMtmp.Pt(), fWeightJetJetMC);
}
}
} // end of iCurrentPiMi
} // end of iCurrenPiPl
} // end of mode if
} // end of NDM from current event loop
}
//______________________________________________________________________
Bool_t AliAnalysisTaskNeutralMesonToPiPlPiMiNeutralMeson::KinematicCut(AliAODConversionMother *negpion, AliAODConversionMother *pospion, AliAODConversionMother *neutpion, AliAODConversionMother *omega){
if(fTolerance == -1) return kTRUE;
if((omega->Pt())<=5.){
if( (omega->Angle(pospion->Vect())) < ((2.78715*(TMath::Exp(-0.589934*(omega->Pt()))+0.0519574))*fTolerance) &&
(omega->Angle(negpion->Vect())) < ((5.94216*(TMath::Exp(-0.444428*(omega->Pt()))-0.0574076))*fTolerance) &&
(omega->Angle(neutpion->Vect())) < ((2.79529*(TMath::Exp(-0.565999*(omega->Pt()))+0.0413576))*fTolerance) &&
(pospion->Angle(negpion->Vect())) < ((3.14446*(TMath::Exp(-0.666433*(omega->Pt()))+0.0964309))*fTolerance) &&
(pospion->Angle(neutpion->Vect())) < ((3.08241*(TMath::Exp(-0.650657*(omega->Pt()))+0.0997539))*fTolerance) &&
(negpion->Angle(neutpion->Vect())) < ((3.18536*(TMath::Exp(-0.752847*(omega->Pt()))+0.1262780))*fTolerance)
){
return kTRUE;
}
}else{
if( (omega->Angle(pospion->Vect())) < ((0.459270*(TMath::Exp(-0.126007*(omega->Pt()))+0.100475))*fTolerance) &&
(omega->Angle(negpion->Vect())) < ((0.521250*(TMath::Exp(-0.152532*(omega->Pt()))+0.114617))*fTolerance) &&
(omega->Angle(neutpion->Vect())) < ((0.409766*(TMath::Exp(-0.108566*(omega->Pt()))+0.103594))*fTolerance) &&
(pospion->Angle(negpion->Vect())) < ((0.709206*(TMath::Exp(-0.149072*(omega->Pt()))+0.111345))*fTolerance) &&
(pospion->Angle(neutpion->Vect())) < ((0.662184*(TMath::Exp(-0.123397*(omega->Pt()))+0.104675))*fTolerance) &&
(negpion->Angle(neutpion->Vect())) < ((0.730228*(TMath::Exp(-0.120859*(omega->Pt()))+0.105522))*fTolerance)
){
return kTRUE;
}
}
return kFALSE;
}
//______________________________________________________________________
void AliAnalysisTaskNeutralMesonToPiPlPiMiNeutralMeson::ProcessTrueMesonCandidates(AliAODConversionMother *mesoncand, AliAODConversionMother *TrueNeutralDecayMesonCandidate, AliAODConversionPhoton *TrueVirtualParticleCandidate)
{
// Process True Mesons
Bool_t isSameMotherPiPlPiMiNDM = kFALSE; // pi+ pi- and pi0 have the same mother
Bool_t isSameMotherPiPlPiMi = kFALSE; // pi+ and pi- have the same mother
Bool_t isSameMotherPiPlNDM = kFALSE; // pi+ and pi0 have the same mother
Bool_t isSameMotherPiMiNDM = kFALSE; // pi- and pi0 have the same mother
Bool_t isNoSameMother = kFALSE; // none of the pions have the same mother
Bool_t areAllPionsCorrectlyIdentified = kFALSE; // All Pion Identifications correct
Bool_t isPiPlWronglyIdentified = kFALSE; // Pi+ Identification not correct
Bool_t isPiMiWronglyIdentified = kFALSE; // Pi- Identification not correct
Bool_t isPiZeroWronglyIdentified = kFALSE; // Pi0 Identification not correct
Bool_t isMultipleWronglyIdentified = kFALSE; // more than one Pion Identification not correct
Bool_t isTrueMeson = kFALSE; //True analyzed meson
Bool_t isDifferentMesonContribution = kFALSE; //True meson, but NOT analyzed meson
Bool_t isCombinatoricsMeson = kFALSE; //Combinatorics candidate
Bool_t isContaminationMeson = kFALSE; //Contamination candidate
Bool_t NDMMC_PDGCheck = kFALSE;
Int_t virtualParticleMCLabel = -1;
virtualParticleMCLabel = TrueVirtualParticleCandidate->GetMCParticleLabel(fMCEvent);
Int_t virtualParticleMotherLabel = -1;
//Is set when:
//if(((TParticle*)fMCEvent->Particle(gamma1MotherLabel))->GetPdgCode() == fPDGCodeNDM) isTrueNDM=kTRUE;
//if(isTrueNDM){// True Pion
//Pi0Candidate->SetTrueMesonValue(1);
Int_t trueMesonFlag = TrueNeutralDecayMesonCandidate->GetTrueMesonValue();
Int_t NDMMCLabel = TrueNeutralDecayMesonCandidate->GetMCLabel();
Float_t weighted= fWeightJetJetMC;
if (fDoMesonQA>0){fHistoTrueMesonFlags[fiCut]->Fill(1);} //All candidates
if ( !(trueMesonFlag == 1 && NDMMCLabel != -1)){ //more understandable: (trueMesonFlag != 1 || NDMMCLabel == -1)
if((fDoMesonQA>0 ) && (!fDoLightOutput)){
fHistoTruePiPlPiMiNDMContamination_Crosscheck_InvMassPt[fiCut]->Fill(mesoncand->M(),mesoncand->Pt(),weighted);
}
isPiZeroWronglyIdentified = kTRUE;
isContaminationMeson = kTRUE;
}
Int_t NDMMotherLabel = 0;
TParticle * negativeMC = (TParticle*)TrueVirtualParticleCandidate->GetNegativeMCDaughter(fMCEvent);
TParticle * positiveMC = (TParticle*)TrueVirtualParticleCandidate->GetPositiveMCDaughter(fMCEvent);
if (NDMMCLabel == -1){
NDMMC_PDGCheck = kFALSE;
} else {
NDMMotherLabel = fMCEvent->Particle(NDMMCLabel)->GetMother(0);
NDMMC_PDGCheck=fMCEvent->Particle(NDMMCLabel)->GetPdgCode()==fPDGCodeNDM;
}
Int_t posMotherLabelMC = positiveMC->GetMother(0);
Int_t negMotherLabelMC = negativeMC->GetMother(0);
if ( (isPiZeroWronglyIdentified)&&(NDMMC_PDGCheck) ){
if (fDoMesonQA>0){fHistoTrueMesonFlags[fiCut]->Fill(10);} //Problem with pi0 flag
}
// Check case present
if((TMath::Abs(negativeMC->GetPdgCode())==211) && (TMath::Abs(positiveMC->GetPdgCode())==211) && (NDMMC_PDGCheck)){
// three pion decay
areAllPionsCorrectlyIdentified = kTRUE;
if(virtualParticleMCLabel!=-1){
// pi+ pi- have same mother
isSameMotherPiPlPiMi = kTRUE;
virtualParticleMotherLabel = virtualParticleMCLabel;
if(virtualParticleMotherLabel==NDMMotherLabel){
// all pions from same mother
isSameMotherPiPlPiMiNDM = kTRUE;
} else{
// only pi+ pi- from same mother
isCombinatoricsMeson = kTRUE;
}
} else{
//pi+ and pi- do not have same mother -> Combinatorics
isCombinatoricsMeson = kTRUE;
if(NDMMotherLabel==negMotherLabelMC && negMotherLabelMC != -1){
// pi0 and pi- same mother
isSameMotherPiMiNDM = kTRUE;
} else if(NDMMotherLabel==posMotherLabelMC && posMotherLabelMC != -1){
// pi0 and pi+ same mother
isSameMotherPiPlNDM = kTRUE;
} else{
// all pions different mother
isNoSameMother = kTRUE;
}
}
} else{
// not a three pion decay, Contamination
isContaminationMeson = kTRUE;
if (!(TMath::Abs(negativeMC->GetPdgCode())==211)){
isPiMiWronglyIdentified = kTRUE;
}
if (!(TMath::Abs(positiveMC->GetPdgCode())==211)){
isPiPlWronglyIdentified = kTRUE;
if (isPiMiWronglyIdentified){
isMultipleWronglyIdentified = kTRUE;
}
}
if (!(NDMMC_PDGCheck)){
isPiZeroWronglyIdentified = kTRUE;
if ((isPiMiWronglyIdentified)||(isPiPlWronglyIdentified)){
isMultipleWronglyIdentified = kTRUE;
}
}
}
if(areAllPionsCorrectlyIdentified&&isSameMotherPiPlPiMiNDM){
if(fMCEvent->Particle(NDMMotherLabel)->GetPdgCode() == fPDGCodeAnalyzedMeson){
isTrueMeson = kTRUE;
} else {
isDifferentMesonContribution = kTRUE;
}
}
Int_t iNumberOfDeclarationFlags=0;
if (isTrueMeson){iNumberOfDeclarationFlags++;}
if (isDifferentMesonContribution){iNumberOfDeclarationFlags++;}
if (isCombinatoricsMeson){iNumberOfDeclarationFlags++;}
if (isContaminationMeson){iNumberOfDeclarationFlags++;}
if (iNumberOfDeclarationFlags!=1){
if (fDoMesonQA>0){fHistoTrueMesonFlags[fiCut]->Fill(11);} //Problem with meson declaration flag
}
if(areAllPionsCorrectlyIdentified&&isSameMotherPiPlPiMiNDM){
if (fDoMesonQA>0){fHistoTrueMesonFlags[fiCut]->Fill(2);} //Same mother
if (isTrueMeson){
if (fDoMesonQA>0){fHistoTrueMesonFlags[fiCut]->Fill(3);} //True
}
} else if (areAllPionsCorrectlyIdentified){
if (fDoMesonQA>0){fHistoTrueMesonFlags[fiCut]->Fill(4);} //Not same mother
} else if (isContaminationMeson){
if (fDoMesonQA>0){fHistoTrueMesonFlags[fiCut]->Fill(5);} //Wrongly identified pions
if (!isMultipleWronglyIdentified){
if (isPiZeroWronglyIdentified){
if (fDoMesonQA>0){fHistoTrueMesonFlags[fiCut]->Fill(6);} //Wrongly identified pi0
} else if (isPiPlWronglyIdentified){
if (fDoMesonQA>0){fHistoTrueMesonFlags[fiCut]->Fill(7);} //Wrongly identified pi+
} else if (isPiMiWronglyIdentified){
if (fDoMesonQA>0){fHistoTrueMesonFlags[fiCut]->Fill(8);} //Wrongly identified pi-
}
} else {
if (fDoMesonQA>0){fHistoTrueMesonFlags[fiCut]->Fill(9);} //Wrongly identified multiple
}
}
// Do things for each case
if(isTrueMeson){
// neutral meson was found
fHistoTrueMotherPiPlPiMiNDMInvMassPt[fiCut]->Fill(mesoncand->M(),mesoncand->Pt(),weighted);
// Subtract mass of used NDM candidate and then add PDG mass
fHistoTrueMotherPiPlPiMiNDMInvMassPtSubNDM[fiCut]->Fill(mesoncand->M()-(TrueNeutralDecayMesonCandidate->M()-fPDGMassNDM),mesoncand->Pt(),weighted);
// Fix Pz of pi0 candidate to match pi0 PDG mass
AliAODConversionMother NDMtmp;
NDMtmp.SetPxPyPzE(TrueNeutralDecayMesonCandidate->Px(), TrueNeutralDecayMesonCandidate->Py(), TrueNeutralDecayMesonCandidate->Pz(), TrueNeutralDecayMesonCandidate->Energy());
FixPzToMatchPDGInvMassNDM(&NDMtmp);
AliAODConversionMother mesontmp(&NDMtmp,TrueVirtualParticleCandidate);
fHistoTrueMotherPiPlPiMiNDMInvMassPtFixedPzNDM[fiCut]->Fill(mesontmp.M(),mesontmp.Pt(),weighted);
AliAODConversionMother PosPiontmp, NegPiontmp;
PosPiontmp.SetPxPyPzE(positiveMC->Px(), positiveMC->Py(), positiveMC->Pz(), positiveMC->Energy());
NegPiontmp.SetPxPyPzE(negativeMC->Px(), negativeMC->Py(), negativeMC->Pz(), negativeMC->Energy());
if(!fDoLightOutput){
fHistoTrueAngleSum[fiCut]->Fill(mesoncand->Pt(),((PosPiontmp.Angle(mesoncand->Vect()))+(NegPiontmp.Angle(PosPiontmp.Vect()))+(PosPiontmp.Angle(TrueNeutralDecayMesonCandidate->Vect()))));
fHistoTrueHNMesonPtvsNDMPt[fiCut]->Fill(mesoncand->Pt(),TrueNeutralDecayMesonCandidate->Pt(),weighted);
}
// Fill tree to get info about event that the eta was found in
if(fDoMesonQA>1 && (!fDoLightOutput)){
fV0MultiplicityHNMEvent = fMCEvent->GetNumberOfV0s();
fTrackMultiplicityHNMEvent = fMCEvent->GetNumberOfTracks();
fZVertexHNMEvent = fMCEvent->GetPrimaryVertex()->GetZ();
fPtHNM = mesoncand->Pt();
fTreeEventInfoHNM[fiCut]->Fill();
}
if (CheckVectorForDoubleCount(fVectorDoubleCountTrueHNMs,NDMMotherLabel) && (!fDoLightOutput)) fHistoDoubleCountTrueHNMInvMassPt[fiCut]->Fill(mesoncand->M(),mesoncand->Pt());
} else if (isDifferentMesonContribution) {
//True Meson, but the analyzed one
fHistoTrueMotherPiPlPiMiNDMInvMassPt_FromDifferent[fiCut]->Fill(mesoncand->M(),mesoncand->Pt(),weighted);
if((fDoMesonQA>0 ) && (!fDoLightOutput)){
if((fMCEvent->Particle(posMotherLabelMC)->GetPdgCode() == 223)||
(fMCEvent->Particle(posMotherLabelMC)->GetPdgCode() == 221)){
// pi+pi- come from eta
fHistoTrueMotherPiPlPiMiNDMInvMassPt_FromEtaOmega[fiCut]->Fill(mesoncand->M(),mesoncand->Pt(),weighted);
} else if(fMCEvent->Particle(posMotherLabelMC)->GetPdgCode() == 113){
// pi+pi- come from rho0
fHistoTrueMotherPiPlPiMiNDMInvMassPt_FromRho[fiCut]->Fill(mesoncand->M(),mesoncand->Pt(),weighted);
} else if(fMCEvent->Particle(posMotherLabelMC)->GetPdgCode() == 331){
// pi+pi- come from eta prime
fHistoTrueMotherPiPlPiMiNDMInvMassPt_FromEtaPrime[fiCut]->Fill(mesoncand->M(),mesoncand->Pt(),weighted);
} else if(fMCEvent->Particle(posMotherLabelMC)->GetPdgCode() == 310){
// pi+pi- come from K0 short
fHistoTrueMotherPiPlPiMiNDMInvMassPt_FromK0s[fiCut]->Fill(mesoncand->M(),mesoncand->Pt(),weighted);
} else if(fMCEvent->Particle(posMotherLabelMC)->GetPdgCode() == 130){
// pi+pi- come from K0 long
fHistoTrueMotherPiPlPiMiNDMInvMassPt_FromK0l[fiCut]->Fill(mesoncand->M(),mesoncand->Pt(),weighted);
} else{
// pi+pi- come from something else
fHistoTrueMotherPiPlPiMiNDMInvMassPt_FromOther[fiCut]->Fill(mesoncand->M(),mesoncand->Pt(),weighted);
}
}
} else if (isCombinatoricsMeson) {
fHistoTruePiPlPiMiNDMCombinatoricalInvMassPt[fiCut]->Fill(mesoncand->M(),mesoncand->Pt(),weighted);
if(isSameMotherPiPlPiMi && (fDoMesonQA>0 ) && (!fDoLightOutput)){
if(fMCEvent->Particle(posMotherLabelMC)->GetPdgCode() == 221){
// pi+pi- come from eta
fHistoTruePiPlPiMiSameMotherFromEtaInvMassPt[fiCut]->Fill(mesoncand->M(),mesoncand->Pt(),weighted);
} else if(fMCEvent->Particle(posMotherLabelMC)->GetPdgCode() == 223){
// pi+pi- come from omega
fHistoTruePiPlPiMiSameMotherFromOmegaInvMassPt[fiCut]->Fill(mesoncand->M(),mesoncand->Pt(),weighted);
} else if(fMCEvent->Particle(posMotherLabelMC)->GetPdgCode() == 113){
// pi+pi- come from rho0
fHistoTruePiPlPiMiSameMotherFromRhoInvMassPt[fiCut]->Fill(mesoncand->M(),mesoncand->Pt(),weighted);
} else if(fMCEvent->Particle(posMotherLabelMC)->GetPdgCode() == 331){
// pi+pi- come from eta prime
fHistoTruePiPlPiMiSameMotherFromEtaPrimeInvMassPt[fiCut]->Fill(mesoncand->M(),mesoncand->Pt(),weighted);
} else if(fMCEvent->Particle(posMotherLabelMC)->GetPdgCode() == 310){
// pi+pi- come from K0 short
fHistoTruePiPlPiMiSameMotherFromK0sInvMassPt[fiCut]->Fill(mesoncand->M(),mesoncand->Pt(),weighted);
} else if(fMCEvent->Particle(posMotherLabelMC)->GetPdgCode() == 130){
// pi+pi- come from K0 short
fHistoTruePiPlPiMiSameMotherFromK0lInvMassPt[fiCut]->Fill(mesoncand->M(),mesoncand->Pt(),weighted);
} else {
// pi+pi- come from something else
fHistoTruePiPlPiMiSameMotherFromOtherlInvMassPt[fiCut]->Fill(mesoncand->M(),mesoncand->Pt(),weighted);
}
} else if(isSameMotherPiMiNDM && (fDoMesonQA>0 ) && (!fDoLightOutput)){
if(fMCEvent->Particle(NDMMotherLabel)->GetPdgCode() == 221){
// pi0pi- come from eta
fHistoTruePiMiPiZeroSameMotherFromEtaInvMassPt[fiCut]->Fill(mesoncand->M(),mesoncand->Pt(),weighted);
} else if(fMCEvent->Particle(NDMMotherLabel)->GetPdgCode() == 223){
// pi0pi- come from omega
fHistoTruePiMiPiZeroSameMotherFromOmegaInvMassPt[fiCut]->Fill(mesoncand->M(),mesoncand->Pt(),weighted);
} else if(fMCEvent->Particle(NDMMotherLabel)->GetPdgCode() ==-213){
// pi0pi- come from rho-
fHistoTruePiMiPiZeroSameMotherFromRhoInvMassPt[fiCut]->Fill(mesoncand->M(),mesoncand->Pt(),weighted);
} else if(fMCEvent->Particle(NDMMotherLabel)->GetPdgCode() == 130){
// pi0pi- come from rho-
fHistoTruePiMiPiZeroSameMotherFromK0lInvMassPt[fiCut]->Fill(mesoncand->M(),mesoncand->Pt(),weighted);
} else {
// pi0pi- come from something else
fHistoTruePiMiPiZeroSameMotherFromOtherlInvMassPt[fiCut]->Fill(mesoncand->M(),mesoncand->Pt(),weighted);
}
} else if(isSameMotherPiPlNDM && (fDoMesonQA>0 ) && (!fDoLightOutput)){
if(fMCEvent->Particle(posMotherLabelMC)->GetPdgCode() == 221){
// pi+pi0 come from eta
fHistoTruePiPlPiZeroSameMotherFromEtaInvMassPt[fiCut]->Fill(mesoncand->M(),mesoncand->Pt(),weighted);
} else if(fMCEvent->Particle(posMotherLabelMC)->GetPdgCode() == 223){
// pi+pi0 come from omega
fHistoTruePiPlPiZeroSameMotherFromOmegaInvMassPt[fiCut]->Fill(mesoncand->M(),mesoncand->Pt(),weighted);
} else if(fMCEvent->Particle(posMotherLabelMC)->GetPdgCode() == 213) {
// pi+pi0 come from rho+
fHistoTruePiPlPiZeroSameMotherFromRhoInvMassPt[fiCut]->Fill(mesoncand->M(),mesoncand->Pt(),weighted);
} else if(fMCEvent->Particle(posMotherLabelMC)->GetPdgCode() == 130) {
// pi+pi0 come from rho+
fHistoTruePiPlPiZeroSameMotherFromK0lInvMassPt[fiCut]->Fill(mesoncand->M(),mesoncand->Pt(),weighted);
} else {
// pi+pi0 come from something else
fHistoTruePiPlPiZeroSameMotherFromOtherInvMassPt[fiCut]->Fill(mesoncand->M(),mesoncand->Pt(),weighted);
}
} else if(isNoSameMother && (fDoMesonQA>0 ) && (!fDoLightOutput)){
// no same mother purecombinatorical
fHistoTruePiPlPiMiNDMPureCombinatoricalInvMassPt[fiCut]->Fill(mesoncand->M(),mesoncand->Pt(),weighted);
}
} else if (isContaminationMeson) {
// no pi pi pi decay contamination
fHistoTruePiPlPiMiNDMContaminationInvMassPt[fiCut]->Fill(mesoncand->M(),mesoncand->Pt(),weighted);
if((fDoMesonQA>0 ) && (!fDoLightOutput)){
if (!isMultipleWronglyIdentified){
if (isPiPlWronglyIdentified){
fHistoTruePiPlPiMiNDMContamination_PiPl_InvMassPt[fiCut]->Fill(mesoncand->M(),mesoncand->Pt(),weighted);
}
if (isPiMiWronglyIdentified){
fHistoTruePiPlPiMiNDMContamination_PiMi_InvMassPt[fiCut]->Fill(mesoncand->M(),mesoncand->Pt(),weighted);
}
if (isPiZeroWronglyIdentified){
fHistoTruePiPlPiMiNDMContamination_Pi0_InvMassPt[fiCut]->Fill(mesoncand->M(),mesoncand->Pt(),weighted);
}
} else {
fHistoTruePiPlPiMiNDMContamination_multipel_InvMassPt[fiCut]->Fill(mesoncand->M(),mesoncand->Pt(),weighted);
}
}
}
}
//______________________________________________________________________
void AliAnalysisTaskNeutralMesonToPiPlPiMiNeutralMeson::ProcessTrueMesonCandidatesAOD(AliAODConversionMother *mesoncand, AliAODConversionMother *TrueNeutralDecayMesonCandidate, AliAODConversionPhoton *TrueVirtualParticleCandidate)
{
// Process True Mesons
Bool_t isSameMotherPiPlPiMiNDM = kFALSE; // pi+ pi- and pi0 have the same mother
Bool_t isSameMotherPiPlPiMi = kFALSE; // pi+ and pi- have the same mother
Bool_t isSameMotherPiPlNDM = kFALSE; // pi+ and pi0 have the same mother
Bool_t isSameMotherPiMiNDM = kFALSE; // pi- and pi0 have the same mother
Bool_t isNoSameMother = kFALSE; // none of the pions have the same mother
Bool_t areAllPionsCorrectlyIdentified = kFALSE; // All Pion Identifications correct
Bool_t isPiPlWronglyIdentified = kFALSE; // Pi+ Identification not correct
Bool_t isPiMiWronglyIdentified = kFALSE; // Pi- Identification not correct
Bool_t isPiZeroWronglyIdentified = kFALSE; // Pi0 Identification not correct
Bool_t isMultipleWronglyIdentified = kFALSE; // more than one Pion Identification not correct
Bool_t isTrueMeson = kFALSE; //True analyzed meson
Bool_t isDifferentMesonContribution = kFALSE; //True meson, but NOT analyzed meson
Bool_t isCombinatoricsMeson = kFALSE; //Combinatorics candidate
Bool_t isContaminationMeson = kFALSE; //Contamination candidate
Bool_t NDMMC_PDGCheck = kFALSE;
TClonesArray *AODMCTrackArray = dynamic_cast<TClonesArray*>(fInputEvent->FindListObject(AliAODMCParticle::StdBranchName()));
Int_t virtualParticleMCLabel = -1;
Int_t virtualParticleMotherLabel = -1;
//Is set when:
//if(((AliAODMCParticle*)AODMCTrackArray->At(gamma1MotherLabel))->GetPdgCode() == fPDGCodeNDM) isTrueNDM=kTRUE;
//if(isTrueNDM){// True Pion
//Pi0Candidate->SetTrueMesonValue(1);
Int_t trueMesonFlag = TrueNeutralDecayMesonCandidate->GetTrueMesonValue();
Int_t NDMMCLabel = TrueNeutralDecayMesonCandidate->GetMCLabel();
Float_t weighted= fWeightJetJetMC;
if (fDoMesonQA>0){fHistoTrueMesonFlags[fiCut]->Fill(1);} //All candidates
if ( !(trueMesonFlag == 1 && NDMMCLabel != -1)){ //more understandable: (trueMesonFlag != 1 || NDMMCLabel == -1)
if((fDoMesonQA>0 ) && (!fDoLightOutput)){
fHistoTruePiPlPiMiNDMContamination_Crosscheck_InvMassPt[fiCut]->Fill(mesoncand->M(),mesoncand->Pt(),weighted);
}
isPiZeroWronglyIdentified = kTRUE;
isContaminationMeson = kTRUE;
//return;
}
Int_t NDMMotherLabel = 0;
AliAODMCParticle *negativeMC = static_cast<AliAODMCParticle*>(AODMCTrackArray->At(TrueVirtualParticleCandidate->GetMCLabelNegative())); // pi-
AliAODMCParticle *positiveMC = static_cast<AliAODMCParticle*>(AODMCTrackArray->At(TrueVirtualParticleCandidate->GetMCLabelPositive())); // pi+
AliAODMCParticle *NDMMC = NULL;
if (NDMMCLabel == -1){
NDMMC_PDGCheck = kFALSE;
} else {
NDMMotherLabel = (static_cast<AliAODMCParticle*>(AODMCTrackArray->At(NDMMCLabel)))->GetMother();
NDMMC = static_cast<AliAODMCParticle*>(AODMCTrackArray->At(NDMMCLabel)); // pi0
NDMMC_PDGCheck=NDMMC->GetPdgCode()==fPDGCodeNDM;
}
if(positiveMC->GetMother()>-1&&(negativeMC->GetMother() == positiveMC->GetMother())){
virtualParticleMCLabel = positiveMC->GetMother();
}
Int_t posMotherLabelMC = positiveMC->GetMother();
Int_t negMotherLabelMC = negativeMC->GetMother();
if ( (isPiZeroWronglyIdentified)&&((NDMMC_PDGCheck)) ){
if (fDoMesonQA>0){fHistoTrueMesonFlags[fiCut]->Fill(10);} //Problem with pi0 flag
}
// Check case present
if((TMath::Abs(negativeMC->GetPdgCode())==211) && (TMath::Abs(positiveMC->GetPdgCode())==211) && (NDMMC_PDGCheck)){
// three pion decay, Combinatorics and trues
areAllPionsCorrectlyIdentified = kTRUE;
if(virtualParticleMCLabel!=-1){
// pi+ pi- have same mother
isSameMotherPiPlPiMi = kTRUE;
virtualParticleMotherLabel = virtualParticleMCLabel;
if(virtualParticleMotherLabel==NDMMotherLabel){
// all pions from same mother
isSameMotherPiPlPiMiNDM = kTRUE;
} else{
// only pi+ pi- from same mother -> Combinatorics
isCombinatoricsMeson = kTRUE;
}
} else{
//pi+ and pi- do not have same mother -> Combinatorics
isCombinatoricsMeson = kTRUE;
if(NDMMotherLabel==negMotherLabelMC && negMotherLabelMC != -1){
// pi0 and pi- same mother
isSameMotherPiMiNDM = kTRUE;
} else if(NDMMotherLabel==posMotherLabelMC && posMotherLabelMC != -1){
// pi0 and pi+ same mother
isSameMotherPiPlNDM = kTRUE;
} else{
// all pions different mother
isNoSameMother = kTRUE;
}
}
} else{
// not a three pion decay, Contamination
isContaminationMeson = kTRUE;
if (!(TMath::Abs(negativeMC->GetPdgCode())==211)){
isPiMiWronglyIdentified = kTRUE;
}
if (!(TMath::Abs(positiveMC->GetPdgCode())==211)){
isPiPlWronglyIdentified = kTRUE;
if (isPiMiWronglyIdentified){
isMultipleWronglyIdentified = kTRUE;
}
}
if (!(NDMMC_PDGCheck)){
isPiZeroWronglyIdentified = kTRUE;
if ((isPiMiWronglyIdentified)||(isPiPlWronglyIdentified)){
isMultipleWronglyIdentified = kTRUE;
}
}
}
if(areAllPionsCorrectlyIdentified&&isSameMotherPiPlPiMiNDM){
if((static_cast<AliAODMCParticle*>(AODMCTrackArray->At(NDMMotherLabel)))->GetPdgCode() == fPDGCodeAnalyzedMeson){
isTrueMeson = kTRUE;
} else {
isDifferentMesonContribution = kTRUE;
}
}
Int_t iNumberOfDeclarationFlags=0;
if (isTrueMeson){iNumberOfDeclarationFlags++;}
if (isDifferentMesonContribution){iNumberOfDeclarationFlags++;}
if (isCombinatoricsMeson){iNumberOfDeclarationFlags++;}
if (isContaminationMeson){iNumberOfDeclarationFlags++;}
if (iNumberOfDeclarationFlags!=1){
if (fDoMesonQA>0){fHistoTrueMesonFlags[fiCut]->Fill(11);} //Problem with meson declaration flag
}
if(areAllPionsCorrectlyIdentified&&isSameMotherPiPlPiMiNDM){
if (fDoMesonQA>0){fHistoTrueMesonFlags[fiCut]->Fill(2);} //Same mother
if (isTrueMeson){
if (fDoMesonQA>0){fHistoTrueMesonFlags[fiCut]->Fill(3);} //True
}
} else if (areAllPionsCorrectlyIdentified){
if (fDoMesonQA>0){fHistoTrueMesonFlags[fiCut]->Fill(4);} //Not same mother
} else if (isContaminationMeson){
if (fDoMesonQA>0){fHistoTrueMesonFlags[fiCut]->Fill(5);} //Wrongly identified pions
if (!isMultipleWronglyIdentified){
if (isPiZeroWronglyIdentified){
if (fDoMesonQA>0){fHistoTrueMesonFlags[fiCut]->Fill(6);} //Wrongly identified pi0
} else if (isPiPlWronglyIdentified){
if (fDoMesonQA>0){fHistoTrueMesonFlags[fiCut]->Fill(7);} //Wrongly identified pi+
} else if (isPiMiWronglyIdentified){
if (fDoMesonQA>0){fHistoTrueMesonFlags[fiCut]->Fill(8);} //Wrongly identified pi-
}
} else {
if (fDoMesonQA>0){fHistoTrueMesonFlags[fiCut]->Fill(9);} //Wrongly identified multiple
}
}
// Do things for each case
if(isTrueMeson){
// neutral meson was found
fHistoTrueMotherPiPlPiMiNDMInvMassPt[fiCut]->Fill(mesoncand->M(),mesoncand->Pt(),weighted);
// Subtract mass of used NDM candidate and then add PDG mass
fHistoTrueMotherPiPlPiMiNDMInvMassPtSubNDM[fiCut]->Fill(mesoncand->M()-(TrueNeutralDecayMesonCandidate->M()-fPDGMassNDM),mesoncand->Pt(),weighted);
// Fix Pz of pi0 candidate to match pi0 PDG mass
AliAODConversionMother NDMtmp;
NDMtmp.SetPxPyPzE(TrueNeutralDecayMesonCandidate->Px(), TrueNeutralDecayMesonCandidate->Py(), TrueNeutralDecayMesonCandidate->Pz(), TrueNeutralDecayMesonCandidate->Energy());
FixPzToMatchPDGInvMassNDM(&NDMtmp);
AliAODConversionMother mesontmp(&NDMtmp,TrueVirtualParticleCandidate);
fHistoTrueMotherPiPlPiMiNDMInvMassPtFixedPzNDM[fiCut]->Fill(mesontmp.M(),mesontmp.Pt(),weighted);
if(fDoMesonQA>0){
//Dalitz plot
TLorentzVector PosPionTLVtmp;
TLorentzVector NegPionTLVtmp;
TLorentzVector PosNegPionTLVtmp;
PosPionTLVtmp.SetPxPyPzE (positiveMC->Px(), positiveMC->Py(), positiveMC->Pz(), positiveMC->E() );
NegPionTLVtmp.SetPxPyPzE (negativeMC->Px(), negativeMC->Py(), negativeMC->Pz(), negativeMC->E() );
PosNegPionTLVtmp = PosPionTLVtmp + NegPionTLVtmp;
TLorentzVector NDMTLVtmp;
TLorentzVector NDMSubTLVtmp;
TLorentzVector PosPionNDMTLVtmp;
TLorentzVector NegPionNDMTLVtmp;
TLorentzVector PosPionNDMSubTLVtmp;
TLorentzVector NegPionNDMSubTLVtmp;
NDMTLVtmp.SetPxPyPzE( NDMtmp.Px(), NDMtmp.Py(), NDMtmp.Pz(), NDMtmp.E() );
NDMSubTLVtmp.SetPxPyPzE (TrueNeutralDecayMesonCandidate->Px(), TrueNeutralDecayMesonCandidate->Py(), TrueNeutralDecayMesonCandidate->Pz(), TrueNeutralDecayMesonCandidate->Energy());
PosPionNDMTLVtmp = PosPionTLVtmp + NDMTLVtmp;
NegPionNDMTLVtmp = NegPionTLVtmp + NDMTLVtmp;
PosPionNDMSubTLVtmp = PosPionTLVtmp + NDMSubTLVtmp;
NegPionNDMSubTLVtmp = NegPionTLVtmp + NDMSubTLVtmp;
//Dalitz All Pt
if (enableDalitzAllPt){
fHistoTrueMotherPiPlPiMiNDMDalitzPlotPosFixedPzNDM[fiCut]->Fill(PosNegPionTLVtmp.M(), PosPionNDMTLVtmp.M() );
fHistoTrueMotherPiPlPiMiNDMDalitzPlotPosSubNDM[fiCut]->Fill(PosNegPionTLVtmp.M(), PosPionNDMSubTLVtmp.M() - (NDMSubTLVtmp.M() - fPDGMassNDM) );
fHistoTrueMotherPiPlPiMiNDMDalitzPlotNegFixedPzNDM[fiCut]->Fill(PosNegPionTLVtmp.M(), NegPionNDMTLVtmp.M() );
fHistoTrueMotherPiPlPiMiNDMDalitzPlotNegSubNDM[fiCut]->Fill(PosNegPionTLVtmp.M(), NegPionNDMSubTLVtmp.M() - (NDMSubTLVtmp.M() - fPDGMassNDM) );
}
//Dalitz Low Pt
if (enableDalitzLowPt){
if ((mesoncand->Pt()>HistoDalitzPtRangeMin_LowPt)&&(mesoncand->Pt()<HistoDalitzPtRangeMax_LowPt)){
fHistoTrueMotherPiPlPiMiNDMDalitzPlotPosFixedPzNDM_LowPt[fiCut]->Fill(PosNegPionTLVtmp.M(), PosPionNDMTLVtmp.M() );
fHistoTrueMotherPiPlPiMiNDMDalitzPlotPosSubNDM_LowPt[fiCut]->Fill(PosNegPionTLVtmp.M(), PosPionNDMSubTLVtmp.M() - (NDMSubTLVtmp.M() - fPDGMassNDM) );
fHistoTrueMotherPiPlPiMiNDMDalitzPlotNegFixedPzNDM_LowPt[fiCut]->Fill(PosNegPionTLVtmp.M(), NegPionNDMTLVtmp.M() );
fHistoTrueMotherPiPlPiMiNDMDalitzPlotNegSubNDM_LowPt[fiCut]->Fill(PosNegPionTLVtmp.M(), NegPionNDMSubTLVtmp.M() - (NDMSubTLVtmp.M() - fPDGMassNDM) );
}
}
//Dalitz Mid Pt
if (enableDalitzMidPt){
if ((mesoncand->Pt()>HistoDalitzPtRangeMin_MidPt)&&(mesoncand->Pt()<HistoDalitzPtRangeMax_MidPt)){
fHistoTrueMotherPiPlPiMiNDMDalitzPlotPosFixedPzNDM_MidPt[fiCut]->Fill(PosNegPionTLVtmp.M(), PosPionNDMTLVtmp.M() );
fHistoTrueMotherPiPlPiMiNDMDalitzPlotPosSubNDM_MidPt[fiCut]->Fill(PosNegPionTLVtmp.M(), PosPionNDMSubTLVtmp.M() - (NDMSubTLVtmp.M() - fPDGMassNDM) );
fHistoTrueMotherPiPlPiMiNDMDalitzPlotNegFixedPzNDM_MidPt[fiCut]->Fill(PosNegPionTLVtmp.M(), NegPionNDMTLVtmp.M() );
fHistoTrueMotherPiPlPiMiNDMDalitzPlotNegSubNDM_MidPt[fiCut]->Fill(PosNegPionTLVtmp.M(), NegPionNDMSubTLVtmp.M() - (NDMSubTLVtmp.M() - fPDGMassNDM) );
}
}
//Dalitz High Pt
if (enableDalitzHighPt){
if ((mesoncand->Pt()>HistoDalitzPtRangeMin_HighPt)&&(mesoncand->Pt()<HistoDalitzPtRangeMax_HighPt)){
fHistoTrueMotherPiPlPiMiNDMDalitzPlotPosFixedPzNDM_HighPt[fiCut]->Fill(PosNegPionTLVtmp.M(), PosPionNDMTLVtmp.M() );
fHistoTrueMotherPiPlPiMiNDMDalitzPlotPosSubNDM_HighPt[fiCut]->Fill(PosNegPionTLVtmp.M(), PosPionNDMSubTLVtmp.M() - (NDMSubTLVtmp.M() - fPDGMassNDM) );
fHistoTrueMotherPiPlPiMiNDMDalitzPlotNegFixedPzNDM_HighPt[fiCut]->Fill(PosNegPionTLVtmp.M(), NegPionNDMTLVtmp.M() );
fHistoTrueMotherPiPlPiMiNDMDalitzPlotNegSubNDM_HighPt[fiCut]->Fill(PosNegPionTLVtmp.M(), NegPionNDMSubTLVtmp.M() - (NDMSubTLVtmp.M() - fPDGMassNDM) );
}
}
}
AliAODConversionMother PosPiontmp, NegPiontmp;
PosPiontmp.SetPxPyPzE(positiveMC->Px(), positiveMC->Py(), positiveMC->Pz(), positiveMC->E());
NegPiontmp.SetPxPyPzE(negativeMC->Px(), negativeMC->Py(), negativeMC->Pz(), negativeMC->E());
if(!fDoLightOutput){
fHistoTrueAngleSum[fiCut]->Fill(mesoncand->Pt(),((PosPiontmp.Angle(mesoncand->Vect()))+(NegPiontmp.Angle(PosPiontmp.Vect()))+(PosPiontmp.Angle(TrueNeutralDecayMesonCandidate->Vect()))));
fHistoTrueHNMesonPtvsNDMPt[fiCut]->Fill(mesoncand->Pt(),TrueNeutralDecayMesonCandidate->Pt(),weighted);
}
// Fill tree to get info about event that the eta was found in
if(fDoMesonQA>1 && (!fDoLightOutput)){
fV0MultiplicityHNMEvent = fMCEvent->GetNumberOfV0s();
fTrackMultiplicityHNMEvent = fMCEvent->GetNumberOfTracks();
fZVertexHNMEvent = fMCEvent->GetPrimaryVertex()->GetZ();
fPtHNM = mesoncand->Pt();
fTreeEventInfoHNM[fiCut]->Fill();
}
if (CheckVectorForDoubleCount(fVectorDoubleCountTrueHNMs,NDMMotherLabel) && (!fDoLightOutput)) fHistoDoubleCountTrueHNMInvMassPt[fiCut]->Fill(mesoncand->M(),mesoncand->Pt());
} else if (isDifferentMesonContribution){
//True Meson, but the analyzed one
fHistoTrueMotherPiPlPiMiNDMInvMassPt_FromDifferent[fiCut]->Fill(mesoncand->M(),mesoncand->Pt(),weighted);
if((fDoMesonQA>0 ) && (!fDoLightOutput)){
if(((static_cast<AliAODMCParticle*>(AODMCTrackArray->At(posMotherLabelMC)))->GetPdgCode() == 223)||
((static_cast<AliAODMCParticle*>(AODMCTrackArray->At(posMotherLabelMC)))->GetPdgCode() == 221)){
// pi+pi- come from eta
fHistoTrueMotherPiPlPiMiNDMInvMassPt_FromEtaOmega[fiCut]->Fill(mesoncand->M(),mesoncand->Pt(),weighted);
} else if((static_cast<AliAODMCParticle*>(AODMCTrackArray->At(posMotherLabelMC)))->GetPdgCode() == 113){
// pi+pi- come from rho0
fHistoTrueMotherPiPlPiMiNDMInvMassPt_FromRho[fiCut]->Fill(mesoncand->M(),mesoncand->Pt(),weighted);
} else if((static_cast<AliAODMCParticle*>(AODMCTrackArray->At(posMotherLabelMC)))->GetPdgCode() == 331){
// pi+pi- come from eta prime
fHistoTrueMotherPiPlPiMiNDMInvMassPt_FromEtaPrime[fiCut]->Fill(mesoncand->M(),mesoncand->Pt(),weighted);
} else if((static_cast<AliAODMCParticle*>(AODMCTrackArray->At(posMotherLabelMC)))->GetPdgCode() == 310){
// pi+pi- come from K0 short
fHistoTrueMotherPiPlPiMiNDMInvMassPt_FromK0s[fiCut]->Fill(mesoncand->M(),mesoncand->Pt(),weighted);
} else if((static_cast<AliAODMCParticle*>(AODMCTrackArray->At(posMotherLabelMC)))->GetPdgCode() == 130){
// pi+pi- come from K0 long
fHistoTrueMotherPiPlPiMiNDMInvMassPt_FromK0l[fiCut]->Fill(mesoncand->M(),mesoncand->Pt(),weighted);
} else{
// pi+pi- come from something else
fHistoTrueMotherPiPlPiMiNDMInvMassPt_FromOther[fiCut]->Fill(mesoncand->M(),mesoncand->Pt(),weighted);
}
}
} else if (isCombinatoricsMeson) {
fHistoTruePiPlPiMiNDMCombinatoricalInvMassPt[fiCut]->Fill(mesoncand->M(),mesoncand->Pt(),weighted);
if(isSameMotherPiPlPiMi && (fDoMesonQA>0 ) && (!fDoLightOutput)){
if((static_cast<AliAODMCParticle*>(AODMCTrackArray->At(posMotherLabelMC)))->GetPdgCode() == 221){
// pi+pi- come from eta
fHistoTruePiPlPiMiSameMotherFromEtaInvMassPt[fiCut]->Fill(mesoncand->M(),mesoncand->Pt(),weighted);
} else if((static_cast<AliAODMCParticle*>(AODMCTrackArray->At(posMotherLabelMC)))->GetPdgCode() == 223){
// pi+pi- come from omega
fHistoTruePiPlPiMiSameMotherFromOmegaInvMassPt[fiCut]->Fill(mesoncand->M(),mesoncand->Pt(),weighted);
} else if((static_cast<AliAODMCParticle*>(AODMCTrackArray->At(posMotherLabelMC)))->GetPdgCode() == 113){
// pi+pi- come from rho0
fHistoTruePiPlPiMiSameMotherFromRhoInvMassPt[fiCut]->Fill(mesoncand->M(),mesoncand->Pt(),weighted);
} else if((static_cast<AliAODMCParticle*>(AODMCTrackArray->At(posMotherLabelMC)))->GetPdgCode() == 331){
// pi+pi- come from eta prime
fHistoTruePiPlPiMiSameMotherFromEtaPrimeInvMassPt[fiCut]->Fill(mesoncand->M(),mesoncand->Pt(),weighted);
} else if((static_cast<AliAODMCParticle*>(AODMCTrackArray->At(posMotherLabelMC)))->GetPdgCode() == 310){
// pi+pi- come from K0 short
fHistoTruePiPlPiMiSameMotherFromK0sInvMassPt[fiCut]->Fill(mesoncand->M(),mesoncand->Pt(),weighted);
} else if((static_cast<AliAODMCParticle*>(AODMCTrackArray->At(posMotherLabelMC)))->GetPdgCode() == 130){
// pi+pi- come from K0 long
fHistoTruePiPlPiMiSameMotherFromK0lInvMassPt[fiCut]->Fill(mesoncand->M(),mesoncand->Pt(),weighted);
} else{
// pi+pi- come from something else
fHistoTruePiPlPiMiSameMotherFromOtherlInvMassPt[fiCut]->Fill(mesoncand->M(),mesoncand->Pt(),weighted);
}
} else if(isSameMotherPiMiNDM && (fDoMesonQA>0 ) && (!fDoLightOutput)){
if((static_cast<AliAODMCParticle*>(AODMCTrackArray->At(NDMMotherLabel)))->GetPdgCode() == 221){
// pi0pi- come from eta
fHistoTruePiMiPiZeroSameMotherFromEtaInvMassPt[fiCut]->Fill(mesoncand->M(),mesoncand->Pt(),weighted);
} else if((static_cast<AliAODMCParticle*>(AODMCTrackArray->At(NDMMotherLabel)))->GetPdgCode() == 223){
// pi0pi- come from omega
fHistoTruePiMiPiZeroSameMotherFromOmegaInvMassPt[fiCut]->Fill(mesoncand->M(),mesoncand->Pt(),weighted);
} else if((static_cast<AliAODMCParticle*>(AODMCTrackArray->At(NDMMotherLabel)))->GetPdgCode() ==-213){
// pi0pi- come from rho-
fHistoTruePiMiPiZeroSameMotherFromRhoInvMassPt[fiCut]->Fill(mesoncand->M(),mesoncand->Pt(),weighted);
} else if((static_cast<AliAODMCParticle*>(AODMCTrackArray->At(NDMMotherLabel)))->GetPdgCode() == 130){
// pi0pi- come from K0l
fHistoTruePiMiPiZeroSameMotherFromK0lInvMassPt[fiCut]->Fill(mesoncand->M(),mesoncand->Pt(),weighted);
} else{
// pi0pi- come from something else
fHistoTruePiMiPiZeroSameMotherFromOtherlInvMassPt[fiCut]->Fill(mesoncand->M(),mesoncand->Pt(),weighted);
}
} else if(isSameMotherPiPlNDM && (fDoMesonQA>0 ) && (!fDoLightOutput)){
if((static_cast<AliAODMCParticle*>(AODMCTrackArray->At(posMotherLabelMC)))->GetPdgCode() == 221){
// pi+pi0 come from eta
fHistoTruePiPlPiZeroSameMotherFromEtaInvMassPt[fiCut]->Fill(mesoncand->M(),mesoncand->Pt(),weighted);
} else if((static_cast<AliAODMCParticle*>(AODMCTrackArray->At(posMotherLabelMC)))->GetPdgCode() == 223){
// pi+pi0 come from omega
fHistoTruePiPlPiZeroSameMotherFromOmegaInvMassPt[fiCut]->Fill(mesoncand->M(),mesoncand->Pt(),weighted);
} else if((static_cast<AliAODMCParticle*>(AODMCTrackArray->At(posMotherLabelMC)))->GetPdgCode() == 213) {
// pi+pi0 come from rho+
fHistoTruePiPlPiZeroSameMotherFromRhoInvMassPt[fiCut]->Fill(mesoncand->M(),mesoncand->Pt(),weighted);
} else if((static_cast<AliAODMCParticle*>(AODMCTrackArray->At(posMotherLabelMC)))->GetPdgCode() == 130) {
// pi+pi0 come from K0l
fHistoTruePiPlPiZeroSameMotherFromK0lInvMassPt[fiCut]->Fill(mesoncand->M(),mesoncand->Pt(),weighted);
} else{
// pi+pi0 come from something else
fHistoTruePiPlPiZeroSameMotherFromOtherInvMassPt[fiCut]->Fill(mesoncand->M(),mesoncand->Pt(),weighted);
}
} else if(isNoSameMother && (fDoMesonQA>0 ) && (!fDoLightOutput)){
// no same mother purecombinatorical
fHistoTruePiPlPiMiNDMPureCombinatoricalInvMassPt[fiCut]->Fill(mesoncand->M(),mesoncand->Pt(),weighted);
}
} else if (isContaminationMeson) {
// no pi pi pi decay contamination
fHistoTruePiPlPiMiNDMContaminationInvMassPt[fiCut]->Fill(mesoncand->M(),mesoncand->Pt(),weighted);
if((fDoMesonQA>0 ) && (!fDoLightOutput)){
if (!isMultipleWronglyIdentified){
if (isPiPlWronglyIdentified){
fHistoTruePiPlPiMiNDMContamination_PiPl_InvMassPt[fiCut]->Fill(mesoncand->M(),mesoncand->Pt(),weighted);
}
if (isPiMiWronglyIdentified){
fHistoTruePiPlPiMiNDMContamination_PiMi_InvMassPt[fiCut]->Fill(mesoncand->M(),mesoncand->Pt(),weighted);
}
if (isPiZeroWronglyIdentified){
fHistoTruePiPlPiMiNDMContamination_Pi0_InvMassPt[fiCut]->Fill(mesoncand->M(),mesoncand->Pt(),weighted);
}
} else {
fHistoTruePiPlPiMiNDMContamination_multipel_InvMassPt[fiCut]->Fill(mesoncand->M(),mesoncand->Pt(),weighted);
}
}
}
}
//________________________________________________________________________
void AliAnalysisTaskNeutralMesonToPiPlPiMiNeutralMeson::UpdateEventByEventData(){
//see header file for documentation
Int_t method = 1;
if( method == 1 ) {
if(fPosPionCandidates->GetEntries() >0 && fNegPionCandidates->GetEntries() >0){
if(((AliConversionMesonCuts*)fMesonCutArray->At(fiCut))->UseTrackMultiplicity()){
fBGHandlerPiPl[fiCut]->AddMesonEvent(fPosPionCandidates,fInputEvent->GetPrimaryVertex()->GetX(),fInputEvent->GetPrimaryVertex()->GetY(),fInputEvent->GetPrimaryVertex()->GetZ(),fV0Reader->GetNumberOfPrimaryTracks(),0);
fBGHandlerPiMi[fiCut]->AddMesonEvent(fNegPionCandidates,fInputEvent->GetPrimaryVertex()->GetX(),fInputEvent->GetPrimaryVertex()->GetY(),fInputEvent->GetPrimaryVertex()->GetZ(),fV0Reader->GetNumberOfPrimaryTracks(),0);
} else { // means we use #V0s for multiplicity
if (fNDMRecoMode < 2){
fBGHandlerPiPl[fiCut]->AddMesonEvent(fPosPionCandidates,fInputEvent->GetPrimaryVertex()->GetX(),fInputEvent->GetPrimaryVertex()->GetY(),fInputEvent->GetPrimaryVertex()->GetZ(),fGoodConvGammas->GetEntries(),0);
fBGHandlerPiMi[fiCut]->AddMesonEvent(fNegPionCandidates,fInputEvent->GetPrimaryVertex()->GetX(),fInputEvent->GetPrimaryVertex()->GetY(),fInputEvent->GetPrimaryVertex()->GetZ(),fGoodConvGammas->GetEntries(),0);
}else {
fBGHandlerPiPl[fiCut]->AddMesonEvent(fPosPionCandidates,fInputEvent->GetPrimaryVertex()->GetX(),fInputEvent->GetPrimaryVertex()->GetY(),fInputEvent->GetPrimaryVertex()->GetZ(),fClusterCandidates->GetEntries(),0);
fBGHandlerPiMi[fiCut]->AddMesonEvent(fNegPionCandidates,fInputEvent->GetPrimaryVertex()->GetX(),fInputEvent->GetPrimaryVertex()->GetY(),fInputEvent->GetPrimaryVertex()->GetZ(),fClusterCandidates->GetEntries(),0);
}
}
}
}
}
//________________________________________________________________________
void AliAnalysisTaskNeutralMesonToPiPlPiMiNeutralMeson::MoveParticleAccordingToVertex(AliAODConversionMother* particle,const AliGammaConversionAODBGHandler::GammaConversionVertex *vertex){
//see header file for documentation
Double_t dx = vertex->fX - fInputEvent->GetPrimaryVertex()->GetX();
Double_t dy = vertex->fY - fInputEvent->GetPrimaryVertex()->GetY();
Double_t dz = vertex->fZ - fInputEvent->GetPrimaryVertex()->GetZ();
Double_t movedPlace[3] = {particle->GetProductionX() - dx,particle->GetProductionY() - dy,particle->GetProductionZ() - dz};
particle->SetProductionPoint(movedPlace);
}
//________________________________________________________________________
void AliAnalysisTaskNeutralMesonToPiPlPiMiNeutralMeson::FixPzToMatchPDGInvMassNDM(AliAODConversionMother* particle) {
Double_t px = particle->Px();
Double_t py = particle->Py();
Int_t signPz = particle->Pz()<0?-1:1;
Double_t energy = particle->Energy();
Double_t pz = signPz*TMath::Sqrt(TMath::Abs(pow(fPDGMassNDM,2)-pow(energy,2)+pow(px,2)+pow(py,2)));
particle->SetPxPyPzE(px,py,pz,energy);
return;
}
//________________________________________________________________________
void AliAnalysisTaskNeutralMesonToPiPlPiMiNeutralMeson::FixPzVecToMatchPDGInvMass(TLorentzVector* track) {
Double_t px = track->Px();
Double_t py = track->Py();
Int_t signPz = track->Pz()<0?-1:1;
Double_t energy = track->E();
Double_t pz = signPz*TMath::Sqrt(TMath::Abs(pow(fPDGMassChargedPion,2)-pow(energy,2)+pow(px,2)+pow(py,2)));
track->SetPxPyPzE(px,py,pz,energy);
return;
}
//_____________________________________________________________________________________
Bool_t AliAnalysisTaskNeutralMesonToPiPlPiMiNeutralMeson::IsEtaPrimePiPlPiMiEtaDaughter( Int_t label ) const {
//
// Returns true if the particle comes from eta -> pi+ pi- gamma
//
if(label<0) return kFALSE;
Int_t motherLabel = fMCEvent->Particle( label )->GetMother(0);
if( motherLabel < 0 || motherLabel >= fMCEvent->GetNumberOfTracks() ) return kFALSE;
TParticle* mother = fMCEvent->Particle( motherLabel );
if( mother->GetPdgCode() != 331 ) return kFALSE;
if( IsPiPlPiMiEtaDecay( mother ) ) return kTRUE;
return kFALSE;
}
//_____________________________________________________________________________________
Bool_t AliAnalysisTaskNeutralMesonToPiPlPiMiNeutralMeson::IsEtaPrimePiPlPiMiEtaDaughterAOD(TClonesArray* trackArray, Int_t label ) const {
//
// Returns true if the particle comes from eta -> pi+ pi- gamma
//
if(label<0) return kFALSE;
Int_t motherLabel = (static_cast<AliAODMCParticle*>(trackArray->At(label)))->GetMother();
if( motherLabel < 0 || motherLabel >= trackArray->GetEntriesFast() ) return kFALSE;
AliAODMCParticle* mother = static_cast<AliAODMCParticle*>(trackArray->At(motherLabel));
if( mother->GetPdgCode() != 331 ) return kFALSE;
if( IsPiPlPiMiEtaDecayAOD(trackArray,mother) ) return kTRUE;
return kFALSE;
}
//_____________________________________________________________________________________
Bool_t AliAnalysisTaskNeutralMesonToPiPlPiMiNeutralMeson::IsEtaPiPlPiMiPiZeroDaughter( Int_t label ) const {
//
// Returns true if the particle comes from eta -> pi+ pi- gamma
//
if(label<0) return kFALSE;
Int_t motherLabel = fMCEvent->Particle( label )->GetMother(0);
if( motherLabel < 0 || motherLabel >= fMCEvent->GetNumberOfTracks() ) return kFALSE;
TParticle* mother = fMCEvent->Particle( motherLabel );
if( mother->GetPdgCode() != 221 ) return kFALSE;
if( IsPiPlPiMiPiZeroDecay( mother ) ) return kTRUE;
return kFALSE;
}
//_____________________________________________________________________________________
Bool_t AliAnalysisTaskNeutralMesonToPiPlPiMiNeutralMeson::IsEtaPiPlPiMiPiZeroDaughterAOD(TClonesArray* trackArray, Int_t label ) const {
//
// Returns true if the particle comes from eta -> pi+ pi- gamma
//
if(label<0) return kFALSE;
Int_t motherLabel = (static_cast<AliAODMCParticle*>(trackArray->At(label)))->GetMother();
if( motherLabel < 0 || motherLabel >= trackArray->GetEntriesFast() ) return kFALSE;
AliAODMCParticle* mother = static_cast<AliAODMCParticle*>(trackArray->At(motherLabel));
if( mother->GetPdgCode() != 221 ) return kFALSE;
if( IsPiPlPiMiPiZeroDecayAOD(trackArray,mother)) return kTRUE;
return kFALSE;
}
//_____________________________________________________________________________________
Bool_t AliAnalysisTaskNeutralMesonToPiPlPiMiNeutralMeson::IsOmegaPiPlPiMiPiZeroDaughter( Int_t label ) const {
//
// Returns true if the particle comes from eta -> pi+ pi- gamma
//
if(label<0) return kFALSE;
Int_t motherLabel = fMCEvent->Particle( label )->GetMother(0);
if( motherLabel < 0 || motherLabel >= fMCEvent->GetNumberOfTracks() ) return kFALSE;
TParticle* mother = fMCEvent->Particle( motherLabel );
if( mother->GetPdgCode() != 223 ) return kFALSE;
if( IsPiPlPiMiPiZeroDecay( mother ) ) return kTRUE;
return kFALSE;
}
//_____________________________________________________________________________________
Bool_t AliAnalysisTaskNeutralMesonToPiPlPiMiNeutralMeson::IsOmegaPiPlPiMiPiZeroDaughterAOD(TClonesArray* trackArray, Int_t label ) const {
//
// Returns true if the particle comes from eta -> pi+ pi- gamma
//
if(label<0) return kFALSE;
Int_t motherLabel = (static_cast<AliAODMCParticle*>(trackArray->At(label)))->GetMother();
if( motherLabel < 0 || motherLabel >= trackArray->GetEntriesFast() ) return kFALSE;
AliAODMCParticle* mother = static_cast<AliAODMCParticle*>(trackArray->At(motherLabel));
if( mother->GetPdgCode() != 223 ) return kFALSE;
if( IsPiPlPiMiPiZeroDecayAOD(trackArray, mother ) ) return kTRUE;
return kFALSE;
}
//_____________________________________________________________________________________
Bool_t AliAnalysisTaskNeutralMesonToPiPlPiMiNeutralMeson::IsD0PiPlPiMiPiZeroDaughter( Int_t label ) const {
//
// Returns true if the particle comes from eta -> pi+ pi- gamma
//
if(label<0) return kFALSE;
Int_t motherLabel = fMCEvent->Particle( label )->GetMother(0);
if( motherLabel < 0 || motherLabel >= fMCEvent->GetNumberOfTracks() ) return kFALSE;
TParticle* mother = fMCEvent->Particle( motherLabel );
if( mother->GetPdgCode() != 421 ) return kFALSE;
if( IsPiPlPiMiPiZeroDecay( mother ) ) return kTRUE;
return kFALSE;
}
//_____________________________________________________________________________________
Bool_t AliAnalysisTaskNeutralMesonToPiPlPiMiNeutralMeson::IsD0PiPlPiMiPiZeroDaughterAOD(TClonesArray* trackArray, Int_t label ) const {
//
// Returns true if the particle comes from eta -> pi+ pi- gamma
//
if(label<0) return kFALSE;
Int_t motherLabel = (static_cast<AliAODMCParticle*>(trackArray->At(label)))->GetMother();
if( motherLabel < 0 || motherLabel >= trackArray->GetEntriesFast() ) return kFALSE;
AliAODMCParticle* mother = static_cast<AliAODMCParticle*>(trackArray->At(motherLabel));
if( mother->GetPdgCode() != 421 ) return kFALSE;
if( IsPiPlPiMiPiZeroDecayAOD(trackArray, mother ) ) return kTRUE;
return kFALSE;
}
//_____________________________________________________________________________
Bool_t AliAnalysisTaskNeutralMesonToPiPlPiMiNeutralMeson::IsPiPlPiMiPiZeroDecay(TParticle *fMCMother) const
{
if( fMCMother->GetNDaughters() != 3 ) return kFALSE;
if( !(fMCMother->GetPdgCode() == 221 || fMCMother->GetPdgCode() == 223 || fMCMother->GetPdgCode() == 421) ) return kFALSE;
TParticle *posPion = 0x0;
TParticle *negPion = 0x0;
TParticle *neutPion = 0x0;
for(Int_t index= fMCMother->GetFirstDaughter();index<= fMCMother->GetLastDaughter();index++){
if(index<0) continue;
TParticle* temp = (TParticle*)fMCEvent->Particle( index );
switch( temp->GetPdgCode() ) {
case 211:
posPion = temp;
break;
case -211:
negPion = temp;
break;
case 111:
neutPion = temp;
break;
}
}
if( posPion && negPion && neutPion) return kTRUE;
return kFALSE;
}
//_____________________________________________________________________________
Bool_t AliAnalysisTaskNeutralMesonToPiPlPiMiNeutralMeson::IsPiPlPiMiPiZeroDecayAOD(TClonesArray* trackArray, AliAODMCParticle *fMCMother) const
{
if( fMCMother->GetNDaughters() != 3 ) return kFALSE;
if( !(fMCMother->GetPdgCode() == 221 || fMCMother->GetPdgCode() == 223 || fMCMother->GetPdgCode() == 421) ) return kFALSE;
AliAODMCParticle *posPion = 0x0;
AliAODMCParticle *negPion = 0x0;
AliAODMCParticle *neutPion = 0x0;
for(Int_t index= fMCMother->GetDaughterFirst();index<= fMCMother->GetDaughterLast();index++){
if(index<0) continue;
AliAODMCParticle* temp = static_cast<AliAODMCParticle*>(trackArray->At( index ));
switch( temp->GetPdgCode() ) {
case 211:
posPion = temp;
break;
case -211:
negPion = temp;
break;
case 111:
neutPion = temp;
break;
}
}
if( posPion && negPion && neutPion) return kTRUE;
return kFALSE;
}
//_____________________________________________________________________________
Bool_t AliAnalysisTaskNeutralMesonToPiPlPiMiNeutralMeson::IsPiPlPiMiEtaDecay(TParticle *fMCMother) const
{
if( fMCMother->GetNDaughters() != 3 ) return kFALSE;
if( !(fMCMother->GetPdgCode() == 331) ) return kFALSE;
TParticle *posPion = 0x0;
TParticle *negPion = 0x0;
TParticle *etaMeson = 0x0;
for(Int_t index= fMCMother->GetFirstDaughter();index<= fMCMother->GetLastDaughter();index++){
if(index<0) continue;
TParticle* temp = (TParticle*)fMCEvent->Particle( index );
switch( temp->GetPdgCode() ) {
case 211:
posPion = temp;
break;
case -211:
negPion = temp;
break;
case 221:
etaMeson = temp;
break;
}
}
if( posPion && negPion && etaMeson) return kTRUE;
return kFALSE;
}
//_____________________________________________________________________________
Bool_t AliAnalysisTaskNeutralMesonToPiPlPiMiNeutralMeson::IsPiPlPiMiEtaDecayAOD(TClonesArray* trackArray, AliAODMCParticle *fMCMother) const
{
if( fMCMother->GetNDaughters() != 3 ) return kFALSE;
if( !(fMCMother->GetPdgCode() == 331) ) return kFALSE;
AliAODMCParticle *posPion = 0x0;
AliAODMCParticle *negPion = 0x0;
AliAODMCParticle *etaMeson = 0x0;
for(Int_t index= fMCMother->GetDaughterFirst();index<= fMCMother->GetDaughterLast();index++){
if(index<0) continue;
AliAODMCParticle * temp =static_cast<AliAODMCParticle*>(trackArray->At( index ));
switch( temp->GetPdgCode() ) {
case 211:
posPion = temp;
break;
case -211:
negPion = temp;
break;
case 221:
etaMeson = temp;
break;
}
}
if( posPion && negPion && etaMeson) return kTRUE;
return kFALSE;
}
//_____________________________________________________________________________________
Bool_t AliAnalysisTaskNeutralMesonToPiPlPiMiNeutralMeson::GammaIsNeutralMesonPiPlPiMiNDMDaughter( Int_t label ) const {
//
// Returns true if the particle comes from eta -> pi+ pi- gamma
//
if(label<0) return kFALSE;
Int_t motherLabel = fMCEvent->Particle( label )->GetMother(0);
if( motherLabel < 0 || motherLabel >= fMCEvent->GetNumberOfTracks() ) return kFALSE;
TParticle* mother = fMCEvent->Particle( motherLabel );
if( mother->GetPdgCode() != fPDGCodeNDM ) return kFALSE;
Int_t grandMotherLabel = mother->GetMother(0);
if( grandMotherLabel < 0 || grandMotherLabel >= fMCEvent->GetNumberOfTracks() ) return kFALSE;
TParticle* grandmother = fMCEvent->Particle( grandMotherLabel );
switch( fSelectedHeavyNeutralMeson ) {
case 0: // ETA MESON
case 1: // OMEGA MESON
if( IsPiPlPiMiPiZeroDecay( grandmother ) ) return kTRUE;
break;
case 2: // ETA PRIME MESON
if( IsPiPlPiMiEtaDecay( grandmother ) ) return kTRUE;
break;
case 3: // D0 MESON
if( IsPiPlPiMiPiZeroDecay(grandmother) ) return kTRUE;
break;
default:
AliError(Form("Heavy neutral meson not correctly selected (only 0,1,2,3 valid)... selected: %d",fSelectedHeavyNeutralMeson));
}
return kFALSE;
}
//_____________________________________________________________________________________
Bool_t AliAnalysisTaskNeutralMesonToPiPlPiMiNeutralMeson::GammaIsNeutralMesonPiPlPiMiNDMDaughterAOD(TClonesArray* trackArray, Int_t label ) const {
//
// Returns true if the particle comes from eta -> pi+ pi- gamma
//
if(label<0) return kFALSE;
Int_t motherLabel = (static_cast<AliAODMCParticle*>(trackArray->At(label)))->GetMother();
if( motherLabel < 0 || motherLabel >= trackArray->GetEntriesFast()) return kFALSE;
AliAODMCParticle* mother = static_cast<AliAODMCParticle*>(trackArray->At(motherLabel));
if( mother->GetPdgCode() != fPDGCodeNDM ) return kFALSE;
Int_t grandMotherLabel = mother->GetMother();
if( grandMotherLabel < 0 || grandMotherLabel >= trackArray->GetEntriesFast()) return kFALSE;
AliAODMCParticle* grandmother = static_cast<AliAODMCParticle*>(trackArray->At(grandMotherLabel));
switch( fSelectedHeavyNeutralMeson ) {
case 0: // ETA MESON
case 1: // OMEGA MESON
if( IsPiPlPiMiPiZeroDecayAOD(trackArray, grandmother ) ) return kTRUE;
break;
case 2: // ETA PRIME MESON
if( IsPiPlPiMiEtaDecayAOD(trackArray, grandmother ) ) return kTRUE;
break;
case 3: // D0 MESON
if( IsPiPlPiMiPiZeroDecayAOD(trackArray, grandmother) ) return kTRUE;
break;
default:
AliError(Form("Heavy neutral meson not correctly selected (only 0,1,2,3 valid)... selected: %d",fSelectedHeavyNeutralMeson));
}
return kFALSE;
}
//_________________________________________________________________________________
Bool_t AliAnalysisTaskNeutralMesonToPiPlPiMiNeutralMeson::CheckVectorForDoubleCount(vector<Int_t> &vec, Int_t tobechecked)
{
if(tobechecked > -1)
{
vector<Int_t>::iterator it;
it = find (vec.begin(), vec.end(), tobechecked);
if (it != vec.end()) return true;
else{
vec.push_back(tobechecked);
return false;
}
}
return false;
}
//________________________________________________________________________
void AliAnalysisTaskNeutralMesonToPiPlPiMiNeutralMeson::RelabelAODPhotonCandidates(Bool_t mode){
// Relabeling For AOD Event
// ESDiD -> AODiD
// MCLabel -> AODMCLabel
if(mode){
fMCEventPos.Set(fReaderGammas->GetEntries());
fMCEventNeg.Set(fReaderGammas->GetEntries());
fESDArrayPos.Set(fReaderGammas->GetEntries());
fESDArrayNeg.Set(fReaderGammas->GetEntries());
}
for(Int_t iGamma = 0;iGamma<fReaderGammas->GetEntries();iGamma++){
AliAODConversionPhoton* PhotonCandidate = (AliAODConversionPhoton*) fReaderGammas->At(iGamma);
if(!PhotonCandidate) continue;
if(!mode){// Back to ESD Labels
PhotonCandidate->SetMCLabelPositive(fMCEventPos[iGamma]);
PhotonCandidate->SetMCLabelNegative(fMCEventNeg[iGamma]);
PhotonCandidate->SetLabelPositive(fESDArrayPos[iGamma]);
PhotonCandidate->SetLabelNegative(fESDArrayNeg[iGamma]);
continue;
}
fMCEventPos[iGamma] = PhotonCandidate->GetMCLabelPositive();
fMCEventNeg[iGamma] = PhotonCandidate->GetMCLabelNegative();
fESDArrayPos[iGamma] = PhotonCandidate->GetTrackLabelPositive();
fESDArrayNeg[iGamma] = PhotonCandidate->GetTrackLabelNegative();
Bool_t AODLabelPos = kFALSE;
Bool_t AODLabelNeg = kFALSE;
for(Int_t i = 0; i<fInputEvent->GetNumberOfTracks();i++){
AliAODTrack *tempDaughter = static_cast<AliAODTrack*>(fInputEvent->GetTrack(i));
if(!AODLabelPos){
if( tempDaughter->GetID() == PhotonCandidate->GetTrackLabelPositive() ){
PhotonCandidate->SetMCLabelPositive(TMath::Abs(tempDaughter->GetLabel()));
PhotonCandidate->SetLabelPositive(i);
AODLabelPos = kTRUE;
}
}
if(!AODLabelNeg){
if( tempDaughter->GetID() == PhotonCandidate->GetTrackLabelNegative()){
PhotonCandidate->SetMCLabelNegative(TMath::Abs(tempDaughter->GetLabel()));
PhotonCandidate->SetLabelNegative(i);
AODLabelNeg = kTRUE;
}
}
if(AODLabelNeg && AODLabelPos){
break;
}
}
if(!AODLabelPos || !AODLabelNeg){
cout<<"WARNING!!! AOD TRACKS NOT FOUND FOR"<<endl;
if(!AODLabelNeg){
PhotonCandidate->SetMCLabelNegative(-999999);
PhotonCandidate->SetLabelNegative(-999999);
}
if(!AODLabelPos){
PhotonCandidate->SetMCLabelPositive(-999999);
PhotonCandidate->SetLabelPositive(-999999);
}
}
}
}
//________________________________________________________________________
AliExternalTrackParam* AliAnalysisTaskNeutralMesonToPiPlPiMiNeutralMeson::GetConstrainedParameterAOD(const AliAODTrack* aodTr, const AliAODVertex* vtx, double bz)
{
double chi2;
AliExternalTrackParam* par = new AliExternalTrackParam();
par->CopyFromVTrack(aodTr);
double dz[2];
if (!par->PropagateToDCA(vtx,bz,999.,dz,0)) {
delete par;
chi2 = 1e9;
return 0;
}
Double_t covar[6]; vtx->GetCovarianceMatrix(covar);
Double_t p[2]= { par->GetParameter()[0]-dz[0], par->GetParameter()[1]-dz[1]};
Double_t c[3]= { covar[2],0.,covar[5] };
chi2 = par->GetPredictedChi2(p,c);
if (chi2>1e9 || !par->Update(p,c)) {
AliFatal(Form("Propagation failed with chi2 = %f",chi2));
delete par;
return 0;
}
return par;
}
//_____________________________________________________________________________
Double32_t AliAnalysisTaskNeutralMesonToPiPlPiMiNeutralMeson::CalculateP2(Double_t xyz[3],Double_t pxpypz[3])
{
//
// create external track parameters from the global parameters
// x,y,z,px,py,pz and their 6x6 covariance matrix
// A.Dainese 10.10.08
// Calculate alpha: the rotation angle of the corresponding local system.
//
// For global radial position inside the beam pipe, alpha is the
// azimuthal angle of the momentum projected on (x,y).
//
// For global radial position outside the ITS, alpha is the
// azimuthal angle of the centre of the TPC sector in which the point
// xyz lies
//
const double kSafe = 1e-5;
Double32_t p2;
Double32_t fAlpha;
Double_t radPos2 = xyz[0]*xyz[0]+xyz[1]*xyz[1];
Double_t radMax = 45.; // approximately ITS outer radius
if (radPos2 < radMax*radMax) { // inside the ITS
fAlpha = TMath::ATan2(pxpypz[1],pxpypz[0]);
} else { // outside the ITS
Float_t phiPos = TMath::Pi()+TMath::ATan2(-xyz[1], -xyz[0]);
fAlpha =
TMath::DegToRad()*(20*((((Int_t)(phiPos*TMath::RadToDeg()))/20))+10);
}
//
Double_t cs=TMath::Cos(fAlpha), sn=TMath::Sin(fAlpha);
// protection: avoid alpha being too close to 0 or +-pi/2
if (TMath::Abs(sn)<2*kSafe) {
if (fAlpha>0) fAlpha += fAlpha< TMath::Pi()/2. ? 2*kSafe : -2*kSafe;
else fAlpha += fAlpha>-TMath::Pi()/2. ? -2*kSafe : 2*kSafe;
cs=TMath::Cos(fAlpha);
sn=TMath::Sin(fAlpha);
}
else if (TMath::Abs(cs)<2*kSafe) {
if (fAlpha>0) fAlpha += fAlpha> TMath::Pi()/2. ? 2*kSafe : -2*kSafe;
else fAlpha += fAlpha>-TMath::Pi()/2. ? 2*kSafe : -2*kSafe;
cs=TMath::Cos(fAlpha);
sn=TMath::Sin(fAlpha);
}
// Get the vertex of origin and the momentum
TVector3 ver(xyz[0],xyz[1],xyz[2]);
TVector3 mom(pxpypz[0],pxpypz[1],pxpypz[2]);
//
// Rotate to the local coordinate system
ver.RotateZ(-fAlpha);
mom.RotateZ(-fAlpha);
//
// x of the reference plane
p2= TMath::Sin(mom.Phi());
//
if (TMath::Abs( 1-p2) < kSafe) p2= 1.- kSafe; //Protection
else if (TMath::Abs(-1-p2) < kSafe) p2=-1.+ kSafe; //Protection
return p2;
}
|
#include <functorch/csrc/CustomFunction.h>
#include <ATen/ATen.h>
#include <torch/csrc/autograd/function.h>
#include <torch/csrc/autograd/variable.h>
#include <torch/csrc/autograd/saved_variable.h>
#include <torch/csrc/autograd/FunctionsManual.h>
#include <torch/csrc/autograd/VariableTypeUtils.h>
#include <torch/csrc/autograd/generated/VariableType.h>
#include <torch/csrc/autograd/FunctionsManual.h>
namespace at { namespace functorch {
class PythonKernelHolder : public c10::OperatorKernel {
PyObject* func_;
public:
PythonKernelHolder(py::object func) : func_(func.release().ptr()) {}
// This is a generally useful pattern and safer than directly using pybind11's
// py::object destructor. This is because this object may outlive
// libtorch_python, so we want to disarm the deallocation if that happens.
// PyInterpreter does this correctly, pybind11 does not.
~PythonKernelHolder() {
getPyInterpreter()->decref(func_, /*is_tensor*/false);
}
void operator()(const c10::OperatorHandle& op, c10::DispatchKeySet, torch::jit::Stack* stack) {
const auto& schema = op.schema();
const auto num_returns = schema.returns().size();
const auto num_arguments = schema.arguments().size();
auto arguments = torch::jit::pop(*stack, num_arguments);
// TODO: Some duplication with torch/csrc/autograd/python_variable.cpp
py::gil_scoped_acquire g;
// Pre-scan for arguments that match defaults
int64_t default_suffix_len = 0;
for (int64_t idx = arguments.size() - 1; idx >= 0; idx--) {
const auto& arg = schema.arguments()[idx];
if (!arg.default_value().has_value()) {
break;
}
const auto& default_ivalue = *arg.default_value();
const auto& ivalue = arguments[idx];
if (default_ivalue != ivalue) {
break;
}
default_suffix_len++;
}
auto args = py::reinterpret_steal<py::object>(PyTuple_New(num_arguments - default_suffix_len));
// TODO: actually populate kwargs sometimes? At the moment, every argument
// // just gets passed positionally
py::dict kwargs;
for (int64_t idx = 0; idx < arguments.size() - default_suffix_len; idx++) {
PyTuple_SET_ITEM(args.ptr(), idx, torch::jit::toPyObject(std::move(arguments[idx])).release().ptr());
}
auto out = py::reinterpret_steal<py::object>(PyObject_Call(func_, args.ptr(), kwargs.ptr()));
if (out.ptr() == nullptr) {
throw python_error();
}
if (op.schema().returns().size() == 1) {
torch::jit::push(stack, torch::jit::toIValue(out.ptr(), op.schema().returns()[0].type()));
} else {
auto outs = py::cast<py::sequence>(out);
for (unsigned idx = 0; idx < outs.size(); idx++) {
torch::jit::push(stack, torch::jit::toIValue(outs[idx].ptr(), op.schema().returns()[idx].type()));
}
}
}
};
torch::Library::Kind parseKind(const std::string& k) {
static std::unordered_map<std::string, torch::Library::Kind> kind_map = {
{"DEF", torch::Library::DEF},
{"IMPL", torch::Library::IMPL},
{"FRAGMENT", torch::Library::FRAGMENT},
};
auto it = kind_map.find(k);
TORCH_CHECK(it != kind_map.end(), "could not parse ", k);
return it->second;
}
c10::AliasAnalysisKind parseAliasAnalysisKind(const std::string& k) {
static std::unordered_map<std::string, c10::AliasAnalysisKind> key_map = {
{"CONSERVATIVE", c10::AliasAnalysisKind::CONSERVATIVE},
{"FROM_SCHEMA", c10::AliasAnalysisKind::FROM_SCHEMA},
{"PURE_FUNCTION", c10::AliasAnalysisKind::PURE_FUNCTION},
{"", c10::AliasAnalysisKind::FROM_SCHEMA}, // default
};
auto it = key_map.find(k);
TORCH_CHECK(it != key_map.end(), "could not parse ", k);
return it->second;
}
template <typename Func>
inline torch::CppFunction dispatch_str(const char* key, Func&& raw_f) {
auto mb_key = std::string(key) == "" ? c10::nullopt : c10::make_optional(c10::parseDispatchKey(key));
if (mb_key) {
return torch::dispatch(*mb_key, std::forward<Func>(raw_f));
} else {
torch::CppFunction f(std::forward<Func>(raw_f));
return f;
}
}
std::vector<at::Tensor> unpack(at::TensorList tl, const char *name, int pos) {
std::vector<at::Tensor> ret(tl.size());
for (const auto i : c10::irange(tl.size())) {
const auto &t = tl[i];
if (!t.defined()) {
continue;
}
ret[i] = static_cast<const torch::autograd::Variable&>(t);
}
return ret;
}
std::vector<Tensor> invoke_backward_fn(
PyObject* backward_function,
TensorList grads,
TensorList intermediates) {
std::vector<Tensor> result;
py::gil_scoped_acquire g;
auto args = py::reinterpret_steal<py::object>(PyTuple_New(grads.size() + intermediates.size()));
py::dict kwargs;
for (int64_t idx = 0; idx < grads.size(); idx++) {
PyTuple_SET_ITEM(args.ptr(), idx, torch::jit::toPyObject(grads[idx]).release().ptr());
}
for (int64_t idx = 0; idx < intermediates.size(); idx++) {
PyTuple_SET_ITEM(args.ptr(), idx, torch::jit::toPyObject(intermediates[idx + grads.size()]).release().ptr());
}
auto out = py::reinterpret_steal<py::object>(PyObject_Call(backward_function, args.ptr(), kwargs.ptr()));
if (out.ptr() == nullptr) {
throw python_error();
}
for (unsigned idx = 0; idx < grads.size(); idx++) {
auto ivalue = torch::jit::toIValue(PyTuple_GetItem(out.ptr(), idx), TensorType::get());
result.push_back(ivalue.toTensor());
}
return result;
}
// TODO: figure out what this is
using torch::autograd::variable_list;
using custom_function_t = std::vector<Tensor> (at::TensorList);
void copy_range(variable_list& out, torch::autograd::IndexRange range, at::ArrayRef<Tensor> t) {
AT_ASSERT(range.second <= out.size());
std::cout << range.second << ", " << range.first << ", " << t.size() << std::endl;
AT_ASSERTM(range.second - range.first == t.size(), "inconsistent range for TensorList output");
std::copy(t.begin(), t.end(), out.begin() + range.first);
}
struct TORCH_API GenericPythonBackward : public torch::autograd::TraceableFunction {
using TraceableFunction::TraceableFunction;
variable_list apply(variable_list&& grads) override;
std::string name() const override { return "GenericPythonBackward"; }
void release_variables() override {
std::lock_guard<std::mutex> lock(mutex_);
for (auto& t : saved_tensors_) {
t.reset_data();
}
}
std::vector<torch::autograd::SavedVariable> saved_tensors_;
int64_t num_inputs_;
optional<c10::OperatorHandle> backward_fn_;
};
variable_list GenericPythonBackward::apply(variable_list&& grads) {
std::lock_guard<std::mutex> lock(mutex_);
torch::autograd::generated::details::IndexRangeGenerator gen;
auto tensors_ix = gen.range(saved_tensors_.size());
variable_list grad_inputs(num_inputs_);
std::vector<Tensor> args;
for (const auto& g : grads) {
args.push_back(g);
}
for (const auto& saved : saved_tensors_) {
args.push_back(saved.unpack(shared_from_this()));
}
if (should_compute_output({ tensors_ix })) {
auto handle = backward_fn_->typed<custom_function_t>();
auto grad_result = handle.call(args);
grad_inputs = grad_result;
// copy_range(grad_inputs, tensors_ix, grad_result);
}
return grad_inputs;
}
typedef TensorList (*custom_python_function_t)(TensorList);
using torch::autograd::compute_requires_grad;
using torch::autograd::collect_next_edges;
using torch::autograd::deleteNode;
using torch::autograd::flatten_tensor_args;
void customFunctionBoxed(const c10::OperatorHandle& op, torch::jit::Stack* stack) {
const auto& schema = op.schema();
const auto num_returns = schema.returns().size();
const auto num_arguments = schema.arguments().size();
const auto arguments = torch::jit::last(stack, num_arguments);
auto tensors = torch::jit::pop(stack).toTensorList().vec();
auto tensors_ = unpack(tensors, "tensors", 0);
auto _any_requires_grad = compute_requires_grad(tensors);
(void)_any_requires_grad;
std::string schema_name = op.schema().name();
std::string vjp_fn_name = schema_name + "_vjp";
auto vjp_fn = c10::Dispatcher::singleton()
.findSchemaOrThrow(vjp_fn_name.c_str(), "");
std::shared_ptr<GenericPythonBackward> grad_fn;
if (_any_requires_grad) {
grad_fn = std::shared_ptr<GenericPythonBackward>(new GenericPythonBackward(), deleteNode);
grad_fn->set_next_edges(collect_next_edges(tensors));
grad_fn->backward_fn_ = std::move(vjp_fn);
grad_fn->num_inputs_ = tensors_.size();
}
auto typed_handle = op.typed<custom_function_t>();
std::vector<Tensor> _tmp = ([&]() {
at::AutoDispatchBelowADInplaceOrView guard;
return typed_handle.call(tensors_);
})();
auto result = std::move(_tmp);
if (grad_fn) {
for (auto& tensor : result) {
// TODO: is this right?
bool is_input = false;
for (const auto& input : tensors_) {
if (tensor.unsafeGetTensorImpl() == input.unsafeGetTensorImpl()) {
is_input = true;
}
}
if (!is_input) {
set_history(tensor, grad_fn);
}
grad_fn->saved_tensors_.push_back(torch::autograd::SavedVariable(tensor, !is_input));
}
}
torch::jit::push(stack, result);
}
void initDispatchBindings(PyObject* module) {
auto m = py::handle(module).cast<py::module>();
py::class_<torch::Library>(m, "_DispatchModule", py::module_local())
.def("def_", [](py::object self, const char* schema, const char* alias) {
self.cast<torch::Library&>().def(torch::schema(schema, at::functorch::parseAliasAnalysisKind(alias)));
return self;
}, "", py::arg("schema"), py::arg("alias") = "")
.def("impl", [](py::object self, const char* name, const char* dispatch, py::object func) {
self.cast<torch::Library&>().impl(
name,
dispatch_str(dispatch, torch::CppFunction::makeFromBoxedFunctor(std::make_unique<at::functorch::PythonKernelHolder>(std::move(func))))
);
}, "", py::arg("name"), py::arg("dispatch"), py::arg("func"))
.def("gen_backward_binding", [](py::object self, const char* name, const char* dispatch) {
self.cast<torch::Library&>().impl(
name,
dispatch_str(dispatch,
torch::CppFunction::makeFromBoxedFunction<&customFunctionBoxed>())
);
}, "", py::arg("name"), py::arg("dispatch"))
.def("fallback_fallthrough", [](py::object self, const char* dispatch) {
self.cast<torch::Library&>().fallback(
dispatch_str(dispatch, torch::CppFunction::makeFallthrough())
);
return self;
}, "", py::arg("dispatch") = "")
;
m.def("_dispatch_library", [](const char* kind, std::string name, const char* dispatch) {
auto mb_key = std::string(dispatch) == "" ? c10::nullopt : c10::make_optional(c10::parseDispatchKey(dispatch) );
return std::make_unique<torch::Library>(parseKind(kind), std::move(name), mb_key, "/dev/null", 0);
});
}
}} // at::functorch
|
/*_############################################################################
_##
_## AGENT++ 4.0 - mib_proxy.cpp
_##
_## Copyright (C) 2000-2013 Frank Fock and Jochen Katz (agentpp.com)
_##
_## Licensed under the Apache License, Version 2.0 (the "License");
_## you may not use this file except in compliance with the License.
_## You may obtain a copy of the License at
_##
_## http://www.apache.org/licenses/LICENSE-2.0
_##
_## Unless required by applicable law or agreed to in writing, software
_## distributed under the License is distributed on an "AS IS" BASIS,
_## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
_## See the License for the specific language governing permissions and
_## limitations under the License.
_##
_##########################################################################*/
#include <libagent.h>
#include <agent_pp/mib_proxy.h>
#include <agent_pp/snmp_request.h>
#include <snmp_pp/log.h>
#ifndef _PROXY_FORWARDER
#ifdef AGENTPP_NAMESPACE
namespace Agentpp {
#endif
static const char *loggerModuleName = "agent++.mib_proxy";
//----------------------- MibProxy ------------------------------------
MibProxy::MibProxy(): MibEntry(), translating(FALSE)
{
community[READING] = "public";
community[WRITING] = "public";
}
MibProxy::MibProxy(const MibProxy& other)
{
oid = other.oid;
access = other.access;
ListCursor<MibEntry> cur;
for (cur.init(&other.notifies); cur.get(); cur.next())
notifies.add(cur.get());
source = other.source;
translation = other.translation;
translating = other.translating;
range = other.range;
for (int i=0; i<WRITING; i++)
community[i] = other.community[i];
}
MibProxy::MibProxy(const Oidx& o,
mib_access a,
const UdpAddress& src): MibEntry(o, a),
source(src), translating(FALSE)
{
community[READING] = "public";
community[WRITING] = "public";
determineDefaultRange(o);
}
MibProxy::MibProxy(const Oidx& o,
mib_access a,
const Oidx& trans,
const UdpAddress& src): MibEntry(o, a),
source(src),
translation(trans),
translating(TRUE)
{
community[READING] = "public";
community[WRITING] = "public";
determineDefaultRange(o);
}
void MibProxy::determineDefaultRange(const Oidx& o)
{
range = o;
range[range.len()-1] += 1;
}
OidxPtr MibProxy::max_key()
{
return ⦥
}
Oidx MibProxy::translate(const Oidx& o)
{
if (translating) {
Oidx retval(translation);
for (unsigned int i=translation.len(); i<o.len(); i++) {
retval += o[i];
}
return retval;
}
return o;
}
Oidx MibProxy::backward_translate(const Oidx& o)
{
if (translating) {
Oidx retval(oid);
for (unsigned int i=translation.len(); i<o.len(); i++) {
retval += o[i];
}
return retval;
}
return o;
}
void MibProxy::get_request(Request* req, int reqind)
{
Vbx vb;
int status, errind;
if (get_access() >= READONLY) {
vb.set_oid(translate(req->get_oid(reqind)));
LOG_BEGIN(loggerModuleName, INFO_LOG | 3);
LOG("MibProxy: get: contacting agent: oid");
LOG(source.get_printable());
LOG(vb.get_printable_oid());
LOG_END;
status = SnmpRequest::get(source, &vb, 1, errind,
community[READING]);
LOG_BEGIN(loggerModuleName, INFO_LOG | 3);
LOG("MibProxy: agent contacted: source, oid, value, status");
LOG(source.get_printable());
LOG(vb.get_printable_oid());
LOG(vb.get_printable_value());
LOG(status);
LOG_END;
vb.set_oid(backward_translate(vb.get_oid()));
if (status < 0) status = SNMP_ERROR_RESOURCE_UNAVAIL;
if (status == SNMP_ERROR_SUCCESS)
Mib::requestList->done(req->get_transaction_id(),
reqind, vb);
else
Mib::requestList->error(req->get_transaction_id(),
reqind, status);
}
else
Mib::requestList->error(req->get_transaction_id(),
reqind, SNMP_ERROR_NO_ACCESS);
}
/**
* Find next proxied oid. This method must be called at least once
* before calling get_next_request, because find_next cashes the
* retreived values for get_next_request.
*
* @param id
* a oid for which its successor is searched for
* @return
* the successor within this proxied oid tree or an empty oid otherwise
*/
Oidx MibProxy::find_succ(const Oidx& id, Request*)
{
int status, errind;
// todo: initialize status for last else **************
if (get_access() >= READONLY) {
Oidx tmpoid;
// skip oids less than this proxied subtree
if (id < oid) {
tmpoid = oid;
}
else {
tmpoid = id;
}
lastNext.set_oid(translate(tmpoid));
LOG_BEGIN(loggerModuleName, INFO_LOG | 3);
LOG("MibProxy: find_next: contacting agent (proxy oid) (src) (oid)");
LOG(oid.get_printable());
LOG(source.get_printable());
LOG(lastNext.get_printable_oid());
LOG_END;
status = SnmpRequest::next(source, &lastNext, 1, errind,
community[READING]);
LOG_BEGIN(loggerModuleName, INFO_LOG | 3);
LOG("MibProxy: agent contacted: source, oid, value, status");
LOG(source.get_printable());
LOG(lastNext.get_printable_oid());
LOG(lastNext.get_printable_value());
LOG(status);
LOG_END;
lastNextStatus = status;
if ((status == SNMP_ERROR_SUCCESS) &&
(lastNext.get_oid().in_subtree_of(((translating) ?
translation : oid)))) {
return backward_translate(lastNext.get_oid());
}
}
return Oidx();
}
void MibProxy::get_next_request(Request* req, int reqind)
{
if (get_access() >= READONLY) {
lastNext.set_oid(backward_translate(lastNext.get_oid()));
LOG_BEGIN(loggerModuleName, DEBUG_LOG | 5);
LOG("MibProxy: get_next_request: returning: oid, value, status");
LOG(lastNext.get_printable_oid());
LOG(lastNext.get_printable_value());
LOG(lastNextStatus);
LOG_END;
if (lastNextStatus != SNMP_ERROR_SUCCESS)
Mib::requestList->error(req->get_transaction_id(),
reqind, lastNextStatus);
else
Mib::requestList->done(req->get_transaction_id(),
reqind, lastNext);
}
else
Mib::requestList->error(req->get_transaction_id(),
reqind, SNMP_ERROR_NO_ACCESS);
}
int MibProxy::prepare_set_request(Request*, int&)
{
if (get_access() >= READWRITE) {
return SNMP_ERROR_SUCCESS;
}
return SNMP_ERROR_NO_ACCESS;
}
int MibProxy::commit_set_request(Request* req, int reqind)
{
int status, errind;
Vbx vb(req->get_value(reqind));
vb.set_oid(translate(req->get_oid(reqind)));
LOG_BEGIN(loggerModuleName, INFO_LOG | 3);
LOG("MibProxy: set: contacting agent");
LOG(source.get_printable());
LOG(vb.get_printable_oid());
LOG_END;
status = SnmpRequest::set(source, &vb, 1, errind,
community[WRITING]);
LOG_BEGIN(loggerModuleName, INFO_LOG | 3);
LOG("MibProxy: agent contacted: source, oid, value, status");
LOG(source.get_printable());
LOG(vb.get_printable_oid());
LOG(vb.get_printable_value());
LOG(status);
LOG_END;
vb.set_oid(backward_translate(vb.get_oid()));
if (status != SNMP_ERROR_SUCCESS) {
Mib::requestList->error(req->get_transaction_id(), errind, status);
return SNMP_ERROR_COMITFAIL;
}
else
Mib::requestList->done(req->get_transaction_id(), errind, vb);
return SNMP_ERROR_SUCCESS;
}
#ifdef _SNMPv3
//----------------------- MibProxyV3 ------------------------------------
MibProxyV3::MibProxyV3(const Oidx& o, mib_access a): MibEntry(o, a)
{
myProxyInfo = snmpProxyEntry::instance;
determineDefaultRange(o);
check_references();
}
MibProxyV3::MibProxyV3(const MibProxyV3& other)
{
oid = other.oid;
access = other.access;
ListCursor<MibEntry> cur;
for (cur.init(&other.notifies); cur.get(); cur.next())
notifies.add(cur.get());
range = other.range;
myProxyInfo = other.myProxyInfo;
}
MibProxyV3::MibProxyV3(snmpProxyEntry* proxyInfo,
const Oidx& o,
mib_access a): MibEntry(o, a)
{
determineDefaultRange(o);
myProxyInfo = proxyInfo;
check_references();
}
void MibProxyV3::check_references()
{
if ((!myProxyInfo) || (!snmpTargetParamsEntry::instance) ||
(!snmpTargetAddrEntry::instance)) {
LOG_BEGIN(loggerModuleName, ERROR_LOG | 0);
LOG("MibProxyV3: internal error: need SNMP-PROXY- and SNMP-TARGET-MIB.");
LOG_END;
}
}
void MibProxyV3::determineDefaultRange(const Oidx& o)
{
range = o;
range[range.len()-1] += 1;
}
OidxPtr MibProxyV3::max_key()
{
return ⦥
}
OidList<MibTableRow>* MibProxyV3::get_matches(Request* req)
{
List<MibTableRow>* list = myProxyInfo->get_rows_cloned(TRUE);
OidList<MibTableRow>* matches = new OidList<MibTableRow>;
ListCursor<MibTableRow> cur;
for (cur.init(list); cur.get(); cur.next()) {
int type = req->get_type();
int state = 0;
cur.get()->get_nth(0)->get_value(state);
OctetStr contextID, contextName, paramsIn;
if ((!(((type == sNMP_PDU_GET) ||
(type == sNMP_PDU_GETNEXT) ||
(type == sNMP_PDU_GETBULK)) && (state == 1))) &&
(!((type == sNMP_PDU_SET) && (state == 2))) &&
(!(((type == sNMP_PDU_TRAP) ||
(type == sNMP_PDU_V1TRAP)) && (state == 3))) &&
(!((type == sNMP_PDU_INFORM) && (state == 4))))
continue;
LOG_BEGIN(loggerModuleName, DEBUG_LOG | 6);
LOG("MibProxyV3: matched proxy (pdu type)(type)");
LOG(type);
LOG(state);
LOG_END;
cur.get()->get_nth(1)->get_value(contextID);
cur.get()->get_nth(2)->get_value(contextName);
cur.get()->get_nth(3)->get_value(paramsIn);
OctetStr cid;
req->get_pdu()->get_context_engine_id(cid);
LOG_BEGIN(loggerModuleName, DEBUG_LOG | 6);
LOG("MibProxyV3: matching (context engine id)(match)");
LOG(cid.get_printable());
LOG(cid.len());
LOG(contextID.get_printable());
LOG(contextID.len());
LOG_END;
if (cid != contextID)
continue;
LOG_BEGIN(loggerModuleName, DEBUG_LOG | 6);
LOG("MibProxyV3: matched (context name)(match)");
LOG(req->get_pdu()->get_context_name().get_printable());
LOG(contextName.get_printable());
LOG_END;
OctetStr cname;
req->get_pdu()->get_context_name(cname);
if (cname != contextName)
continue;
if (!match_target_params(req, paramsIn))
continue;
matches->add(cur.get()->clone());
}
delete list;
return matches;
}
bool MibProxyV3::match_target_params(Request* req,
const OctetStr& paramsIn)
{
snmpTargetParamsEntry::instance->start_synch();
MibTableRow* paramsRow =
snmpTargetParamsEntry::instance->
find_index(Oidx::from_string(paramsIn, FALSE));
if ((!paramsRow) ||
(paramsRow->get_row_status()->get() != rowActive)) {
snmpTargetParamsEntry::instance->end_synch();
LOG_BEGIN(loggerModuleName, WARNING_LOG | 3);
LOG("MibProxyV3: target addr parameter (row) not found.");
LOG(OctetStr(paramsIn).get_printable());
LOG((paramsRow) ? "no active row found" :
"missing row");
LOG_END;
return FALSE;
}
int secModel, secLevel, mpModel;
OctetStr secName;
paramsRow->get_nth(0)->get_value(mpModel);
paramsRow->get_nth(1)->get_value(secModel);
paramsRow->get_nth(2)->get_value(secName);
paramsRow->get_nth(3)->get_value(secLevel);
snmpTargetParamsEntry::instance->end_synch();
LOG_BEGIN(loggerModuleName, DEBUG_LOG | 6);
LOG("MibProxyV3: matching (MPModel)(match)(secModel)(match)(secLevel)(match)");
LOG(req->get_address()->get_version());
LOG(mpModel);
LOG(req->get_address()->get_security_model());
LOG(secModel);
LOG(req->get_pdu()->get_security_level());
LOG(secLevel);
LOG_END;
if ((req->get_address()->get_version() == version1) &&
(mpModel != 0))
return FALSE;
if ((req->get_address()->get_version() == version2c) &&
(mpModel != 1))
return FALSE;
if ((req->get_address()->get_version() == version3) &&
(mpModel != 3))
return FALSE;
OctetStr sname;
req->get_address()->get_security_name(sname);
LOG_BEGIN(loggerModuleName, DEBUG_LOG | 6);
LOG("MibProxyV3: matching (secName)(match)");
LOG(sname.get_printable());
LOG(secName.get_printable());
LOG_END;
if (sname != secName)
return FALSE;
if ((secModel != 0) &&
(req->get_address()->get_security_model() != secModel))
return FALSE;
if (req->get_pdu()->get_security_level() != secLevel)
return FALSE;
return TRUE;
}
void MibProxyV3::get_request(Request* req, int reqind)
{
Vbx vb(req->get_value(reqind));
Pdux pdu;
int status;
pdu.set_type(sNMP_PDU_GET);
pdu.set_request_id(req->get_request_id());
if (get_access() >= READONLY) {
pdu += vb;
status = process_single(pdu, req);
pdu.get_vb(vb, 0);
LOG_BEGIN(loggerModuleName, INFO_LOG | 3);
LOG("MibProxyV3: agent contacted: (oid), (value), (status)");
LOG(vb.get_printable_oid());
LOG(vb.get_printable_value());
LOG(status);
LOG_END;
if (status < 0) status = SNMP_ERROR_RESOURCE_UNAVAIL;
if (status == SNMP_ERROR_SUCCESS)
Mib::requestList->done(req->get_transaction_id(),
reqind, vb);
else
Mib::requestList->error(req->get_transaction_id(),
reqind, status);
}
else
Mib::requestList->error(req->get_transaction_id(),
reqind, SNMP_ERROR_NO_ACCESS);
}
/**
* Find next proxied oid. This method must be called at least once
* before calling get_next_request, because find_next cashes the
* retreived values for get_next_request.
*
* @param id
* a oid for which its successor is searched for
* @return
* the successor within this proxied oid tree or an empty oid otherwise
*/
Oidx MibProxyV3::find_succ(const Oidx& id, Request* req)
{
if (!req) return Oidx();
Pdux pdu;
int status;
pdu.set_type(sNMP_PDU_GETNEXT);
pdu.set_request_id(req->get_request_id());
pdu.set_context_engine_id(req->get_pdu()->get_context_engine_id());
pdu.set_context_name(req->get_context());
if (get_access() >= READONLY) {
Oidx tmpoid;
// skip oids less than this proxied subtree
if (id < oid) {
tmpoid = oid;
}
else {
tmpoid = id;
}
lastNext.set_oid(tmpoid);
pdu += lastNext;
status = process_single(pdu, req);
pdu.get_vb(lastNext, 0);
lastNextStatus = status;
if ((status == SNMP_ERROR_SUCCESS) &&
(lastNext.get_oid().in_subtree_of(oid))) {
return lastNext.get_oid();
}
}
return Oidx();
}
void MibProxyV3::get_next_request(Request* req, int reqind)
{
if (get_access() >= READONLY) {
LOG_BEGIN(loggerModuleName, DEBUG_LOG | 5);
LOG("MibProxyV3: next: returning: oid, value, status");
LOG(lastNext.get_printable_oid());
LOG(lastNext.get_printable_value());
LOG(lastNextStatus);
LOG_END;
if (lastNextStatus != SNMP_ERROR_SUCCESS)
Mib::requestList->error(req->get_transaction_id(),
reqind, lastNextStatus);
else
Mib::requestList->done(req->get_transaction_id(),
reqind, lastNext);
}
else
Mib::requestList->error(req->get_transaction_id(),
reqind, SNMP_ERROR_NO_ACCESS);
}
int MibProxyV3::prepare_set_request(Request*, int&)
{
if (get_access() >= READWRITE) {
return SNMP_ERROR_SUCCESS;
}
return SNMP_ERROR_NO_ACCESS;
}
int MibProxyV3::commit_set_request(Request* req, int reqind)
{
Vbx vb(req->get_value(reqind));
Pdux pdu;
int status;
pdu.set_type(sNMP_PDU_SET);
pdu.set_request_id(req->get_request_id());
pdu += vb;
status = process_single(pdu, req);
pdu.get_vb(vb, 0);
if (status == sNMP_SYNTAX_NOSUCHOBJECT) {
status = SNMP_ERROR_SUCCESS;
vb.set_syntax(sNMP_SYNTAX_NOSUCHOBJECT);
}
if (status < 0) status = SNMP_ERROR_RESOURCE_UNAVAIL;
if (status == SNMP_ERROR_SUCCESS)
Mib::requestList->done(req->get_transaction_id(), reqind, vb);
else
Mib::requestList->error(req->get_transaction_id(),
reqind, status);
return status;
}
int MibProxyV3::process_single(Pdux& pdu, Request* req)
{
OidList<MibTableRow>* matches = get_matches(req);
if (!matches) return sNMP_SYNTAX_NOSUCHOBJECT;
MibTableRow* match = matches->first();
if (!match) {
LOG_BEGIN(loggerModuleName, INFO_LOG | 3);
LOG("MibProxyV3: no matching proxy entry");
LOG_END;
return sNMP_SYNTAX_NOSUCHOBJECT;
}
OctetStr out;
match->get_nth(4)->get_value(out);
int secLevel = 0;
UTarget* target =
snmpTargetAddrEntry::instance->
get_target(out, snmpTargetParamsEntry::instance, secLevel);
if (!target) {
LOG_BEGIN(loggerModuleName, INFO_LOG | 3);
LOG("MibProxyV3: no matching single out address entry");
LOG_END;
return sNMP_SYNTAX_NOSUCHOBJECT;
}
pdu.set_security_level(secLevel);
GenAddress addr;
target->get_address(addr);
LOG_BEGIN(loggerModuleName, INFO_LOG | 3);
LOG("MibProxyV3: get: contacting agent (address)(secName)(secLevel)(context)(contextEngineID)");
LOG(addr.get_printable());
LOG(target->get_security_name().get_printable());
LOG(secLevel);
LOG(pdu.get_context_name().get_printable());
LOG(pdu.get_context_engine_id().get_printable());
LOG_END;
int status = SnmpRequestV3::send(*target, pdu);
delete target;
Vbx vb;
pdu.get_vb(vb, 0);
LOG_BEGIN(loggerModuleName, INFO_LOG | 3);
LOG("MibProxyV3: agent contacted: (oid), (value), (status)");
LOG(vb.get_printable_oid());
LOG(vb.get_printable_value());
LOG(status);
LOG_END;
return status;
}
#endif // _SNMPv3
#ifdef AGENTPP_NAMESPACE
}
#endif
#endif // _PROXY_FORWARDER
|
/****************************************************************************
*
* Copyright (c) 2013-2020 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
/**
* @file mag_calibration.cpp
*
* Magnetometer calibration routine
*/
#include "mag_calibration.h"
#include "commander_helper.h"
#include "calibration_routines.h"
#include "lm_fit.hpp"
#include "calibration_messages.h"
#include "factory_calibration_storage.h"
#include <px4_platform_common/defines.h>
#include <px4_platform_common/posix.h>
#include <px4_platform_common/time.h>
#include <drivers/drv_hrt.h>
#include <drivers/drv_tone_alarm.h>
#include <matrix/math.hpp>
#include <lib/sensor_calibration/Magnetometer.hpp>
#include <lib/sensor_calibration/Utilities.hpp>
#include <lib/conversion/rotation.h>
#include <lib/ecl/geo_lookup/geo_mag_declination.h>
#include <lib/systemlib/mavlink_log.h>
#include <lib/parameters/param.h>
#include <lib/systemlib/err.h>
#include <uORB/Subscription.hpp>
#include <uORB/SubscriptionBlocking.hpp>
#include <uORB/SubscriptionMultiArray.hpp>
#include <uORB/topics/sensor_mag.h>
#include <uORB/topics/sensor_gyro.h>
#include <uORB/topics/vehicle_attitude.h>
#include <uORB/topics/vehicle_gps_position.h>
#include <uORB/topics/mag_worker_data.h>
using namespace matrix;
using namespace time_literals;
static constexpr char sensor_name[] {"mag"};
static constexpr int MAX_MAGS = 4;
static constexpr float MAG_SPHERE_RADIUS_DEFAULT = 0.2f;
static constexpr unsigned int calibration_total_points = 240; ///< The total points per magnetometer
static constexpr unsigned int calibraton_duration_s = 42; ///< The total duration the routine is allowed to take
calibrate_return mag_calibrate_all(orb_advert_t *mavlink_log_pub, int32_t cal_mask);
/// Data passed to calibration worker routine
struct mag_worker_data_t {
orb_advert_t *mavlink_log_pub;
orb_advert_t mag_worker_data_pub;
bool append_to_existing_calibration;
unsigned last_mag_progress;
unsigned done_count;
unsigned calibration_sides; ///< The total number of sides
bool side_data_collected[detect_orientation_side_count];
unsigned int calibration_points_perside;
uint64_t calibration_interval_perside_us;
unsigned int calibration_counter_total[MAX_MAGS];
float *x[MAX_MAGS];
float *y[MAX_MAGS];
float *z[MAX_MAGS];
calibration::Magnetometer calibration[MAX_MAGS] {};
};
int do_mag_calibration(orb_advert_t *mavlink_log_pub)
{
calibration_log_info(mavlink_log_pub, CAL_QGC_STARTED_MSG, sensor_name);
int result = PX4_OK;
// Collect: As defined by configuration
// start with a full mask, all six bits set
int32_t cal_mask = (1 << 6) - 1;
param_get(param_find("CAL_MAG_SIDES"), &cal_mask);
// Calibrate all mags at the same time
if (result == PX4_OK) {
switch (mag_calibrate_all(mavlink_log_pub, cal_mask)) {
case calibrate_return_cancelled:
// Cancel message already displayed, we're done here
result = PX4_ERROR;
break;
case calibrate_return_ok:
/* if there is a any preflight-check system response, let the barrage of messages through */
px4_usleep(200000);
calibration_log_info(mavlink_log_pub, CAL_QGC_PROGRESS_MSG, 100);
px4_usleep(20000);
calibration_log_info(mavlink_log_pub, CAL_QGC_DONE_MSG, sensor_name);
px4_usleep(20000);
break;
default:
calibration_log_critical(mavlink_log_pub, CAL_QGC_FAILED_MSG, sensor_name);
px4_usleep(20000);
break;
}
}
/* give this message enough time to propagate */
px4_usleep(600000);
return result;
}
static bool reject_sample(float sx, float sy, float sz, float x[], float y[], float z[], unsigned count,
unsigned max_count, float mag_sphere_radius)
{
float min_sample_dist = fabsf(5.4f * mag_sphere_radius / sqrtf(max_count)) / 3.0f;
for (size_t i = 0; i < count; i++) {
float dx = sx - x[i];
float dy = sy - y[i];
float dz = sz - z[i];
float dist = sqrtf(dx * dx + dy * dy + dz * dz);
if (dist < min_sample_dist) {
PX4_DEBUG("rejected X: %.3f Y: %.3f Z: %.3f (%.3f < %.3f) (%d/%d) ", (double)sx, (double)sy, (double)sz, (double)dist,
(double)min_sample_dist, count, max_count);
return true;
}
}
return false;
}
static unsigned progress_percentage(mag_worker_data_t *worker_data)
{
return 100 * ((float)worker_data->done_count) / worker_data->calibration_sides;
}
// Returns calibrate_return_error if any parameter is not finite
// Logs if parameters are out of range
static calibrate_return check_calibration_result(float offset_x, float offset_y, float offset_z,
float sphere_radius,
float diag_x, float diag_y, float diag_z,
float offdiag_x, float offdiag_y, float offdiag_z,
orb_advert_t *mavlink_log_pub, uint8_t cur_mag)
{
float must_be_finite[] = {offset_x, offset_y, offset_z,
sphere_radius,
diag_x, diag_y, diag_z,
offdiag_x, offdiag_y, offdiag_z
};
float should_be_not_huge[] = {offset_x, offset_y, offset_z};
float should_be_positive[] = {sphere_radius, diag_x, diag_y, diag_z};
// Make sure every parameter is finite
const int num_finite = sizeof(must_be_finite) / sizeof(*must_be_finite);
for (unsigned i = 0; i < num_finite; ++i) {
if (!PX4_ISFINITE(must_be_finite[i])) {
calibration_log_emergency(mavlink_log_pub, "Retry calibration (sphere NaN, %u)", cur_mag);
return calibrate_return_error;
}
}
// earth field between 0.25 and 0.65 Gauss
if (sphere_radius < 0.2f || sphere_radius >= 0.7f) {
calibration_log_emergency(mavlink_log_pub, "Retry calibration (mag %u sphere radius invalid %.3f)", cur_mag,
(double)sphere_radius);
return calibrate_return_error;
}
// Notify if a parameter which should be positive is non-positive
const int num_positive = sizeof(should_be_positive) / sizeof(*should_be_positive);
for (unsigned i = 0; i < num_positive; ++i) {
if (should_be_positive[i] <= 0.0f) {
calibration_log_emergency(mavlink_log_pub, "Retry calibration (mag %u with non-positive scale)", cur_mag);
return calibrate_return_error;
}
}
// Notify if offsets are too large
const int num_not_huge = sizeof(should_be_not_huge) / sizeof(*should_be_not_huge);
for (unsigned i = 0; i < num_not_huge; ++i) {
// maximum measurement range is ~1.9 Ga, the earth field is ~0.6 Ga,
// so an offset larger than ~1.3 Ga means the mag will saturate in some directions.
static constexpr float MAG_MAX_OFFSET_LEN = 1.3f;
if (fabsf(should_be_not_huge[i]) > MAG_MAX_OFFSET_LEN) {
calibration_log_critical(mavlink_log_pub, "Warning: mag %u with large offsets", cur_mag);
break;
}
}
return calibrate_return_ok;
}
static float get_sphere_radius()
{
// if GPS is available use real field intensity from world magnetic model
uORB::SubscriptionMultiArray<vehicle_gps_position_s, 3> gps_subs{ORB_ID::vehicle_gps_position};
for (auto &gps_sub : gps_subs) {
vehicle_gps_position_s gps;
if (gps_sub.copy(&gps)) {
if (hrt_elapsed_time(&gps.timestamp) < 100_s && (gps.fix_type >= 2) && (gps.eph < 1000)) {
const double lat = gps.lat / 1.e7;
const double lon = gps.lon / 1.e7;
// magnetic field data returned by the geo library using the current GPS position
return get_mag_strength_gauss(lat, lon);
}
}
}
return MAG_SPHERE_RADIUS_DEFAULT;
}
static calibrate_return mag_calibration_worker(detect_orientation_return orientation, void *data)
{
const hrt_abstime calibration_started = hrt_absolute_time();
calibrate_return result = calibrate_return_ok;
mag_worker_data_t *worker_data = (mag_worker_data_t *)(data);
float mag_sphere_radius = get_sphere_radius();
// notify user to start rotating
set_tune(tune_control_s::TUNE_ID_SINGLE_BEEP);
calibration_log_info(worker_data->mavlink_log_pub, "[cal] Rotate vehicle");
/*
* Detect if the system is rotating.
*
* We're detecting this as a general rotation on any axis, not necessary on the one we
* asked the user for. This is because we really just need two roughly orthogonal axes
* for a good result, so we're not constraining the user more than we have to.
*/
const hrt_abstime detection_deadline = hrt_absolute_time() + worker_data->calibration_interval_perside_us * 5;
hrt_abstime last_gyro = 0;
float gyro_x_integral = 0.0f;
float gyro_y_integral = 0.0f;
float gyro_z_integral = 0.0f;
static constexpr float gyro_int_thresh_rad = 0.5f;
uORB::SubscriptionBlocking<sensor_gyro_s> gyro_sub{ORB_ID(sensor_gyro)};
while (fabsf(gyro_x_integral) < gyro_int_thresh_rad &&
fabsf(gyro_y_integral) < gyro_int_thresh_rad &&
fabsf(gyro_z_integral) < gyro_int_thresh_rad) {
/* abort on request */
if (calibrate_cancel_check(worker_data->mavlink_log_pub, calibration_started)) {
result = calibrate_return_cancelled;
return result;
}
/* abort with timeout */
if (hrt_absolute_time() > detection_deadline) {
result = calibrate_return_error;
PX4_ERR("gyro int: %8.4f, %8.4f, %8.4f", (double)gyro_x_integral, (double)gyro_y_integral, (double)gyro_z_integral);
calibration_log_critical(worker_data->mavlink_log_pub, "Failed: This calibration requires rotation.");
break;
}
/* Wait clocking for new data on all gyro */
sensor_gyro_s gyro;
if (gyro_sub.updateBlocking(gyro, 1000_ms)) {
/* ensure we have a valid first timestamp */
if (last_gyro > 0) {
/* integrate */
float delta_t = (gyro.timestamp - last_gyro) / 1e6f;
gyro_x_integral += gyro.x * delta_t;
gyro_y_integral += gyro.y * delta_t;
gyro_z_integral += gyro.z * delta_t;
}
last_gyro = gyro.timestamp;
}
}
uORB::SubscriptionBlocking<sensor_mag_s> mag_sub[MAX_MAGS] {
{ORB_ID(sensor_mag), 0, 0},
{ORB_ID(sensor_mag), 0, 1},
{ORB_ID(sensor_mag), 0, 2},
{ORB_ID(sensor_mag), 0, 3},
};
uint64_t calibration_deadline = hrt_absolute_time() + worker_data->calibration_interval_perside_us;
unsigned poll_errcount = 0;
unsigned calibration_counter_side = 0;
while (hrt_absolute_time() < calibration_deadline &&
calibration_counter_side < worker_data->calibration_points_perside) {
if (calibrate_cancel_check(worker_data->mavlink_log_pub, calibration_started)) {
result = calibrate_return_cancelled;
break;
}
if (mag_sub[0].updatedBlocking(1000_ms)) {
bool rejected = false;
Vector3f new_samples[MAX_MAGS] {};
for (uint8_t cur_mag = 0; cur_mag < MAX_MAGS; cur_mag++) {
if (worker_data->calibration[cur_mag].device_id() != 0) {
bool updated = false;
sensor_mag_s mag;
while (mag_sub[cur_mag].update(&mag)) {
if (worker_data->append_to_existing_calibration) {
// keep and update the existing calibration when we are not doing a full 6-axis calibration
const Matrix3f &scale = worker_data->calibration[cur_mag].scale();
const Vector3f &offset = worker_data->calibration[cur_mag].offset();
const Vector3f m{scale *(Vector3f{mag.x, mag.y, mag.z} - offset)};
mag.x = m(0);
mag.y = m(1);
mag.z = m(2);
}
// Check if this measurement is good to go in
bool reject = reject_sample(mag.x, mag.y, mag.z,
worker_data->x[cur_mag], worker_data->y[cur_mag], worker_data->z[cur_mag],
worker_data->calibration_counter_total[cur_mag],
worker_data->calibration_sides * worker_data->calibration_points_perside,
mag_sphere_radius);
if (!reject) {
new_samples[cur_mag] = Vector3f{mag.x, mag.y, mag.z};
updated = true;
break;
}
}
// require an update for all valid mags
if (!updated) {
rejected = true;
}
}
}
// Keep calibration of all mags in lockstep
if (!rejected) {
for (uint8_t cur_mag = 0; cur_mag < MAX_MAGS; cur_mag++) {
if (worker_data->calibration[cur_mag].device_id() != 0) {
worker_data->x[cur_mag][worker_data->calibration_counter_total[cur_mag]] = new_samples[cur_mag](0);
worker_data->y[cur_mag][worker_data->calibration_counter_total[cur_mag]] = new_samples[cur_mag](1);
worker_data->z[cur_mag][worker_data->calibration_counter_total[cur_mag]] = new_samples[cur_mag](2);
worker_data->calibration_counter_total[cur_mag]++;
}
}
hrt_abstime now = hrt_absolute_time();
mag_worker_data_s status;
status.timestamp = now;
status.timestamp_sample = now;
status.done_count = worker_data->done_count;
status.calibration_points_perside = worker_data->calibration_points_perside;
status.calibration_interval_perside_us = worker_data->calibration_interval_perside_us;
for (size_t cur_mag = 0; cur_mag < MAX_MAGS; cur_mag++) {
status.calibration_counter_total[cur_mag] = worker_data->calibration_counter_total[cur_mag];
status.side_data_collected[cur_mag] = worker_data->side_data_collected[cur_mag];
if (worker_data->calibration[cur_mag].device_id() != 0) {
const unsigned int sample = worker_data->calibration_counter_total[cur_mag] - 1;
status.x[cur_mag] = worker_data->x[cur_mag][sample];
status.y[cur_mag] = worker_data->y[cur_mag][sample];
status.z[cur_mag] = worker_data->z[cur_mag][sample];
} else {
status.x[cur_mag] = 0.f;
status.y[cur_mag] = 0.f;
status.z[cur_mag] = 0.f;
}
}
if (worker_data->mag_worker_data_pub == nullptr) {
worker_data->mag_worker_data_pub = orb_advertise(ORB_ID(mag_worker_data), &status);
} else {
orb_publish(ORB_ID(mag_worker_data), worker_data->mag_worker_data_pub, &status);
}
calibration_counter_side++;
unsigned new_progress = progress_percentage(worker_data) +
(unsigned)((100 / worker_data->calibration_sides) * ((float)calibration_counter_side / (float)
worker_data->calibration_points_perside));
if (new_progress - worker_data->last_mag_progress > 0) {
// Progress indicator for side
calibration_log_info(worker_data->mavlink_log_pub,
"[cal] %s side calibration: progress <%u>",
detect_orientation_str(orientation), new_progress);
px4_usleep(10000);
worker_data->last_mag_progress = new_progress;
}
}
PX4_DEBUG("side counter %d / %d", calibration_counter_side, worker_data->calibration_points_perside);
} else {
poll_errcount++;
}
if (poll_errcount > worker_data->calibration_points_perside * 3) {
result = calibrate_return_error;
calibration_log_info(worker_data->mavlink_log_pub, CAL_ERROR_SENSOR_MSG);
break;
}
}
if (result == calibrate_return_ok) {
calibration_log_info(worker_data->mavlink_log_pub, "[cal] %s side done, rotate to a different side",
detect_orientation_str(orientation));
worker_data->done_count++;
px4_usleep(20000);
calibration_log_info(worker_data->mavlink_log_pub, CAL_QGC_PROGRESS_MSG, progress_percentage(worker_data));
}
return result;
}
calibrate_return mag_calibrate_all(orb_advert_t *mavlink_log_pub, int32_t cal_mask)
{
// We should not try to subscribe if the topic doesn't actually exist and can be counted.
const unsigned orb_mag_count = orb_group_count(ORB_ID(sensor_mag));
// Warn that we will not calibrate more than MAX_GYROS gyroscopes
if (orb_mag_count > MAX_MAGS) {
calibration_log_critical(mavlink_log_pub, "Detected %u mags, but will calibrate only %u", orb_mag_count, MAX_MAGS);
} else if (orb_mag_count < 1) {
calibration_log_critical(mavlink_log_pub, "No mags found");
return calibrate_return_error;
}
calibrate_return result = calibrate_return_ok;
mag_worker_data_t worker_data{};
worker_data.mag_worker_data_pub = nullptr;
// keep and update the existing calibration when we are not doing a full 6-axis calibration
worker_data.append_to_existing_calibration = cal_mask < ((1 << 6) - 1);
worker_data.mavlink_log_pub = mavlink_log_pub;
worker_data.last_mag_progress = 0;
worker_data.calibration_sides = 0;
worker_data.done_count = 0;
worker_data.calibration_points_perside = calibration_total_points / detect_orientation_side_count;
worker_data.calibration_interval_perside_us = (calibraton_duration_s / detect_orientation_side_count) * 1000 * 1000;
for (unsigned i = 0; i < (sizeof(worker_data.side_data_collected) / sizeof(worker_data.side_data_collected[0])); i++) {
if ((cal_mask & (1 << i)) > 0) {
// mark as missing
worker_data.side_data_collected[i] = false;
worker_data.calibration_sides++;
} else {
// mark as completed from the beginning
worker_data.side_data_collected[i] = true;
calibration_log_info(mavlink_log_pub,
"[cal] %s side done, rotate to a different side",
detect_orientation_str(static_cast<enum detect_orientation_return>(i)));
px4_usleep(100000);
}
}
for (size_t cur_mag = 0; cur_mag < MAX_MAGS; cur_mag++) {
// Initialize to no memory allocated
worker_data.x[cur_mag] = nullptr;
worker_data.y[cur_mag] = nullptr;
worker_data.z[cur_mag] = nullptr;
worker_data.calibration_counter_total[cur_mag] = 0;
}
const unsigned int calibration_points_maxcount = worker_data.calibration_sides * worker_data.calibration_points_perside;
for (uint8_t cur_mag = 0; cur_mag < MAX_MAGS; cur_mag++) {
uORB::SubscriptionData<sensor_mag_s> mag_sub{ORB_ID(sensor_mag), cur_mag};
if (mag_sub.advertised() && (mag_sub.get().device_id != 0) && (mag_sub.get().timestamp > 0)) {
worker_data.calibration[cur_mag].set_device_id(mag_sub.get().device_id, mag_sub.get().is_external);
}
// reset calibration index to match uORB numbering
worker_data.calibration[cur_mag].set_calibration_index(cur_mag);
if (worker_data.calibration[cur_mag].device_id() != 0) {
worker_data.x[cur_mag] = static_cast<float *>(malloc(sizeof(float) * calibration_points_maxcount));
worker_data.y[cur_mag] = static_cast<float *>(malloc(sizeof(float) * calibration_points_maxcount));
worker_data.z[cur_mag] = static_cast<float *>(malloc(sizeof(float) * calibration_points_maxcount));
if (worker_data.x[cur_mag] == nullptr || worker_data.y[cur_mag] == nullptr || worker_data.z[cur_mag] == nullptr) {
calibration_log_critical(mavlink_log_pub, "ERROR: out of memory");
result = calibrate_return_error;
break;
}
} else {
break;
}
}
if (result == calibrate_return_ok) {
result = calibrate_from_orientation(mavlink_log_pub, // uORB handle to write output
worker_data.side_data_collected, // Sides to calibrate
mag_calibration_worker, // Calibration worker
&worker_data, // Opaque data for calibration worked
true); // true: lenient still detection
}
// calibration values for each mag
Vector3f sphere[MAX_MAGS];
Vector3f diag[MAX_MAGS];
Vector3f offdiag[MAX_MAGS];
float sphere_radius[MAX_MAGS];
const float mag_sphere_radius = get_sphere_radius();
for (size_t cur_mag = 0; cur_mag < MAX_MAGS; cur_mag++) {
sphere_radius[cur_mag] = mag_sphere_radius;
sphere[cur_mag].zero();
diag[cur_mag] = Vector3f{1.f, 1.f, 1.f};
offdiag[cur_mag].zero();
}
if (result == calibrate_return_ok) {
// Sphere fit the data to get calibration values
for (uint8_t cur_mag = 0; cur_mag < MAX_MAGS; cur_mag++) {
if (worker_data.calibration[cur_mag].device_id() != 0) {
// Mag in this slot is available and we should have values for it to calibrate
// Estimate only the offsets if two-sided calibration is selected, as the problem is not constrained
// enough to reliably estimate both scales and offsets with 2 sides only (even if the existing calibration
// is already close)
bool sphere_fit_only = worker_data.calibration_sides <= 2;
sphere_params sphere_data;
sphere_data.radius = sphere_radius[cur_mag];
sphere_data.offset = matrix::Vector3f(sphere[cur_mag](0), sphere[cur_mag](1), sphere[cur_mag](2));
sphere_data.diag = matrix::Vector3f(diag[cur_mag](0), diag[cur_mag](1), diag[cur_mag](2));
sphere_data.offdiag = matrix::Vector3f(offdiag[cur_mag](0), offdiag[cur_mag](1), offdiag[cur_mag](2));
bool sphere_fit_success = false;
bool ellipsoid_fit_success = false;
int ret = lm_mag_fit(worker_data.x[cur_mag], worker_data.y[cur_mag], worker_data.z[cur_mag],
worker_data.calibration_counter_total[cur_mag], sphere_data, false);
if (ret == PX4_OK) {
sphere_fit_success = true;
PX4_INFO("Mag: %d sphere radius: %.4f", cur_mag, (double)sphere_data.radius);
if (!sphere_fit_only) {
int ellipsoid_ret = lm_mag_fit(worker_data.x[cur_mag], worker_data.y[cur_mag], worker_data.z[cur_mag],
worker_data.calibration_counter_total[cur_mag], sphere_data, true);
if (ellipsoid_ret == PX4_OK) {
ellipsoid_fit_success = true;
}
}
}
sphere_radius[cur_mag] = sphere_data.radius;
for (int i = 0; i < 3; i++) {
sphere[cur_mag](i) = sphere_data.offset(i);
diag[cur_mag](i) = sphere_data.diag(i);
offdiag[cur_mag](i) = sphere_data.offdiag(i);
}
if (!sphere_fit_success && !ellipsoid_fit_success) {
calibration_log_emergency(mavlink_log_pub, "Retry calibration (unable to fit mag %u)", cur_mag);
result = calibrate_return_error;
break;
}
result = check_calibration_result(sphere[cur_mag](0), sphere[cur_mag](1), sphere[cur_mag](2),
sphere_radius[cur_mag],
diag[cur_mag](0), diag[cur_mag](1), diag[cur_mag](2),
offdiag[cur_mag](0), offdiag[cur_mag](1), offdiag[cur_mag](2),
mavlink_log_pub, cur_mag);
if (result == calibrate_return_error) {
break;
}
}
}
}
#if 0
// DO NOT REMOVE! Critical validation data!
if (result == calibrate_return_ok) {
// Print uncalibrated data points
for (uint8_t cur_mag = 0; cur_mag < MAX_MAGS; cur_mag++) {
if (worker_data.calibration_counter_total[cur_mag] == 0) {
continue;
}
printf("MAG %u with %u samples:\n", cur_mag, worker_data.calibration_counter_total[cur_mag]);
printf("RAW -> CALIBRATED\n");
float scale_data[9] {
diag[cur_mag](0), offdiag[cur_mag](0), offdiag[cur_mag](1),
offdiag[cur_mag](0), diag[cur_mag](1), offdiag[cur_mag](2),
offdiag[cur_mag](1), offdiag[cur_mag](2), diag[cur_mag](2)
};
const Matrix3f scale{scale_data};
const Vector3f &offset = sphere[cur_mag];
for (size_t i = 0; i < worker_data.calibration_counter_total[cur_mag]; i++) {
float x = worker_data.x[cur_mag][i];
float y = worker_data.y[cur_mag][i];
float z = worker_data.z[cur_mag][i];
// apply calibration
const Vector3f cal{scale *(Vector3f{x, y, z} - offset)};
printf("[%.3f, %.3f, %.3f] -> [%.3f, %.3f, %.3f]\n",
(double)x, (double)y, (double)z,
(double)cal(0), (double)cal(1), (double)cal(2));
}
printf("SPHERE RADIUS: %8.4f\n", (double)sphere_radius[cur_mag]);
}
}
#endif // DO NOT REMOVE! Critical validation data!
// Attempt to automatically determine external mag rotations
if (result == calibrate_return_ok) {
int32_t param_cal_mag_rot_auto = 0;
param_get(param_find("CAL_MAG_ROT_AUTO"), ¶m_cal_mag_rot_auto);
if ((worker_data.calibration_sides >= 3) && (param_cal_mag_rot_auto == 1)) {
// find first internal mag to use as reference
int internal_index = -1;
for (unsigned cur_mag = 0; cur_mag < MAX_MAGS; cur_mag++) {
if (!worker_data.calibration[cur_mag].external() && (worker_data.calibration[cur_mag].device_id() != 0)) {
internal_index = cur_mag;
break;
}
}
// only proceed if there's a valid internal
if (internal_index >= 0) {
const Dcmf board_rotation = calibration::GetBoardRotationMatrix();
// apply new calibrations to all raw sensor data before comparison
for (unsigned cur_mag = 0; cur_mag < MAX_MAGS; cur_mag++) {
if (worker_data.calibration[cur_mag].device_id() != 0) {
float scale_data[9] {
diag[cur_mag](0), offdiag[cur_mag](0), offdiag[cur_mag](1),
offdiag[cur_mag](0), diag[cur_mag](1), offdiag[cur_mag](2),
offdiag[cur_mag](1), offdiag[cur_mag](2), diag[cur_mag](2)
};
const Matrix3f scale{scale_data};
const Vector3f &offset{sphere[cur_mag]};
for (unsigned i = 0; i < worker_data.calibration_counter_total[cur_mag]; i++) {
const Vector3f sample{worker_data.x[cur_mag][i], worker_data.y[cur_mag][i], worker_data.z[cur_mag][i]};
// apply calibration
Vector3f m{scale *(sample - offset)};
if (!worker_data.calibration[cur_mag].external()) {
// rotate internal mag data to board
m = board_rotation * m;
}
// store back in worker_data
worker_data.x[cur_mag][i] = m(0);
worker_data.y[cur_mag][i] = m(1);
worker_data.z[cur_mag][i] = m(2);
}
}
}
// external mags try all rotations and compute mean square error (MSE) compared with first internal mag
for (int cur_mag = 0; cur_mag < MAX_MAGS; cur_mag++) {
if ((worker_data.calibration[cur_mag].device_id() != 0) && (cur_mag != internal_index)) {
const int last_sample_index = math::min(worker_data.calibration_counter_total[internal_index],
worker_data.calibration_counter_total[cur_mag]);
float MSE[ROTATION_MAX] {}; // mean square error for each rotation
float min_mse = FLT_MAX;
Rotation best_rotation = ROTATION_NONE;
for (int r = ROTATION_NONE; r < ROTATION_MAX; r++) {
switch (r) {
case ROTATION_ROLL_90_PITCH_68_YAW_293: // skip
// FALLTHROUGH
case ROTATION_PITCH_180_YAW_90: // skip 26, same as 14 ROTATION_ROLL_180_YAW_270
// FALLTHROUGH
case ROTATION_PITCH_180_YAW_270: // skip 27, same as 10 ROTATION_ROLL_180_YAW_90
MSE[r] = FLT_MAX;
break;
default:
float diff_sum = 0.f;
for (int i = 0; i < last_sample_index; i++) {
float x = worker_data.x[cur_mag][i];
float y = worker_data.y[cur_mag][i];
float z = worker_data.z[cur_mag][i];
rotate_3f((enum Rotation)r, x, y, z);
Vector3f diff = Vector3f{x, y, z} - Vector3f{worker_data.x[internal_index][i], worker_data.y[internal_index][i], worker_data.z[internal_index][i]};
diff_sum += diff.norm_squared();
}
// compute mean squared error
MSE[r] = diff_sum / last_sample_index;
if (MSE[r] < min_mse) {
min_mse = MSE[r];
best_rotation = (Rotation)r;
}
break;
}
}
// Check that the best rotation is at least twice as good as the next best
bool smallest_check_passed = true;
for (int r = ROTATION_NONE; r < ROTATION_MAX; r++) {
if (r != best_rotation) {
if (MSE[r] < (min_mse * 2.f)) {
smallest_check_passed = false;
}
}
}
// Check that the average error across all samples (relative to internal mag) is less than the minimum earth field (~0.25 Gauss)
const float mag_error_gs = sqrt(min_mse / last_sample_index);
bool total_error_check_passed = (mag_error_gs < 0.25f);
#if defined(DEBUG_BUILD)
bool print_all_mse = true;
#else
bool print_all_mse = false;
#endif // DEBUG_BUILD
if (worker_data.calibration[cur_mag].external()) {
switch (worker_data.calibration[cur_mag].rotation_enum()) {
case ROTATION_ROLL_90_PITCH_68_YAW_293:
PX4_INFO("[cal] External Mag: %d (%d), keeping manually configured rotation %d", cur_mag,
worker_data.calibration[cur_mag].device_id(), worker_data.calibration[cur_mag].rotation_enum());
continue;
default:
break;
}
if (smallest_check_passed && total_error_check_passed) {
if (best_rotation != worker_data.calibration[cur_mag].rotation_enum()) {
calibration_log_info(mavlink_log_pub, "[cal] External Mag: %d (%d), determined rotation: %d", cur_mag,
worker_data.calibration[cur_mag].device_id(), best_rotation);
worker_data.calibration[cur_mag].set_rotation(best_rotation);
} else {
PX4_INFO("[cal] External Mag: %d (%d), no rotation change: %d", cur_mag,
worker_data.calibration[cur_mag].device_id(), best_rotation);
}
} else {
PX4_ERR("External Mag: %d (%d), determining rotation failed", cur_mag, worker_data.calibration[cur_mag].device_id());
print_all_mse = true;
}
} else {
// non-primary internal mags, warn if there seems to be a rotation relative to the first primary (internal_index)
if (best_rotation != ROTATION_NONE) {
calibration_log_critical(mavlink_log_pub, "[cal] Internal Mag: %d (%d) rotation %d relative to primary %d (%d)",
cur_mag, worker_data.calibration[cur_mag].device_id(), best_rotation,
internal_index, worker_data.calibration[internal_index].device_id());
print_all_mse = true;
}
}
if (print_all_mse) {
for (int r = ROTATION_NONE; r < ROTATION_MAX; r++) {
PX4_ERR("%s Mag: %d (%d), rotation: %d, MSE: %.3f",
worker_data.calibration[cur_mag].external() ? "External" : "Internal",
cur_mag, worker_data.calibration[cur_mag].device_id(), r, (double)MSE[r]);
}
}
}
}
}
}
}
// Data points are no longer needed
for (size_t cur_mag = 0; cur_mag < MAX_MAGS; cur_mag++) {
free(worker_data.x[cur_mag]);
free(worker_data.y[cur_mag]);
free(worker_data.z[cur_mag]);
}
FactoryCalibrationStorage factory_storage;
if (result == calibrate_return_ok && factory_storage.open() != PX4_OK) {
calibration_log_critical(mavlink_log_pub, "ERROR: cannot open calibration storage");
result = calibrate_return_error;
}
if (result == calibrate_return_ok) {
bool param_save = false;
bool failed = true;
for (unsigned cur_mag = 0; cur_mag < MAX_MAGS; cur_mag++) {
auto ¤t_cal = worker_data.calibration[cur_mag];
if (current_cal.device_id() != 0) {
if (worker_data.append_to_existing_calibration) {
// Update calibration
// The formula for applying the calibration is:
// mag_value = (mag_readout - (offset_existing + offset_new/scale_existing)) * scale_existing
Vector3f offset = current_cal.offset() + sphere[cur_mag].edivide(current_cal.scale().diag());
current_cal.set_offset(offset);
} else {
current_cal.set_offset(sphere[cur_mag]);
current_cal.set_scale(diag[cur_mag]);
current_cal.set_offdiagonal(offdiag[cur_mag]);
}
current_cal.PrintStatus();
} else {
current_cal.Reset();
}
current_cal.set_calibration_index(cur_mag);
if (current_cal.ParametersSave()) {
param_save = true;
failed = false;
} else {
failed = true;
calibration_log_critical(mavlink_log_pub, "calibration save failed");
break;
}
}
if (!failed && factory_storage.store() != PX4_OK) {
failed = true;
}
if (param_save) {
param_notify_changes();
}
if (failed) {
result = calibrate_return_error;
}
}
return result;
}
int do_mag_calibration_quick(orb_advert_t *mavlink_log_pub, float heading_radians, float latitude, float longitude)
{
// magnetometer quick calibration
// if GPS available use world magnetic model to zero mag offsets
bool mag_earth_available = false;
if (PX4_ISFINITE(latitude) && PX4_ISFINITE(longitude)) {
mag_earth_available = true;
} else {
uORB::Subscription vehicle_gps_position_sub{ORB_ID(vehicle_gps_position)};
vehicle_gps_position_s gps;
if (vehicle_gps_position_sub.copy(&gps)) {
if ((gps.timestamp != 0) && (gps.eph < 1000)) {
latitude = gps.lat / 1.e7f;
longitude = gps.lon / 1.e7f;
mag_earth_available = true;
}
}
}
if (!mag_earth_available) {
calibration_log_critical(mavlink_log_pub, "GPS required for mag quick cal");
return PX4_ERROR;
} else {
// magnetic field data returned by the geo library using the current GPS position
const float mag_declination_gps = get_mag_declination_radians(latitude, longitude);
const float mag_inclination_gps = get_mag_inclination_radians(latitude, longitude);
const float mag_strength_gps = get_mag_strength_gauss(latitude, longitude);
const Vector3f mag_earth_pred = Dcmf(Eulerf(0, -mag_inclination_gps, mag_declination_gps)) * Vector3f(mag_strength_gps,
0, 0);
uORB::Subscription vehicle_attitude_sub{ORB_ID(vehicle_attitude)};
vehicle_attitude_s attitude{};
vehicle_attitude_sub.copy(&attitude);
if (hrt_elapsed_time(&attitude.timestamp) > 1_s) {
calibration_log_critical(mavlink_log_pub, "attitude required for mag quick cal");
return PX4_ERROR;
}
FactoryCalibrationStorage factory_storage;
if (factory_storage.open() != PX4_OK) {
calibration_log_critical(mavlink_log_pub, "ERROR: cannot open calibration storage");
return PX4_ERROR;
}
calibration_log_critical(mavlink_log_pub, "Assuming vehicle is facing heading %.1f degrees",
(double)math::radians(heading_radians));
matrix::Eulerf euler{matrix::Quatf{attitude.q}};
euler(2) = heading_radians;
const Vector3f expected_field = Dcmf(euler).transpose() * mag_earth_pred;
bool param_save = false;
bool failed = true;
for (uint8_t cur_mag = 0; cur_mag < MAX_MAGS; cur_mag++) {
uORB::Subscription mag_sub{ORB_ID(sensor_mag), cur_mag};
sensor_mag_s mag{};
mag_sub.copy(&mag);
if (mag_sub.advertised() && (mag.timestamp != 0)) {
calibration::Magnetometer cal{mag.device_id, mag.is_external};
// force calibration index to uORB index
cal.set_calibration_index(cur_mag);
// use any existing scale and store the offset to the expected earth field
const Vector3f offset = Vector3f{mag.x, mag.y, mag.z} - (cal.scale().I() * cal.rotation().transpose() * expected_field);
cal.set_offset(offset);
// save new calibration
if (cal.ParametersSave()) {
cal.PrintStatus();
param_save = true;
failed = false;
} else {
failed = true;
calibration_log_critical(mavlink_log_pub, "calibration save failed");
break;
}
}
}
if (param_save) {
param_notify_changes();
}
if (!failed && factory_storage.store() != PX4_OK) {
failed = true;
}
if (!failed) {
calibration_log_info(mavlink_log_pub, "Mag quick calibration finished");
return PX4_OK;
}
}
calibration_log_critical(mavlink_log_pub, CAL_QGC_FAILED_MSG, sensor_name);
return PX4_ERROR;
}
|
// Copyright 2008 Isis Innovation Limited
#include "ATANCamera.h"
#include <TooN/helpers.h>
#include <cvd/vector_image_ref.h>
#include <iostream>
#include <gvars3/instances.h>
using namespace std;
using namespace CVD;
using namespace GVars3;
ATANCamera::ATANCamera(string sName)
{
// The camera name is used to find the camera's parameters in a GVar.
msName = sName;
GV2.Register(mgvvCameraParams, sName+".Parameters", mvDefaultParams, HIDDEN | FATAL_IF_NOT_DEFINED);
mvImageSize[0] = 640.0;
mvImageSize[1] = 480.0;
RefreshParams();
}
void ATANCamera::SetImageSize(Vector<2> vImageSize)
{
mvImageSize = vImageSize;
RefreshParams();
};
void ATANCamera::RefreshParams()
{
// This updates internal member variables according to the current camera parameters,
// and the currently selected target image size.
//
// First: Focal length and image center in pixel coordinates
mvFocal[0] = mvImageSize[0] * (*mgvvCameraParams)[0];
mvFocal[1] = mvImageSize[1] * (*mgvvCameraParams)[1];
mvCenter[0] = mvImageSize[0] * (*mgvvCameraParams)[2] - 0.5;
mvCenter[1] = mvImageSize[1] * (*mgvvCameraParams)[3] - 0.5;
// One over focal length
mvInvFocal[0] = 1.0 / mvFocal[0];
mvInvFocal[1] = 1.0 / mvFocal[1];
// Some radial distortion parameters..
mdW = (*mgvvCameraParams)[4];
if(mdW != 0.0)
{
md2Tan = 2.0 * tan(mdW / 2.0);
mdOneOver2Tan = 1.0 / md2Tan;
mdWinv = 1.0 / mdW;
mdDistortionEnabled = 1.0;
}
else
{
mdWinv = 0.0;
md2Tan = 0.0;
mdDistortionEnabled = 0.0;
}
// work out biggest radius in image
Vector<2> v2;
v2[0]= max((*mgvvCameraParams)[2], 1.0 - (*mgvvCameraParams)[2]) / (*mgvvCameraParams)[0];
v2[1]= max((*mgvvCameraParams)[3], 1.0 - (*mgvvCameraParams)[3]) / (*mgvvCameraParams)[1];
mdLargestRadius = invrtrans(sqrt(v2*v2));
// At what stage does the model become invalid?
mdMaxR = 1.5 * mdLargestRadius; // (pretty arbitrary)
// work out world radius of one pixel
// (This only really makes sense for square-ish pixels)
{
Vector<2> v2Center = UnProject(mvImageSize / 2);
Vector<2> v2RootTwoAway = UnProject(mvImageSize / 2 + vec(ImageRef(1,1)));
Vector<2> v2Diff = v2Center - v2RootTwoAway;
mdOnePixelDist = sqrt(v2Diff * v2Diff) / sqrt(2.0);
}
// Work out the linear projection values for the UFB
{
// First: Find out how big the linear bounding rectangle must be
vector<Vector<2> > vv2Verts;
vv2Verts.push_back(UnProject(makeVector( -0.5, -0.5)));
vv2Verts.push_back(UnProject(makeVector( mvImageSize[0]-0.5, -0.5)));
vv2Verts.push_back(UnProject(makeVector( mvImageSize[0]-0.5, mvImageSize[1]-0.5)));
vv2Verts.push_back(UnProject(makeVector( -0.5, mvImageSize[1]-0.5)));
Vector<2> v2Min = vv2Verts[0];
Vector<2> v2Max = vv2Verts[0];
for(int i=0; i<4; i++)
for(int j=0; j<2; j++)
{
if(vv2Verts[i][j] < v2Min[j]) v2Min[j] = vv2Verts[i][j];
if(vv2Verts[i][j] > v2Max[j]) v2Max[j] = vv2Verts[i][j];
}
mvImplaneTL = v2Min;
mvImplaneBR = v2Max;
// Store projection parameters to fill this bounding box
Vector<2> v2Range = v2Max - v2Min;
mvUFBLinearInvFocal = v2Range;
mvUFBLinearFocal[0] = 1.0 / mvUFBLinearInvFocal[0];
mvUFBLinearFocal[1] = 1.0 / mvUFBLinearInvFocal[1];
mvUFBLinearCenter[0] = -1.0 * v2Min[0] * mvUFBLinearFocal[0];
mvUFBLinearCenter[1] = -1.0 * v2Min[1] * mvUFBLinearFocal[1];
}
}
// Project from the camera z=1 plane to image pixels,
// while storing intermediate calculation results in member variables
Vector<2> ATANCamera::Project(const Vector<2>& vCam){
mvLastCam = vCam;
mdLastR = sqrt(vCam * vCam);
mbInvalid = (mdLastR > mdMaxR);
mdLastFactor = rtrans_factor(mdLastR);
mdLastDistR = mdLastFactor * mdLastR;
mvLastDistCam = mdLastFactor * mvLastCam;
mvLastIm[0] = mvCenter[0] + mvFocal[0] * mvLastDistCam[0];
mvLastIm[1] = mvCenter[1] + mvFocal[1] * mvLastDistCam[1];
return mvLastIm;
}
// Un-project from image pixel coords to the camera z=1 plane
// while storing intermediate calculation results in member variables
Vector<2> ATANCamera::UnProject(const Vector<2>& v2Im)
{
mvLastIm = v2Im;
mvLastDistCam[0] = (mvLastIm[0] - mvCenter[0]) * mvInvFocal[0];
mvLastDistCam[1] = (mvLastIm[1] - mvCenter[1]) * mvInvFocal[1];
mdLastDistR = sqrt(mvLastDistCam * mvLastDistCam);
mdLastR = invrtrans(mdLastDistR);
double dFactor;
if(mdLastDistR > 0.01)
dFactor = mdLastR / mdLastDistR;
else
dFactor = 1.0;
mdLastFactor = 1.0 / dFactor;
mvLastCam = dFactor * mvLastDistCam;
return mvLastCam;
}
// Utility function for easy drawing with OpenGL
// C.f. comment in top of ATANCamera.h
Matrix<4> ATANCamera::MakeUFBLinearFrustumMatrix(double near, double far)
{
Matrix<4> m4 = Zeros;
double left = mvImplaneTL[0] * near;
double right = mvImplaneBR[0] * near;
double top = mvImplaneTL[1] * near;
double bottom = mvImplaneBR[1] * near;
// The openGhelL frustum manpage is A PACK OF LIES!!
// Two of the elements are NOT what the manpage says they should be.
// Anyway, below code makes a frustum projection matrix
// Which projects a RHS-coord frame with +z in front of the camera
// Which is what I usually want, instead of glFrustum's LHS, -z idea.
m4[0][0] = (2 * near) / (right - left);
m4[1][1] = (2 * near) / (top - bottom);
m4[0][2] = (right + left) / (left - right);
m4[1][2] = (top + bottom) / (bottom - top);
m4[2][2] = (far + near) / (far - near);
m4[3][2] = 1;
m4[2][3] = 2*near*far / (near - far);
return m4;
};
Matrix<2,2> ATANCamera::GetProjectionDerivs()
{
// get the derivative of image frame wrt camera z=1 frame at the last computed projection
// in the form (d im1/d cam1, d im1/d cam2)
// (d im2/d cam1, d im2/d cam2)
double dFracBydx;
double dFracBydy;
double &k = md2Tan;
double &x = mvLastCam[0];
double &y = mvLastCam[1];
double r = mdLastR * mdDistortionEnabled;
if(r < 0.01)
{
dFracBydx = 0.0;
dFracBydy = 0.0;
}
else
{
dFracBydx =
mdWinv * (k * x) / (r*r*(1 + k*k*r*r)) - x * mdLastFactor / (r*r);
dFracBydy =
mdWinv * (k * y) / (r*r*(1 + k*k*r*r)) - y * mdLastFactor / (r*r);
}
Matrix<2> m2Derivs;
m2Derivs[0][0] = mvFocal[0] * (dFracBydx * x + mdLastFactor);
m2Derivs[1][0] = mvFocal[1] * (dFracBydx * y);
m2Derivs[0][1] = mvFocal[0] * (dFracBydy * x);
m2Derivs[1][1] = mvFocal[1] * (dFracBydy * y + mdLastFactor);
return m2Derivs;
}
Matrix<2,NUMTRACKERCAMPARAMETERS> ATANCamera::GetCameraParameterDerivs()
{
// Differentials wrt to the camera parameters
// Use these to calibrate the camera
// No need for this to be quick, so do them numerically
Matrix<2, NUMTRACKERCAMPARAMETERS> m2NNumDerivs;
Vector<NUMTRACKERCAMPARAMETERS> vNNormal = *mgvvCameraParams;
Vector<2> v2Cam = mvLastCam;
Vector<2> v2Out = Project(v2Cam);
for(int i=0; i<NUMTRACKERCAMPARAMETERS; i++)
{
if(i == NUMTRACKERCAMPARAMETERS-1 && mdW == 0.0)
continue;
Vector<NUMTRACKERCAMPARAMETERS> vNUpdate;
vNUpdate = Zeros;
vNUpdate[i] += 0.001;
UpdateParams(vNUpdate);
Vector<2> v2Out_B = Project(v2Cam);
m2NNumDerivs.T()[i] = (v2Out_B - v2Out) / 0.001;
*mgvvCameraParams = vNNormal;
RefreshParams();
}
if(mdW == 0.0)
m2NNumDerivs.T()[NUMTRACKERCAMPARAMETERS-1] = Zeros;
return m2NNumDerivs;
}
void ATANCamera::UpdateParams(Vector<5> vUpdate)
{
// Update the camera parameters; use this as part of camera calibration.
(*mgvvCameraParams) = (*mgvvCameraParams) + vUpdate;
RefreshParams();
}
void ATANCamera::DisableRadialDistortion()
{
// Set the radial distortion parameter to zero
// This disables radial distortion and also disables its differentials
(*mgvvCameraParams)[NUMTRACKERCAMPARAMETERS-1] = 0.0;
RefreshParams();
}
Vector<2> ATANCamera::UFBProject(const Vector<2>& vCam)
{
// Project from camera z=1 plane to UFB, storing intermediate calc results.
mvLastCam = vCam;
mdLastR = sqrt(vCam * vCam);
mbInvalid = (mdLastR > mdMaxR);
mdLastFactor = rtrans_factor(mdLastR);
mdLastDistR = mdLastFactor * mdLastR;
mvLastDistCam = mdLastFactor * mvLastCam;
mvLastIm[0] = (*mgvvCameraParams)[2] + (*mgvvCameraParams)[0] * mvLastDistCam[0];
mvLastIm[1] = (*mgvvCameraParams)[3] + (*mgvvCameraParams)[1] * mvLastDistCam[1];
return mvLastIm;
}
Vector<2> ATANCamera::UFBUnProject(const Vector<2>& v2Im)
{
mvLastIm = v2Im;
mvLastDistCam[0] = (mvLastIm[0] - (*mgvvCameraParams)[2]) / (*mgvvCameraParams)[0];
mvLastDistCam[1] = (mvLastIm[1] - (*mgvvCameraParams)[3]) / (*mgvvCameraParams)[1];
mdLastDistR = sqrt(mvLastDistCam * mvLastDistCam);
mdLastR = invrtrans(mdLastDistR);
double dFactor;
if(mdLastDistR > 0.01)
dFactor = mdLastR / mdLastDistR;
else
dFactor = 1.0;
mdLastFactor = 1.0 / dFactor;
mvLastCam = dFactor * mvLastDistCam;
return mvLastCam;
}
const Vector<NUMTRACKERCAMPARAMETERS> ATANCamera::mvDefaultParams = makeVector(0.5, 0.75, 0.5, 0.5, 0.1);
|
#include <eepp/physics/cshapesegment.hpp>
#include <eepp/physics/cspace.hpp>
#include <eepp/helper/chipmunk/chipmunk_unsafe.h>
#ifdef PHYSICS_RENDERER_ENABLED
#include <eepp/graphics/renderer/cgl.hpp>
#include <eepp/graphics/cprimitives.hpp>
using namespace EE::Graphics;
#endif
CP_NAMESPACE_BEGIN
cShapeSegment * cShapeSegment::New( cBody * body, cVect a, cVect b, cpFloat radius ) {
return cpNew( cShapeSegment, ( body, a, b, radius ) );
}
cShapeSegment::cShapeSegment( cBody * body, cVect a, cVect b, cpFloat radius ) {
mShape = cpSegmentShapeNew( body->Body(), tocpv( a ), tocpv( b ), radius );
SetData();
}
cVect cShapeSegment::A() {
return tovect( cpSegmentShapeGetA( mShape ) );
}
cVect cShapeSegment::B() {
return tovect( cpSegmentShapeGetB( mShape ) );
}
cVect cShapeSegment::Normal() {
return tovect( cpSegmentShapeGetNormal( mShape ) );
}
cpFloat cShapeSegment::Radius() {
return cpSegmentShapeGetRadius( mShape );
}
void cShapeSegment::Radius( const cpFloat& radius ) {
cpSegmentShapeSetRadius( mShape, radius );
}
void cShapeSegment::Endpoints( const cVect& a, const cVect& b ) {
cpSegmentShapeSetEndpoints( mShape, tocpv( a ), tocpv( b ) );
}
bool cShapeSegment::Query( cVect a, cVect b, cpSegmentQueryInfo * info ) {
return 0 != cpShapeSegmentQuery( mShape, tocpv( a ), tocpv( b ), info );
}
cVect cShapeSegment::QueryHitPoint( const cVect start, const cVect end, const cpSegmentQueryInfo info ) {
return tovect( cpSegmentQueryHitPoint( tocpv( start ), tocpv( end ), info ) );
}
cpFloat cShapeSegment::QueryHitDist( const cVect start, const cVect end, const cpSegmentQueryInfo info ) {
return cpSegmentQueryHitDist( tocpv( start ), tocpv( end ), info );
}
void cShapeSegment::Draw( cSpace * space ) {
#ifdef PHYSICS_RENDERER_ENABLED
static const float pillVAR[] = {
0.0000f, 1.0000f, 1.0f,
0.2588f, 0.9659f, 1.0f,
0.5000f, 0.8660f, 1.0f,
0.7071f, 0.7071f, 1.0f,
0.8660f, 0.5000f, 1.0f,
0.9659f, 0.2588f, 1.0f,
1.0000f, 0.0000f, 1.0f,
0.9659f, -0.2588f, 1.0f,
0.8660f, -0.5000f, 1.0f,
0.7071f, -0.7071f, 1.0f,
0.5000f, -0.8660f, 1.0f,
0.2588f, -0.9659f, 1.0f,
0.0000f, -1.0000f, 1.0f,
0.0000f, -1.0000f, 0.0f,
-0.2588f, -0.9659f, 0.0f,
-0.5000f, -0.8660f, 0.0f,
-0.7071f, -0.7071f, 0.0f,
-0.8660f, -0.5000f, 0.0f,
-0.9659f, -0.2588f, 0.0f,
-1.0000f, -0.0000f, 0.0f,
-0.9659f, 0.2588f, 0.0f,
-0.8660f, 0.5000f, 0.0f,
-0.7071f, 0.7071f, 0.0f,
-0.5000f, 0.8660f, 0.0f,
-0.2588f, 0.9659f, 0.0f,
0.0000f, 1.0000f, 0.0f,
};
static const int pillVAR_count = sizeof(pillVAR)/sizeof(float)/3;
cpSegmentShape * seg = (cpSegmentShape *)mShape;
cVect a = tovect( seg->CP_PRIVATE(ta) );
cVect b = tovect( seg->CP_PRIVATE(tb) );
if ( seg->CP_PRIVATE(r) ) {
GLi->Disable( GL_TEXTURE_2D );
GLi->DisableClientState( GL_TEXTURE_COORD_ARRAY );
std::vector<eeColorA> tcolors( pillVAR_count * 4 );
GLi->PushMatrix();
cVect d = b - a;
cVect r = d * ( seg->CP_PRIVATE(r) / cpvlength( tocpv( d ) ) );
const GLfloat matrix[] = {
(GLfloat)r.x , (GLfloat)r.y, 0.0f, 0.0f,
(GLfloat)-r.y , (GLfloat)r.x, 0.0f, 0.0f,
(GLfloat)d.x , (GLfloat)d.y, 0.0f, 0.0f,
(GLfloat)a.x , (GLfloat)a.y, 0.0f, 1.0f,
};
GLi->MultMatrixf( matrix );
GLi->VertexPointer( 3, GL_FLOAT, 0, pillVAR, pillVAR_count * sizeof(GLfloat) * 3 );
if( !seg->CP_PRIVATE(shape).sensor ) {
eeColorA C = ColorForShape( mShape, space->Space() );
tcolors.assign( tcolors.size(), C );
GLi->ColorPointer( 4, GL_UNSIGNED_BYTE, 0, reinterpret_cast<const GLvoid*>( &tcolors[0] ), pillVAR_count * 4 );
GLi->DrawArrays( GL_TRIANGLE_FAN, 0, pillVAR_count );
}
tcolors.assign( tcolors.size(), eeColorA( 102, 102, 102, 255 ) );
GLi->ColorPointer( 4, GL_UNSIGNED_BYTE, 0, reinterpret_cast<const GLvoid*>( &tcolors[0] ), pillVAR_count * 4 );
GLi->DrawArrays( GL_LINE_LOOP, 0, pillVAR_count );
GLi->PopMatrix();
GLi->Enable( GL_TEXTURE_2D );
GLi->EnableClientState( GL_TEXTURE_COORD_ARRAY );
} else {
cPrimitives p;
p.DrawLine( eeLine2f( eeVector2f( a.x, a.y ), eeVector2f( b.x, b.y ) ) );
}
#endif
}
CP_NAMESPACE_END
|
namespace hx {
unsigned char __res_44[] = {
0x80, 0x00, 0x00, 0x80,
137,80,78,71,13,10,26,10,0,0,
0,13,73,72,68,82,0,0,0,11,
0,0,0,11,8,6,0,0,0,169,
172,119,38,0,0,0,4,115,66,73,
84,8,8,8,8,124,8,100,136,0,
0,0,9,112,72,89,115,0,0,11,
18,0,0,11,18,1,210,221,126,252,
0,0,0,28,116,69,88,116,83,111,
102,116,119,97,114,101,0,65,100,111,
98,101,32,70,105,114,101,119,111,114,
107,115,32,67,83,53,113,181,227,54,
0,0,2,111,112,114,86,87,120,156,
237,154,203,142,211,48,20,134,35,177,
179,250,16,86,88,176,33,113,156,166,
183,168,201,8,181,26,205,166,104,196,
84,12,98,151,38,110,39,106,19,71,
73,70,73,251,54,188,3,11,36,36,
216,35,30,128,183,152,21,91,192,233,
141,78,53,98,193,162,169,228,243,245,
106,215,199,95,254,19,47,251,237,215,
151,7,37,81,146,223,21,223,39,141,
28,79,216,44,140,29,245,225,243,87,
21,135,129,163,222,182,70,198,40,25,
176,187,240,106,149,178,155,213,235,177,
191,154,251,189,64,189,112,81,191,180,
203,40,137,88,238,225,50,90,196,153,
93,58,170,23,240,9,179,197,247,106,
154,168,120,189,36,159,59,234,171,234,
7,252,110,116,141,7,60,101,184,165,
27,154,111,180,13,220,166,58,109,90,
157,78,231,37,54,13,106,16,195,36,
212,212,104,199,110,154,182,97,224,45,
170,139,196,123,63,13,166,246,155,225,
229,86,39,70,142,122,151,231,137,77,
72,81,20,122,209,212,121,58,35,180,
215,235,85,219,152,166,38,86,104,217,
50,206,189,82,139,179,231,155,77,118,
251,12,89,230,167,97,146,135,60,198,
213,216,155,240,251,220,81,85,132,15,
216,230,138,146,189,40,206,244,117,70,
221,231,17,41,189,132,80,221,32,251,
157,171,205,197,106,123,144,50,47,231,
233,152,243,133,187,73,126,25,166,172,
224,233,60,195,131,155,22,166,162,74,
60,172,174,133,111,195,56,224,69,214,
39,199,117,79,109,201,134,226,229,138,
70,89,154,209,213,12,107,76,187,182,
213,181,105,243,253,65,253,102,209,81,
249,136,7,225,116,249,68,121,171,105,
91,237,109,249,193,162,93,171,200,81,
175,254,183,135,129,191,111,97,114,159,
46,214,119,42,240,9,91,176,136,197,
121,38,218,72,31,183,49,240,237,41,
79,35,47,119,195,200,155,49,146,196,
179,62,249,59,249,207,235,219,204,138,
147,34,14,41,217,159,82,247,209,101,
29,162,156,24,240,239,65,146,231,151,
214,143,36,207,15,126,240,131,31,252,
245,250,145,228,249,165,245,35,201,243,
131,31,252,224,7,127,189,126,36,121,
126,105,253,72,242,252,224,7,255,217,
248,81,205,126,12,254,122,252,72,242,
252,210,250,145,228,249,193,15,254,179,
241,163,154,253,117,231,151,214,143,36,
207,47,173,255,248,143,24,167,246,215,
157,31,252,224,63,27,63,146,60,191,
180,126,36,121,126,240,131,31,252,224,
175,215,143,36,207,47,173,31,213,158,
31,245,47,202,196,243,231,236,212,126,
0,0,0,0,0,0,0,0,0,160,
30,62,136,231,179,159,75,229,211,219,
143,141,31,47,252,70,221,215,3,0,
167,228,90,241,148,153,194,20,172,80,
49,218,125,2,178,240,7,149,163,171,
243,16,152,60,113,0,0,0,72,109,
107,66,70,250,222,202,254,0,0,0,
4,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,41,164,51,161,0,
0,57,40,109,107,84,83,120,156,237,
125,219,115,219,198,146,62,54,39,142,
35,249,158,108,101,31,246,69,85,187,
191,250,61,197,135,184,144,4,31,69,
82,148,20,83,18,15,65,217,114,94,
92,32,72,196,218,216,86,142,36,43,
199,203,194,255,190,211,221,131,219,96,
112,37,41,81,14,194,88,67,98,112,
25,124,221,243,77,119,79,15,112,244,
170,123,179,120,61,182,206,23,182,247,
122,124,116,190,80,189,193,184,23,41,
198,255,56,62,95,52,27,122,71,107,
155,13,239,108,216,115,23,13,239,45,
21,111,14,251,238,66,85,189,131,195,
9,150,227,61,203,93,180,53,111,108,
157,158,179,234,238,62,59,131,139,255,
121,163,225,240,102,209,29,177,63,189,
221,201,213,66,249,94,153,42,142,242,
78,233,42,182,114,165,156,43,142,119,
120,124,196,182,63,102,219,63,177,237,
7,108,251,165,50,83,118,148,33,171,
253,164,204,189,113,255,100,10,39,221,
61,198,115,239,178,38,235,115,211,235,
246,15,207,23,134,215,61,98,109,159,
179,2,239,164,107,237,225,78,214,0,
110,161,107,29,224,175,238,144,138,87,
88,244,142,249,9,246,6,248,123,60,
193,125,7,93,252,53,24,99,113,76,
27,173,17,219,215,241,186,19,170,156,
208,217,39,22,93,228,136,206,71,197,
225,46,180,242,24,90,213,240,250,39,
42,52,167,127,162,193,105,250,39,58,
22,3,182,81,99,133,70,133,14,133,
87,0,155,103,9,108,198,202,133,242,
153,109,155,41,115,101,182,44,66,234,
253,71,200,215,30,139,225,226,42,215,
203,104,143,234,26,149,245,71,93,18,
29,117,189,250,19,162,179,164,254,136,
24,149,209,160,59,198,232,49,199,104,
151,225,115,201,144,232,178,191,159,25,
90,239,57,86,223,115,172,66,12,179,
208,129,118,71,224,105,25,132,15,214,
231,226,99,26,49,124,26,49,124,116,
45,142,208,108,201,62,166,17,66,26,
33,100,16,66,6,33,100,120,214,232,
87,146,170,101,177,47,206,148,109,56,
161,219,176,172,19,220,80,6,195,71,
28,195,9,211,174,127,49,125,251,204,
234,243,244,76,215,100,138,150,13,164,
218,225,80,106,83,167,4,148,142,73,
80,226,246,181,129,169,117,138,129,249,
148,131,217,99,10,247,129,125,206,149,
223,24,92,182,242,135,242,94,249,194,
1,221,138,40,229,71,246,253,66,185,
200,4,83,229,189,86,213,11,211,190,
218,48,228,221,182,145,209,109,155,13,
66,18,249,0,144,116,237,194,61,87,
51,11,99,169,155,26,97,169,171,179,
210,216,101,119,232,246,140,160,51,29,
66,110,190,34,131,162,145,53,92,106,
21,201,174,24,100,85,1,250,7,235,
167,231,176,87,12,32,163,73,0,169,
83,65,183,92,14,81,131,48,114,178,
58,42,168,69,190,110,33,33,70,112,
2,54,5,156,80,169,214,0,84,82,
183,130,142,90,181,131,142,89,237,20,
59,232,167,76,53,83,59,171,213,179,
213,14,170,235,209,179,239,56,70,111,
216,88,112,45,69,167,45,168,152,96,
116,100,217,101,112,104,12,31,237,206,
241,177,70,93,98,127,171,155,32,253,
71,1,94,239,209,166,119,152,198,48,
228,4,109,234,225,184,9,148,255,165,
16,221,115,188,84,205,145,34,38,16,
126,219,41,175,82,70,139,32,179,57,
102,250,204,40,60,118,86,239,148,236,
130,90,211,38,32,97,168,41,143,228,
8,201,255,154,161,249,161,20,146,174,
81,96,228,116,253,145,19,236,137,130,
64,6,220,198,129,68,155,100,245,56,
2,124,150,111,141,0,185,145,89,226,
127,1,100,201,46,241,191,140,75,67,
252,48,238,92,148,129,23,199,140,92,
119,2,213,185,52,190,115,110,153,192,
193,0,112,167,181,106,128,199,12,87,
109,62,39,204,196,65,35,27,179,42,
6,178,156,20,181,102,166,129,236,104,
229,251,120,96,30,55,53,130,142,48,
44,134,157,58,47,76,141,129,226,105,
110,12,186,173,0,58,24,65,190,224,
88,90,197,55,139,187,102,232,34,84,
140,125,20,233,200,154,201,173,20,116,
74,10,162,165,107,50,180,90,132,86,
139,208,106,81,87,38,2,132,47,83,
87,232,202,48,198,140,15,74,224,248,
48,176,86,108,229,247,156,24,137,73,
40,118,8,69,52,209,34,40,54,150,
69,209,32,20,73,197,164,48,54,109,
194,81,203,192,177,217,224,97,128,14,
143,3,116,56,146,92,241,90,92,243,
90,70,26,152,180,37,2,38,51,58,
203,41,229,132,245,116,166,146,202,239,
101,122,113,33,173,44,102,61,203,213,
18,59,51,12,212,211,149,243,31,14,
48,216,135,125,32,199,209,145,134,198,
158,124,245,236,99,103,126,143,252,23,
15,87,69,106,10,119,122,105,20,97,
3,194,85,106,197,112,85,58,74,207,
165,40,245,49,176,55,101,38,120,118,
183,222,84,156,180,91,194,105,194,250,
241,57,115,79,238,43,78,250,202,113,
218,10,112,186,96,22,201,245,45,6,
134,179,120,172,227,24,21,157,52,62,
36,52,8,154,6,65,211,32,104,26,
4,77,163,32,52,79,165,42,196,103,
99,202,171,79,156,235,27,183,63,251,
146,69,70,77,66,168,73,8,53,151,
162,236,3,244,94,111,114,188,215,77,
157,97,224,40,177,17,27,97,106,18,
76,77,130,201,38,152,108,130,201,150,
218,254,3,112,55,113,186,101,2,92,
35,81,166,75,102,126,237,40,71,252,
219,92,185,44,98,138,149,49,29,212,
230,188,200,100,67,67,234,228,151,238,
114,114,195,129,155,179,38,65,101,146,
241,79,115,13,233,129,145,108,236,14,
48,192,244,158,7,154,222,35,91,197,
177,3,171,17,195,150,224,1,161,52,
27,49,67,150,252,166,132,33,43,237,
140,168,139,69,35,226,246,90,177,43,
14,149,223,35,135,1,68,233,138,38,
198,223,28,89,143,132,168,117,42,109,
133,62,122,133,96,210,218,244,44,106,
215,135,145,36,176,84,49,146,100,206,
75,224,249,48,102,230,127,90,237,156,
123,193,137,44,97,104,188,133,110,26,
128,5,56,70,193,250,142,131,117,2,
83,6,28,162,237,192,61,7,219,10,
194,109,121,214,149,93,53,57,1,188,
153,60,152,116,193,181,244,93,33,63,
212,134,10,157,112,44,213,2,225,12,
216,138,22,22,7,75,51,201,247,65,
79,103,23,29,54,84,190,86,139,60,
31,3,74,12,39,230,98,248,34,130,
33,68,140,32,217,195,66,59,213,230,
86,89,246,24,97,75,3,108,5,32,
133,72,86,198,212,140,99,19,168,26,
7,213,209,132,248,218,140,199,136,104,
224,206,241,48,153,234,18,172,38,199,
213,36,96,29,147,128,117,56,176,142,
41,250,235,240,101,236,127,137,117,112,
170,10,190,248,1,166,209,152,251,164,
227,177,31,226,180,146,225,58,153,40,
252,32,221,173,192,175,207,10,193,47,
132,232,2,244,51,231,93,83,98,37,
6,183,251,12,194,158,25,72,136,61,
150,58,150,136,52,161,40,69,26,7,
113,0,24,21,125,76,138,95,20,222,
237,0,222,107,140,169,64,50,202,85,
17,251,199,159,212,246,147,45,84,123,
94,0,223,34,246,79,83,96,140,56,
179,2,223,90,152,40,151,14,110,203,
40,7,174,15,156,234,6,49,18,4,
80,203,103,138,31,229,49,100,158,142,
81,140,127,219,21,249,183,208,48,197,
67,123,174,45,228,8,112,56,141,105,
140,126,13,25,253,250,112,138,60,209,
228,126,92,147,59,114,172,140,39,93,
80,20,106,76,128,90,99,78,205,252,
55,0,173,186,82,74,246,61,156,17,
131,242,19,251,150,84,87,85,249,153,
213,158,51,200,115,231,146,226,243,228,
149,163,207,89,190,95,9,27,32,174,
168,102,213,192,65,18,153,255,144,33,
195,212,112,151,109,189,102,191,127,102,
223,192,80,7,207,48,119,146,99,181,
152,173,214,110,90,33,102,254,48,223,
99,131,252,7,246,207,239,186,209,61,
101,238,12,186,45,169,38,166,93,62,
176,80,194,192,44,62,196,20,2,10,
251,41,240,95,114,108,1,203,19,106,
44,42,139,65,234,15,215,251,65,226,
193,57,12,216,235,73,31,118,138,155,
233,165,178,205,4,235,147,211,159,77,
64,218,4,164,153,48,212,185,233,25,
205,54,139,1,26,5,240,9,7,240,
13,90,52,115,62,53,137,58,40,76,
104,20,139,222,8,121,123,129,95,93,
44,128,3,83,140,37,181,49,176,121,
208,100,90,106,90,82,138,100,48,103,
30,78,180,97,172,194,255,50,62,137,
12,219,13,26,77,4,37,45,142,113,
177,73,35,205,148,233,41,5,128,86,
136,176,63,103,164,251,243,190,205,226,
0,203,125,74,93,54,103,132,61,59,
173,239,151,131,177,140,83,238,114,235,
209,141,91,143,174,93,0,196,34,238,
230,178,1,32,185,138,106,50,4,201,
43,143,122,65,193,100,155,152,33,233,
243,229,152,91,216,23,202,71,129,47,
97,8,250,164,184,144,148,5,195,181,
12,67,181,105,16,134,173,56,134,118,
9,8,91,82,61,148,26,53,52,245,
91,197,170,241,181,48,78,152,26,87,
67,44,117,44,169,247,182,120,247,45,
14,154,175,112,52,73,146,237,174,232,
178,78,43,164,73,202,71,151,70,113,
235,26,249,54,137,213,212,200,159,52,
15,124,21,97,210,28,8,22,241,162,
47,58,125,33,251,218,156,115,251,26,
190,140,124,12,45,223,245,27,251,28,
73,65,143,98,152,250,121,129,3,112,
97,100,136,78,141,152,115,237,107,95,
25,239,58,115,188,70,12,101,201,8,
114,255,143,99,170,203,48,117,76,185,
195,210,225,209,181,14,79,234,232,180,
40,82,132,110,137,63,71,222,13,221,
20,127,206,92,136,142,167,131,24,122,
211,255,100,48,218,104,80,102,171,103,
179,170,237,83,98,68,33,159,47,18,
123,43,145,133,197,252,67,169,122,194,
246,1,223,62,160,237,1,148,56,90,
183,249,96,221,38,13,245,33,69,5,
61,32,215,176,92,103,127,139,120,102,
143,46,241,17,186,80,222,96,25,91,
146,107,230,84,58,25,42,120,210,210,
209,37,45,48,145,150,33,19,207,192,
228,170,136,30,115,202,90,144,83,6,
213,39,28,168,63,163,1,238,155,229,
15,56,136,186,210,175,144,222,214,46,
178,142,166,136,75,163,199,77,156,56,
128,76,85,36,161,136,98,97,51,205,
148,196,130,15,104,140,46,131,211,118,
136,19,243,3,247,209,204,249,51,27,
49,233,0,83,108,233,145,15,153,154,
175,115,142,116,128,81,231,50,50,84,
111,21,178,199,129,5,243,30,147,164,
33,236,48,79,164,222,139,176,181,170,
206,57,168,197,103,1,3,95,69,111,
149,79,10,244,13,193,60,175,239,192,
55,157,15,146,166,115,30,116,47,130,
49,247,3,174,250,40,59,205,32,159,
33,92,94,245,48,159,60,50,207,96,
75,173,105,95,249,138,68,98,197,145,
88,170,124,190,69,51,14,38,11,146,
6,76,209,14,124,194,182,95,99,192,
43,111,249,233,42,58,112,179,120,0,
86,192,176,147,63,104,248,233,169,130,
57,189,162,238,235,235,32,228,230,159,
99,172,112,237,58,152,200,164,212,165,
74,216,49,227,147,93,174,116,212,144,
207,31,10,9,190,142,156,2,101,246,
160,24,198,9,167,185,184,21,19,141,
99,147,186,178,27,108,55,105,88,110,
149,211,214,39,129,231,124,129,174,204,
123,6,60,95,34,145,173,179,171,75,
136,203,26,167,77,233,18,57,136,131,
68,16,215,202,204,192,164,105,45,217,
55,86,210,9,204,67,240,105,4,193,
127,97,16,103,7,35,21,165,49,196,
192,96,137,197,174,1,142,70,190,43,
93,121,126,0,124,229,2,131,16,6,
33,156,182,36,33,29,147,124,112,131,
255,197,159,126,25,113,99,18,110,145,
38,100,35,214,165,56,115,152,39,133,
159,184,20,94,227,140,151,131,217,175,
87,56,249,0,12,12,49,226,157,144,
96,202,211,9,45,165,42,170,216,82,
54,137,43,182,96,77,97,168,45,201,
37,165,44,80,157,199,136,116,30,90,
103,37,114,9,23,79,116,124,27,113,
225,196,130,153,40,173,200,84,153,25,
159,41,3,123,223,27,12,251,55,139,
65,244,73,3,46,138,197,194,128,220,
121,36,137,212,69,113,28,227,156,198,
71,20,212,105,106,13,23,199,128,0,
25,16,55,12,8,135,193,30,106,241,
96,220,199,93,198,99,170,59,160,226,
12,10,111,16,245,226,168,65,252,177,
15,224,177,9,77,138,214,156,166,214,
84,107,146,70,77,98,197,126,208,162,
23,172,61,78,48,31,49,227,218,120,
29,153,242,185,10,184,216,225,57,31,
48,244,57,202,239,140,71,252,217,139,
193,254,107,6,252,113,143,78,126,200,
190,239,143,224,9,44,3,122,196,74,
3,255,243,34,85,170,95,197,159,191,
2,117,111,161,174,177,252,121,212,138,
167,240,171,216,111,132,206,139,137,238,
17,23,93,15,159,38,224,176,14,252,
65,34,190,49,7,49,169,81,209,154,
106,226,211,73,124,122,45,190,10,226,
123,202,197,55,102,0,57,236,166,33,
138,242,155,32,196,167,129,168,100,251,
156,22,216,167,154,96,109,18,172,93,
11,182,130,96,183,131,126,9,19,4,
96,224,68,157,29,55,50,121,224,215,
157,102,212,85,19,160,65,2,52,106,
1,46,209,51,73,16,215,104,27,93,
250,176,9,61,83,190,207,105,129,125,
150,162,92,85,173,37,91,65,178,161,
249,101,99,138,77,184,22,209,229,179,
0,254,246,211,148,237,213,164,214,36,
169,53,107,161,45,33,180,17,154,155,
78,228,137,83,46,143,131,248,219,79,
83,182,87,19,90,155,132,214,174,133,
182,132,208,6,8,204,44,128,197,23,
78,184,253,52,101,123,53,161,153,36,
52,179,22,90,5,161,61,225,66,219,
227,207,162,249,3,73,47,106,191,60,
225,98,146,237,113,154,187,71,53,145,
118,72,164,157,90,164,21,68,250,144,
139,180,139,115,177,87,193,12,173,27,
60,16,226,50,232,131,226,214,106,226,
114,72,92,78,45,174,10,226,218,10,
156,66,232,57,180,204,90,244,231,195,
26,209,159,15,107,170,137,110,70,162,
155,213,162,91,98,196,123,131,201,159,
243,196,136,23,110,63,77,217,94,77,
104,115,18,218,188,22,218,18,190,250,
40,156,59,11,156,130,237,192,142,140,
214,157,102,212,85,19,160,75,2,116,
99,13,123,28,104,211,92,153,42,125,
148,200,123,156,218,243,231,240,125,237,
17,235,79,115,234,171,53,82,229,209,
99,40,251,106,4,216,65,95,139,253,
210,99,191,140,216,175,9,9,96,31,
131,226,85,180,245,41,215,86,168,153,
130,73,129,147,159,93,156,140,143,234,
107,75,174,36,186,9,202,20,169,122,
169,153,97,173,214,177,219,241,90,163,
25,214,78,91,226,177,173,172,67,219,
25,135,170,98,139,196,110,114,255,154,
191,186,222,89,179,216,26,113,122,198,
113,26,227,178,153,125,204,118,132,125,
147,61,72,151,53,144,218,17,215,148,
136,162,192,191,212,214,203,128,92,215,
69,54,4,101,152,91,189,192,220,170,
107,229,132,175,213,252,45,95,35,181,
78,195,110,118,82,52,169,237,240,6,
230,107,100,177,243,108,72,207,13,250,
107,216,135,243,112,242,187,85,118,227,
242,113,42,118,158,59,198,233,121,132,
225,88,79,229,61,248,45,230,238,81,
202,99,78,223,109,116,24,147,107,41,
221,42,217,231,162,228,37,85,185,117,
93,228,142,113,126,33,224,28,65,56,
143,37,95,134,109,153,54,52,219,78,
131,97,230,178,234,120,101,71,60,50,
19,237,21,95,104,67,52,123,15,51,
81,49,71,5,211,42,131,209,201,203,
177,235,180,134,238,136,3,70,104,24,
169,211,78,91,157,166,25,70,234,220,
112,217,175,88,109,96,24,181,236,185,
211,80,211,12,163,228,137,85,177,69,
162,20,239,95,243,239,88,55,30,113,
221,128,244,70,154,221,134,23,38,124,
204,211,8,153,9,161,69,43,69,91,
216,8,219,173,217,25,134,178,104,124,
52,94,154,225,105,83,45,19,191,57,
133,212,97,115,219,126,199,186,176,205,
117,33,242,72,106,86,151,171,9,173,
22,100,120,202,59,151,217,48,147,112,
6,61,164,213,18,237,130,8,158,112,
96,219,77,235,92,116,225,52,211,139,
253,95,88,25,54,184,249,119,172,15,
91,145,88,192,31,200,15,151,17,109,
48,100,141,234,180,141,150,42,12,151,
122,112,103,211,153,233,8,92,106,6,
181,45,71,155,171,114,72,230,238,108,
234,204,146,18,189,155,38,108,136,84,
44,124,37,198,141,32,21,169,146,119,
244,14,179,27,211,148,220,208,224,147,
166,228,211,230,84,159,170,41,74,222,
106,37,123,79,168,228,179,57,124,164,
88,64,199,50,139,18,246,70,55,127,
67,56,155,188,149,164,253,156,226,143,
165,55,139,251,23,162,96,150,56,207,
10,227,202,123,131,254,205,98,111,16,
153,78,157,35,78,135,152,131,13,182,
109,151,253,189,193,7,224,248,243,112,
243,96,57,145,173,92,123,123,35,235,
102,209,239,237,193,159,87,136,159,197,
252,98,240,61,78,148,169,242,63,100,
3,121,253,222,107,92,32,232,162,173,
124,197,16,245,34,199,108,249,139,224,
152,79,13,11,148,174,149,247,252,136,
127,83,26,177,61,183,195,246,36,246,
253,70,81,133,189,183,88,91,62,32,
215,206,149,137,242,5,202,148,243,62,
194,86,219,184,38,244,207,80,43,248,
222,15,149,255,82,26,225,71,56,114,
143,221,149,203,109,189,35,124,146,219,
161,210,231,71,254,63,101,161,180,177,
182,197,90,199,218,167,104,202,207,236,
187,195,182,192,55,216,54,195,199,233,
152,108,91,155,213,208,53,154,184,103,
155,253,85,89,13,252,242,4,28,194,
135,61,238,98,140,230,67,112,111,127,
99,199,232,74,83,104,229,1,178,27,
197,43,100,247,231,134,31,225,200,46,
174,114,186,198,140,48,11,179,53,175,
83,113,220,138,200,39,27,241,39,145,
61,253,108,179,75,178,147,2,121,182,
133,187,120,194,176,158,65,60,10,159,
2,129,235,158,81,215,152,247,149,122,
149,16,167,62,127,82,150,141,41,54,
81,180,68,153,62,139,232,205,17,230,
165,94,243,39,72,159,227,232,224,95,
75,21,174,21,72,34,120,253,222,39,
108,227,85,112,132,30,59,226,49,62,
166,243,74,249,61,117,127,177,93,180,
226,44,214,47,165,210,156,177,179,201,
180,245,41,62,206,224,79,30,63,133,
158,60,75,28,191,21,215,118,166,75,
174,208,138,168,198,31,178,246,210,138,
140,115,254,44,114,58,203,183,220,243,
153,11,24,29,160,14,102,95,61,162,
139,210,171,211,123,209,24,78,140,133,
108,236,75,121,247,32,226,240,34,96,
28,210,232,203,84,253,16,101,240,255,
217,213,127,103,215,31,96,127,154,99,
28,240,146,247,171,19,118,228,7,166,
245,244,164,182,143,76,99,46,80,167,
47,217,182,40,102,167,108,255,99,90,
199,202,175,242,40,194,184,59,17,206,
69,138,174,192,206,99,76,36,251,237,
222,178,179,200,94,53,59,215,236,92,
179,115,205,206,247,155,157,127,224,236,
108,177,115,251,107,113,105,127,244,58,
21,122,19,195,125,229,108,173,230,236,
154,179,107,206,174,57,251,171,226,236,
173,36,103,223,91,134,86,107,134,174,
25,186,102,232,154,161,191,42,134,222,
230,12,253,43,106,253,175,236,26,191,
49,91,244,190,114,180,81,115,116,205,
209,53,71,215,28,253,85,113,180,111,
69,71,56,250,222,50,180,94,51,116,
205,208,53,67,215,12,253,85,50,244,
152,33,15,215,3,121,220,87,134,110,
213,12,93,51,116,205,208,53,67,223,
67,134,150,104,65,157,121,87,179,243,
82,236,44,114,89,205,206,53,59,215,
236,236,179,115,40,217,85,176,115,157,
121,87,179,115,205,206,53,59,215,236,
188,73,236,92,103,222,213,156,93,115,
118,205,217,53,103,223,31,206,174,51,
239,106,134,174,25,186,102,232,154,161,
55,149,161,235,204,187,154,163,107,142,
174,57,186,230,232,205,229,232,58,243,
174,102,232,154,161,107,134,174,25,122,
211,25,186,206,188,171,25,186,102,232,
154,161,107,134,190,27,134,238,179,189,
64,59,35,156,37,228,118,112,125,74,
176,115,54,207,137,168,181,18,44,153,
199,117,54,235,179,29,197,96,159,25,
195,200,92,9,215,45,163,111,79,99,
247,43,151,48,140,27,154,192,174,209,
163,178,179,2,227,251,210,83,24,67,
134,48,51,70,153,36,111,235,172,37,
205,91,209,54,95,131,118,98,58,84,
86,219,158,113,109,11,223,12,242,46,
182,215,114,218,103,39,102,139,191,70,
237,251,55,165,189,38,221,203,138,18,
110,186,238,61,229,186,23,229,122,209,
26,253,158,107,31,228,70,48,139,114,
163,242,140,197,76,135,58,203,120,147,
44,81,93,176,73,106,75,52,223,18,
213,132,118,213,150,104,53,75,84,21,
218,177,105,150,232,227,144,79,25,67,
71,238,112,9,134,30,179,43,156,35,
211,214,12,93,51,116,17,134,214,106,
134,174,25,186,142,21,72,25,250,73,
200,167,202,44,147,163,159,197,152,106,
7,91,75,111,127,250,16,241,226,30,
199,86,253,173,210,127,19,121,37,143,
253,154,156,211,92,100,51,224,188,54,
251,24,108,127,159,253,116,246,13,222,
77,10,109,240,175,99,34,95,186,232,
245,1,7,214,254,219,250,237,3,153,
182,84,209,189,103,200,102,31,112,108,
142,157,77,121,9,31,137,6,230,233,
208,84,233,48,45,112,216,95,24,9,
231,56,130,26,200,113,190,14,65,92,
0,52,200,101,26,230,107,42,236,109,
178,223,160,121,51,182,127,92,135,254,
147,93,169,203,176,114,17,73,226,212,
119,12,179,75,228,85,224,249,63,217,
239,235,0,103,208,174,255,13,16,123,
128,87,222,129,191,177,179,126,175,204,
10,198,163,214,35,201,60,236,163,45,
120,160,216,130,198,125,195,80,106,10,
251,56,57,252,140,204,90,65,75,182,
99,58,231,215,137,186,145,101,23,138,
125,41,79,139,52,100,25,147,105,3,
147,5,178,14,104,7,232,75,117,38,
42,98,197,180,4,76,243,71,125,163,
226,168,159,54,218,45,195,151,155,54,
82,202,245,38,174,129,143,25,151,206,
152,231,241,25,91,185,19,193,202,127,
75,222,46,34,122,193,234,134,1,162,
87,21,152,9,116,194,96,245,46,218,
239,42,142,110,42,187,103,35,97,219,
155,156,153,108,28,5,97,252,155,177,
127,96,93,117,110,133,153,158,178,253,
46,96,44,66,123,233,29,151,233,59,
246,251,55,101,154,34,193,103,194,49,
239,185,45,29,63,234,111,236,126,154,
130,142,111,179,122,144,218,71,246,247,
29,106,217,231,212,89,195,173,216,190,
112,151,179,148,61,31,197,246,252,77,
241,223,119,89,236,188,209,251,140,239,
249,60,245,62,227,45,151,221,233,139,
212,99,197,246,201,142,22,175,236,75,
37,121,111,183,51,99,37,239,23,113,
198,155,33,91,93,11,250,16,74,77,
118,159,207,164,71,21,65,40,75,7,
243,174,41,199,86,212,70,209,67,74,
235,39,243,12,47,83,142,73,118,31,
121,28,57,170,72,111,124,34,217,63,
239,94,146,71,228,105,150,188,85,233,
247,254,84,122,239,41,253,166,20,75,
111,177,45,32,135,27,60,127,85,219,
81,103,92,11,28,59,197,177,124,142,
236,216,225,227,127,56,234,67,61,220,
71,3,237,75,96,232,14,198,5,102,
104,67,138,209,151,245,48,244,227,80,
54,120,182,11,229,28,237,137,43,111,
127,196,64,219,31,77,110,22,103,195,
30,188,109,237,45,21,94,184,77,107,
54,105,43,124,241,4,214,228,210,88,
233,89,183,73,87,87,126,78,240,127,
87,121,206,245,48,165,76,55,203,106,
119,132,97,43,107,119,220,254,208,2,
251,163,89,219,31,181,253,113,239,236,
15,89,159,168,109,143,218,246,184,125,
219,227,187,232,211,25,42,241,50,92,
213,192,72,67,135,251,133,96,77,180,
36,188,220,184,83,94,94,79,79,142,
227,87,14,251,23,202,1,90,43,127,
87,44,156,107,250,140,215,132,251,130,
248,202,106,236,192,89,96,7,106,27,
104,7,190,71,254,123,23,198,222,132,
227,228,115,168,219,236,56,178,242,108,
92,179,254,25,236,167,148,158,3,163,
70,18,219,34,71,62,199,232,34,205,
168,241,184,85,161,227,214,163,103,69,
116,165,156,246,253,196,36,122,153,184,
195,191,139,209,189,21,233,161,19,232,
161,186,113,122,248,12,245,47,122,207,
197,52,107,42,193,239,238,52,164,156,
60,203,233,202,118,184,133,213,82,187,
63,72,98,216,225,108,39,96,48,203,
200,66,200,31,87,102,56,174,216,124,
148,128,89,15,13,51,36,227,49,108,
208,40,59,150,75,128,51,169,152,67,
57,95,225,108,218,67,38,153,63,112,
14,22,228,244,37,24,115,147,115,234,
15,82,179,14,100,17,235,117,197,142,
101,242,138,203,252,1,59,63,60,159,
105,30,145,242,0,125,81,154,151,165,
252,131,42,177,98,23,51,60,26,76,
54,32,9,232,239,46,206,81,133,51,
161,13,180,9,64,66,119,235,171,173,
11,125,25,142,121,232,63,231,61,213,
127,82,214,14,143,79,238,178,86,252,
1,243,76,21,36,161,161,12,52,236,
75,54,90,0,14,43,13,156,69,140,
90,103,77,156,251,41,150,145,115,159,
36,145,143,105,92,42,223,6,243,216,
36,147,240,119,149,94,160,178,58,23,
61,28,35,152,49,241,35,115,155,20,
177,88,15,246,33,118,217,24,111,249,
191,89,203,142,240,236,201,76,187,178,
104,107,127,57,180,101,40,102,227,254,
20,51,113,96,22,31,108,236,157,224,
248,234,17,58,144,128,142,185,28,36,
1,13,207,15,92,99,160,221,215,196,
81,28,112,6,57,53,89,93,7,173,
68,144,137,139,50,112,110,69,2,63,
32,166,254,157,251,126,244,165,212,118,
251,134,181,48,62,98,255,152,122,244,
63,89,105,43,31,98,22,194,55,160,
109,183,32,255,108,105,102,107,194,115,
101,159,29,245,25,237,197,115,156,235,
206,211,134,127,199,136,95,244,136,40,
14,62,62,159,131,153,254,31,152,148,
95,162,69,144,254,41,187,90,43,30,
17,110,4,17,97,253,47,210,227,243,
165,150,45,245,199,202,175,10,60,239,
237,227,10,250,126,135,175,90,130,184,
79,43,240,235,52,100,95,88,209,52,
197,12,38,240,231,90,104,211,79,89,
57,71,43,125,134,214,137,142,22,199,
109,200,226,57,219,135,238,186,108,191,
127,33,61,242,46,251,124,186,4,243,
152,31,100,232,199,14,242,251,250,199,
200,222,209,123,79,207,0,43,235,237,
53,25,218,38,90,156,45,212,141,159,
113,127,138,34,26,56,142,187,56,118,
168,56,70,52,49,75,110,142,58,52,
103,117,176,135,157,240,246,214,163,63,
47,82,209,72,230,152,117,110,137,249,
179,164,25,215,132,135,60,99,237,18,
51,190,63,5,235,110,227,91,203,247,
127,7,25,22,124,60,200,61,35,143,
143,178,252,147,30,95,251,43,228,98,
17,193,34,168,63,99,231,249,132,121,
253,84,179,19,100,203,201,251,225,79,
200,79,225,254,239,112,190,237,10,215,
173,94,23,92,37,80,214,142,54,54,
216,142,254,49,3,143,85,88,32,89,
231,151,141,23,205,91,233,237,121,90,
83,68,243,30,199,183,46,229,119,65,
198,168,134,255,154,124,254,167,131,150,
64,59,161,47,126,174,233,215,213,243,
211,177,20,227,61,199,152,233,1,115,
25,190,20,118,209,254,217,9,107,42,
219,95,115,196,179,129,217,187,83,140,
179,57,136,180,142,227,167,195,173,98,
248,219,196,53,83,126,62,48,88,93,
115,180,221,192,39,187,29,251,203,198,
187,126,199,176,242,239,186,88,127,250,
81,122,228,103,94,138,217,219,105,115,
71,235,210,130,52,89,138,253,145,214,
29,198,51,196,253,231,94,28,96,139,
47,214,190,206,48,158,117,93,191,113,
202,199,225,254,173,52,140,75,178,88,
142,190,152,239,144,191,210,80,92,253,
183,73,43,13,193,215,42,187,234,64,
204,96,169,215,26,222,254,90,67,243,
22,88,249,219,148,85,19,114,22,246,
159,15,119,140,231,7,91,47,57,195,
185,106,38,22,115,249,106,38,254,43,
49,113,249,53,223,95,23,19,39,215,
10,214,92,252,181,174,251,78,227,226,
239,216,157,125,64,219,127,198,244,194,
207,73,140,110,171,50,23,232,98,84,
144,252,77,135,199,160,59,145,181,106,
180,138,182,193,56,232,110,87,209,174,
43,39,49,138,95,156,193,160,55,126,
145,248,75,208,167,58,232,5,66,174,
70,71,96,73,39,56,95,250,145,29,
156,205,211,11,200,247,5,106,34,221,
193,37,246,18,208,240,157,37,165,62,
195,249,134,54,142,51,29,148,122,11,
103,23,59,49,169,79,49,114,220,137,
73,29,254,185,184,239,237,196,144,215,
149,33,152,143,234,221,234,194,15,152,
15,243,133,183,138,86,75,127,97,223,
13,46,13,88,139,183,199,117,36,58,
130,66,76,155,216,176,250,220,180,137,
35,225,28,123,56,197,167,77,156,107,
136,198,167,91,152,7,163,227,124,2,
252,165,223,6,234,211,253,214,141,44,
52,171,203,232,153,48,243,48,193,214,
64,187,239,74,78,148,51,120,127,229,
148,135,104,117,89,109,161,45,118,73,
22,204,29,202,7,182,221,95,249,200,
80,140,203,228,71,204,45,59,87,40,
22,108,177,54,156,243,111,96,97,131,
119,17,149,202,247,97,126,224,154,101,
210,102,146,104,99,102,78,27,51,116,
224,111,11,199,202,38,90,71,247,87,
38,73,12,227,18,121,132,216,207,49,
115,23,252,115,63,27,214,207,130,31,
161,151,117,141,156,248,94,161,103,123,
130,95,117,131,253,42,122,237,42,86,
9,204,156,205,209,247,118,209,211,133,
249,145,57,30,225,75,199,70,91,180,
141,253,163,193,87,201,104,220,114,237,
176,26,200,168,168,146,199,156,22,143,
248,22,237,4,39,226,137,138,145,133,
117,229,167,151,65,26,254,59,178,152,
16,189,95,241,239,104,119,114,179,232,
246,134,231,11,215,117,13,248,120,3,
250,213,192,255,188,238,40,144,248,247,
56,7,2,79,246,181,17,21,39,152,
113,153,6,113,246,75,140,214,15,177,
119,206,189,113,255,100,186,96,231,216,
61,62,199,194,58,95,232,115,211,235,
246,15,207,23,170,215,61,58,58,95,
204,89,193,54,219,94,215,218,195,157,
172,1,214,89,7,248,171,59,164,226,
21,22,189,99,126,130,189,1,254,30,
79,112,223,65,23,127,13,198,88,28,
211,70,107,196,246,117,188,238,132,42,
39,116,246,137,69,23,57,162,243,81,
113,184,11,173,60,134,86,53,188,254,
137,10,205,233,159,104,112,154,254,137,
142,197,128,109,212,88,161,81,161,67,
225,13,162,216,184,136,77,240,244,156,
96,124,112,19,209,175,211,212,26,142,
215,128,218,60,160,187,28,64,99,53,
246,11,239,107,48,238,227,46,227,49,
213,29,80,113,6,133,55,57,235,222,
44,232,194,15,152,99,72,131,220,39,
38,240,87,55,139,55,35,182,143,217,
240,14,120,57,177,126,101,231,99,18,
158,28,178,187,152,28,246,207,23,109,
119,102,184,248,52,158,201,217,96,53,
39,242,246,206,70,55,139,193,209,4,
110,161,55,28,67,49,26,226,157,140,
118,81,1,135,168,27,35,168,130,147,
140,38,252,55,67,66,245,118,71,67,
42,44,184,233,221,221,30,254,218,237,
99,97,77,64,125,70,195,62,28,176,
15,39,109,120,191,140,254,113,190,104,
66,105,209,207,19,42,70,112,252,254,
224,16,138,95,44,216,199,102,229,30,
253,156,192,233,126,177,186,8,236,112,
132,136,30,67,227,246,173,33,108,27,
90,167,80,244,169,24,90,40,129,158,
117,4,135,237,245,44,184,153,227,183,
22,252,26,90,248,235,96,130,138,117,
48,33,162,236,35,193,67,167,253,19,
75,76,155,246,206,6,184,239,217,17,
182,127,50,198,211,177,35,161,56,235,
239,226,201,7,103,236,4,138,119,124,
100,220,44,216,159,243,69,203,195,194,
165,66,165,162,33,20,172,28,192,254,
76,125,154,30,22,108,192,56,182,26,
116,46,75,229,165,198,75,29,203,189,
227,30,236,55,217,197,30,55,25,189,
129,226,12,110,68,245,122,221,83,220,
167,215,69,173,235,117,119,113,107,127,
23,127,245,143,110,22,195,193,196,93,
52,94,54,189,201,201,136,190,140,15,
249,150,238,9,255,226,245,206,16,98,
239,232,152,53,239,232,184,143,231,244,
70,251,199,232,208,142,20,27,135,155,
29,54,188,29,30,161,192,70,135,67,
42,96,215,255,230,83,221,29,52,119,
136,234,91,152,254,106,243,233,88,216,
74,169,176,26,159,40,135,96,4,76,
135,171,56,117,110,227,178,150,25,147,
18,107,177,119,56,36,225,190,101,146,
30,238,190,101,52,248,106,31,54,156,
142,81,231,134,188,151,190,97,23,154,
34,167,217,104,19,94,122,195,33,66,
116,100,225,126,71,61,60,77,255,16,
21,160,55,4,74,216,131,83,246,94,
193,246,189,33,92,203,243,94,31,178,
123,126,77,59,121,94,226,122,13,126,
189,109,100,87,120,106,58,172,117,165,
185,219,89,236,138,141,66,87,60,60,
218,15,54,156,157,12,240,169,7,84,
196,159,129,128,157,121,74,125,121,74,
93,217,140,247,228,169,106,67,16,118,
178,139,183,81,248,70,30,134,128,161,
68,37,183,160,150,4,205,219,31,247,
111,22,251,39,103,208,240,253,147,183,
88,88,236,151,222,98,229,91,42,253,
193,139,13,103,46,59,162,207,12,139,
253,62,94,115,191,255,42,82,181,223,
63,128,14,222,127,13,23,58,177,144,
112,79,44,84,104,111,212,239,177,203,
142,113,88,122,61,62,34,218,237,69,
138,241,63,142,129,101,244,142,214,54,
19,136,30,246,221,133,202,122,50,232,
63,43,199,123,150,187,104,107,222,216,
58,197,193,102,191,135,99,45,180,97,
4,247,189,182,1,214,184,255,3,108,
1,108,158,37,176,25,251,221,70,129,
133,223,75,34,164,222,127,132,124,237,
241,39,11,150,208,30,149,153,135,85,
245,71,93,18,29,117,189,250,19,162,
179,164,254,136,24,149,209,160,59,198,
232,49,199,104,151,225,67,175,156,185,
196,68,160,247,129,91,77,88,133,24,
102,161,3,237,142,192,211,50,8,31,
172,207,197,199,52,98,248,52,98,248,
232,90,28,161,217,146,125,76,35,132,
52,66,200,32,132,12,66,200,240,172,
209,175,36,85,11,70,71,103,202,54,
156,208,109,88,214,9,110,40,131,225,
35,142,33,184,121,255,82,104,193,121,
158,158,233,154,76,209,178,129,84,59,
28,74,109,234,148,128,210,49,9,74,
220,190,54,48,181,78,49,48,159,114,
48,123,232,113,211,115,3,192,23,129,
53,134,95,2,15,43,84,74,154,223,
187,200,246,59,121,175,85,245,194,180,
175,54,12,121,183,109,100,116,219,102,
131,144,68,62,0,36,93,187,112,207,
213,204,194,88,234,166,70,88,234,234,
172,52,118,217,29,186,61,35,232,76,
135,144,155,175,200,160,104,100,13,151,
90,69,178,43,6,89,85,128,254,193,
250,41,133,183,162,0,25,77,2,72,
157,10,186,229,114,136,26,132,145,147,
213,81,65,45,242,117,11,9,49,130,
19,176,41,224,132,74,181,6,160,146,
186,21,116,212,170,29,116,140,129,52,
232,160,159,50,213,76,237,172,86,207,
86,59,168,174,71,207,190,227,24,129,
179,121,45,69,167,45,168,152,96,116,
100,217,101,112,104,12,31,237,206,241,
177,70,93,98,127,171,155,32,253,71,
1,94,148,0,238,96,248,247,131,160,
77,189,32,166,242,165,16,221,115,188,
84,205,145,34,38,16,126,219,41,175,
82,70,139,32,179,57,102,250,204,40,
60,118,86,239,148,236,130,90,211,38,
32,97,168,41,143,228,136,18,168,96,
18,179,20,146,174,81,96,228,116,253,
145,19,236,137,130,64,6,220,198,129,
68,155,100,245,56,2,124,150,111,141,
0,185,145,89,226,127,1,100,201,46,
241,191,140,75,67,252,48,238,92,148,
129,23,199,140,92,119,2,213,185,52,
190,115,110,153,192,193,0,112,167,181,
106,128,199,12,87,109,62,39,204,196,
65,35,27,179,42,6,178,156,20,181,
102,166,129,236,104,229,251,120,96,30,
55,53,130,142,48,44,134,157,58,47,
76,141,129,226,105,110,12,186,173,0,
186,75,140,174,93,4,139,143,202,249,
102,113,215,12,93,132,138,177,143,34,
29,89,51,185,149,130,78,73,65,180,
116,77,134,86,139,208,106,17,90,45,
234,202,68,128,240,101,234,10,93,25,
198,152,241,65,9,28,31,6,214,138,
173,252,158,19,35,49,9,197,14,161,
136,38,90,4,197,198,178,40,26,132,
34,169,152,20,198,166,77,56,106,25,
56,54,27,60,12,208,225,113,128,14,
71,146,43,94,139,107,94,203,72,3,
147,182,68,192,100,70,103,57,165,156,
224,211,21,29,229,247,50,189,184,144,
86,22,179,158,229,106,137,157,25,6,
234,233,202,249,15,7,24,236,195,62,
144,227,232,72,67,99,79,190,122,246,
177,51,191,71,254,139,135,171,34,53,
133,59,189,52,138,176,1,225,42,181,
98,184,42,29,165,231,82,148,250,24,
216,163,185,252,251,136,147,118,75,56,
77,48,43,225,143,123,139,147,190,114,
156,182,2,156,46,112,85,195,237,5,
134,179,120,172,227,24,21,157,52,62,
36,52,8,154,6,65,211,32,104,26,
4,77,163,32,52,79,165,42,196,103,
99,202,171,79,156,235,27,183,63,251,
146,69,70,77,66,168,73,8,53,151,
162,236,3,158,9,144,237,189,110,234,
12,3,71,137,141,216,8,83,147,96,
106,18,76,54,193,100,19,76,182,212,
246,31,96,206,236,53,230,98,50,174,
145,40,211,37,51,191,118,120,94,224,
239,56,239,94,192,20,43,99,58,168,
205,121,145,201,134,134,212,201,47,221,
229,228,134,3,55,103,77,130,202,36,
227,159,230,26,210,3,35,217,216,29,
240,181,75,225,83,118,69,236,192,106,
196,176,37,120,64,40,205,70,204,144,
37,191,41,97,200,74,59,35,234,98,
209,136,184,189,86,236,138,67,229,247,
200,112,153,87,186,162,137,241,55,71,
214,35,33,106,157,74,91,161,143,94,
33,152,180,54,61,139,218,245,97,36,
9,44,85,140,36,153,243,18,120,62,
140,153,249,159,86,59,231,94,112,34,
75,24,26,111,161,155,6,96,1,142,
81,176,190,227,96,157,192,148,65,240,
12,88,223,61,191,228,171,197,242,172,
43,187,106,114,2,120,51,121,48,233,
130,107,233,187,66,126,168,13,21,58,
225,88,170,5,194,25,176,21,45,44,
14,150,102,146,239,131,158,206,46,58,
108,168,124,173,22,121,62,6,148,24,
78,204,197,240,69,4,195,11,76,6,
139,230,127,39,121,46,27,81,199,44,
12,41,68,178,50,166,102,28,155,64,
213,56,168,142,38,196,215,102,60,70,
68,3,119,142,135,201,84,151,96,53,
57,174,38,1,235,152,4,172,195,129,
117,76,209,95,135,47,99,255,75,172,
131,83,85,240,197,15,48,141,198,220,
39,133,100,82,10,113,90,201,112,157,
76,20,126,144,238,86,224,215,103,133,
224,23,66,116,1,250,153,243,174,41,
177,18,131,219,125,6,97,207,12,36,
196,30,75,29,75,68,154,80,148,34,
141,131,56,0,140,138,62,38,197,47,
10,239,118,0,47,173,111,254,132,171,
204,10,216,63,254,164,182,159,108,161,
218,243,2,248,22,177,127,154,2,99,
196,153,21,248,214,194,68,185,116,112,
91,70,57,112,125,224,84,55,136,145,
32,128,90,62,83,252,40,143,33,243,
116,140,98,252,219,174,200,191,133,134,
41,30,218,115,109,33,71,128,195,105,
76,99,244,107,200,232,215,135,83,228,
137,38,247,227,154,220,145,99,101,60,
233,130,162,80,99,2,212,26,115,106,
230,191,1,104,213,149,82,178,239,225,
140,248,34,200,164,186,194,34,153,17,
219,254,175,252,185,164,248,60,121,229,
232,115,150,239,87,194,6,136,43,170,
89,53,112,144,68,230,63,100,200,224,
131,178,63,225,50,159,159,249,178,38,
27,31,109,148,51,201,177,90,204,86,
107,55,173,16,51,127,152,15,31,181,
79,93,55,186,167,204,157,65,183,37,
213,196,180,203,7,22,74,24,152,197,
135,152,66,64,97,63,5,254,75,142,
45,96,121,66,141,69,101,49,72,253,
225,122,63,72,60,192,85,71,235,73,
31,118,138,155,233,165,178,205,4,235,
147,211,159,77,64,218,4,164,153,48,
212,185,233,25,205,54,139,1,26,5,
240,9,7,240,13,61,174,132,79,77,
70,95,216,241,125,224,100,23,137,222,
8,121,123,129,95,93,44,128,3,83,
140,37,181,49,176,121,208,100,90,106,
90,82,138,100,48,103,30,78,180,97,
172,194,255,50,62,137,12,219,13,26,
77,4,37,45,142,113,177,73,35,205,
148,233,41,5,128,86,136,176,63,103,
164,251,243,190,205,226,0,203,125,74,
93,54,103,132,61,59,173,239,151,131,
177,140,83,238,114,235,209,141,91,143,
174,93,0,196,34,238,230,178,1,32,
185,138,106,50,4,201,43,143,122,65,
193,100,155,152,33,233,243,229,152,91,
216,23,202,71,129,47,233,25,67,176,
212,8,28,156,115,25,134,106,211,32,
12,91,113,12,237,18,16,182,164,122,
40,53,106,104,234,183,138,85,227,107,
97,156,48,53,174,134,88,234,88,82,
239,109,241,238,91,28,52,95,225,104,
146,36,219,93,209,101,157,86,72,147,
148,143,46,141,226,214,53,242,109,18,
171,169,145,63,105,30,248,42,194,164,
57,16,44,226,69,95,116,250,66,246,
181,57,231,246,53,124,25,249,24,90,
190,235,55,246,57,146,130,30,197,48,
245,243,2,7,248,152,113,9,162,83,
35,230,92,251,218,87,198,187,206,28,
175,17,67,89,50,130,220,255,227,152,
234,50,76,29,83,238,176,116,120,116,
173,195,147,58,58,45,138,20,161,91,
226,207,145,119,67,55,197,159,51,23,
162,227,233,32,134,222,52,61,85,30,
159,1,150,169,158,205,170,182,79,137,
17,133,124,190,72,236,173,68,22,22,
243,15,165,234,9,219,7,124,251,128,
182,7,80,226,104,221,230,131,117,155,
52,212,135,20,21,244,128,92,195,114,
157,253,45,226,153,61,186,196,71,232,
66,121,131,101,108,73,174,153,83,233,
100,168,224,73,75,71,151,180,192,68,
90,134,76,60,3,147,171,34,122,204,
41,107,65,224,209,210,159,148,240,245,
130,190,89,254,128,131,168,43,253,10,
233,109,237,34,235,104,138,184,52,122,
220,196,137,3,200,84,69,18,138,40,
22,54,211,76,73,44,248,128,198,232,
50,56,109,135,56,49,63,208,127,224,
89,38,98,210,1,166,216,210,35,31,
50,53,95,231,28,233,0,163,206,101,
100,168,222,42,100,143,3,11,230,61,
61,45,2,159,56,33,166,222,139,176,
181,170,206,57,168,197,103,1,3,95,
69,111,149,79,10,244,13,193,60,175,
239,192,55,157,15,146,166,115,30,116,
47,130,49,247,3,174,250,40,59,205,
32,159,33,92,94,245,48,159,60,50,
207,96,75,173,105,95,249,138,68,98,
197,145,88,170,124,190,69,51,14,38,
11,146,6,76,209,14,76,79,161,252,
80,228,233,32,43,232,192,205,226,1,
88,1,195,78,254,160,225,167,167,10,
230,244,138,186,175,175,131,35,122,240,
6,206,184,174,89,7,19,153,148,186,
84,9,59,102,124,178,203,149,142,26,
242,249,67,33,193,215,145,83,160,204,
30,20,195,56,225,52,23,183,98,162,
113,108,82,87,118,131,237,38,13,203,
173,114,218,250,36,240,156,47,208,149,
121,143,111,40,189,202,141,152,169,171,
75,136,203,26,167,77,233,18,57,136,
131,68,16,215,202,204,192,164,105,45,
217,55,86,210,9,204,67,240,105,4,
193,127,97,16,103,7,35,21,165,49,
196,192,96,137,197,174,1,142,70,190,
43,93,121,126,0,124,229,2,131,16,
6,33,156,182,36,33,29,147,124,112,
131,255,197,159,126,25,113,99,18,110,
145,38,100,35,214,165,56,115,152,39,
133,159,184,20,232,41,86,14,102,191,
94,241,183,116,250,79,82,11,8,166,
60,157,208,82,170,162,138,45,101,147,
184,98,11,214,20,134,218,146,92,82,
202,2,213,121,140,72,231,161,117,86,
34,151,112,241,68,199,183,17,23,78,
44,152,137,210,138,76,149,153,241,153,
50,176,247,189,193,176,127,179,216,184,
71,65,13,162,94,28,53,136,63,246,
1,60,54,161,73,209,154,211,212,154,
106,77,210,168,73,172,216,15,90,244,
130,181,199,9,230,35,102,92,27,175,
35,83,62,87,1,23,59,60,231,227,
3,127,46,206,155,96,246,98,176,255,
154,1,15,143,45,130,147,31,178,239,
251,240,236,33,246,189,23,121,128,89,
164,74,245,171,248,243,87,160,238,45,
212,53,150,63,143,90,241,20,126,21,
251,141,208,121,49,209,61,226,162,235,
225,211,4,28,124,172,120,82,124,145,
87,84,10,226,139,214,84,19,159,78,
226,211,107,241,85,16,223,83,46,190,
49,127,254,30,189,203,46,46,196,167,
129,168,100,251,156,22,216,167,154,96,
109,18,172,93,11,182,130,96,183,131,
126,9,19,4,96,224,68,157,29,55,
50,121,224,215,157,102,212,85,19,160,
65,2,52,106,1,46,209,51,253,183,
72,92,160,237,196,97,19,122,166,124,
159,211,2,251,44,69,185,170,90,75,
182,130,100,67,243,203,198,20,155,112,
45,162,203,103,1,252,237,167,41,219,
171,73,173,73,82,107,214,66,91,66,
104,35,52,55,157,200,19,167,92,30,
7,241,183,159,166,108,175,38,180,54,
9,173,93,11,109,9,161,13,232,109,
58,1,44,190,112,194,237,167,41,219,
171,9,205,36,161,153,181,208,42,8,
237,9,23,218,30,127,22,205,31,72,
122,81,251,229,9,23,147,108,143,211,
220,61,170,137,180,67,34,237,212,34,
173,32,210,135,92,164,93,156,139,189,
10,102,104,221,224,129,16,151,65,31,
20,183,86,19,151,67,226,114,106,113,
85,16,215,86,224,20,66,207,161,101,
214,162,63,31,214,136,254,124,88,83,
77,116,51,18,221,172,22,221,18,35,
222,27,133,30,226,45,142,120,225,246,
211,148,237,213,132,54,39,161,205,107,
161,45,225,171,143,194,185,179,192,41,
216,14,236,200,104,221,105,70,93,53,
1,186,36,64,55,214,176,199,129,54,
193,19,198,251,40,145,247,56,181,231,
207,225,251,218,35,214,159,230,212,87,
107,164,202,163,199,80,246,213,8,176,
131,190,22,251,165,199,126,25,177,95,
19,18,192,62,6,197,171,104,235,83,
174,173,80,51,5,147,2,39,63,187,
56,25,31,213,215,150,92,73,116,19,
148,41,82,245,82,51,195,90,173,99,
183,227,181,70,51,172,157,182,196,99,
91,89,135,182,51,14,85,197,22,137,
221,228,254,53,127,117,189,179,102,177,
53,226,244,140,227,52,198,101,51,251,
152,237,8,251,38,123,144,46,107,32,
181,35,174,41,17,69,129,127,169,173,
151,1,185,174,139,108,8,202,48,183,
122,129,185,85,215,202,9,95,171,249,
91,190,70,106,157,134,221,236,164,104,
82,219,225,13,204,215,200,98,231,217,
144,158,27,244,215,176,15,231,225,228,
119,171,236,198,229,227,84,236,60,119,
140,211,243,8,195,177,158,202,123,240,
91,204,221,163,148,199,156,190,219,232,
48,38,215,82,186,85,178,207,69,201,
75,170,114,235,186,200,29,227,252,66,
192,57,130,112,30,75,190,12,219,50,
109,104,182,157,6,195,204,101,213,241,
202,142,120,100,38,218,43,190,208,134,
104,246,30,102,162,98,142,10,166,85,
6,163,147,151,99,215,105,13,221,17,
7,140,208,48,82,167,157,182,58,77,
51,140,212,185,225,178,95,177,218,192,
48,106,217,115,167,161,166,25,70,201,
19,171,98,139,68,41,222,191,230,223,
177,110,60,226,186,225,191,77,144,222,
254,253,49,79,35,100,38,132,22,173,
20,109,97,35,108,183,102,103,24,202,
162,241,209,120,105,134,167,77,181,76,
252,230,20,82,135,205,109,251,29,235,
194,54,215,133,200,35,169,89,93,174,
38,180,90,144,225,41,239,92,102,195,
76,194,25,244,144,86,75,180,11,34,
120,194,129,109,55,173,115,209,133,211,
76,47,246,127,97,101,216,224,230,223,
177,62,108,69,98,1,127,32,63,92,
70,180,193,144,53,170,211,54,90,170,
48,92,234,193,157,77,103,166,35,112,
169,25,212,182,28,109,174,202,33,153,
187,179,169,51,75,74,244,110,154,176,
33,82,177,240,149,24,55,130,84,164,
74,222,209,59,204,110,76,83,114,67,
131,79,154,146,79,155,83,125,170,166,
40,121,171,149,236,61,161,146,207,230,
240,145,98,1,29,203,44,74,216,27,
221,252,13,225,108,242,86,146,246,115,
138,63,150,222,44,238,95,136,130,89,
226,60,43,140,43,239,13,250,55,139,
200,91,144,159,160,205,242,78,57,196,
28,108,176,109,131,55,194,7,243,112,
243,96,57,145,173,92,39,222,117,188,
205,250,209,123,244,61,78,148,169,242,
63,100,3,229,188,107,120,203,95,4,
199,124,106,88,160,116,173,188,231,71,
252,155,240,206,225,237,200,27,234,197,
125,147,111,40,222,98,109,249,128,92,
59,87,38,202,23,40,83,206,251,8,
91,109,227,154,208,63,67,173,224,123,
63,84,254,139,191,43,29,63,194,145,
121,239,118,110,99,109,11,223,227,12,
239,108,134,215,124,58,108,139,22,188,
219,25,30,167,99,178,109,109,124,183,
51,124,154,184,103,155,253,85,89,13,
252,242,4,28,194,135,61,238,98,140,
38,124,163,243,223,240,125,234,77,161,
149,7,200,110,20,175,144,221,159,27,
126,132,35,187,184,202,233,26,51,194,
44,204,214,188,78,197,113,43,34,159,
108,196,159,68,246,244,179,205,46,201,
78,10,228,217,22,238,226,73,240,14,
111,120,10,4,174,123,70,93,99,222,
87,234,85,66,156,250,252,73,89,54,
166,216,68,209,18,101,250,44,162,55,
71,152,151,122,205,159,32,125,142,163,
131,127,45,85,184,86,32,137,224,245,
123,159,176,141,87,193,17,122,236,136,
199,248,152,206,43,229,247,212,253,197,
118,209,138,179,88,191,148,74,19,222,
35,46,211,214,167,248,56,131,63,121,
252,20,122,242,44,113,252,86,92,219,
153,46,185,21,222,43,254,45,247,124,
230,2,70,7,168,131,217,87,143,232,
162,244,234,244,94,52,134,19,99,33,
27,251,82,222,61,136,56,188,8,24,
135,52,250,50,85,63,68,25,172,231,
173,231,143,34,140,187,19,225,92,47,
246,142,250,124,118,222,226,236,252,43,
106,253,175,236,26,191,221,91,134,214,
107,134,174,25,186,102,232,154,161,191,
42,134,222,78,50,180,162,221,91,142,
54,106,142,174,57,186,230,232,154,163,
191,42,142,246,99,28,99,92,142,113,
127,45,104,145,189,106,118,174,217,185,
102,231,154,157,239,55,59,251,49,142,
49,67,30,174,7,242,184,175,12,221,
170,25,186,102,232,154,161,107,134,254,
170,24,250,7,206,208,22,59,183,255,
204,49,218,31,103,215,21,122,227,228,
125,229,108,173,230,236,154,179,107,206,
174,57,251,171,226,108,223,170,142,112,
246,189,101,104,181,102,232,154,161,107,
134,174,25,250,30,50,180,68,11,234,
204,187,154,157,151,98,103,145,203,106,
118,174,217,185,102,103,159,157,67,201,
46,195,206,117,230,93,205,208,53,67,
215,12,93,51,244,166,50,116,157,121,
87,115,116,205,209,53,71,215,28,189,
185,28,93,103,222,213,236,92,179,115,
205,206,53,59,111,34,59,215,153,119,
53,67,215,12,93,51,116,205,208,155,
202,208,117,230,93,205,217,53,103,215,
156,93,115,246,253,225,236,58,243,174,
102,232,154,161,107,134,174,25,250,110,
25,186,207,246,2,237,140,112,86,240,
116,124,98,232,240,93,13,239,98,123,
137,108,157,205,123,34,138,118,194,174,
205,227,62,155,245,225,142,98,176,207,
140,97,102,174,132,251,150,209,191,167,
177,251,77,147,120,91,224,218,232,49,
217,57,130,241,125,233,153,140,33,95,
100,205,132,38,89,92,103,247,223,188,
21,221,243,245,105,39,166,43,101,117,
207,159,17,225,92,182,164,174,181,18,
113,175,175,81,215,192,102,209,214,164,
109,230,61,214,182,167,92,219,162,92,
47,90,163,223,115,125,131,152,1,179,
40,55,42,207,88,140,0,212,89,198,
155,100,137,234,130,77,82,91,162,249,
150,168,38,180,171,182,68,171,89,162,
170,208,142,77,179,68,31,135,124,202,
24,58,114,135,75,48,244,152,93,225,
28,153,182,102,232,154,161,139,48,180,
86,51,116,205,208,117,172,64,202,208,
79,66,62,85,102,153,28,253,44,198,
84,59,216,90,122,251,211,135,136,223,
182,29,91,245,231,215,137,76,157,197,
186,162,95,155,199,114,26,190,95,212,
100,125,150,121,63,76,106,192,104,26,
251,52,2,150,131,109,176,15,180,221,
151,138,137,188,232,162,127,7,92,231,
149,230,136,150,192,17,249,125,202,168,
216,167,210,116,105,153,254,176,105,122,
40,215,155,42,26,248,56,118,166,85,
198,171,196,145,45,79,51,155,124,84,
117,113,60,133,81,183,205,62,6,219,
191,186,102,214,241,170,117,88,168,50,
109,169,162,123,207,176,239,127,64,78,
139,157,77,121,9,31,137,6,230,233,
208,84,233,48,45,112,216,95,176,197,
230,104,195,25,56,202,250,58,4,177,
41,208,32,23,57,143,52,21,246,6,
22,4,205,155,177,253,227,58,244,159,
236,74,93,134,149,139,72,18,3,189,
99,152,93,34,11,129,165,241,39,251,
125,29,224,12,218,245,191,1,98,15,
240,202,59,240,55,118,214,239,149,89,
193,168,212,122,36,153,135,125,180,5,
15,20,91,208,184,111,24,74,77,97,
31,39,199,66,64,62,142,105,201,99,
166,201,51,230,121,124,70,28,118,34,
156,226,191,37,111,23,57,255,130,213,
13,3,206,191,170,160,23,192,13,6,
171,119,209,126,87,145,91,84,134,169,
145,176,237,77,174,23,54,114,16,176,
207,140,253,3,235,170,115,43,122,241,
148,237,119,1,76,128,246,210,59,62,
234,188,99,191,127,83,166,41,76,242,
76,56,230,61,183,165,227,71,253,141,
221,79,83,144,218,54,171,7,173,248,
200,254,190,67,78,252,156,58,107,184,
21,219,23,238,114,150,178,231,163,216,
158,191,41,254,251,46,139,157,55,122,
159,241,61,159,167,222,103,188,229,178,
59,125,145,122,172,216,62,217,209,226,
149,125,169,36,239,237,118,102,172,228,
253,34,110,147,205,208,158,186,22,244,
33,148,154,236,62,159,73,143,42,130,
80,150,14,230,93,83,142,173,168,141,
162,135,148,214,79,230,25,94,166,28,
147,236,62,242,56,114,84,145,222,248,
68,178,127,222,189,36,143,200,211,44,
121,171,210,239,253,169,244,222,83,250,
77,41,150,254,137,177,224,101,224,189,
115,43,94,249,187,232,9,84,30,211,
117,198,194,192,190,83,180,246,200,26,
236,176,150,170,49,187,16,234,225,14,
27,56,238,3,119,119,48,98,48,195,
177,93,140,203,172,135,187,159,225,24,
24,189,231,119,216,111,65,79,63,5,
190,144,40,153,23,172,229,73,252,138,
28,185,30,118,41,39,207,114,186,178,
29,121,151,222,14,111,247,7,137,191,
27,198,29,0,131,89,70,60,48,127,
228,7,13,48,208,186,113,208,203,181,
49,98,215,17,188,10,208,40,59,22,
213,195,152,6,206,103,206,87,232,85,
60,100,146,249,3,163,33,32,167,47,
25,209,173,7,169,241,63,153,119,187,
46,63,83,38,175,114,50,223,98,91,
128,167,111,80,147,86,195,2,243,128,
5,244,141,99,129,199,33,119,227,217,
46,148,115,236,55,87,222,254,136,129,
182,63,154,220,44,206,134,61,120,27,
227,91,42,188,112,155,214,108,210,86,
248,226,9,186,206,217,122,165,103,221,
166,177,108,229,231,132,248,216,42,207,
185,30,253,150,233,102,57,237,126,161,
28,160,76,254,206,124,40,136,184,127,
198,43,131,206,0,91,174,70,219,103,
129,182,107,27,168,237,239,113,158,232,
93,232,255,9,199,201,103,146,182,217,
113,164,203,69,70,200,43,9,182,69,
142,124,142,30,238,166,140,172,69,116,
165,156,246,125,23,93,181,81,201,47,
214,112,116,84,185,238,252,140,177,183,
153,210,146,248,197,126,180,228,110,252,
226,245,72,36,142,95,217,113,45,226,
123,85,238,233,241,200,132,22,68,38,
154,117,100,162,142,76,220,187,200,132,
172,79,212,81,137,58,42,177,250,168,
196,3,166,165,176,110,113,30,240,241,
115,238,161,250,107,24,119,120,132,108,
151,157,237,15,136,111,87,96,103,24,
21,117,246,23,44,42,27,217,217,97,
165,129,179,8,81,118,110,226,44,84,
177,156,144,251,52,62,230,99,154,39,
149,109,108,209,39,62,91,78,89,33,
85,34,248,46,230,221,52,80,30,46,
162,238,226,188,77,56,59,216,64,73,
128,183,126,183,227,228,186,60,113,25,
142,113,244,191,13,102,17,9,251,240,
119,21,188,85,86,231,34,143,25,193,
140,137,239,121,111,146,93,178,30,188,
67,236,178,49,222,242,127,179,150,29,
225,217,147,153,118,101,209,214,254,114,
104,203,80,204,198,253,185,178,207,206,
240,25,61,186,115,156,159,220,9,206,
33,183,197,255,29,173,185,232,17,254,
72,115,137,163,148,141,51,178,159,131,
12,148,31,24,186,47,145,113,210,63,
101,215,73,196,173,253,70,96,237,235,
127,17,57,231,75,45,91,234,79,17,
85,223,99,206,151,248,199,200,222,81,
105,167,207,189,151,141,47,55,153,68,
76,28,235,91,236,252,45,28,151,92,
238,65,27,216,135,93,140,57,171,152,
151,208,196,252,4,200,50,5,43,202,
196,61,108,69,140,47,175,71,162,47,
82,209,72,206,238,119,110,197,91,200,
150,102,158,38,140,121,143,133,232,82,
158,38,20,233,153,192,192,58,102,210,
16,3,107,120,126,19,229,8,179,77,
77,148,35,244,63,23,37,57,67,91,
196,192,190,234,98,223,116,110,69,142,
63,4,92,5,119,30,151,163,24,215,
250,134,181,48,46,201,31,83,143,254,
39,43,109,229,67,108,94,226,27,96,
161,91,209,132,44,105,102,107,194,99,
229,87,5,86,196,127,92,129,22,116,
248,10,54,232,191,173,32,198,170,225,
56,12,171,219,166,216,155,161,191,183,
112,78,105,138,61,217,197,89,38,13,
163,178,96,249,223,134,22,60,103,251,
208,93,151,213,128,23,210,35,239,82,
250,233,18,140,75,254,33,207,83,186,
196,140,239,79,193,218,199,248,214,242,
82,119,112,172,5,111,2,178,99,201,
183,160,44,255,164,111,209,254,10,71,
101,17,193,34,168,63,142,111,93,202,
250,85,49,27,207,69,63,159,162,208,
29,236,133,237,132,85,228,103,126,126,
93,248,167,99,89,68,18,207,216,25,
63,225,10,11,170,217,9,50,171,229,
44,248,19,242,67,184,255,59,140,111,
94,225,122,245,235,130,235,53,202,122,
52,198,6,123,52,63,102,224,177,10,
175,32,235,252,50,190,110,222,10,231,
230,105,141,24,215,57,198,153,92,152,
197,243,251,255,46,142,122,59,97,77,
229,81,119,142,82,135,204,111,24,97,
29,140,178,53,208,214,250,25,107,166,
60,71,67,103,216,168,104,111,211,138,
5,24,107,231,56,98,131,77,118,59,
163,174,141,119,253,142,97,231,223,117,
49,41,254,40,61,242,51,47,197,220,
217,180,89,211,117,241,79,154,44,227,
90,240,157,210,195,86,126,102,251,94,
5,51,144,209,109,85,34,31,46,250,
65,196,235,14,183,179,58,145,204,92,
202,216,110,48,89,223,109,198,246,186,
102,32,163,248,197,103,159,160,55,126,
145,104,7,228,1,117,80,231,33,6,
218,17,152,217,9,206,151,126,100,7,
125,23,189,128,124,95,224,202,7,186,
131,75,28,157,128,209,119,150,148,250,
12,109,234,54,218,88,29,148,122,11,
125,169,78,76,234,83,244,149,59,49,
169,195,63,23,247,189,29,175,121,93,
153,0,249,168,222,173,46,252,128,113,
230,47,188,85,180,126,227,11,251,110,
112,105,64,230,241,30,215,145,232,250,
47,176,224,105,205,95,117,79,220,196,
104,201,28,123,56,89,227,38,70,87,
162,214,120,11,231,92,116,140,160,192,
95,250,109,160,62,221,111,221,200,66,
179,186,140,182,112,124,191,164,12,197,
59,147,205,12,183,221,95,217,200,80,
172,46,147,103,66,252,107,130,173,128,
246,222,157,124,154,247,122,52,205,67,
52,46,171,31,113,30,243,156,251,92,
22,107,207,57,255,6,107,200,109,156,
239,12,165,245,125,56,239,182,102,249,
180,153,84,218,24,135,108,99,60,18,
254,182,112,172,108,162,117,116,127,229,
147,196,48,46,145,71,136,253,28,179,
163,193,254,245,51,142,253,149,6,35,
244,75,175,145,19,225,219,31,40,161,
115,100,203,157,216,181,171,88,37,224,
157,206,209,78,119,113,222,30,226,16,
115,60,194,151,142,141,182,104,27,251,
74,131,231,196,105,220,114,237,176,26,
136,26,86,201,21,79,179,247,191,69,
59,193,137,248,21,226,12,197,186,214,
0,148,65,90,140,82,208,211,73,226,
107,61,253,231,151,30,99,27,192,3,
78,230,253,175,250,137,36,98,70,89,
253,110,90,194,225,254,61,147,36,190,
26,186,202,243,6,138,60,147,68,124,
78,200,38,61,147,4,98,241,229,158,
160,144,92,73,92,63,151,228,107,125,
46,201,183,41,207,128,144,115,177,255,
180,200,3,100,212,139,181,243,176,81,
243,240,95,152,135,197,60,212,191,26,
15,139,118,72,205,194,119,193,194,230,
109,179,176,55,218,157,220,44,186,189,
225,249,194,117,93,3,62,222,128,126,
53,240,63,175,59,10,120,250,123,156,
247,128,103,71,219,40,3,39,152,101,
153,6,76,125,137,17,250,33,250,168,
115,111,220,63,153,46,216,57,118,143,
207,177,176,206,23,250,220,244,186,253,
195,243,133,234,117,143,142,206,23,115,
86,176,205,182,215,181,246,112,39,107,
128,117,214,1,254,234,14,169,120,133,
69,239,152,159,96,111,128,191,199,19,
220,119,208,197,95,131,49,22,199,180,
209,26,177,125,29,175,59,161,202,9,
157,125,98,209,69,142,232,124,84,28,
238,66,43,143,161,85,13,175,127,162,
66,115,250,39,26,156,166,127,162,99,
49,96,27,53,86,104,84,232,80,120,
131,40,54,46,98,19,60,175,36,240,
40,220,132,71,113,154,90,195,241,26,
80,155,7,116,151,3,104,172,198,126,
225,125,13,198,125,220,101,60,166,186,
3,42,206,160,240,38,103,221,155,5,
93,248,1,19,51,133,21,62,121,71,
214,171,155,197,155,17,219,199,108,120,
7,188,156,88,191,178,243,49,9,79,
14,217,93,76,14,251,231,139,182,59,
51,92,124,254,201,228,108,176,154,19,
121,123,103,163,155,197,224,104,2,183,
208,27,142,161,24,13,241,78,70,187,
108,119,246,3,117,99,4,85,112,146,
209,132,255,102,72,168,222,238,104,72,
133,5,55,189,187,219,195,95,187,125,
44,172,9,168,207,104,216,135,3,246,
225,164,13,239,151,209,63,206,23,77,
40,45,250,121,66,197,8,142,223,31,
28,66,241,139,5,251,216,172,220,163,
159,19,56,221,47,86,23,129,29,142,
16,209,99,104,220,190,53,132,109,67,
235,20,138,62,21,67,11,37,208,179,
142,224,176,189,158,5,55,115,252,214,
130,95,67,11,127,29,76,80,177,14,
38,20,46,232,227,16,2,157,240,79,
44,49,81,221,59,27,224,190,103,71,
216,254,201,24,79,199,142,132,226,172,
191,139,39,31,156,177,19,40,222,241,
145,113,179,96,127,206,23,45,15,11,
151,10,149,138,134,80,176,114,0,251,
51,245,105,122,88,176,1,228,216,106,
208,185,44,149,151,26,47,117,44,247,
142,123,176,223,100,23,123,220,100,244,
6,138,51,184,17,213,235,117,79,113,
159,94,23,181,174,215,221,197,173,253,
93,252,213,63,186,89,12,7,19,119,
209,120,217,244,38,39,35,250,50,62,
228,91,186,39,252,139,215,59,67,136,
189,163,99,214,188,163,227,62,158,211,
27,237,31,95,193,180,206,72,177,113,
200,221,97,195,221,225,17,10,108,116,
56,164,2,118,253,111,70,208,54,134,
4,27,24,112,130,48,71,19,141,158,
6,78,200,205,49,8,5,161,15,48,
254,52,172,117,216,118,23,141,29,10,
134,64,232,16,164,196,90,236,13,223,
50,17,15,119,223,50,254,123,181,15,
151,57,29,147,180,249,146,128,174,66,
15,200,135,229,36,52,113,58,243,134,
67,68,231,136,244,226,168,135,69,255,
16,101,223,27,2,27,236,193,73,123,
175,96,251,222,144,93,230,240,104,63,
216,112,118,50,192,37,197,84,196,23,
24,99,175,154,82,167,154,82,159,50,
227,93,106,170,218,96,217,76,118,89,
219,225,191,215,135,12,197,215,116,109,
207,75,189,145,135,140,141,109,140,245,
94,34,180,146,91,80,179,111,33,255,
90,42,191,214,22,27,161,230,108,52,
216,9,175,25,187,158,90,8,178,196,
245,188,253,62,179,253,247,251,7,208,
37,251,175,97,143,19,11,41,242,196,
66,21,244,254,15,159,155,129,53,90,
63,109,62,0,0,0,190,109,107,66,
83,120,156,93,78,203,14,130,48,16,
236,205,223,240,19,0,131,224,17,202,
195,134,173,26,168,17,188,129,177,9,
87,77,154,152,205,254,187,45,32,7,
231,50,147,153,157,205,200,42,53,88,
212,124,68,159,90,224,26,61,234,102,
186,137,76,99,16,238,233,40,148,70,
63,10,168,206,27,141,142,155,235,104,
15,210,210,182,244,2,130,14,12,66,
210,25,76,171,114,176,241,181,6,71,
112,146,111,100,27,6,172,103,31,246,
100,47,182,101,62,201,102,10,57,216,
18,207,93,147,87,206,200,65,26,20,
178,92,141,246,92,76,155,102,250,91,
120,105,237,108,207,163,163,19,253,131,
84,115,31,49,246,72,9,251,81,137,
108,196,72,31,130,216,167,69,135,209,
208,255,116,31,236,246,171,14,227,144,
40,83,137,65,90,240,5,167,166,95,
89,32,237,4,88,0,0,10,181,109,
107,66,84,250,206,202,254,0,127,87,
186,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,120,
156,237,157,141,145,219,56,12,70,83,
72,26,73,33,41,36,141,164,144,20,
146,70,82,72,110,144,155,119,243,238,
11,72,201,89,175,29,219,120,51,158,
213,234,135,164,8,18,162,0,144,250,
249,115,24,134,97,24,134,97,24,134,
97,24,134,97,120,73,190,127,255,254,
219,239,199,143,31,255,29,187,39,85,
142,123,151,225,217,249,240,225,195,111,
191,175,95,191,254,170,247,218,190,103,
253,87,57,170,12,195,251,129,188,207,
226,246,240,150,254,185,187,182,142,213,
111,39,127,174,71,87,13,123,62,126,
252,216,214,213,74,254,238,255,108,127,
250,244,233,215,223,111,223,190,253,252,
242,229,203,127,250,162,246,23,181,175,
242,41,42,47,206,229,24,231,145,78,
253,92,174,218,207,177,218,111,249,147,
118,157,91,105,90,95,213,177,97,207,
74,206,157,254,47,58,249,127,254,252,
249,215,54,245,79,255,45,185,148,12,
144,57,50,98,63,231,84,254,200,20,
153,215,254,108,23,244,107,206,37,63,
183,19,218,2,229,27,246,236,228,95,
50,242,248,175,232,228,207,49,228,66,
127,181,12,145,115,181,21,247,89,228,
199,53,224,62,190,58,134,62,0,202,
99,61,49,236,217,201,255,172,254,79,
249,119,239,12,232,121,228,94,127,171,
45,32,215,218,182,44,253,204,88,201,
223,122,0,232,251,149,158,117,195,208,
115,77,249,35,215,146,85,93,235,62,
72,95,247,152,192,121,248,89,146,199,
118,186,33,219,137,245,140,229,95,109,
196,105,12,255,82,117,226,254,115,180,
31,93,205,88,156,109,31,167,95,103,
251,41,89,89,222,41,15,250,109,230,
93,215,121,44,151,178,172,109,218,32,
122,134,49,201,234,154,97,24,134,97,
24,134,97,120,69,24,199,223,147,71,
176,215,167,255,243,111,47,239,89,242,
221,250,30,92,234,107,186,54,245,174,
120,132,203,232,237,106,7,207,230,103,
72,157,240,150,246,190,187,150,247,243,
157,252,207,216,241,143,124,134,121,158,
247,117,190,196,46,189,149,252,255,134,
254,243,22,92,254,244,179,97,207,195,
166,142,77,38,253,119,233,219,195,23,
228,107,233,35,157,207,144,250,36,63,
206,93,249,3,77,231,111,164,140,92,
143,253,200,190,44,219,47,237,223,218,
165,151,242,183,31,226,81,219,64,202,
223,126,54,31,115,63,41,125,137,206,
44,185,32,27,108,190,236,231,156,244,
11,216,103,88,32,35,236,118,5,231,
81,231,180,15,147,246,103,183,29,218,
12,247,66,158,153,22,242,238,236,217,
153,94,202,223,117,244,168,227,129,174,
255,3,117,104,189,224,190,109,63,142,
125,123,93,140,208,46,126,200,125,208,
118,95,247,255,74,59,235,120,231,111,
204,103,74,246,235,244,89,93,146,222,
179,235,127,64,182,233,3,46,236,171,
41,153,225,111,113,127,67,150,252,191,
147,63,125,223,62,64,199,251,88,159,
192,206,223,152,242,39,45,252,0,228,
211,201,255,40,189,87,145,63,207,246,
250,155,178,177,188,139,244,197,219,23,
231,250,222,233,6,244,137,219,9,186,
197,186,24,118,254,198,148,191,207,235,
228,79,156,202,153,244,82,254,156,215,
249,195,254,118,236,91,75,63,91,65,
125,165,63,45,253,119,246,237,229,181,
212,109,209,213,145,253,125,60,71,200,
99,229,75,132,149,191,49,125,136,188,
167,117,229,241,120,230,76,122,222,166,
30,30,85,254,195,48,12,195,48,12,
195,80,99,91,236,155,252,60,62,191,
103,92,61,246,128,25,99,191,31,182,
125,241,179,77,190,139,11,189,21,127,
195,252,195,103,103,103,211,234,252,224,
214,9,232,14,199,132,231,220,192,244,
45,66,94,235,243,107,95,103,63,204,
242,160,175,70,63,156,163,179,171,32,
255,149,221,215,118,48,124,124,216,142,
208,27,216,127,61,199,167,72,191,80,
198,238,219,103,231,115,236,183,227,47,
199,104,31,216,145,241,73,13,199,116,
253,220,126,23,215,123,145,242,231,250,
110,94,167,125,129,182,239,90,230,248,
15,186,121,68,158,235,151,243,207,236,
183,243,53,232,136,233,255,231,88,201,
127,165,255,87,118,240,244,165,167,79,
29,27,41,237,34,251,177,99,48,206,
28,203,118,89,224,147,216,197,11,12,
255,231,90,242,239,124,126,224,185,95,
37,47,207,5,44,206,244,127,112,92,
128,203,201,185,121,206,176,231,90,242,
47,208,201,233,59,47,120,134,23,214,
225,206,115,245,252,95,233,6,183,57,
63,255,29,171,80,204,220,175,53,221,
187,92,237,91,189,227,121,124,222,217,
2,24,195,231,245,196,141,56,157,212,
207,221,248,159,103,0,228,251,191,203,
202,177,76,123,228,63,12,195,48,12,
195,48,12,231,24,95,224,107,51,190,
192,231,134,62,180,146,227,248,2,159,
27,219,220,198,23,248,122,228,26,171,
201,248,2,95,131,157,252,199,23,248,
252,92,83,254,227,11,124,60,174,41,
255,98,124,129,143,197,202,231,55,190,
192,97,24,134,97,24,134,97,120,110,
46,181,149,116,235,134,28,97,127,18,
63,108,196,247,94,67,227,149,223,17,
118,107,173,172,216,189,35,174,224,253,
220,126,101,251,144,238,41,255,180,51,
60,51,94,215,7,219,27,182,185,194,
107,240,172,100,108,249,99,127,193,38,
183,106,75,43,155,156,229,111,127,34,
101,242,250,60,46,227,202,158,96,155,
193,234,94,40,51,122,204,242,207,246,
232,117,10,159,193,166,108,219,43,54,
187,250,223,118,180,238,155,60,153,134,
215,16,195,175,135,13,190,107,55,93,
255,47,108,211,99,27,91,96,253,79,
218,246,249,208,110,125,189,215,231,242,
154,132,171,239,11,145,71,202,223,235,
142,177,6,154,215,196,122,116,144,17,
184,94,118,223,228,50,41,127,63,59,
87,109,198,114,245,53,157,252,29,111,
228,99,246,31,179,159,254,73,122,236,
63,250,190,152,143,145,79,238,247,122,
120,247,140,123,185,38,216,199,33,251,
133,101,185,122,46,254,169,252,187,253,
157,252,211,23,212,197,34,209,175,209,
237,164,127,244,13,185,221,49,252,20,
214,243,228,193,241,71,103,215,255,237,
123,43,210,143,3,183,146,127,215,30,
108,251,119,60,1,253,61,125,71,221,
189,236,218,70,198,168,144,94,250,41,
31,245,157,129,182,236,122,73,29,112,
228,71,191,149,252,11,175,227,75,236,
0,172,214,156,206,123,205,123,217,201,
223,101,200,239,11,251,154,71,149,127,
145,49,50,233,199,219,173,175,207,113,
175,167,153,105,117,109,102,23,151,147,
62,191,46,191,213,254,221,125,172,174,
205,235,242,156,174,126,158,97,236,63,
12,195,48,12,195,48,12,176,154,91,
117,180,191,155,43,240,55,248,83,118,
113,172,195,239,236,230,214,173,246,121,
206,133,231,10,29,189,63,222,130,145,
127,143,125,24,182,161,229,156,26,88,
249,231,119,237,197,182,145,218,118,204,
63,223,229,176,223,169,240,247,68,240,
255,129,143,249,90,219,147,240,45,113,
47,150,63,223,179,241,61,191,234,60,
17,203,204,126,182,140,155,135,35,253,
223,217,230,173,255,217,230,187,62,182,
211,217,70,107,255,140,219,34,113,254,
248,122,176,1,114,173,191,81,232,111,
9,57,198,196,114,166,44,248,136,238,
173,167,110,205,89,91,59,28,237,167,
111,230,58,1,41,127,64,15,184,45,
96,215,167,45,216,55,139,252,40,123,
206,27,177,223,175,155,83,210,237,167,
221,250,187,64,175,194,181,229,223,245,
159,75,228,239,57,31,232,238,252,214,
160,191,201,184,147,127,62,15,58,159,
110,193,51,233,21,231,10,95,91,255,
95,42,127,235,109,116,176,99,109,236,
195,67,62,228,113,164,255,83,254,180,
141,76,147,248,16,199,8,60,178,63,
231,18,60,110,162,143,209,175,110,33,
255,194,62,61,247,231,221,60,242,188,
54,199,127,59,249,227,199,171,244,115,
252,247,232,254,220,97,24,134,97,24,
134,97,24,134,123,224,120,203,140,153,
92,197,127,222,138,221,251,234,112,29,
120,231,182,63,48,215,139,188,23,35,
255,53,158,223,224,248,122,230,199,209,
143,153,131,99,191,93,166,179,178,161,
120,14,94,250,234,108,135,242,188,160,
149,15,208,199,40,19,215,102,249,177,
255,58,126,31,159,166,203,211,217,163,
94,1,108,160,105,15,197,110,231,53,
26,57,175,179,169,23,158,87,199,207,
126,183,92,59,20,219,63,118,254,110,
142,151,237,187,246,231,146,54,101,204,
114,165,223,209,253,191,243,85,98,83,
126,118,249,167,254,163,94,185,247,85,
12,79,55,79,40,233,124,59,43,249,
83,207,233,71,244,252,52,124,63,216,
102,237,31,180,255,208,247,182,42,63,
199,114,142,151,247,87,126,207,50,207,
111,197,78,254,150,217,159,202,127,165,
255,83,254,57,255,215,126,100,142,97,
171,231,152,231,242,238,214,135,220,201,
223,109,20,72,139,54,246,236,109,192,
88,255,91,255,221,74,254,133,253,144,
126,206,115,46,227,18,218,3,121,156,
209,255,144,109,131,52,217,182,79,220,
237,239,21,124,66,30,255,173,100,252,
158,242,247,248,47,231,248,217,7,152,
254,193,98,53,254,219,201,191,200,121,
254,221,248,239,85,228,63,12,195,48,
12,195,48,12,195,48,12,195,48,12,
195,48,12,195,48,12,195,48,188,46,
196,80,22,151,126,15,4,31,254,42,
214,206,49,64,71,92,226,159,191,228,
220,75,202,240,222,16,223,114,75,88,
255,152,181,115,50,127,226,177,40,223,
165,242,231,186,142,74,235,236,183,22,
186,56,148,142,140,39,62,226,146,88,
64,226,150,188,14,206,81,172,251,81,
253,26,98,163,224,218,113,244,142,157,
242,119,120,137,11,236,98,247,41,147,
191,235,238,184,95,202,75,124,149,143,
145,118,206,23,32,222,220,49,231,142,
213,77,188,54,16,107,8,101,159,101,
45,50,199,155,239,250,53,249,159,57,
151,243,29,63,75,94,142,69,186,164,
126,137,57,242,207,177,81,239,177,174,
89,174,215,70,185,56,150,235,127,17,
15,78,63,229,126,59,58,61,74,60,
151,239,219,223,254,161,45,236,116,0,
241,186,196,146,121,78,65,222,27,199,
233,103,187,254,67,254,142,9,92,225,
251,78,253,226,88,202,75,234,151,115,
41,39,233,94,75,255,103,92,126,226,
231,50,125,155,54,237,125,212,179,191,
183,225,239,41,185,30,220,110,93,79,
187,251,114,222,29,94,27,204,247,179,
106,135,126,134,34,183,238,123,31,112,
230,185,226,249,50,57,119,128,54,148,
28,213,47,208,46,28,159,122,45,118,
237,58,251,43,253,199,255,163,243,178,
77,123,222,87,151,30,253,143,251,74,
89,185,175,90,247,173,202,234,181,162,
96,37,183,140,13,237,210,164,108,57,
143,133,188,18,231,149,237,158,182,153,
28,213,175,207,35,79,207,85,122,43,
232,193,85,255,63,59,238,253,19,249,
115,142,231,220,100,154,126,30,118,241,
224,78,183,155,135,68,157,231,55,42,
46,89,231,171,27,43,118,58,211,121,
101,59,244,248,56,203,125,166,126,233,
255,221,124,133,183,178,43,195,145,222,
133,78,254,57,127,163,224,221,192,125,
149,123,66,198,158,35,116,6,175,233,
152,215,120,238,144,227,213,173,115,143,
88,201,191,107,175,140,83,172,31,86,
237,155,252,47,213,231,187,117,74,61,
111,234,12,71,253,191,240,60,139,213,
187,76,39,255,163,178,243,76,172,242,
58,15,228,68,93,178,54,220,106,172,
102,157,153,242,103,76,152,235,4,122,
157,47,175,43,216,189,91,123,142,153,
223,29,186,114,240,221,67,244,77,174,
89,215,113,166,126,225,232,91,187,28,
123,143,121,139,188,163,174,242,205,121,
26,9,99,5,200,122,65,191,167,222,
244,187,244,145,222,59,211,238,119,239,
132,171,177,128,199,57,151,172,19,122,
201,115,122,87,191,148,251,72,174,156,
243,236,243,86,135,97,120,51,255,0,
160,130,250,32,224,191,37,163,0,0,
14,215,109,107,66,84,250,206,202,254,
0,127,146,129,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,
0,0,120,156,237,157,141,145,28,41,
12,133,29,136,19,113,32,14,196,137,
56,16,7,226,68,28,200,94,233,234,
62,215,187,103,73,64,207,207,254,88,
175,106,106,103,187,105,16,18,8,208,
131,158,151,151,193,96,48,24,12,6,
131,193,96,48,24,12,6,131,193,224,
63,252,250,245,235,229,231,207,159,127,
124,226,58,247,170,231,226,115,165,172,
0,101,248,247,193,255,81,233,249,138,
254,51,124,255,254,253,229,211,167,79,
127,124,226,58,247,50,124,249,242,229,
223,207,46,190,125,251,246,59,239,176,
55,101,4,244,251,71,70,212,251,180,
158,149,158,79,245,191,2,54,209,254,
174,246,95,245,81,250,118,149,166,147,
215,237,223,249,157,93,84,242,172,228,
4,93,26,189,94,165,203,174,103,237,
188,123,62,112,106,231,171,122,235,236,
31,229,107,223,117,185,180,111,123,30,
154,15,121,5,170,254,175,121,101,245,
142,251,159,63,127,254,247,123,232,45,
210,253,248,241,227,247,189,120,134,186,
168,47,11,68,58,189,30,233,51,68,
254,158,38,242,136,188,185,23,101,171,
94,72,23,215,245,121,234,160,105,35,
47,79,71,29,244,122,252,141,207,170,
255,199,223,175,95,191,254,126,238,10,
58,251,115,77,101,209,242,35,77,148,
207,51,89,159,35,61,247,50,251,187,
12,81,158,219,8,155,199,223,208,153,
166,137,239,140,91,92,115,61,69,26,
157,243,56,180,125,69,62,164,71,23,
200,169,233,84,238,248,160,11,218,178,
202,29,215,84,31,170,103,45,159,241,
125,215,254,250,204,21,172,252,127,86,
102,214,255,233,127,157,188,129,204,254,
234,111,168,83,86,119,236,28,122,86,
125,209,46,226,131,47,208,62,168,126,
129,60,86,114,118,186,64,62,202,33,
63,247,21,85,157,253,249,144,207,203,
223,25,255,239,49,23,184,197,254,232,
60,250,35,245,238,228,165,254,149,253,
125,29,226,192,182,216,61,254,70,91,
32,127,254,247,126,134,172,244,81,218,
139,66,243,161,78,153,46,240,183,46,
43,237,145,185,94,101,127,100,212,231,
189,252,76,111,43,91,92,197,45,246,
167,29,107,187,239,228,13,100,246,87,
127,135,239,205,250,40,125,221,253,143,
234,54,238,113,221,253,36,190,35,179,
63,122,208,54,150,233,66,211,169,205,
105,23,200,239,246,199,63,242,76,252,
229,25,205,55,174,33,227,51,236,79,
95,81,125,208,159,1,117,245,239,234,
111,25,223,28,154,30,153,233,91,250,
61,158,165,15,116,107,165,200,139,251,
248,77,192,255,145,198,239,33,39,125,
47,3,245,198,135,100,186,208,114,50,
249,201,95,199,67,250,135,255,239,178,
168,252,58,151,169,244,233,186,29,12,
6,131,193,96,48,24,12,58,56,247,
151,221,127,205,242,111,193,61,184,132,
43,56,45,243,52,125,197,219,158,194,
99,229,196,165,88,207,100,113,129,123,
98,85,254,234,217,21,159,214,113,152,
143,194,169,206,174,232,184,226,109,239,
33,171,198,182,171,103,42,206,170,242,
31,85,92,122,183,252,91,249,180,71,
65,229,214,61,19,94,167,43,114,117,
241,252,123,181,235,76,86,229,213,252,
254,9,231,85,165,63,41,255,86,62,
173,210,147,243,134,206,41,250,30,5,
231,120,144,133,124,156,3,89,233,172,
210,129,198,21,187,103,30,105,127,244,
227,156,92,197,121,105,220,94,99,230,
85,250,211,242,111,225,211,42,61,17,
163,11,192,179,194,243,33,243,202,254,
196,237,84,22,149,179,211,89,165,3,
181,63,114,102,242,103,254,255,202,30,
154,19,251,87,156,151,115,214,202,189,
86,28,217,110,249,212,245,42,159,86,
217,31,238,88,249,35,229,20,61,255,
204,70,200,220,253,127,170,3,207,171,
146,127,151,43,91,161,26,171,224,70,
244,126,197,121,5,72,171,92,76,151,
126,183,252,91,249,180,206,79,210,135,
163,140,104,15,244,53,158,221,181,191,
142,25,158,246,84,7,167,246,191,21,
234,111,224,26,148,119,175,124,83,102,
23,174,251,220,193,211,159,148,127,43,
159,214,233,41,179,183,206,59,25,23,
180,236,204,70,1,229,22,179,180,59,
58,120,13,251,235,216,201,199,247,226,
41,47,136,79,83,206,11,121,178,235,
85,250,147,242,111,225,211,50,222,206,
101,3,202,41,86,101,51,39,119,174,
148,231,145,103,71,103,153,142,61,239,
74,254,174,94,131,193,96,48,24,12,
6,131,193,10,196,190,136,249,156,130,
117,32,107,152,85,44,170,75,19,115,
219,29,254,231,30,216,145,53,128,110,
30,89,230,174,44,247,6,231,98,88,
119,123,12,127,5,226,31,172,191,119,
214,38,221,250,245,153,251,25,51,174,
81,215,148,129,248,78,172,240,81,101,
118,215,31,9,143,93,7,168,175,198,
183,186,246,175,103,99,72,175,250,203,
158,231,25,238,105,189,157,247,138,123,
238,151,244,204,65,166,51,158,233,244,
73,127,243,56,134,199,104,179,242,119,
242,202,100,204,210,117,215,119,203,200,
244,184,131,85,28,73,247,228,87,231,
113,148,131,240,56,173,238,213,215,231,
73,163,62,7,157,43,151,163,241,64,
229,236,148,15,112,153,244,28,81,197,
159,225,243,200,71,99,254,90,151,170,
252,157,242,92,198,170,204,234,250,142,
188,196,27,85,198,19,172,236,223,157,
183,4,93,204,210,249,47,248,58,237,
255,232,202,207,51,100,231,59,201,171,
58,103,66,57,200,82,157,141,200,244,
239,124,71,87,126,149,151,238,215,119,
25,171,50,171,235,59,242,102,122,60,
65,199,143,145,223,138,103,236,236,95,
233,127,231,108,17,249,250,167,203,23,
121,208,253,142,207,210,254,158,197,226,
179,242,61,175,157,179,132,85,153,213,
245,29,121,51,61,158,32,27,255,149,
91,244,54,95,237,251,185,218,255,51,
93,85,253,95,203,238,236,239,28,244,
170,255,107,222,93,255,175,230,127,93,
255,215,178,171,50,171,235,59,242,222,
106,255,128,142,45,62,134,225,159,116,
124,233,248,43,151,105,53,254,171,220,
110,255,128,158,225,171,206,159,103,186,
90,205,89,124,60,245,49,78,121,197,
172,124,69,55,254,107,250,170,204,234,
250,142,188,247,176,63,245,174,214,255,
122,47,107,155,220,215,62,228,60,154,
207,255,61,141,206,145,125,78,159,205,
229,187,24,129,206,133,249,158,1,25,
252,62,229,117,229,87,121,173,100,172,
202,172,174,175,210,100,122,28,12,6,
131,193,96,48,24,12,42,232,220,92,
63,87,56,192,71,163,146,203,215,31,
31,1,207,226,2,89,187,251,30,204,
213,58,130,253,210,207,68,21,103,171,
246,99,190,103,60,139,11,204,246,50,
43,178,184,128,238,217,213,253,255,39,
235,87,181,21,177,54,189,158,113,110,
216,159,123,158,7,114,232,117,231,34,
119,184,60,210,84,107,244,206,46,153,
30,244,92,160,114,164,149,190,110,229,
27,79,224,251,239,213,62,85,236,143,
152,19,126,99,135,35,84,63,163,241,
43,174,235,158,121,246,239,123,188,81,
249,194,44,143,44,94,157,113,70,29,
47,88,197,251,118,56,186,46,214,169,
103,19,225,215,51,125,237,200,184,226,
2,79,80,249,127,236,143,12,126,110,
37,227,104,85,7,222,71,52,14,167,
231,248,40,95,251,133,115,110,124,87,
125,84,103,38,120,94,99,235,244,147,
44,70,237,253,133,182,199,249,21,176,
195,209,173,184,14,242,171,244,181,43,
227,138,11,60,193,202,255,35,43,125,
47,227,85,119,56,66,206,82,104,95,
207,202,239,228,209,124,187,51,51,33,
15,109,150,114,92,55,85,57,140,109,
234,223,40,123,197,209,157,112,157,153,
190,118,101,220,229,2,119,208,233,91,
251,172,250,120,175,235,14,71,168,239,
181,204,250,191,142,223,93,255,223,177,
63,103,59,245,44,231,110,223,210,189,
3,218,111,119,56,186,93,174,179,210,
215,149,254,175,207,223,98,127,247,255,
200,238,227,63,250,199,79,86,233,188,
61,249,184,90,217,95,243,206,198,255,
29,251,163,35,191,118,101,252,63,225,
232,118,185,206,78,95,87,198,255,157,
179,142,21,170,245,191,114,222,89,76,
128,235,218,111,59,142,16,249,176,159,
206,49,179,103,178,57,112,86,94,149,
71,181,126,62,153,91,95,225,232,118,
184,78,79,183,83,247,29,25,159,21,
51,24,12,6,131,193,96,48,24,188,
127,192,231,232,218,239,81,184,146,183,
190,91,227,30,239,190,215,216,192,9,
118,101,127,79,92,20,107,94,56,0,
214,148,143,168,3,118,60,1,235,90,
98,122,186,175,178,219,7,92,1,142,
225,20,26,79,236,112,165,142,175,5,
98,22,190,110,36,126,22,240,125,172,
190,14,199,111,232,122,149,51,24,241,
209,152,13,109,75,227,11,232,171,227,
118,85,198,206,254,93,94,187,105,180,
78,186,15,222,229,184,87,29,65,246,
187,35,180,247,120,142,235,148,171,233,
2,145,230,106,223,202,116,196,245,236,
28,11,113,11,141,179,58,7,163,191,
207,69,61,208,13,122,37,214,133,223,
113,249,41,67,99,241,213,89,1,181,
69,197,209,237,164,113,153,180,174,202,
121,82,71,253,45,161,43,117,12,40,
15,75,92,15,251,104,172,80,211,17,
39,165,220,42,94,216,161,178,191,94,
175,236,175,241,113,218,61,109,18,61,
121,124,75,243,242,248,118,197,171,101,
252,137,219,92,253,152,114,200,138,157,
52,1,181,159,199,31,61,142,155,241,
123,87,234,184,250,221,49,210,251,251,
4,157,59,61,221,183,229,242,120,28,
218,235,19,112,251,59,111,64,62,250,
155,148,200,152,233,6,84,92,212,142,
253,43,30,67,177,147,6,61,42,239,
153,201,171,124,152,191,71,240,74,29,
79,184,67,202,229,3,87,93,249,150,
21,120,142,49,46,179,153,239,181,160,
15,57,95,69,159,208,177,169,226,13,
189,253,86,253,113,199,254,1,245,127,
202,227,41,118,210,40,231,168,227,160,
202,145,125,207,236,191,91,71,229,4,
241,249,29,119,168,156,159,238,199,186,
2,29,219,244,227,123,45,226,131,111,
244,189,28,220,83,29,100,215,149,95,
203,158,239,206,215,131,202,254,248,50,
229,212,29,59,105,84,38,159,119,42,
223,206,119,250,135,183,153,147,58,6,
212,6,186,167,199,199,103,215,173,182,
147,83,254,79,161,227,7,115,204,236,
222,106,143,221,234,186,239,37,90,141,
91,126,95,203,175,100,233,214,174,183,
164,241,178,43,157,156,214,241,244,185,
204,119,93,217,255,55,24,12,6,131,
193,96,48,248,187,160,235,24,93,207,
220,107,30,217,237,73,140,117,144,190,
43,101,167,76,93,171,18,239,206,214,
130,239,1,111,65,94,143,231,176,238,
59,61,71,82,161,179,63,156,0,233,
118,236,175,177,22,214,59,60,247,22,
244,121,130,183,32,111,22,143,36,78,
238,49,27,231,180,136,61,58,223,165,
80,238,86,227,21,1,158,117,159,163,
60,180,199,32,60,38,171,252,191,234,
51,75,171,121,19,67,169,184,24,47,
23,249,52,150,163,28,114,199,41,105,
61,181,254,42,47,124,206,142,94,144,
93,203,81,185,78,208,157,49,113,142,
71,185,8,141,165,119,62,195,185,123,
229,149,225,11,60,70,170,245,243,243,
141,206,193,86,254,159,114,178,50,189,
110,217,222,108,111,255,216,141,216,167,
199,124,177,109,182,111,155,182,2,39,
226,113,98,236,173,237,162,211,139,203,
238,114,157,96,101,127,236,234,101,102,
177,255,21,143,232,54,10,48,7,168,
108,122,146,159,115,65,222,95,178,188,
171,24,176,238,15,210,120,55,177,214,
236,183,163,42,238,85,125,141,238,173,
82,174,37,243,25,43,189,184,191,67,
174,19,172,252,191,219,95,231,9,183,
218,159,126,73,92,253,81,246,215,126,
177,107,127,252,6,121,169,207,35,95,
183,255,106,111,7,126,68,121,85,229,
15,192,174,94,170,250,158,96,53,255,
163,158,112,140,186,7,229,22,251,107,
185,238,135,111,181,63,58,164,28,213,
203,174,253,201,67,199,14,181,185,238,
119,217,201,7,127,174,252,159,203,235,
62,63,211,75,118,207,229,58,65,182,
254,243,125,69,58,183,200,206,95,171,
110,28,43,123,209,254,117,255,195,61,
236,175,243,191,234,220,114,160,179,155,
247,113,205,147,190,204,179,93,62,62,
255,203,100,209,125,24,43,189,248,252,
207,229,26,124,76,188,133,245,226,224,
245,48,246,255,187,49,252,254,96,48,
24,12,238,133,108,253,183,138,101,128,
183,244,174,249,142,103,58,133,174,215,
186,241,182,138,157,158,96,87,215,247,
44,51,203,79,227,63,171,189,145,1,
93,151,190,5,92,57,251,80,129,248,
215,238,126,205,91,176,163,107,79,255,
8,251,87,249,105,236,71,99,21,126,
198,41,227,8,29,196,45,60,158,14,
119,166,188,46,253,143,51,113,204,125,
149,15,227,158,127,39,118,170,117,240,
119,36,86,177,146,172,110,26,147,209,
118,225,242,40,178,114,178,186,194,255,
184,174,53,142,239,50,169,189,136,83,
59,87,184,139,202,255,107,140,95,207,
75,209,207,148,243,173,56,66,47,7,
221,193,157,104,249,232,69,207,213,160,
31,151,39,139,57,234,119,63,127,75,
59,210,120,58,242,120,27,240,186,5,
60,150,236,124,64,182,15,219,99,179,
196,207,189,174,21,135,167,249,86,250,
224,121,226,198,21,7,187,99,127,247,
255,64,219,150,142,83,30,119,205,56,
66,7,28,149,242,113,174,195,238,255,
93,251,163,23,61,143,233,50,7,244,
108,143,66,211,101,54,86,125,101,246,
247,185,136,158,173,171,242,82,253,40,
183,216,233,195,203,225,222,9,86,254,
223,101,202,246,90,84,28,161,235,132,
52,221,251,31,239,97,127,100,162,173,
101,50,7,222,146,253,43,110,241,89,
246,207,230,127,248,66,245,151,186,143,
2,159,84,113,132,174,83,252,127,215,
255,3,187,254,14,223,148,233,60,155,
195,239,248,127,173,91,38,207,61,252,
127,102,255,142,91,124,134,255,247,15,
245,247,115,176,122,238,80,231,41,25,
71,232,229,232,217,193,170,125,123,90,
215,133,206,51,171,179,153,110,55,197,
106,254,23,112,251,87,243,191,206,119,
102,229,116,246,239,184,69,191,119,207,
249,223,91,199,189,215,59,131,247,133,
177,255,96,108,63,24,12,6,131,193,
96,48,24,12,6,131,193,96,48,24,
12,6,131,193,96,240,247,225,17,123,
209,217,251,244,145,193,126,19,255,172,
246,189,179,199,210,223,105,17,96,111,
76,246,121,132,62,117,111,169,195,223,
105,92,113,137,236,75,243,124,125,255,
8,239,0,210,15,251,55,158,201,83,
118,117,57,205,71,247,237,241,169,236,
175,191,99,194,190,35,246,217,233,62,
183,44,207,106,111,240,173,242,119,123,
245,213,134,250,30,16,135,214,27,221,
178,135,76,251,4,249,61,171,109,87,
232,234,242,200,50,117,95,164,246,141,
172,255,56,216,175,150,229,233,159,106,
111,158,63,187,218,27,178,107,127,222,
203,68,250,248,223,223,177,161,246,127,
109,188,134,253,253,119,7,212,62,244,
195,14,236,35,174,160,125,169,219,203,
22,215,245,183,69,58,172,236,79,219,
161,79,59,60,255,172,255,115,157,252,
121,151,155,238,161,212,125,155,1,218,
155,190,107,137,125,126,250,140,238,177,
213,124,181,77,146,134,239,39,56,25,
67,84,23,254,174,161,172,111,43,168,
91,87,158,250,130,204,246,140,189,248,
134,85,153,228,169,239,239,81,153,245,
253,114,39,246,247,189,238,92,231,127,
173,39,231,146,116,156,84,89,184,207,
119,244,138,204,122,46,68,243,165,61,
168,220,87,124,211,201,126,113,61,95,
161,190,0,121,170,190,77,187,220,241,
231,217,217,1,205,199,247,150,175,228,
199,143,107,254,1,116,167,239,98,83,
61,50,230,251,124,165,210,177,207,121,
180,78,218,95,125,79,175,238,101,215,
249,148,230,145,189,219,143,246,224,253,
240,116,76,224,156,83,54,159,113,96,
67,255,237,204,106,28,102,253,180,51,
150,35,203,233,220,176,179,63,122,213,
49,11,255,233,237,72,237,175,254,93,
247,154,147,231,137,253,245,92,34,237,
87,203,204,222,93,229,243,172,202,254,
252,79,59,190,50,39,64,190,236,227,
64,126,116,71,27,206,252,58,186,171,
252,170,231,123,229,221,117,129,202,254,
234,55,1,109,49,139,21,232,153,81,
93,223,80,87,157,31,86,231,27,50,
251,83,174,142,229,122,93,207,165,122,
159,210,115,31,157,253,145,201,219,215,
51,208,197,93,118,231,22,145,238,170,
220,221,120,119,210,158,244,221,58,218,
151,62,218,121,138,193,96,240,161,241,
15,136,36,106,162,235,119,189,22,0,
0,4,121,109,107,66,84,250,206,202,
254,0,127,162,54,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,
0,0,0,120,156,237,154,137,109,235,
48,16,5,93,72,26,73,33,41,36,
141,164,144,20,146,70,82,136,63,54,
248,99,60,108,72,217,177,100,248,154,
7,12,116,144,226,177,203,67,34,181,
223,43,165,148,82,74,41,165,148,82,
74,253,215,247,247,247,254,235,235,107,
74,133,223,131,178,30,151,76,251,18,
233,95,83,85,159,221,110,55,229,243,
243,115,255,250,250,250,115,126,203,117,
167,30,85,214,45,85,190,127,121,121,
57,216,99,235,244,175,173,244,255,251,
251,251,47,74,117,172,122,63,163,255,
105,251,207,224,255,153,62,62,62,126,
218,0,115,1,109,163,174,43,140,118,
193,117,133,213,145,248,21,206,189,89,
154,117,204,56,179,180,250,179,117,78,
25,210,63,164,87,80,62,202,49,74,
115,164,138,87,105,86,255,231,252,145,
253,95,117,75,240,69,31,255,137,207,
184,136,47,114,156,204,249,163,194,136,
95,226,154,103,75,149,87,93,215,177,
158,153,205,69,89,30,242,99,108,202,
243,44,91,166,159,84,156,89,27,72,
187,84,190,207,224,255,14,182,155,249,
255,237,237,237,240,142,136,125,120,166,
247,199,76,35,125,65,155,32,188,210,
226,156,246,71,252,158,86,29,203,55,
188,151,145,94,247,125,62,147,105,210,
158,186,178,45,231,28,248,232,254,159,
105,230,255,236,59,125,158,76,74,248,
176,236,88,237,38,199,84,202,80,247,
51,253,84,222,35,175,244,223,168,29,
103,255,174,240,74,31,31,214,249,108,
14,32,30,101,228,253,39,239,61,138,
214,248,63,133,205,152,111,233,231,249,
110,128,237,177,97,246,235,236,155,244,
189,124,55,24,141,21,249,62,154,253,
63,199,144,244,85,150,37,203,59,171,
239,18,143,162,173,252,143,47,241,109,
246,181,158,78,127,47,232,227,73,142,
181,217,247,102,243,81,214,131,252,122,
123,200,241,60,211,100,204,233,54,233,
100,153,110,249,59,232,175,218,202,255,
165,178,81,190,3,150,109,251,123,123,
247,53,237,36,253,192,251,4,105,209,
166,120,230,20,255,103,60,198,36,242,
34,205,94,190,37,61,234,252,175,148,
82,74,41,165,158,83,151,218,231,205,
116,239,101,47,249,214,148,235,32,151,
176,97,125,27,205,190,107,250,247,212,
95,181,246,121,181,63,172,57,212,154,
201,108,205,122,141,210,255,125,109,35,
191,243,71,223,252,75,107,33,172,155,
244,243,107,40,203,57,234,71,252,227,
49,187,191,148,222,232,122,150,215,44,
173,81,191,38,238,108,205,105,86,230,
191,138,253,178,220,251,35,95,214,60,
242,156,246,194,51,185,206,158,109,36,
247,94,57,103,13,151,123,57,38,176,
119,179,38,188,219,58,203,153,235,137,
117,143,245,102,214,154,250,186,82,133,
247,58,214,189,76,43,109,87,199,244,
25,144,87,94,163,30,167,196,122,37,
247,73,151,189,238,165,50,159,163,238,
151,108,111,163,254,207,90,27,182,102,
63,190,107,52,246,87,188,220,199,45,
232,35,172,243,173,9,63,86,47,236,
151,99,94,255,183,33,247,33,16,123,
25,117,204,181,202,180,85,166,217,243,
26,217,183,255,19,65,156,209,253,145,
255,71,101,62,71,125,254,63,197,255,
25,127,246,254,144,118,226,156,189,25,
142,248,51,255,201,88,19,126,106,189,
250,156,151,123,2,248,122,84,167,244,
65,183,79,94,207,242,202,176,209,62,
19,247,179,63,115,157,121,143,202,124,
174,182,240,127,223,71,41,159,80,166,
60,47,49,214,49,126,50,150,209,158,
215,134,159,82,47,194,24,55,248,143,
0,27,211,190,16,115,109,247,127,31,
115,114,143,242,152,255,249,127,34,243,
40,245,251,221,255,179,50,159,171,99,
254,207,185,29,59,244,126,146,117,45,
245,241,41,125,131,191,136,203,60,182,
85,248,49,187,103,24,182,228,253,58,
231,97,198,112,226,98,231,180,53,123,
157,248,51,247,40,143,149,131,127,107,
241,33,109,39,109,202,158,217,200,255,
163,50,159,243,46,200,126,91,214,41,
125,71,223,206,186,98,143,209,88,69,
220,76,175,231,215,253,217,251,193,154,
112,194,150,234,149,97,212,131,185,164,
251,55,231,242,209,55,24,207,247,231,
70,121,245,48,218,64,223,139,76,27,
19,63,243,158,149,185,247,181,75,104,
105,189,64,61,190,244,191,82,74,41,
165,148,82,74,41,165,148,82,74,93,
77,59,17,17,17,17,17,17,17,17,
17,17,17,17,17,17,17,17,17,17,
17,17,17,17,17,17,17,17,17,17,
17,17,17,17,17,17,17,17,17,17,
17,17,17,17,17,17,17,17,17,17,
17,17,17,17,17,17,17,17,17,17,
17,17,17,17,17,17,17,17,17,17,
17,17,17,17,17,17,17,17,17,17,
17,17,17,17,145,59,228,31,135,151,
142,106,217,59,142,156,0,0,1,83,
109,107,66,84,250,206,202,254,0,127,
165,133,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,
120,156,237,214,225,105,131,96,20,134,
81,7,113,17,7,113,16,23,113,16,
7,113,17,7,177,188,129,11,183,166,
33,255,138,9,231,129,67,155,79,251,
235,77,108,206,83,146,36,73,146,36,
73,146,36,73,146,36,73,146,36,73,
146,36,73,31,209,113,28,231,190,239,
79,231,57,203,181,119,247,191,186,79,
247,111,93,215,115,28,199,115,154,166,
199,207,236,24,253,44,247,212,189,117,
22,203,178,60,94,199,48,12,127,190,
135,116,239,178,99,149,125,179,97,118,
173,205,251,61,181,127,213,55,191,254,
141,238,95,182,235,123,86,57,235,159,
229,122,157,125,251,198,217,191,186,94,
211,253,203,115,190,239,95,255,215,231,
121,126,218,63,215,236,255,125,101,219,
122,238,215,239,219,182,253,250,204,247,
231,191,253,191,175,250,30,215,247,171,
247,64,174,213,119,251,156,69,213,159,
29,215,107,146,36,73,146,36,73,146,
36,73,250,247,6,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,248,64,63,10,
249,172,184,82,218,42,102,0,0,1,
5,109,107,66,84,250,206,202,254,0,
127,177,164,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,
0,120,156,237,215,209,10,130,64,16,
5,80,203,146,254,255,111,35,98,106,
65,73,6,95,130,108,150,58,23,14,
56,235,203,133,157,7,29,34,98,72,
98,227,140,255,176,78,117,23,234,118,
160,186,3,223,115,72,115,204,103,99,
7,221,216,223,45,205,45,235,157,184,
118,208,145,125,188,147,234,174,124,222,
152,238,246,60,207,211,211,37,94,59,
114,234,160,43,251,56,166,231,229,190,
167,141,247,252,190,232,160,3,53,218,
183,96,203,189,131,46,212,104,201,255,
132,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,208,
60,0,157,104,104,54,236,25,80,26,
0,0,42,23,109,107,66,84,250,206,
202,254,0,127,212,240,0,0,0,1,
0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,
0,0,0,0,120,156,237,125,43,184,
236,40,214,246,146,72,44,18,137,196,
34,145,72,36,22,25,137,196,34,35,
145,88,36,18,25,137,141,140,140,140,
141,44,153,127,81,251,156,238,158,158,
233,249,212,255,212,136,90,115,233,62,
85,123,215,9,176,46,239,187,46,84,
230,231,125,54,158,0,218,179,145,45,
198,215,70,96,135,163,195,2,112,93,
197,5,107,0,223,133,126,195,243,98,
29,224,129,10,16,1,182,10,27,208,
158,36,193,119,221,147,217,177,132,193,
241,205,124,115,252,241,67,111,0,149,
155,221,65,43,213,113,51,182,190,108,
79,21,20,224,120,157,64,225,40,233,
48,240,97,185,175,43,63,247,9,18,
160,220,84,44,164,95,141,3,175,55,
129,184,115,92,157,219,222,207,152,94,
66,108,49,41,252,67,17,243,149,210,
15,15,43,212,107,219,40,238,70,121,
78,34,56,245,150,100,80,67,204,95,
57,22,200,210,62,79,6,48,38,108,
171,52,184,143,73,109,43,254,238,235,
110,144,119,238,219,71,23,143,114,197,
176,248,141,153,224,1,60,81,170,131,
113,9,15,209,20,9,43,175,151,178,
133,72,147,125,12,250,161,174,193,101,
161,183,29,127,113,143,185,174,126,126,
130,91,41,46,163,53,99,131,137,54,
44,214,250,184,197,192,193,130,109,14,
158,29,4,117,79,160,248,239,168,57,
112,92,248,211,253,60,47,27,15,47,
63,188,252,183,184,78,196,58,18,158,
147,77,194,155,5,112,41,182,21,32,
21,246,196,156,45,28,213,30,50,112,
192,39,15,135,117,75,113,96,2,190,
180,205,95,183,224,218,230,192,31,213,
47,184,153,251,54,252,52,29,60,126,
0,133,11,180,30,55,55,83,234,27,
129,199,225,78,221,213,66,81,215,225,
214,237,243,235,167,168,148,117,77,224,
247,123,143,142,251,53,200,37,46,66,
166,78,201,138,11,24,107,58,24,9,
107,155,78,192,188,109,129,57,216,15,
252,231,2,42,167,117,129,85,197,124,
50,168,134,217,37,59,209,239,17,129,
155,171,29,184,93,70,225,97,215,146,
41,207,11,170,82,69,37,72,87,99,
48,77,103,3,198,62,187,248,41,47,
116,105,104,147,102,152,245,213,9,209,
184,88,134,62,202,202,28,168,18,203,
69,203,197,242,227,41,21,150,212,60,
15,44,233,54,246,115,52,197,225,192,
127,214,53,155,122,224,98,240,63,164,
162,74,31,240,224,246,92,27,60,25,
79,28,77,37,79,35,40,55,228,54,
224,58,167,22,61,9,157,170,234,253,
211,139,7,89,65,163,247,194,131,72,
13,182,171,8,144,76,160,115,54,155,
206,3,77,131,88,234,200,249,66,99,
88,157,38,199,152,74,189,19,116,4,
101,187,46,202,246,18,252,168,207,9,
51,46,24,106,101,40,148,207,63,212,
60,63,157,45,49,233,36,112,157,79,
1,61,0,253,127,120,20,26,18,140,
11,255,218,253,9,31,93,60,74,116,
194,161,183,86,103,155,154,96,124,73,
44,60,228,184,149,125,224,70,243,14,
81,106,93,208,111,37,91,80,97,209,
253,1,136,54,253,24,88,18,89,191,
205,60,225,23,170,63,16,168,89,111,
104,0,128,70,158,23,252,48,54,55,
225,129,173,31,54,74,70,241,151,71,
91,240,133,5,119,118,41,154,207,55,
63,44,28,228,64,119,142,10,141,6,
110,77,224,199,166,221,19,109,204,5,
202,107,62,63,245,232,201,76,218,106,
239,15,179,21,61,128,221,15,218,37,
119,131,90,136,105,122,70,84,120,6,
129,16,244,132,36,17,129,175,107,80,
246,56,155,69,183,144,109,242,248,9,
106,65,79,153,241,212,215,250,222,128,
171,158,28,62,126,254,146,134,229,220,
224,216,134,145,186,6,233,66,57,250,
181,226,9,134,11,214,164,2,56,85,
173,171,75,28,14,67,195,118,180,106,
98,235,15,76,11,232,229,231,67,188,
2,239,128,121,175,5,161,11,231,30,
141,59,164,109,23,106,11,80,46,212,
5,32,151,248,227,239,68,107,241,21,
194,234,119,254,161,85,255,69,194,194,
128,51,244,220,168,193,148,145,149,146,
56,120,235,85,192,133,74,202,252,185,
115,18,143,163,18,137,158,92,132,179,
8,14,232,201,159,142,43,59,6,125,
7,4,115,173,24,70,16,227,29,81,
40,30,75,73,173,238,247,166,88,221,
155,132,198,168,10,185,49,11,203,250,
254,43,75,143,250,168,232,100,88,140,
31,93,59,74,196,163,142,239,99,8,
136,120,36,157,167,68,209,215,183,222,
15,16,158,162,19,88,96,105,215,30,
32,236,168,235,209,16,64,108,204,143,
251,114,110,176,109,36,129,168,198,94,
215,57,206,132,239,122,66,71,207,158,
160,81,61,21,198,110,102,16,228,107,
132,68,234,246,172,101,59,10,60,168,
253,248,22,97,211,252,62,44,181,226,
162,158,155,106,198,239,107,135,48,66,
159,91,112,40,245,226,36,191,29,0,
186,135,199,160,145,219,246,204,112,253,
52,12,110,203,25,203,113,96,148,88,
198,147,249,9,250,118,207,181,246,232,
24,217,46,120,245,72,110,140,251,141,
111,114,159,74,190,128,207,53,172,241,
193,224,255,72,224,28,117,169,137,241,
234,235,135,151,143,11,102,224,167,22,
12,237,215,215,97,236,24,149,134,137,
91,90,23,25,58,62,60,199,77,64,
74,163,57,243,2,253,2,172,226,36,
211,113,93,21,1,161,0,125,61,72,
133,22,12,107,4,208,254,51,198,202,
24,186,227,175,249,233,178,186,116,191,
81,147,61,127,130,1,44,9,55,198,
199,6,181,223,187,253,236,234,231,115,
13,196,62,144,227,162,51,248,182,239,
222,220,54,91,166,209,103,149,168,151,
12,82,76,141,216,141,170,168,249,17,
173,63,23,183,40,12,141,38,119,221,
46,55,67,35,126,66,123,8,130,93,
175,211,10,215,226,151,85,212,87,2,
178,12,55,153,210,49,127,106,107,126,
130,101,148,99,71,187,191,114,22,203,
199,249,31,208,227,68,216,46,27,18,
61,244,203,75,180,220,238,235,8,197,
64,221,87,221,199,177,77,18,3,251,
48,229,128,144,3,227,251,237,232,228,
188,48,206,92,6,218,242,120,127,144,
243,174,118,207,113,223,78,90,162,11,
62,35,4,198,13,131,132,140,224,66,
69,151,9,153,165,41,149,130,186,38,
121,216,65,125,116,229,63,66,251,234,
11,89,236,109,40,194,87,73,112,225,
129,201,177,242,128,241,11,184,124,189,
50,151,43,232,253,224,92,50,183,246,
32,237,222,41,144,108,220,56,183,214,
116,108,24,5,28,193,64,90,46,66,
189,128,163,239,24,4,149,101,241,133,
139,141,131,82,83,223,244,129,198,131,
109,62,100,152,73,129,233,254,108,254,
244,242,39,78,13,97,134,100,196,162,
71,51,185,37,141,134,188,35,171,41,
63,232,188,207,36,5,1,115,31,28,
223,9,3,95,53,61,19,178,237,89,
28,199,66,82,35,45,107,34,113,71,
80,45,208,101,18,254,34,231,102,173,
193,8,194,225,37,214,169,45,207,147,
51,30,55,234,208,228,204,200,56,212,
77,57,153,25,129,207,138,25,138,44,
27,172,232,228,95,42,110,59,72,130,
193,250,198,69,22,66,198,177,134,29,
214,99,108,191,126,248,206,238,177,231,
13,203,157,91,131,142,47,115,97,159,
103,184,73,21,23,69,8,50,229,44,
122,3,210,49,218,23,116,129,27,58,
146,107,76,198,211,231,206,193,6,161,
205,237,28,200,153,8,15,229,163,139,
71,41,230,28,212,123,18,55,202,111,
240,203,197,110,100,168,248,164,232,183,
240,225,149,123,64,114,245,80,152,62,
16,198,107,194,119,140,107,215,189,190,
161,11,35,184,15,107,88,23,102,121,
145,18,214,69,199,247,154,200,65,169,
205,66,194,57,194,117,77,16,176,219,
222,52,80,61,185,95,4,211,108,146,
144,198,103,87,143,174,216,135,221,78,
149,20,213,35,150,95,110,153,135,71,
239,164,112,3,112,11,44,90,133,30,
18,255,85,117,155,54,200,147,247,195,
86,166,155,211,176,184,229,48,69,75,
145,55,42,124,183,253,24,93,175,123,
157,252,55,53,70,92,233,212,182,187,
250,122,81,216,21,160,122,33,225,130,
199,7,9,117,21,72,128,62,238,255,
243,166,117,112,154,178,218,246,245,84,
217,163,187,111,51,80,41,136,248,180,
91,224,94,213,54,227,214,218,243,227,
96,32,45,154,100,38,18,225,42,61,
182,37,196,192,202,102,89,146,60,191,
94,146,131,216,183,96,95,54,157,168,
223,200,124,104,29,184,204,235,5,51,
216,161,62,128,132,50,32,25,80,186,
16,250,113,255,215,55,7,21,207,142,
179,11,253,213,14,252,44,78,115,190,
106,187,70,153,61,66,181,138,252,96,
11,168,237,129,179,149,67,167,242,246,
4,105,142,85,146,41,1,82,233,144,
143,64,76,197,223,6,210,174,132,139,
255,137,29,2,183,199,167,109,98,60,
50,19,70,72,147,82,113,176,178,28,
195,185,70,189,30,229,227,248,247,88,
28,186,105,141,228,142,178,245,79,109,
172,71,65,253,221,16,183,244,210,125,
58,182,42,26,190,203,19,117,12,196,
102,5,216,58,29,64,202,171,82,72,
153,46,3,242,217,239,138,176,54,194,
241,188,177,195,54,142,106,144,229,1,
167,99,230,71,79,112,79,45,13,16,
250,173,54,29,72,23,210,253,250,220,
202,127,75,157,201,74,230,219,85,192,
206,236,22,58,186,74,199,131,190,157,
138,253,201,118,60,103,122,142,227,140,
232,4,241,32,241,255,8,49,70,42,
113,109,153,45,59,147,13,73,242,141,
20,0,55,13,63,3,222,30,226,79,
236,40,89,114,13,217,100,101,199,10,
207,201,70,6,202,23,13,229,153,9,
210,250,209,165,255,150,114,197,216,72,
150,16,31,203,193,97,236,199,199,219,
161,232,165,62,24,198,16,0,44,161,
149,184,175,51,255,139,27,68,236,90,
8,139,185,69,241,202,198,174,1,210,
113,113,240,236,216,55,112,27,129,63,
184,131,200,140,222,75,172,6,144,247,
197,37,14,200,167,36,129,59,15,226,
188,63,30,253,81,172,114,24,141,54,
179,112,80,3,55,96,188,97,153,134,
184,233,94,61,132,7,132,253,201,82,
231,182,95,23,134,245,153,179,41,109,
163,132,199,62,192,68,51,35,30,194,
163,12,188,95,39,13,231,73,254,194,
29,201,173,117,15,205,139,67,193,202,
45,82,141,110,16,101,227,175,132,179,
178,207,243,31,115,115,149,192,238,76,
207,204,60,200,173,47,19,181,224,27,
82,41,124,76,116,95,49,187,233,242,
193,60,117,245,125,69,10,68,200,122,
108,194,241,36,20,72,211,17,14,43,
239,78,8,29,95,21,50,236,191,115,
7,99,1,219,175,45,242,114,72,145,
86,46,160,25,179,165,136,244,26,255,
206,212,214,143,39,128,145,239,140,153,
133,40,125,11,224,111,9,178,237,58,
93,232,172,167,219,54,167,70,104,108,
119,177,134,188,64,140,210,122,198,123,
54,186,80,95,153,63,12,1,182,13,
69,235,27,210,221,24,208,104,179,162,
246,223,185,163,131,195,118,162,230,75,
171,12,47,251,66,233,34,77,210,254,
178,104,59,192,215,241,241,250,23,231,
4,208,177,161,111,191,235,41,103,82,
2,109,32,195,36,172,53,191,44,32,
148,69,131,120,252,40,63,170,58,19,
182,103,192,85,235,181,133,23,70,188,
52,158,153,234,192,32,9,232,224,22,
8,243,181,223,185,195,69,52,140,129,
6,33,150,179,113,63,16,108,228,152,
7,144,245,65,174,245,14,136,159,22,
89,118,180,238,115,58,109,82,30,170,
40,71,7,255,176,90,223,121,218,71,
113,132,43,119,48,17,41,78,122,251,
246,231,225,117,136,89,244,45,197,38,
149,167,143,232,192,34,162,89,16,9,
61,39,73,134,253,206,29,131,56,240,
183,232,24,123,187,153,109,136,27,76,
47,126,132,185,143,25,131,194,33,254,
143,199,251,255,46,227,66,239,174,224,
216,209,204,65,61,168,158,248,231,188,
177,89,153,203,12,124,122,4,244,240,
58,102,137,27,35,194,172,127,111,104,
185,50,88,106,129,248,199,188,73,124,
49,214,216,105,51,19,65,40,124,249,
167,118,16,102,49,197,3,19,165,214,
13,78,75,128,136,154,76,192,205,171,
26,218,46,159,235,211,235,63,210,114,
217,93,195,113,66,83,160,94,35,111,
22,242,254,46,108,128,37,4,122,2,
226,226,129,139,13,175,196,247,89,210,
227,126,105,136,228,148,131,80,174,0,
136,113,16,30,235,117,38,55,40,132,
5,28,249,85,59,66,2,161,146,108,
32,122,70,235,120,215,142,6,179,129,
162,139,77,155,247,203,242,11,44,124,
80,102,12,86,245,214,160,246,107,130,
145,39,155,78,186,244,98,204,148,47,
161,36,69,78,149,185,170,10,72,3,
65,215,105,222,251,81,11,61,130,117,
45,31,47,84,230,81,65,68,57,147,
163,168,210,103,213,236,87,237,240,224,
37,89,90,239,174,92,128,159,218,97,
212,165,164,227,53,144,79,173,106,114,
168,15,203,209,241,169,248,117,34,57,
227,214,66,216,122,112,131,204,172,214,
118,108,165,173,108,61,11,131,16,143,
30,21,201,184,89,236,232,199,121,159,
21,220,190,53,116,3,253,133,166,210,
17,11,215,109,69,131,129,122,158,43,
252,170,29,239,77,27,177,190,139,62,
168,76,191,107,199,61,139,114,114,12,
52,141,3,249,236,234,167,252,20,47,
103,253,15,154,69,192,114,18,254,192,
126,80,134,24,166,110,66,223,91,160,
174,92,103,91,21,123,161,171,135,146,
103,26,163,227,89,219,3,118,82,159,
87,39,27,134,135,10,123,70,101,176,
109,49,239,222,1,140,123,11,2,221,
119,190,7,3,76,255,213,59,144,29,
55,168,38,36,145,231,254,120,250,99,
218,248,195,208,48,159,11,129,142,158,
110,221,246,137,243,237,38,17,250,218,
117,197,64,53,115,67,232,20,67,213,
177,109,156,241,31,56,72,24,131,227,
101,102,241,239,185,198,116,12,146,206,
60,80,74,90,255,244,142,176,64,131,
143,239,144,249,200,220,255,232,29,161,
187,22,52,157,75,124,174,143,35,96,
14,23,125,23,97,159,107,17,82,78,
226,255,160,39,151,126,73,85,33,194,
107,242,87,1,128,129,76,140,155,90,
215,245,68,152,4,78,75,149,193,165,
5,247,204,161,85,227,6,12,163,156,
207,196,247,253,221,59,180,154,103,204,
18,239,76,126,97,40,93,229,175,222,
33,66,106,118,232,40,209,102,242,199,
245,31,163,191,185,244,92,183,243,66,
229,5,125,146,65,117,72,247,82,161,
164,160,17,6,206,2,0,213,103,235,
247,152,238,26,77,31,238,11,168,60,
55,135,12,79,139,183,58,200,237,202,
91,247,109,54,117,237,118,246,142,221,
199,59,51,142,230,181,61,200,252,238,
119,29,233,167,119,140,110,30,232,251,
175,255,248,250,143,151,4,164,164,51,
112,75,254,206,77,162,164,182,165,131,
168,171,123,243,46,0,116,11,174,34,
161,3,243,110,116,154,26,63,19,224,
235,141,100,105,241,176,98,204,67,54,
179,243,61,176,202,69,9,179,25,160,
30,173,30,213,14,133,44,128,165,27,
209,174,79,200,10,178,156,245,48,185,
104,254,118,135,203,71,23,143,146,59,
30,61,186,239,245,77,86,37,165,19,
246,247,155,202,170,136,114,252,167,0,
192,228,194,52,157,72,24,13,29,56,
114,228,217,212,6,75,236,141,128,201,
120,186,237,65,28,244,58,202,50,13,
218,17,101,192,46,169,172,1,215,221,
159,48,78,60,103,157,235,228,131,248,
153,39,136,166,202,238,205,54,163,233,
135,37,193,195,71,204,49,214,214,183,
109,125,238,161,94,106,174,110,237,210,
189,211,83,253,48,12,67,122,1,139,
199,237,76,88,134,51,253,156,200,85,
131,246,132,77,59,94,5,226,254,94,
21,126,88,99,176,189,142,128,1,97,
1,26,232,118,3,71,72,5,117,34,
225,231,13,49,138,243,107,78,215,75,
253,84,130,63,44,136,217,231,114,131,
61,238,220,142,134,88,125,54,67,66,
16,87,54,219,187,0,144,70,223,23,
168,92,238,51,150,109,123,52,33,93,
57,255,225,187,173,215,220,74,52,110,
233,20,216,19,53,74,211,115,132,119,
130,220,94,12,170,68,159,247,104,168,
15,130,141,244,140,122,246,130,187,182,
163,223,253,56,255,149,224,28,80,235,
148,93,151,122,157,23,240,243,186,49,
182,27,120,165,226,126,23,0,252,181,
74,56,35,99,190,37,129,207,190,19,
174,183,99,70,123,100,243,151,27,221,
223,3,29,186,189,111,29,247,136,64,
119,197,48,137,81,115,80,175,227,185,
18,154,95,21,204,129,206,32,63,8,
51,121,66,50,196,144,123,124,190,255,
5,53,179,167,184,135,125,203,62,120,
123,113,40,97,191,178,219,209,130,97,
161,63,5,128,142,208,254,81,147,37,
242,167,204,108,193,172,246,52,244,130,
164,207,130,120,109,87,73,215,134,128,
71,237,175,166,67,232,26,210,244,236,
49,18,234,18,146,8,219,18,107,215,
81,214,253,140,51,105,74,104,27,220,
44,199,255,128,250,227,250,137,26,75,
186,154,82,136,247,197,196,240,162,21,
196,194,200,246,200,79,1,96,250,200,
231,133,202,178,187,134,143,60,33,243,
141,91,16,158,184,78,119,217,244,182,
97,196,220,248,182,162,90,128,142,192,
120,137,92,82,116,118,154,1,210,94,
90,74,237,221,97,92,40,1,202,30,
200,90,153,80,69,150,143,235,255,238,
32,49,138,154,222,163,5,161,104,142,
224,247,157,236,121,6,48,247,83,0,
144,76,33,200,121,14,205,81,3,80,
15,204,158,16,237,35,82,64,211,177,
38,52,175,97,159,57,16,2,39,50,
201,1,158,196,139,224,182,73,21,172,
69,199,56,88,201,248,73,114,213,196,
10,52,168,19,150,42,121,158,253,98,
31,207,127,139,203,188,211,26,47,35,
137,13,120,176,221,209,220,59,198,50,
82,126,23,0,170,139,1,245,226,25,
214,225,79,55,207,237,162,104,239,147,
213,152,85,142,243,94,8,167,107,4,
244,13,187,154,165,227,167,40,228,190,
160,44,165,136,159,50,24,135,252,215,
41,207,67,7,247,58,40,217,144,59,
151,28,81,51,62,189,254,52,225,41,
250,37,136,249,212,98,54,238,23,66,
56,1,253,92,160,20,31,179,0,112,
181,245,154,201,236,171,101,60,234,186,
237,83,233,185,16,144,130,216,236,218,
43,211,106,115,240,196,112,140,132,184,
8,223,37,60,38,25,116,123,51,63,
140,163,8,172,124,78,6,41,112,55,
17,98,153,212,2,127,238,227,233,63,
212,97,164,105,228,68,19,181,87,108,
8,127,146,22,1,161,189,240,136,88,
151,159,2,192,90,218,62,59,117,248,
157,41,164,107,111,3,41,35,87,225,
200,205,83,154,110,174,99,82,189,120,
244,148,123,91,192,115,88,118,49,164,
172,57,53,137,17,95,172,26,172,48,
75,233,24,245,193,24,138,17,182,213,
153,55,218,62,158,0,84,112,161,53,
135,139,184,217,180,164,108,26,51,165,
83,252,34,216,157,234,76,238,189,136,
88,144,234,133,231,157,171,91,225,53,
109,246,161,248,14,12,186,191,81,0,
61,34,117,125,246,145,198,112,207,152,
42,120,141,98,246,213,137,186,238,227,
151,227,35,105,77,43,179,249,64,187,
90,33,144,9,254,183,207,174,126,106,
224,210,89,148,221,172,21,24,145,161,
180,210,36,30,63,53,138,149,160,109,
6,116,234,117,136,93,32,135,37,142,
64,142,247,221,133,58,14,52,104,56,
219,131,184,152,161,187,116,117,236,23,
51,192,59,250,10,206,145,79,164,49,
65,47,114,139,191,4,190,153,5,10,
27,198,17,207,82,42,53,192,199,251,
255,203,236,105,220,38,106,35,4,89,
30,50,58,186,36,90,8,40,97,173,
100,230,64,223,62,39,122,10,158,20,
6,132,215,76,16,172,175,179,172,219,
2,23,235,135,182,169,189,54,90,144,
209,192,56,124,96,27,198,54,221,34,
2,229,140,88,1,49,223,95,128,15,
122,5,39,16,13,238,70,45,169,247,
187,209,143,251,63,176,250,88,94,2,
242,11,65,58,63,49,8,162,7,59,
216,204,104,47,75,24,158,86,66,39,
245,7,12,252,118,79,110,18,31,25,
207,4,70,83,242,130,188,201,12,245,
6,198,164,234,176,239,204,222,81,123,
61,107,104,55,153,192,23,77,229,175,
192,119,88,81,249,112,252,92,118,239,
205,147,206,79,47,255,182,46,197,246,
218,241,185,10,244,141,78,51,183,205,
72,75,82,240,201,108,138,75,150,34,
155,113,29,15,242,148,30,137,94,87,
220,4,179,104,129,188,49,119,116,249,
30,227,160,11,104,64,7,2,167,172,
209,51,240,101,18,31,54,254,78,124,
150,146,23,182,193,169,139,73,59,121,
238,143,243,63,31,3,56,116,91,6,
131,91,233,33,145,11,250,165,181,36,
44,31,206,174,76,173,183,101,150,34,
143,5,122,166,229,37,73,222,134,65,
234,107,220,204,23,17,82,228,108,33,
51,117,250,56,224,218,129,121,19,223,
235,63,19,95,158,87,197,233,189,41,
131,65,98,67,210,245,233,245,79,249,
33,114,122,191,132,97,162,164,53,83,
177,205,110,214,151,163,179,136,17,35,
194,20,60,253,52,51,121,143,220,54,
34,170,21,160,210,82,253,234,209,244,
223,131,67,129,130,81,4,229,191,38,
62,184,91,143,188,35,10,66,0,72,
205,199,189,223,123,118,161,101,224,5,
215,107,79,195,215,84,201,108,113,40,
143,85,72,3,240,205,181,104,143,15,
12,187,221,148,56,16,186,44,64,116,
176,181,246,200,195,213,130,76,219,123,
112,8,180,25,149,252,31,137,47,216,
42,203,76,34,141,20,100,95,121,12,
31,239,127,159,107,44,52,238,11,71,
204,150,253,209,98,68,62,44,193,207,
46,111,107,18,34,253,68,59,134,124,
55,150,91,46,21,28,181,68,214,67,
237,23,65,156,159,17,228,35,137,105,
199,230,233,108,255,252,175,137,207,159,
161,73,214,172,208,22,242,8,226,243,
222,31,68,191,113,189,93,43,222,24,
101,69,9,149,242,150,95,171,45,45,
160,153,131,166,11,218,176,99,169,28,
155,179,232,231,128,94,248,191,165,76,
244,18,152,113,177,49,126,17,235,16,
67,144,223,67,147,255,148,248,158,67,
147,57,161,142,8,103,78,141,17,228,
243,253,255,251,26,147,245,72,200,4,
56,66,22,107,104,234,231,171,74,193,
142,35,90,164,45,96,250,86,129,111,
167,153,77,203,97,32,57,114,24,17,
23,36,0,19,238,213,186,20,3,90,
45,188,104,243,107,104,242,31,10,31,
63,67,147,36,183,9,251,94,150,241,
116,196,143,247,191,57,100,40,145,56,
22,80,221,133,93,218,182,154,163,215,
119,91,18,162,1,119,108,24,233,207,
59,181,140,100,149,212,110,151,215,134,
244,111,206,75,171,232,141,100,249,12,
72,26,166,222,132,40,68,250,175,133,
175,159,161,73,110,252,73,204,32,77,
239,227,252,95,40,0,249,129,188,14,
25,240,26,156,146,24,238,240,53,41,
54,18,72,47,246,245,204,89,205,49,
135,184,32,177,81,82,230,140,107,31,
44,110,203,214,251,88,72,189,173,6,
202,137,240,14,145,131,202,203,63,20,
62,255,24,154,100,102,147,4,1,231,
38,54,179,127,252,252,189,94,69,127,
21,74,150,109,139,18,20,170,233,116,
222,200,123,165,67,151,181,155,189,204,
67,172,2,99,96,189,238,217,48,202,
133,118,30,53,29,195,194,120,60,228,
131,243,92,57,89,2,183,221,255,99,
225,251,215,208,228,125,49,218,48,54,
34,215,180,33,214,143,243,159,235,57,
234,100,108,58,39,150,12,251,49,72,
34,193,60,72,78,182,2,38,93,11,
196,53,207,246,143,54,182,57,199,33,
22,73,237,49,59,34,144,201,30,248,
238,89,120,65,207,215,75,45,151,121,
245,127,109,124,104,127,31,154,12,100,
28,13,162,34,93,240,207,215,255,219,
235,185,8,85,185,46,97,107,171,103,
98,98,119,50,52,172,141,166,253,152,
131,192,106,45,185,32,81,14,170,204,
194,0,79,100,150,45,214,4,214,193,
58,78,138,20,9,100,71,167,151,203,
165,77,217,254,165,241,229,248,247,161,
73,9,86,248,71,61,179,87,248,127,
33,1,114,54,233,155,119,209,72,51,
243,177,24,187,22,251,210,112,34,241,
29,215,219,139,23,12,1,185,161,130,
163,35,103,54,42,120,165,57,31,240,
174,132,239,107,123,72,144,174,60,87,
144,168,246,8,237,220,66,22,81,223,
141,79,231,191,15,77,86,4,17,249,
133,123,75,104,245,159,94,60,204,70,
127,21,137,87,13,29,60,228,181,76,
192,134,199,253,58,119,36,124,176,111,
89,128,156,45,81,93,60,19,202,171,
205,218,33,225,33,229,158,185,251,240,
70,207,30,113,64,16,125,51,102,161,
82,248,37,29,187,152,141,111,21,196,
191,15,77,142,163,208,6,114,175,68,
245,242,241,254,15,43,203,78,124,236,
89,205,89,252,153,142,54,253,106,27,
151,114,3,49,209,49,21,107,52,248,
250,105,39,88,201,25,252,102,131,92,
58,220,101,174,222,188,247,32,220,126,
185,80,57,154,229,210,49,237,223,141,
143,179,10,246,31,134,38,55,142,56,
81,161,97,112,101,245,199,241,239,134,
232,246,136,53,32,57,111,115,166,77,
218,121,151,9,245,75,4,45,209,219,
117,138,164,117,22,57,230,220,7,66,
100,120,55,72,135,86,153,190,214,216,
38,166,95,15,168,175,157,33,67,242,
163,108,1,24,103,76,14,32,255,48,
52,137,177,127,183,121,83,247,2,165,
125,124,254,113,217,179,222,107,208,240,
236,1,217,250,204,98,174,115,58,1,
102,186,39,47,208,252,130,192,14,29,
227,188,179,64,33,254,93,37,185,131,
220,122,35,215,61,196,74,164,115,199,
96,51,151,127,87,32,101,122,60,141,
80,73,71,242,15,67,147,130,174,251,
48,168,64,232,52,237,199,251,191,11,
3,213,222,30,251,53,184,2,53,103,
181,149,120,255,99,142,237,84,191,71,
244,220,251,85,25,244,35,175,82,212,
27,67,67,198,63,116,100,120,199,28,
244,134,248,76,96,140,198,129,56,167,
245,235,233,100,103,115,84,226,63,15,
77,54,125,44,12,2,95,157,154,147,
32,31,150,92,130,107,217,172,4,222,
248,158,108,116,206,132,108,175,115,160,
139,58,109,34,50,215,227,53,183,98,
1,101,92,93,8,92,242,12,203,155,
220,228,123,120,97,223,76,111,185,139,
81,211,127,108,80,119,75,55,141,236,
233,63,15,77,238,165,137,0,94,97,
44,213,31,95,254,108,98,40,212,192,
49,135,63,241,191,235,131,6,237,243,
14,207,51,147,29,132,221,140,94,55,
162,219,246,58,240,16,133,203,222,131,
195,195,94,186,117,115,172,207,154,113,
66,185,56,42,193,141,232,104,128,71,
120,140,31,176,89,254,15,67,147,109,
53,2,131,77,126,237,123,83,31,103,
192,57,110,232,145,82,88,150,29,67,
125,91,249,171,139,23,159,104,7,79,
206,116,67,155,151,49,35,87,51,232,
7,42,154,251,58,59,189,38,95,24,
135,71,20,219,219,130,180,38,156,72,
124,137,221,208,224,193,232,53,130,76,
145,137,255,60,52,201,131,239,242,92,
98,5,166,251,199,251,191,134,17,151,
68,63,93,102,77,123,86,54,42,130,
83,228,60,135,155,217,219,101,153,141,
48,44,160,33,171,216,13,65,180,203,
216,190,188,231,246,133,228,161,246,140,
75,184,8,159,109,164,156,109,157,193,
198,223,141,195,114,139,157,189,79,247,
111,67,147,173,164,154,252,188,50,137,
10,8,31,247,127,214,225,35,131,195,
112,39,36,180,70,144,203,191,64,33,
210,123,48,158,23,86,132,17,166,89,
87,169,216,194,111,101,173,44,169,138,
39,170,139,72,39,186,191,247,96,231,
114,253,49,206,226,218,232,21,131,35,
154,205,191,15,77,82,83,150,26,221,
16,19,89,186,143,223,127,146,90,66,
29,208,104,196,124,150,120,178,183,72,
243,64,13,54,219,89,122,105,87,31,
108,132,119,81,19,193,12,17,28,225,
125,130,121,113,15,23,115,224,173,236,
179,33,96,171,179,31,126,121,35,162,
45,79,24,221,11,213,145,170,246,183,
161,73,162,88,149,247,144,109,214,203,
17,20,127,188,254,7,241,168,204,121,
207,241,129,209,245,159,124,239,252,42,
48,111,64,162,129,27,93,219,147,137,
94,40,96,80,15,17,202,113,237,171,
194,131,118,182,173,101,102,183,1,233,
207,118,238,39,154,79,65,61,66,128,
251,30,140,131,221,130,112,228,239,67,
147,74,35,10,188,168,16,12,214,158,
158,143,167,255,113,149,230,53,177,13,
82,209,195,238,23,186,128,235,129,119,
86,38,237,133,41,12,212,169,131,217,
110,64,112,111,239,141,231,178,93,221,
204,123,51,172,118,182,58,11,250,14,
24,199,250,181,134,222,195,89,145,232,
205,102,42,97,87,239,210,95,135,38,
39,10,74,107,48,110,165,137,162,175,
68,184,120,232,143,251,127,11,148,92,
47,72,147,220,204,201,68,12,225,117,
3,206,113,15,90,150,92,218,140,71,
43,229,149,181,88,11,127,236,90,165,
84,62,122,39,17,55,249,81,135,129,
113,17,155,132,185,142,190,185,201,140,
237,2,35,75,226,82,46,242,47,67,
147,187,7,86,214,220,103,199,81,215,
200,172,168,229,233,227,243,31,92,11,
226,16,236,96,184,183,63,100,220,219,
23,49,121,179,148,229,117,77,219,54,
198,181,56,90,88,93,56,195,248,94,
112,133,170,119,81,235,22,69,190,231,
13,38,8,239,140,135,173,49,22,102,
114,19,82,154,3,193,75,105,251,241,
231,208,36,16,71,164,22,206,19,211,
240,212,221,156,157,143,219,199,1,208,
149,24,30,140,175,240,104,51,39,129,
192,174,194,248,148,183,147,6,199,123,
188,28,20,1,177,154,30,30,59,59,
214,126,70,160,246,75,238,51,55,208,
107,154,20,150,204,117,60,8,112,246,
181,100,202,142,229,232,136,43,67,168,
127,25,154,164,8,153,12,141,82,225,
15,145,247,77,122,185,198,143,231,191,
55,27,41,110,0,210,128,8,169,230,
4,246,212,32,108,69,3,14,71,29,
27,121,205,108,189,135,58,18,204,145,
255,73,141,222,237,146,111,31,177,66,
236,60,65,92,142,140,154,92,54,143,
100,240,232,253,70,166,224,113,31,224,
207,161,201,133,81,137,91,226,181,49,
60,107,168,238,221,78,195,62,222,255,
151,83,37,124,235,130,206,208,149,239,
115,1,84,117,198,108,101,193,245,146,
98,154,65,125,65,184,235,230,237,22,
158,205,180,254,49,227,253,27,48,192,
65,123,31,201,75,249,147,202,152,27,
20,211,186,188,116,106,209,7,242,199,
208,100,22,76,73,61,114,158,9,17,
15,162,80,82,103,243,251,199,243,95,
76,98,184,82,179,163,233,13,197,158,
235,16,108,63,171,226,144,148,158,41,
33,176,214,91,171,137,70,194,230,8,
111,214,231,11,119,105,38,2,107,94,
148,67,86,40,116,64,112,252,87,50,
211,247,178,14,243,123,104,210,120,129,
72,151,71,82,110,178,4,205,137,140,
101,17,4,67,98,250,120,5,212,137,
176,129,170,233,54,71,193,179,169,247,
29,145,172,141,81,133,214,100,50,55,
92,204,216,171,100,156,83,145,27,201,
61,92,187,70,2,167,102,42,188,48,
233,145,29,3,219,163,0,220,14,79,
80,3,144,250,199,53,40,114,132,90,
223,153,19,120,81,145,16,90,22,62,
8,165,126,71,160,65,101,30,78,45,
245,227,249,255,106,89,244,220,55,151,
210,190,110,59,250,110,63,211,185,34,
80,183,175,120,210,125,22,135,183,149,
26,22,16,29,47,224,78,228,246,24,
0,222,87,58,221,138,38,180,151,215,
190,134,217,58,120,34,12,234,173,165,
209,131,16,59,134,196,82,231,20,237,
142,148,185,23,12,129,174,99,228,155,
133,209,153,245,177,241,220,21,253,252,
253,23,69,108,109,71,194,167,97,61,
143,11,23,104,8,242,22,194,168,66,
71,95,230,117,133,179,215,89,110,90,
236,171,173,70,89,115,32,244,85,233,
181,34,21,122,77,27,38,203,58,203,
221,71,110,184,1,207,117,237,46,245,
68,88,137,26,131,201,53,88,110,20,
28,154,193,161,246,2,155,59,222,125,
182,212,171,37,88,79,63,189,126,50,
38,249,221,216,28,238,184,7,70,114,
106,106,162,17,24,162,29,133,56,136,
155,11,121,65,202,198,228,23,42,177,
87,16,9,17,161,179,19,137,128,169,
210,16,73,144,210,17,152,247,4,147,
57,47,185,167,117,130,98,41,245,129,
90,179,108,24,58,235,12,115,225,188,
14,185,32,56,178,8,53,192,192,74,
245,154,62,126,255,105,180,129,156,129,
144,208,243,152,73,60,144,107,157,237,
14,194,182,13,136,217,164,227,94,162,
83,215,120,154,91,139,232,7,178,214,
115,14,128,173,71,68,23,184,225,22,
192,227,40,134,0,43,137,151,34,69,
163,185,179,72,110,214,134,65,95,155,
225,92,70,176,11,90,249,189,217,25,
37,210,204,27,139,146,196,210,63,222,
255,52,96,181,4,172,172,119,157,215,
30,95,123,217,55,161,28,28,18,185,
16,34,244,221,48,171,89,237,6,241,
174,64,147,102,125,152,165,182,201,255,
231,197,80,69,106,175,109,200,218,118,
58,239,81,200,30,29,136,191,4,239,
210,222,114,78,190,175,91,119,204,244,
157,122,224,42,246,177,138,53,28,8,
139,99,63,162,106,31,159,255,229,24,
148,172,148,102,157,55,181,181,151,63,
75,95,209,26,80,157,209,39,44,32,
115,90,40,111,84,13,124,145,234,195,
147,92,45,37,234,232,148,146,251,104,
132,146,236,121,131,193,248,197,243,202,
92,9,99,75,47,23,9,203,167,89,
71,212,187,218,144,254,134,141,18,209,
122,38,99,34,12,42,199,40,44,223,
209,127,220,255,183,121,237,69,159,113,
40,154,121,7,152,91,245,188,178,28,
113,96,229,97,160,55,88,196,188,221,
224,126,16,255,193,254,164,190,82,174,
165,208,47,230,201,123,104,146,104,133,
241,204,34,166,103,248,195,26,17,61,
119,8,152,142,247,221,160,251,213,151,
136,138,132,63,250,211,233,255,204,182,
145,117,18,78,29,104,123,220,103,23,
15,243,250,63,116,113,170,158,136,109,
237,44,229,162,117,162,91,247,89,194,
243,218,111,116,255,6,161,43,244,128,
20,33,171,104,102,218,231,46,50,93,
236,221,185,63,135,38,149,156,119,65,
225,82,136,180,190,70,195,196,190,235,
182,190,17,85,101,173,130,171,7,37,
253,157,100,207,203,108,2,27,179,105,
248,129,139,218,254,113,254,151,77,115,
38,231,54,153,88,155,119,22,45,38,
206,30,22,89,237,190,133,51,40,165,
173,153,71,57,145,172,123,99,215,129,
204,214,172,199,191,15,77,230,221,59,
163,162,173,233,28,118,222,240,250,128,
110,129,34,151,206,8,1,237,98,181,
29,185,41,4,189,60,131,215,190,205,
220,241,135,101,95,240,49,182,21,29,
252,156,112,232,232,247,231,125,247,171,
49,49,244,221,70,35,145,223,89,88,
131,129,112,21,164,113,20,26,93,151,
220,115,142,127,31,154,44,91,194,37,
42,38,28,161,6,177,64,131,29,68,
188,102,243,195,210,185,65,135,217,153,
102,115,148,12,189,203,44,168,131,222,
62,191,254,51,89,207,28,212,149,23,
8,59,231,58,35,104,69,76,172,215,
157,91,1,82,79,100,139,202,17,94,
71,233,154,65,141,203,169,102,223,126,
89,33,253,203,208,228,69,229,234,24,
241,8,110,23,183,14,244,252,48,175,
126,197,224,47,171,65,14,221,242,129,
10,150,75,229,109,247,130,1,177,16,
62,94,255,221,87,89,162,113,134,34,
181,1,18,19,165,226,60,24,8,209,
134,70,138,178,206,235,42,99,7,185,
189,58,26,120,219,119,132,124,164,205,
158,119,173,151,37,253,101,104,82,103,
176,229,216,250,1,230,220,230,100,191,
57,231,180,252,204,149,170,203,195,118,
158,51,192,118,13,68,103,153,141,104,
231,62,62,63,255,242,51,233,137,104,
159,89,68,107,144,103,67,227,40,3,
202,185,16,194,131,170,212,149,141,244,
215,83,201,1,183,134,172,212,156,124,
232,13,17,50,81,193,252,57,52,169,
40,241,189,63,79,71,20,149,81,51,
52,133,13,102,235,99,99,179,182,80,
111,112,3,84,128,89,97,131,150,87,
40,163,62,31,199,255,64,173,116,227,
88,52,136,96,240,76,71,166,217,158,
112,149,8,139,201,132,227,97,239,227,
154,197,176,108,30,92,164,91,57,130,
99,251,50,54,243,226,85,14,127,12,
77,54,102,44,186,138,242,188,203,0,
39,155,23,164,17,133,6,158,67,208,
214,241,52,248,105,60,68,247,110,4,
178,239,161,35,248,120,252,151,208,179,
13,72,122,53,231,190,15,91,170,10,
178,95,169,207,193,183,232,27,180,81,
116,156,193,109,137,118,78,203,67,95,
204,241,96,160,135,120,232,209,252,226,
126,13,77,98,8,13,115,0,22,215,
20,80,69,120,187,134,199,216,135,59,
226,192,247,99,87,193,23,140,42,110,
92,2,152,214,63,153,255,143,215,191,
118,131,58,79,8,245,177,51,64,102,
190,31,131,194,210,82,207,38,198,101,
219,242,245,243,29,21,239,199,109,5,
150,91,109,217,156,67,7,132,135,234,
53,102,23,40,252,12,77,214,228,214,
217,78,105,3,191,142,89,88,208,120,
208,168,19,165,230,213,61,167,52,10,
121,196,72,24,79,145,60,228,158,48,
124,154,143,231,127,28,19,51,244,165,
204,16,8,204,91,255,246,66,9,58,
127,100,49,145,34,90,217,79,36,43,
75,120,247,105,204,146,61,239,115,152,
229,74,184,254,128,212,103,166,136,200,
12,5,126,223,105,91,82,122,39,134,
24,188,154,7,198,71,21,158,35,175,
118,145,151,125,218,62,165,63,87,126,
112,31,175,115,207,160,63,158,255,107,
179,222,65,247,215,75,195,114,197,181,
196,197,206,107,64,150,73,240,124,62,
94,120,240,115,184,63,253,92,213,240,
96,44,68,27,232,228,245,204,146,1,
169,140,176,142,251,53,175,7,233,157,
87,3,23,143,219,252,201,94,163,19,
232,248,231,119,11,128,68,211,25,181,
77,7,136,225,22,248,88,102,95,56,
60,37,124,30,0,19,56,95,236,153,
137,112,18,80,243,49,134,133,227,238,
132,87,254,192,108,109,223,131,152,147,
138,102,63,52,158,253,188,187,58,189,
242,204,129,15,147,95,163,212,148,118,
32,251,143,29,251,77,224,59,107,158,
58,112,205,214,127,178,31,14,226,28,
141,95,214,249,225,115,106,216,142,113,
119,93,36,70,135,163,125,28,255,162,
21,187,121,171,13,215,215,251,44,98,
24,39,213,232,176,78,135,206,254,61,
212,111,185,246,214,244,212,48,44,10,
245,168,199,255,186,187,226,126,150,198,
77,139,30,131,196,251,10,89,149,82,
180,137,165,52,226,54,43,33,143,148,
125,64,126,117,135,106,176,99,116,157,
67,212,250,224,245,80,46,197,89,40,
253,120,255,215,142,143,160,189,215,122,
181,63,55,18,48,198,87,88,70,220,
163,190,111,27,3,140,27,189,183,175,
139,51,122,14,139,129,138,128,48,8,
127,176,22,174,16,193,99,56,168,82,
163,234,71,177,162,103,31,155,48,224,
246,19,12,2,166,84,151,85,235,26,
248,242,132,189,187,4,139,157,119,173,
34,47,52,179,222,214,143,143,247,191,
190,238,67,190,81,96,91,5,123,79,
179,147,4,186,99,200,110,175,93,149,
3,182,43,149,123,219,123,173,231,188,
222,213,206,11,78,17,33,129,51,149,
129,60,174,222,199,86,237,130,236,121,
120,233,44,33,67,10,230,153,98,178,
46,160,234,8,108,102,214,215,229,193,
248,39,14,132,210,193,92,32,215,159,
206,207,237,227,235,103,117,44,16,206,
188,183,184,154,119,45,47,22,244,223,
51,219,165,249,186,241,237,78,176,237,
226,88,40,155,99,13,131,142,211,226,
111,245,77,17,68,240,145,115,202,25,
162,97,183,35,252,35,48,123,99,13,
193,200,192,240,37,181,117,68,87,67,
66,1,19,165,90,128,65,233,205,90,
54,187,44,216,143,231,251,120,253,11,
40,90,37,135,177,181,216,231,119,128,
209,192,225,138,72,98,6,104,84,98,
50,249,254,60,36,247,198,42,99,192,
188,230,8,110,107,247,179,148,95,247,
215,144,149,240,171,208,247,191,35,123,
68,43,66,16,60,153,33,226,199,252,
83,47,188,103,255,3,195,143,96,248,
57,148,173,46,94,7,93,159,143,195,
159,153,198,67,237,204,43,62,153,236,
51,239,131,43,149,5,253,53,198,235,
93,164,6,113,157,135,132,196,112,166,
106,39,10,114,175,57,181,188,70,68,
200,172,41,126,58,12,227,232,19,186,
159,151,57,71,109,220,236,147,120,50,
146,165,249,45,63,115,6,150,114,97,
71,34,121,118,85,179,129,112,97,59,
82,15,15,2,171,231,227,248,247,196,
131,156,23,32,204,65,159,92,38,23,
250,185,147,10,255,63,141,35,196,7,
236,110,9,219,237,48,218,101,101,141,
189,180,147,100,126,111,146,113,229,182,
173,175,33,0,33,199,178,80,94,72,
41,62,190,111,181,235,200,145,46,174,
196,188,8,145,212,182,61,72,121,187,
25,55,180,83,180,45,77,2,189,10,
225,63,222,255,244,56,121,163,99,182,
206,17,153,223,167,113,19,132,124,220,
35,8,222,53,34,249,50,208,145,11,
135,108,181,109,35,151,253,85,137,209,
202,14,187,236,253,101,252,206,164,206,
86,134,206,200,98,23,77,144,20,131,
164,205,152,5,247,106,65,204,99,55,
6,190,90,31,10,228,93,62,11,52,
189,103,98,246,10,196,21,253,241,245,
115,9,50,87,82,115,21,75,103,3,
237,54,222,8,230,231,13,39,115,56,
113,31,27,122,241,84,84,91,148,82,
155,91,119,196,0,205,41,73,139,151,
57,248,53,120,165,142,220,87,106,253,
218,13,35,148,33,110,78,43,122,80,
146,196,218,148,19,226,9,193,75,16,
103,226,178,193,222,84,69,140,44,7,
194,1,193,249,199,235,63,179,165,123,
233,94,82,127,168,68,221,165,61,180,
4,82,165,117,94,122,195,174,99,175,
146,167,179,204,7,165,38,68,14,188,
4,137,39,105,55,52,248,83,21,203,
74,189,28,223,148,143,237,38,72,165,
230,85,169,27,71,224,187,28,91,17,
251,130,225,99,114,8,195,205,166,129,
138,60,250,146,139,161,30,215,191,126,
30,254,137,52,125,218,133,24,158,237,
104,162,176,206,59,175,252,242,108,112,
65,90,240,180,37,146,88,212,90,22,
59,116,174,81,63,132,19,177,247,247,
29,14,158,243,121,153,239,107,49,43,
198,179,117,54,194,29,91,171,169,204,
214,232,134,12,225,68,245,153,99,52,
191,198,156,218,243,208,221,42,100,132,
149,66,35,33,125,222,255,101,62,199,
115,97,109,104,161,185,255,234,71,51,
99,94,231,30,230,151,56,117,57,243,
188,181,149,27,226,184,136,223,130,207,
85,233,121,135,135,66,59,102,11,34,
89,144,105,61,214,68,167,11,61,202,
226,28,130,193,52,145,237,138,38,161,
142,146,222,215,124,190,67,253,147,210,
51,187,196,247,154,103,93,216,126,252,
254,155,87,103,106,6,104,83,73,88,
85,14,147,145,34,49,65,53,70,30,
127,114,52,6,215,18,123,252,225,220,
235,65,228,151,233,108,106,159,119,184,
84,240,206,225,150,221,116,54,60,29,
239,47,78,193,160,32,141,92,251,164,
245,243,171,82,165,116,199,251,14,152,
97,124,12,198,105,168,204,205,62,137,
84,46,154,87,111,62,62,255,120,140,
149,207,175,188,89,188,230,200,123,231,
183,183,0,109,44,7,74,178,123,103,
103,125,201,118,126,41,234,93,15,23,
209,230,115,33,63,119,248,232,247,88,
155,137,129,230,232,152,30,71,151,70,
176,165,108,33,55,142,134,85,156,214,
124,67,110,225,22,102,239,179,133,58,
46,64,109,113,37,174,193,232,135,148,
177,127,220,255,211,82,6,23,117,63,
7,46,150,143,58,175,232,97,66,235,
188,214,186,204,204,15,69,35,71,28,
131,103,39,121,88,171,68,229,255,117,
135,83,87,186,228,153,199,138,68,41,
140,152,50,49,215,209,181,25,137,86,
181,136,97,103,87,172,224,80,142,179,
178,113,141,189,231,171,207,200,146,207,
11,3,205,22,115,148,31,63,127,194,
182,149,64,229,103,34,41,170,237,170,
231,169,115,92,214,84,242,226,244,123,
222,1,234,171,102,51,103,247,137,111,
2,209,254,207,29,94,16,119,58,94,
235,188,34,0,149,221,123,185,24,170,
100,35,179,21,24,33,207,134,116,224,
125,169,44,110,198,121,87,70,75,118,
8,143,194,132,88,148,18,52,150,131,
124,60,251,141,66,43,4,160,232,174,
194,56,136,105,61,143,45,59,180,8,
179,88,9,53,28,108,61,47,120,108,
234,243,142,119,149,150,229,247,29,110,
179,93,236,32,10,25,224,43,83,219,
211,188,44,123,213,158,0,175,47,208,
148,226,86,0,161,251,187,43,60,60,
13,216,204,8,164,174,192,111,32,30,
159,226,222,231,232,212,135,101,78,112,
249,94,79,255,254,22,188,217,249,142,
79,118,11,113,82,182,32,163,19,119,
72,1,70,51,251,221,129,223,61,111,
253,143,59,252,96,126,107,146,82,207,
3,119,67,223,207,237,178,148,117,194,
166,227,25,107,161,106,69,152,19,124,
251,137,113,207,169,142,212,20,4,130,
75,86,44,207,11,224,207,42,63,222,
255,254,120,107,225,220,125,81,144,120,
193,85,185,233,19,6,156,47,77,219,
252,222,3,196,194,225,129,61,157,11,
164,213,176,112,253,190,202,230,61,231,
138,144,8,30,206,94,120,250,66,22,
203,143,247,23,222,218,75,120,171,167,
211,64,240,91,144,242,206,73,153,190,
212,89,66,93,22,84,170,166,226,158,
144,7,153,143,231,255,250,209,75,113,
5,201,46,2,225,189,128,80,214,219,
119,27,255,188,195,211,65,71,92,244,
154,87,194,207,139,129,216,226,57,249,
227,14,207,50,83,30,179,151,229,65,
92,232,147,89,92,156,223,121,61,199,
168,240,71,106,247,190,204,233,199,245,
213,162,194,77,238,64,26,226,140,116,
212,130,182,132,118,3,68,127,190,252,
131,14,122,206,43,178,217,204,66,14,
196,186,92,183,159,172,252,188,195,213,
172,133,247,217,235,54,203,219,107,153,
54,76,254,184,202,166,218,82,223,95,
114,253,110,157,108,124,85,65,207,175,
16,60,17,10,162,185,203,124,166,178,
33,130,184,59,186,18,193,56,153,95,
49,220,103,233,115,222,141,249,198,67,
159,135,255,191,228,32,11,62,234,86,
66,137,126,230,44,182,185,174,25,160,
203,152,95,255,38,102,153,228,213,106,
112,241,47,87,217,212,141,202,119,97,
0,249,79,32,188,154,176,72,12,18,
51,201,219,251,254,190,1,73,96,152,
200,242,117,216,249,21,187,245,184,49,
234,205,164,201,251,183,8,200,207,247,
255,127,229,43,95,249,202,87,190,242,
149,175,124,229,43,95,249,202,87,190,
242,149,175,124,229,43,95,249,202,87,
190,242,149,175,124,229,43,95,249,202,
87,190,242,149,175,124,229,43,95,249,
202,87,190,242,149,175,124,229,43,95,
249,202,87,190,242,149,175,124,229,43,
95,249,202,87,190,242,149,175,124,229,
43,95,249,202,87,190,242,149,175,124,
229,43,95,249,202,87,190,242,149,175,
124,229,43,95,249,202,87,190,242,149,
175,124,229,43,95,249,202,87,190,242,
149,175,124,229,43,95,249,202,87,190,
242,149,175,124,229,43,95,249,202,87,
190,242,149,175,124,229,43,95,249,202,
87,190,242,149,175,124,229,43,95,249,
202,87,190,242,149,175,124,229,43,95,
249,202,87,190,242,21,128,255,7,221,
154,25,153,119,41,166,247,0,0,50,
33,105,84,88,116,88,77,76,58,99,
111,109,46,97,100,111,98,101,46,120,
109,112,0,0,0,0,0,60,63,120,
112,97,99,107,101,116,32,98,101,103,
105,110,61,34,239,187,191,34,32,105,
100,61,34,87,53,77,48,77,112,67,
101,104,105,72,122,114,101,83,122,78,
84,99,122,107,99,57,100,34,63,62,
10,60,120,58,120,109,112,109,101,116,
97,32,120,109,108,110,115,58,120,61,
34,97,100,111,98,101,58,110,115,58,
109,101,116,97,47,34,32,120,58,120,
109,112,116,107,61,34,65,100,111,98,
101,32,88,77,80,32,67,111,114,101,
32,53,46,48,45,99,48,54,48,32,
54,49,46,49,51,52,55,55,55,44,
32,50,48,49,48,47,48,50,47,49,
50,45,49,55,58,51,50,58,48,48,
32,32,32,32,32,32,32,32,34,62,
10,32,32,32,60,114,100,102,58,82,
68,70,32,120,109,108,110,115,58,114,
100,102,61,34,104,116,116,112,58,47,
47,119,119,119,46,119,51,46,111,114,
103,47,49,57,57,57,47,48,50,47,
50,50,45,114,100,102,45,115,121,110,
116,97,120,45,110,115,35,34,62,10,
32,32,32,32,32,32,60,114,100,102,
58,68,101,115,99,114,105,112,116,105,
111,110,32,114,100,102,58,97,98,111,
117,116,61,34,34,10,32,32,32,32,
32,32,32,32,32,32,32,32,120,109,
108,110,115,58,120,109,112,61,34,104,
116,116,112,58,47,47,110,115,46,97,
100,111,98,101,46,99,111,109,47,120,
97,112,47,49,46,48,47,34,62,10,
32,32,32,32,32,32,32,32,32,60,
120,109,112,58,67,114,101,97,116,111,
114,84,111,111,108,62,65,100,111,98,
101,32,70,105,114,101,119,111,114,107,
115,32,67,83,53,32,49,49,46,48,
46,48,46,52,56,52,32,87,105,110,
100,111,119,115,60,47,120,109,112,58,
67,114,101,97,116,111,114,84,111,111,
108,62,10,32,32,32,32,32,32,32,
32,32,60,120,109,112,58,67,114,101,
97,116,101,68,97,116,101,62,50,48,
49,52,45,48,56,45,48,52,84,49,
56,58,52,56,58,49,51,90,60,47,
120,109,112,58,67,114,101,97,116,101,
68,97,116,101,62,10,32,32,32,32,
32,32,32,32,32,60,120,109,112,58,
77,111,100,105,102,121,68,97,116,101,
62,50,48,49,52,45,48,56,45,48,
52,84,49,56,58,53,51,58,53,51,
90,60,47,120,109,112,58,77,111,100,
105,102,121,68,97,116,101,62,10,32,
32,32,32,32,32,60,47,114,100,102,
58,68,101,115,99,114,105,112,116,105,
111,110,62,10,32,32,32,32,32,32,
60,114,100,102,58,68,101,115,99,114,
105,112,116,105,111,110,32,114,100,102,
58,97,98,111,117,116,61,34,34,10,
32,32,32,32,32,32,32,32,32,32,
32,32,120,109,108,110,115,58,100,99,
61,34,104,116,116,112,58,47,47,112,
117,114,108,46,111,114,103,47,100,99,
47,101,108,101,109,101,110,116,115,47,
49,46,49,47,34,62,10,32,32,32,
32,32,32,32,32,32,60,100,99,58,
102,111,114,109,97,116,62,105,109,97,
103,101,47,112,110,103,60,47,100,99,
58,102,111,114,109,97,116,62,10,32,
32,32,32,32,32,60,47,114,100,102,
58,68,101,115,99,114,105,112,116,105,
111,110,62,10,32,32,32,60,47,114,
100,102,58,82,68,70,62,10,60,47,
120,58,120,109,112,109,101,116,97,62,
10,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,10,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,10,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,10,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,10,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,10,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,10,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,10,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,10,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,10,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
10,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,10,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,10,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,10,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,10,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,10,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,10,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,10,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,10,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,10,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
10,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,10,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,10,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,10,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,10,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,10,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,10,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,10,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,10,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,10,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
10,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,10,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,10,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,10,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,10,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,10,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,10,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,10,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,10,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,10,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
10,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,10,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,10,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,10,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,10,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,10,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,10,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,10,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,10,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,10,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
10,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,10,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,10,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,10,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,10,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,10,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,10,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,10,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,10,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,10,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
10,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,10,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,10,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,10,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,10,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,10,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,10,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,10,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,10,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,10,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
10,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,10,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,10,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,10,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,10,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,10,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,10,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,10,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,10,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,10,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
10,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,10,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,10,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,10,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,10,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,10,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,10,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,10,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,10,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,10,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
10,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,10,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,10,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,10,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,10,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,10,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,10,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,10,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,10,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,10,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
10,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,10,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,10,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,10,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,10,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,10,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,10,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,10,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,10,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,10,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
10,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,10,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,10,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,10,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,10,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,10,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,10,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,10,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,10,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,10,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,10,60,
63,120,112,97,99,107,101,116,32,101,
110,100,61,34,119,34,63,62,122,154,
41,131,0,0,0,99,73,68,65,84,
24,149,165,145,65,14,128,32,12,4,
167,128,26,255,255,90,53,82,47,104,
154,82,184,184,151,13,203,132,45,32,
170,74,32,5,196,135,105,0,90,159,
194,226,188,131,187,141,150,229,8,62,
3,24,224,110,126,0,136,14,110,24,
41,1,197,212,10,176,182,245,6,236,
102,196,165,180,42,59,219,91,93,77,
150,129,42,127,223,249,114,13,159,102,
39,39,220,199,60,44,17,28,19,251,
246,33,243,0,0,0,0,73,69,78,
68,174,66,96,130,0x00 };
}
|
// Copyright Catch2 Authors
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// https://www.boost.org/LICENSE_1_0.txt)
// SPDX-License-Identifier: BSL-1.0
/**\file
* Test that Catch's prefixed macros compile and run properly.
*
* We intentionally do not provide full coverage of all macros, but we
* test a smattering and can add other ones as they have regressions.
*/
#include <catch2/catch_test_macros.hpp>
#include <catch2/matchers/catch_matchers_predicate.hpp>
#include <catch2/matchers/catch_matchers_string.hpp>
#include <type_traits>
#include <stdexcept>
namespace {
[[noreturn]]
void this_throws() {
throw std::runtime_error("Some msg");
}
void this_doesnt_throw() {}
}
CATCH_TEST_CASE("PrefixedMacros") {
using namespace Catch::Matchers;
CATCH_REQUIRE( 1 == 1 );
CATCH_REQUIRE_FALSE( 1 != 1 );
CATCH_REQUIRE_THROWS(this_throws());
CATCH_REQUIRE_THROWS_AS(this_throws(), std::runtime_error);
CATCH_REQUIRE_THROWS_WITH(this_throws(), "Some msg");
CATCH_REQUIRE_THROWS_MATCHES(this_throws(), std::runtime_error, Predicate<std::runtime_error>([](std::runtime_error const&) { return true; }));
CATCH_REQUIRE_NOTHROW(this_doesnt_throw());
CATCH_CHECK( 1 == 1 );
CATCH_CHECK_FALSE( 1 != 1 );
CATCH_CHECKED_IF( 1 == 1 ) {
CATCH_SUCCEED("don't care");
} CATCH_CHECKED_ELSE ( 1 == 1 ) {
CATCH_SUCCEED("don't care");
}
CATCH_CHECK_NOFAIL(1 == 2);
CATCH_CHECK_THROWS(this_throws());
CATCH_CHECK_THROWS_AS(this_throws(), std::runtime_error);
CATCH_CHECK_THROWS_WITH(this_throws(), "Some msg");
CATCH_CHECK_THROWS_MATCHES(this_throws(), std::runtime_error, Predicate<std::runtime_error>([](std::runtime_error const&) { return true; }));
CATCH_CHECK_NOTHROW(this_doesnt_throw());
CATCH_REQUIRE_THAT("abcd", Equals("abcd"));
CATCH_CHECK_THAT("bdef", Equals("bdef"));
CATCH_INFO( "some info" );
CATCH_UNSCOPED_INFO( "some info" );
CATCH_WARN( "some warn" );
CATCH_SECTION("some section") {
int i = 1;
CATCH_CAPTURE( i );
CATCH_DYNAMIC_SECTION("Dynamic section: " << i) {
CATCH_FAIL_CHECK( "failure" );
}
}
CATCH_STATIC_REQUIRE( std::is_void<void>::value );
CATCH_STATIC_REQUIRE_FALSE( std::is_void<int>::value );
CATCH_STATIC_CHECK( std::is_void<void>::value );
CATCH_STATIC_CHECK_FALSE( std::is_void<int>::value );
CATCH_FAIL("");
}
// Missing:
//
// #define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ )
// #define CATCH_METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ )
// #define CATCH_REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ )
//
// // "BDD-style" convenience wrappers
// #define CATCH_SCENARIO( ... ) CATCH_TEST_CASE( "Scenario: " __VA_ARGS__ )
// #define CATCH_SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ )
// #define CATCH_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Given: " << desc )
// #define CATCH_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " When: " << desc )
// #define CATCH_AND_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( "And when: " << desc )
// #define CATCH_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Then: " << desc )
// #define CATCH_AND_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And: " << desc )
//
|
#include "mapping/mapProperties.h"
namespace gnssShadowing {
namespace mapping {
std::ostream& operator<<(std::ostream& os, const MapProperties& mapProperties)
{
os << "["
"min_x: " << mapProperties.m_min_x << " "
"min_y: " << mapProperties.m_min_y << " "
"num_cols: " << mapProperties.m_num_cols << " "
"num_rows: " << mapProperties.m_num_rows << " "
"x_resolution: " << mapProperties.m_x_resolution << " "
"y_resolution: " << mapProperties.m_y_resolution << " "
"plane_levels: ";
bool first = true;
for (double planeLevel : mapProperties.m_plane_levels)
{
if (!first) os << "; ";
first = false;
os << planeLevel;
}
os << "]" << std::endl;
return os;
}
} // namespace mapping
} // namespace gnssShadowing
|
#pragma once
#include <Register/Utility.hpp>
namespace Kvasir {
//Analog to Digital Converter
namespace Adc2Isr{ ///<ADC interrupt and status register
using Addr = Register::Address<0x40022100,0xfffff800,0x00000000,std::uint32_t>;
///ADC group injected contexts queue overflow flag
constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::ReadWriteAccess,unsigned> jqovf{};
///ADC analog watchdog 3 flag
constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,unsigned> awd3{};
///ADC analog watchdog 2 flag
constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> awd2{};
///ADC analog watchdog 1 flag
constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> awd1{};
///ADC group injected end of sequence conversions flag
constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> jeos{};
///ADC group injected end of unitary conversion flag
constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> jeoc{};
///ADC group regular overrun flag
constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> ovr{};
///ADC group regular end of sequence conversions flag
constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> eos{};
///ADC group regular end of unitary conversion flag
constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> eoc{};
///ADC group regular end of sampling flag
constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> eosmp{};
///ADC ready flag
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> adrdy{};
}
namespace Adc2Ier{ ///<ADC interrupt enable register
using Addr = Register::Address<0x40022104,0xfffff800,0x00000000,std::uint32_t>;
///ADC group injected contexts queue overflow interrupt
constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::ReadWriteAccess,unsigned> jqovfie{};
///ADC analog watchdog 3 interrupt
constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,unsigned> awd3ie{};
///ADC analog watchdog 2 interrupt
constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> awd2ie{};
///ADC analog watchdog 1 interrupt
constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> awd1ie{};
///ADC group injected end of sequence conversions interrupt
constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> jeosie{};
///ADC group injected end of unitary conversion interrupt
constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> jeocie{};
///ADC group regular overrun interrupt
constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> ovrie{};
///ADC group regular end of sequence conversions interrupt
constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> eosie{};
///ADC group regular end of unitary conversion interrupt
constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> eocie{};
///ADC group regular end of sampling interrupt
constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> eosmpie{};
///ADC ready interrupt
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> adrdyie{};
}
namespace Adc2Cr{ ///<ADC control register
using Addr = Register::Address<0x40022108,0x003efec0,0x00000000,std::uint32_t>;
///ADC calibration
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,31),Register::ReadWriteAccess,unsigned> adcal{};
///ADC differential mode for calibration
constexpr Register::FieldLocation<Addr,Register::maskFromRange(30,30),Register::ReadWriteAccess,unsigned> adcaldif{};
///ADC deep power down enable
constexpr Register::FieldLocation<Addr,Register::maskFromRange(29,29),Register::ReadWriteAccess,unsigned> deeppwd{};
///ADC voltage regulator enable
constexpr Register::FieldLocation<Addr,Register::maskFromRange(28,28),Register::ReadWriteAccess,unsigned> advregen{};
///Linearity calibration ready Word 6
constexpr Register::FieldLocation<Addr,Register::maskFromRange(27,27),Register::ReadWriteAccess,unsigned> lincalrdyw6{};
///Linearity calibration ready Word 5
constexpr Register::FieldLocation<Addr,Register::maskFromRange(26,26),Register::ReadWriteAccess,unsigned> lincalrdyw5{};
///Linearity calibration ready Word 4
constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,25),Register::ReadWriteAccess,unsigned> lincalrdyw4{};
///Linearity calibration ready Word 3
constexpr Register::FieldLocation<Addr,Register::maskFromRange(24,24),Register::ReadWriteAccess,unsigned> lincalrdyw3{};
///Linearity calibration ready Word 2
constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,23),Register::ReadWriteAccess,unsigned> lincalrdyw2{};
///Linearity calibration ready Word 1
constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,22),Register::ReadWriteAccess,unsigned> lincalrdyw1{};
///Linearity calibration
constexpr Register::FieldLocation<Addr,Register::maskFromRange(16,16),Register::ReadWriteAccess,unsigned> adcallin{};
///Boost mode control
constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> boost{};
///ADC group injected conversion stop
constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> jadstp{};
///ADC group regular conversion stop
constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> adstp{};
///ADC group injected conversion start
constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> jadstart{};
///ADC group regular conversion start
constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> adstart{};
///ADC disable
constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> addis{};
///ADC enable
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> aden{};
}
namespace Adc2Cfgr{ ///<ADC configuration register 1
using Addr = Register::Address<0x4002210c,0x00008010,0x00000000,std::uint32_t>;
///ADC group injected contexts queue disable
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,31),Register::ReadWriteAccess,unsigned> jqdis{};
///ADC analog watchdog 1 monitored channel selection
constexpr Register::FieldLocation<Addr,Register::maskFromRange(30,26),Register::ReadWriteAccess,unsigned> awdch1ch{};
///ADC group injected automatic trigger mode
constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,25),Register::ReadWriteAccess,unsigned> jauto{};
///ADC analog watchdog 1 enable on scope ADC group injected
constexpr Register::FieldLocation<Addr,Register::maskFromRange(24,24),Register::ReadWriteAccess,unsigned> jawd1en{};
///ADC analog watchdog 1 enable on scope ADC group regular
constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,23),Register::ReadWriteAccess,unsigned> awd1en{};
///ADC analog watchdog 1 monitoring a single channel or all channels
constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,22),Register::ReadWriteAccess,unsigned> awd1sgl{};
///ADC group injected contexts queue mode
constexpr Register::FieldLocation<Addr,Register::maskFromRange(21,21),Register::ReadWriteAccess,unsigned> jqm{};
///ADC group injected sequencer discontinuous mode
constexpr Register::FieldLocation<Addr,Register::maskFromRange(20,20),Register::ReadWriteAccess,unsigned> jdiscen{};
///ADC group regular sequencer discontinuous number of ranks
constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,17),Register::ReadWriteAccess,unsigned> discnum{};
///ADC group regular sequencer discontinuous mode
constexpr Register::FieldLocation<Addr,Register::maskFromRange(16,16),Register::ReadWriteAccess,unsigned> discen{};
///ADC low power auto wait
constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,14),Register::ReadWriteAccess,unsigned> autdly{};
///ADC group regular continuous conversion mode
constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,13),Register::ReadWriteAccess,unsigned> cont{};
///ADC group regular overrun configuration
constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::ReadWriteAccess,unsigned> ovrmod{};
///ADC group regular external trigger polarity
constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,10),Register::ReadWriteAccess,unsigned> exten{};
///ADC group regular external trigger source
constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,5),Register::ReadWriteAccess,unsigned> extsel{};
///ADC data resolution
constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,2),Register::ReadWriteAccess,unsigned> res{};
///ADC DMA transfer enable
constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,0),Register::ReadWriteAccess,unsigned> dmngt{};
}
namespace Adc2Cfgr2{ ///<ADC configuration register 2
using Addr = Register::Address<0x40022110,0x0c00801c,0x00000000,std::uint32_t>;
///ADC oversampler enable on scope ADC group regular
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> rovse{};
///ADC oversampler enable on scope ADC group injected
constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> jovse{};
///ADC oversampling shift
constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,5),Register::ReadWriteAccess,unsigned> ovss{};
///ADC oversampling discontinuous mode (triggered mode) for ADC group regular
constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,unsigned> trovs{};
///Regular Oversampling mode
constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::ReadWriteAccess,unsigned> rovsm{};
///Right-shift data after Offset 1 correction
constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,11),Register::ReadWriteAccess,unsigned> rshift1{};
///Right-shift data after Offset 2 correction
constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::ReadWriteAccess,unsigned> rshift2{};
///Right-shift data after Offset 3 correction
constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,13),Register::ReadWriteAccess,unsigned> rshift3{};
///Right-shift data after Offset 4 correction
constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,14),Register::ReadWriteAccess,unsigned> rshift4{};
///Oversampling ratio
constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,16),Register::ReadWriteAccess,unsigned> osr{};
///Left shift factor
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,28),Register::ReadWriteAccess,unsigned> lshift{};
}
namespace Adc2Smpr1{ ///<ADC sampling time register 1
using Addr = Register::Address<0x40022114,0xc0000007,0x00000000,std::uint32_t>;
///ADC channel 9 sampling time selection
constexpr Register::FieldLocation<Addr,Register::maskFromRange(29,27),Register::ReadWriteAccess,unsigned> smp9{};
///ADC channel 8 sampling time selection
constexpr Register::FieldLocation<Addr,Register::maskFromRange(26,24),Register::ReadWriteAccess,unsigned> smp8{};
///ADC channel 7 sampling time selection
constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,21),Register::ReadWriteAccess,unsigned> smp7{};
///ADC channel 6 sampling time selection
constexpr Register::FieldLocation<Addr,Register::maskFromRange(20,18),Register::ReadWriteAccess,unsigned> smp6{};
///ADC channel 5 sampling time selection
constexpr Register::FieldLocation<Addr,Register::maskFromRange(17,15),Register::ReadWriteAccess,unsigned> smp5{};
///ADC channel 4 sampling time selection
constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,12),Register::ReadWriteAccess,unsigned> smp4{};
///ADC channel 3 sampling time selection
constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,9),Register::ReadWriteAccess,unsigned> smp3{};
///ADC channel 2 sampling time selection
constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,6),Register::ReadWriteAccess,unsigned> smp2{};
///ADC channel 1 sampling time selection
constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,3),Register::ReadWriteAccess,unsigned> smp1{};
}
namespace Adc2Smpr2{ ///<ADC sampling time register 2
using Addr = Register::Address<0x40022118,0xc0000000,0x00000000,std::uint32_t>;
///ADC channel 18 sampling time selection
constexpr Register::FieldLocation<Addr,Register::maskFromRange(29,27),Register::ReadWriteAccess,unsigned> smp19{};
///ADC channel 18 sampling time selection
constexpr Register::FieldLocation<Addr,Register::maskFromRange(26,24),Register::ReadWriteAccess,unsigned> smp18{};
///ADC channel 17 sampling time selection
constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,21),Register::ReadWriteAccess,unsigned> smp17{};
///ADC channel 16 sampling time selection
constexpr Register::FieldLocation<Addr,Register::maskFromRange(20,18),Register::ReadWriteAccess,unsigned> smp16{};
///ADC channel 15 sampling time selection
constexpr Register::FieldLocation<Addr,Register::maskFromRange(17,15),Register::ReadWriteAccess,unsigned> smp15{};
///ADC channel 14 sampling time selection
constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,12),Register::ReadWriteAccess,unsigned> smp14{};
///ADC channel 13 sampling time selection
constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,9),Register::ReadWriteAccess,unsigned> smp13{};
///ADC channel 12 sampling time selection
constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,6),Register::ReadWriteAccess,unsigned> smp12{};
///ADC channel 11 sampling time selection
constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,3),Register::ReadWriteAccess,unsigned> smp11{};
///ADC channel 10 sampling time selection
constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,0),Register::ReadWriteAccess,unsigned> smp10{};
}
namespace Adc2Ltr1{ ///<ADC analog watchdog 1 threshold register
using Addr = Register::Address<0x40022120,0xfc000000,0x00000000,std::uint32_t>;
///ADC analog watchdog 1 threshold low
constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,0),Register::ReadWriteAccess,unsigned> ltr1{};
}
namespace Adc2Lhtr1{ ///<ADC analog watchdog 2 threshold register
using Addr = Register::Address<0x40022124,0xfc000000,0x00000000,std::uint32_t>;
///ADC analog watchdog 2 threshold low
constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,0),Register::ReadWriteAccess,unsigned> lhtr1{};
}
namespace Adc2Sqr1{ ///<ADC group regular sequencer ranks register 1
using Addr = Register::Address<0x40022130,0xe0820830,0x00000000,std::uint32_t>;
///ADC group regular sequencer rank 4
constexpr Register::FieldLocation<Addr,Register::maskFromRange(28,24),Register::ReadWriteAccess,unsigned> sq4{};
///ADC group regular sequencer rank 3
constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,18),Register::ReadWriteAccess,unsigned> sq3{};
///ADC group regular sequencer rank 2
constexpr Register::FieldLocation<Addr,Register::maskFromRange(16,12),Register::ReadWriteAccess,unsigned> sq2{};
///ADC group regular sequencer rank 1
constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,6),Register::ReadWriteAccess,unsigned> sq1{};
///L3
constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,0),Register::ReadWriteAccess,unsigned> l3{};
}
namespace Adc2Sqr2{ ///<ADC group regular sequencer ranks register 2
using Addr = Register::Address<0x40022134,0xe0820820,0x00000000,std::uint32_t>;
///ADC group regular sequencer rank 9
constexpr Register::FieldLocation<Addr,Register::maskFromRange(28,24),Register::ReadWriteAccess,unsigned> sq9{};
///ADC group regular sequencer rank 8
constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,18),Register::ReadWriteAccess,unsigned> sq8{};
///ADC group regular sequencer rank 7
constexpr Register::FieldLocation<Addr,Register::maskFromRange(16,12),Register::ReadWriteAccess,unsigned> sq7{};
///ADC group regular sequencer rank 6
constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,6),Register::ReadWriteAccess,unsigned> sq6{};
///ADC group regular sequencer rank 5
constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,0),Register::ReadWriteAccess,unsigned> sq5{};
}
namespace Adc2Sqr3{ ///<ADC group regular sequencer ranks register 3
using Addr = Register::Address<0x40022138,0xe0820820,0x00000000,std::uint32_t>;
///ADC group regular sequencer rank 14
constexpr Register::FieldLocation<Addr,Register::maskFromRange(28,24),Register::ReadWriteAccess,unsigned> sq14{};
///ADC group regular sequencer rank 13
constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,18),Register::ReadWriteAccess,unsigned> sq13{};
///ADC group regular sequencer rank 12
constexpr Register::FieldLocation<Addr,Register::maskFromRange(16,12),Register::ReadWriteAccess,unsigned> sq12{};
///ADC group regular sequencer rank 11
constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,6),Register::ReadWriteAccess,unsigned> sq11{};
///ADC group regular sequencer rank 10
constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,0),Register::ReadWriteAccess,unsigned> sq10{};
}
namespace Adc2Sqr4{ ///<ADC group regular sequencer ranks register 4
using Addr = Register::Address<0x4002213c,0xfffff820,0x00000000,std::uint32_t>;
///ADC group regular sequencer rank 16
constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,6),Register::ReadWriteAccess,unsigned> sq16{};
///ADC group regular sequencer rank 15
constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,0),Register::ReadWriteAccess,unsigned> sq15{};
}
namespace Adc2Dr{ ///<ADC group regular conversion data register
using Addr = Register::Address<0x40022140,0xffff0000,0x00000000,std::uint32_t>;
///ADC group regular conversion data
constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,0),Register::ReadWriteAccess,unsigned> rdata{};
}
namespace Adc2Jsqr{ ///<ADC group injected sequencer register
using Addr = Register::Address<0x4002214c,0x04104000,0x00000000,std::uint32_t>;
///ADC group injected sequencer rank 4
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,27),Register::ReadWriteAccess,unsigned> jsq4{};
///ADC group injected sequencer rank 3
constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,21),Register::ReadWriteAccess,unsigned> jsq3{};
///ADC group injected sequencer rank 2
constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,15),Register::ReadWriteAccess,unsigned> jsq2{};
///ADC group injected sequencer rank 1
constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,9),Register::ReadWriteAccess,unsigned> jsq1{};
///ADC group injected external trigger polarity
constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,7),Register::ReadWriteAccess,unsigned> jexten{};
///ADC group injected external trigger source
constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,2),Register::ReadWriteAccess,unsigned> jextsel{};
///ADC group injected sequencer scan length
constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,0),Register::ReadWriteAccess,unsigned> jl{};
}
namespace Adc2Ofr1{ ///<ADC offset number 1 register
using Addr = Register::Address<0x40022160,0x00000000,0x00000000,std::uint32_t>;
///ADC offset number 1 enable
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,31),Register::ReadWriteAccess,unsigned> ssate{};
///ADC offset number 1 channel selection
constexpr Register::FieldLocation<Addr,Register::maskFromRange(30,26),Register::ReadWriteAccess,unsigned> offset1Ch{};
///ADC offset number 1 offset level
constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,0),Register::ReadWriteAccess,unsigned> offset1{};
}
namespace Adc2Ofr2{ ///<ADC offset number 2 register
using Addr = Register::Address<0x40022164,0x00000000,0x00000000,std::uint32_t>;
///ADC offset number 1 enable
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,31),Register::ReadWriteAccess,unsigned> ssate{};
///ADC offset number 1 channel selection
constexpr Register::FieldLocation<Addr,Register::maskFromRange(30,26),Register::ReadWriteAccess,unsigned> offset1Ch{};
///ADC offset number 1 offset level
constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,0),Register::ReadWriteAccess,unsigned> offset1{};
}
namespace Adc2Ofr3{ ///<ADC offset number 3 register
using Addr = Register::Address<0x40022168,0x00000000,0x00000000,std::uint32_t>;
///ADC offset number 1 enable
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,31),Register::ReadWriteAccess,unsigned> ssate{};
///ADC offset number 1 channel selection
constexpr Register::FieldLocation<Addr,Register::maskFromRange(30,26),Register::ReadWriteAccess,unsigned> offset1Ch{};
///ADC offset number 1 offset level
constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,0),Register::ReadWriteAccess,unsigned> offset1{};
}
namespace Adc2Ofr4{ ///<ADC offset number 4 register
using Addr = Register::Address<0x4002216c,0x00000000,0x00000000,std::uint32_t>;
///ADC offset number 1 enable
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,31),Register::ReadWriteAccess,unsigned> ssate{};
///ADC offset number 1 channel selection
constexpr Register::FieldLocation<Addr,Register::maskFromRange(30,26),Register::ReadWriteAccess,unsigned> offset1Ch{};
///ADC offset number 1 offset level
constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,0),Register::ReadWriteAccess,unsigned> offset1{};
}
namespace Adc2Jdr1{ ///<ADC group injected sequencer rank 1 register
using Addr = Register::Address<0x40022180,0x00000000,0x00000000,std::uint32_t>;
///ADC group injected sequencer rank 1 conversion data
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> jdata1{};
}
namespace Adc2Jdr2{ ///<ADC group injected sequencer rank 2 register
using Addr = Register::Address<0x40022184,0x00000000,0x00000000,std::uint32_t>;
///ADC group injected sequencer rank 2 conversion data
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> jdata2{};
}
namespace Adc2Jdr3{ ///<ADC group injected sequencer rank 3 register
using Addr = Register::Address<0x40022188,0x00000000,0x00000000,std::uint32_t>;
///ADC group injected sequencer rank 3 conversion data
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> jdata3{};
}
namespace Adc2Jdr4{ ///<ADC group injected sequencer rank 4 register
using Addr = Register::Address<0x4002218c,0x00000000,0x00000000,std::uint32_t>;
///ADC group injected sequencer rank 4 conversion data
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> jdata4{};
}
namespace Adc2Awd2cr{ ///<ADC analog watchdog 2 configuration register
using Addr = Register::Address<0x400221a0,0xfff00000,0x00000000,std::uint32_t>;
///ADC analog watchdog 2 monitored channel selection
constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,0),Register::ReadWriteAccess,unsigned> awd2ch{};
}
namespace Adc2Awd3cr{ ///<ADC analog watchdog 3 configuration register
using Addr = Register::Address<0x400221a4,0xffe00001,0x00000000,std::uint32_t>;
///ADC analog watchdog 3 monitored channel selection
constexpr Register::FieldLocation<Addr,Register::maskFromRange(20,1),Register::ReadWriteAccess,unsigned> awd3ch{};
}
namespace Adc2Difsel{ ///<ADC channel differential or single-ended mode selection register
using Addr = Register::Address<0x400221c0,0xfff00000,0x00000000,std::uint32_t>;
///ADC channel differential or single-ended mode for channel
constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,0),Register::ReadWriteAccess,unsigned> difsel{};
}
namespace Adc2Calfact{ ///<ADC calibration factors register
using Addr = Register::Address<0x400221c4,0xf800f800,0x00000000,std::uint32_t>;
///ADC calibration factor in differential mode
constexpr Register::FieldLocation<Addr,Register::maskFromRange(26,16),Register::ReadWriteAccess,unsigned> calfactD{};
///ADC calibration factor in single-ended mode
constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,0),Register::ReadWriteAccess,unsigned> calfactS{};
}
namespace Adc2Ccr{ ///<ADC common control register
using Addr = Register::Address<0x40022108,0xfe00ffff,0x00000000,std::uint32_t>;
///ADC clock mode
constexpr Register::FieldLocation<Addr,Register::maskFromRange(17,16),Register::ReadWriteAccess,unsigned> ckmode{};
///ADC prescaler
constexpr Register::FieldLocation<Addr,Register::maskFromRange(21,18),Register::ReadWriteAccess,unsigned> presc{};
///VREFINT enable
constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,22),Register::ReadWriteAccess,unsigned> vrefen{};
///Temperature sensor enable
constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,23),Register::ReadWriteAccess,unsigned> tsen{};
///VBAT enable
constexpr Register::FieldLocation<Addr,Register::maskFromRange(24,24),Register::ReadWriteAccess,unsigned> vbaten{};
}
namespace Adc2Pcsel{ ///<ADC pre channel selection register
using Addr = Register::Address<0x4002211c,0xfff00000,0x00000000,std::uint32_t>;
///Channel x (VINP[i]) pre selection
constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,0),Register::ReadWriteAccess,unsigned> pcsel{};
}
namespace Adc2Ltr2{ ///<ADC watchdog lower threshold register 2
using Addr = Register::Address<0x400221b0,0xfc000000,0x00000000,std::uint32_t>;
///Analog watchdog 2 lower threshold
constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,0),Register::ReadWriteAccess,unsigned> ltr2{};
}
namespace Adc2Htr2{ ///<ADC watchdog higher threshold register 2
using Addr = Register::Address<0x400221b4,0xfc000000,0x00000000,std::uint32_t>;
///Analog watchdog 2 higher threshold
constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,0),Register::ReadWriteAccess,unsigned> htr2{};
}
namespace Adc2Ltr3{ ///<ADC watchdog lower threshold register 3
using Addr = Register::Address<0x400221b8,0xfc000000,0x00000000,std::uint32_t>;
///Analog watchdog 3 lower threshold
constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,0),Register::ReadWriteAccess,unsigned> ltr3{};
}
namespace Adc2Htr3{ ///<ADC watchdog higher threshold register 3
using Addr = Register::Address<0x400221bc,0xfc000000,0x00000000,std::uint32_t>;
///Analog watchdog 3 higher threshold
constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,0),Register::ReadWriteAccess,unsigned> htr3{};
}
namespace Adc2Calfact2{ ///<ADC Calibration Factor register 2
using Addr = Register::Address<0x400221c8,0xc0000000,0x00000000,std::uint32_t>;
///Linearity Calibration Factor
constexpr Register::FieldLocation<Addr,Register::maskFromRange(29,0),Register::ReadWriteAccess,unsigned> lincalfact{};
}
}
|
/*
* Copyright 2008-2011 NVIDIA Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <thrust/functional.h>
#include <thrust/transform.h>
#include <thrust/replace.h>
#include <thrust/iterator/zip_iterator.h>
#include <thrust/iterator/iterator_traits.h>
#include <thrust/detail/raw_buffer.h>
#include <thrust/detail/internal_functional.h>
#include <thrust/detail/device/scan.h>
namespace thrust
{
namespace detail
{
namespace device
{
namespace generic
{
namespace detail
{
template <typename OutputType, typename HeadFlagType, typename AssociativeOperator>
struct segmented_scan_functor
{
AssociativeOperator binary_op;
typedef typename thrust::tuple<OutputType, HeadFlagType> result_type;
__host__ __device__
segmented_scan_functor(AssociativeOperator _binary_op) : binary_op(_binary_op) {}
__host__ __device__
result_type operator()(result_type a, result_type b)
{
return result_type(thrust::get<1>(b) ? thrust::get<0>(b) : binary_op(thrust::get<0>(a), thrust::get<0>(b)),
thrust::get<1>(a) | thrust::get<1>(b));
}
};
} // end namespace detail
template<typename InputIterator1,
typename InputIterator2,
typename OutputIterator,
typename BinaryPredicate,
typename AssociativeOperator>
OutputIterator inclusive_scan_by_key(InputIterator1 first1,
InputIterator1 last1,
InputIterator2 first2,
OutputIterator result,
BinaryPredicate binary_pred,
AssociativeOperator binary_op)
{
typedef typename thrust::iterator_traits<OutputIterator>::value_type OutputType;
typedef typename thrust::iterator_space<OutputIterator>::type Space;
typedef unsigned int HeadFlagType;
const size_t n = last1 - first1;
if(n != 0)
{
// compute head flags
thrust::detail::raw_buffer<HeadFlagType,Space> flags(n);
flags[0] = 1; thrust::transform(first1, last1 - 1, first1 + 1, flags.begin() + 1, thrust::detail::not2(binary_pred));
// scan key-flag tuples,
// For additional details refer to Section 2 of the following paper
// S. Sengupta, M. Harris, and M. Garland. "Efficient parallel scan algorithms for GPUs"
// NVIDIA Technical Report NVR-2008-003, December 2008
// http://mgarland.org/files/papers/nvr-2008-003.pdf
thrust::detail::device::inclusive_scan
(thrust::make_zip_iterator(thrust::make_tuple(first2, flags.begin())),
thrust::make_zip_iterator(thrust::make_tuple(first2, flags.begin())) + n,
thrust::make_zip_iterator(thrust::make_tuple(result, flags.begin())),
detail::segmented_scan_functor<OutputType, HeadFlagType, AssociativeOperator>(binary_op));
}
return result + n;
}
template<typename InputIterator1,
typename InputIterator2,
typename OutputIterator,
typename T,
typename BinaryPredicate,
typename AssociativeOperator>
OutputIterator exclusive_scan_by_key(InputIterator1 first1,
InputIterator1 last1,
InputIterator2 first2,
OutputIterator result,
const T init,
BinaryPredicate binary_pred,
AssociativeOperator binary_op)
{
typedef typename thrust::iterator_traits<OutputIterator>::value_type OutputType;
typedef typename thrust::iterator_space<OutputIterator>::type Space;
typedef unsigned int HeadFlagType;
const size_t n = last1 - first1;
if(n != 0)
{
InputIterator2 last2 = first2 + n;
// compute head flags
thrust::detail::raw_buffer<HeadFlagType,Space> flags(n);
flags[0] = 1; thrust::transform(first1, last1 - 1, first1 + 1, flags.begin() + 1, thrust::detail::not2(binary_pred));
// shift input one to the right and initialize segments with init
thrust::detail::raw_buffer<OutputType,Space> temp(n);
thrust::replace_copy_if(first2, last2 - 1, flags.begin() + 1, temp.begin() + 1, thrust::negate<HeadFlagType>(), init);
temp[0] = init;
// scan key-flag tuples,
// For additional details refer to Section 2 of the following paper
// S. Sengupta, M. Harris, and M. Garland. "Efficient parallel scan algorithms for GPUs"
// NVIDIA Technical Report NVR-2008-003, December 2008
// http://mgarland.org/files/papers/nvr-2008-003.pdf
thrust::detail::device::inclusive_scan(thrust::make_zip_iterator(thrust::make_tuple(temp.begin(), flags.begin())),
thrust::make_zip_iterator(thrust::make_tuple(temp.begin(), flags.begin())) + n,
thrust::make_zip_iterator(thrust::make_tuple(result, flags.begin())),
detail::segmented_scan_functor<OutputType, HeadFlagType, AssociativeOperator>(binary_op));
}
return result + n;
}
} // end namespace generic
} // end namespace device
} // end namespace detail
} // end namespace thrust
|
//
// Copyright © 2017 Arm Ltd. All rights reserved.
// See LICENSE file in the project root for full license information.
//
#include "../InferenceTest.hpp"
#include "../Cifar10Database.hpp"
#include "armnnCaffeParser/ICaffeParser.hpp"
int main(int argc, char* argv[])
{
int retVal = EXIT_FAILURE;
try
{
using DataType = float;
using DatabaseType = Cifar10Database;
using ParserType = armnnCaffeParser::ICaffeParser;
using ModelType = InferenceModel<ParserType, DataType>;
// Coverity fix: ClassifierInferenceTestMain() may throw uncaught exceptions.
retVal = armnn::test::ClassifierInferenceTestMain<DatabaseType, ParserType>(
argc, argv, "cifar10_full_iter_60000.caffemodel", true, "data", "prob",
{ 0, 1, 2, 4, 7 },
[](const char* dataDir, const ModelType&) {
return DatabaseType(dataDir);
});
}
catch (const std::exception& e)
{
// Coverity fix: BOOST_LOG_TRIVIAL (typically used to report errors) may throw an
// exception of type std::length_error.
// Using stderr instead in this context as there is no point in nesting try-catch blocks here.
std::cerr << "WARNING: CaffeCifar10AcrossChannels-Armnn: An error has occurred when running "
"the classifier inference tests: " << e.what() << std::endl;
}
return retVal;
}
|
// Copyright (c) 2012-2015 The Bitcoin Core developers
// Copyright (c) 2014-2017 The Beenode Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "netbase.h"
#include "test/test_beenode.h"
#include <string>
#include <boost/assign/list_of.hpp>
#include <boost/test/unit_test.hpp>
using namespace std;
BOOST_FIXTURE_TEST_SUITE(netbase_tests, BasicTestingSetup)
BOOST_AUTO_TEST_CASE(netbase_networks)
{
BOOST_CHECK(CNetAddr("127.0.0.1").GetNetwork() == NET_UNROUTABLE);
BOOST_CHECK(CNetAddr("::1").GetNetwork() == NET_UNROUTABLE);
BOOST_CHECK(CNetAddr("8.8.8.8").GetNetwork() == NET_IPV4);
BOOST_CHECK(CNetAddr("2001::8888").GetNetwork() == NET_IPV6);
BOOST_CHECK(CNetAddr("FD87:D87E:EB43:edb1:8e4:3588:e546:35ca").GetNetwork() == NET_TOR);
}
BOOST_AUTO_TEST_CASE(netbase_properties)
{
BOOST_CHECK(CNetAddr("127.0.0.1").IsIPv4());
BOOST_CHECK(CNetAddr("::FFFF:192.168.1.1").IsIPv4());
BOOST_CHECK(CNetAddr("::1").IsIPv6());
BOOST_CHECK(CNetAddr("10.0.0.1").IsRFC1918());
BOOST_CHECK(CNetAddr("192.168.1.1").IsRFC1918());
BOOST_CHECK(CNetAddr("172.31.255.255").IsRFC1918());
BOOST_CHECK(CNetAddr("2001:0DB8::").IsRFC3849());
BOOST_CHECK(CNetAddr("169.254.1.1").IsRFC3927());
BOOST_CHECK(CNetAddr("2002::1").IsRFC3964());
BOOST_CHECK(CNetAddr("FC00::").IsRFC4193());
BOOST_CHECK(CNetAddr("2001::2").IsRFC4380());
BOOST_CHECK(CNetAddr("2001:10::").IsRFC4843());
BOOST_CHECK(CNetAddr("FE80::").IsRFC4862());
BOOST_CHECK(CNetAddr("64:FF9B::").IsRFC6052());
BOOST_CHECK(CNetAddr("FD87:D87E:EB43:edb1:8e4:3588:e546:35ca").IsTor());
BOOST_CHECK(CNetAddr("127.0.0.1").IsLocal());
BOOST_CHECK(CNetAddr("::1").IsLocal());
BOOST_CHECK(CNetAddr("8.8.8.8").IsRoutable());
BOOST_CHECK(CNetAddr("2001::1").IsRoutable());
BOOST_CHECK(CNetAddr("127.0.0.1").IsValid());
}
bool static TestSplitHost(string test, string host, int port)
{
string hostOut;
int portOut = -1;
SplitHostPort(test, portOut, hostOut);
return hostOut == host && port == portOut;
}
BOOST_AUTO_TEST_CASE(netbase_splithost)
{
BOOST_CHECK(TestSplitHost("www.bitcoin.org", "www.bitcoin.org", -1));
BOOST_CHECK(TestSplitHost("[www.bitcoin.org]", "www.bitcoin.org", -1));
BOOST_CHECK(TestSplitHost("www.bitcoin.org:80", "www.bitcoin.org", 80));
BOOST_CHECK(TestSplitHost("[www.bitcoin.org]:80", "www.bitcoin.org", 80));
BOOST_CHECK(TestSplitHost("127.0.0.1", "127.0.0.1", -1));
BOOST_CHECK(TestSplitHost("127.0.0.1:4244", "127.0.0.1", 4244));
BOOST_CHECK(TestSplitHost("[127.0.0.1]", "127.0.0.1", -1));
BOOST_CHECK(TestSplitHost("[127.0.0.1]:4244", "127.0.0.1", 4244));
BOOST_CHECK(TestSplitHost("::ffff:127.0.0.1", "::ffff:127.0.0.1", -1));
BOOST_CHECK(TestSplitHost("[::ffff:127.0.0.1]:4244", "::ffff:127.0.0.1", 4244));
BOOST_CHECK(TestSplitHost("[::]:4244", "::", 4244));
BOOST_CHECK(TestSplitHost("::4244", "::4244", -1));
BOOST_CHECK(TestSplitHost(":4244", "", 4244));
BOOST_CHECK(TestSplitHost("[]:4244", "", 4244));
BOOST_CHECK(TestSplitHost("", "", -1));
}
bool static TestParse(string src, string canon)
{
CService addr;
if (!LookupNumeric(src.c_str(), addr, 65535))
return canon == "";
return canon == addr.ToString();
}
BOOST_AUTO_TEST_CASE(netbase_lookupnumeric)
{
BOOST_CHECK(TestParse("127.0.0.1", "127.0.0.1:65535"));
BOOST_CHECK(TestParse("127.0.0.1:4244", "127.0.0.1:4244"));
BOOST_CHECK(TestParse("::ffff:127.0.0.1", "127.0.0.1:65535"));
BOOST_CHECK(TestParse("::", "[::]:65535"));
BOOST_CHECK(TestParse("[::]:4244", "[::]:4244"));
BOOST_CHECK(TestParse("[127.0.0.1]", "127.0.0.1:65535"));
BOOST_CHECK(TestParse(":::", ""));
}
BOOST_AUTO_TEST_CASE(onioncat_test)
{
// values from https://web.archive.org/web/20121122003543/http://www.cypherpunk.at/onioncat/wiki/OnionCat
CNetAddr addr1("5wyqrzbvrdsumnok.onion");
CNetAddr addr2("FD87:D87E:EB43:edb1:8e4:3588:e546:35ca");
BOOST_CHECK(addr1 == addr2);
BOOST_CHECK(addr1.IsTor());
BOOST_CHECK(addr1.ToStringIP() == "5wyqrzbvrdsumnok.onion");
BOOST_CHECK(addr1.IsRoutable());
}
BOOST_AUTO_TEST_CASE(subnet_test)
{
BOOST_CHECK(CSubNet("1.2.3.0/24") == CSubNet("1.2.3.0/255.255.255.0"));
BOOST_CHECK(CSubNet("1.2.3.0/24") != CSubNet("1.2.4.0/255.255.255.0"));
BOOST_CHECK(CSubNet("1.2.3.0/24").Match(CNetAddr("1.2.3.4")));
BOOST_CHECK(!CSubNet("1.2.2.0/24").Match(CNetAddr("1.2.3.4")));
BOOST_CHECK(CSubNet("1.2.3.4").Match(CNetAddr("1.2.3.4")));
BOOST_CHECK(CSubNet("1.2.3.4/32").Match(CNetAddr("1.2.3.4")));
BOOST_CHECK(!CSubNet("1.2.3.4").Match(CNetAddr("5.6.7.8")));
BOOST_CHECK(!CSubNet("1.2.3.4/32").Match(CNetAddr("5.6.7.8")));
BOOST_CHECK(CSubNet("::ffff:127.0.0.1").Match(CNetAddr("127.0.0.1")));
BOOST_CHECK(CSubNet("1:2:3:4:5:6:7:8").Match(CNetAddr("1:2:3:4:5:6:7:8")));
BOOST_CHECK(!CSubNet("1:2:3:4:5:6:7:8").Match(CNetAddr("1:2:3:4:5:6:7:9")));
BOOST_CHECK(CSubNet("1:2:3:4:5:6:7:0/112").Match(CNetAddr("1:2:3:4:5:6:7:1234")));
BOOST_CHECK(CSubNet("192.168.0.1/24").Match(CNetAddr("192.168.0.2")));
BOOST_CHECK(CSubNet("192.168.0.20/29").Match(CNetAddr("192.168.0.18")));
BOOST_CHECK(CSubNet("1.2.2.1/24").Match(CNetAddr("1.2.2.4")));
BOOST_CHECK(CSubNet("1.2.2.110/31").Match(CNetAddr("1.2.2.111")));
BOOST_CHECK(CSubNet("1.2.2.20/26").Match(CNetAddr("1.2.2.63")));
// All-Matching IPv6 Matches arbitrary IPv4 and IPv6
BOOST_CHECK(CSubNet("::/0").Match(CNetAddr("1:2:3:4:5:6:7:1234")));
BOOST_CHECK(CSubNet("::/0").Match(CNetAddr("1.2.3.4")));
// All-Matching IPv4 does not Match IPv6
BOOST_CHECK(!CSubNet("0.0.0.0/0").Match(CNetAddr("1:2:3:4:5:6:7:1234")));
// Invalid subnets Match nothing (not even invalid addresses)
BOOST_CHECK(!CSubNet().Match(CNetAddr("1.2.3.4")));
BOOST_CHECK(!CSubNet("").Match(CNetAddr("4.5.6.7")));
BOOST_CHECK(!CSubNet("bloop").Match(CNetAddr("0.0.0.0")));
BOOST_CHECK(!CSubNet("bloop").Match(CNetAddr("hab")));
// Check valid/invalid
BOOST_CHECK(CSubNet("1.2.3.0/0").IsValid());
BOOST_CHECK(!CSubNet("1.2.3.0/-1").IsValid());
BOOST_CHECK(CSubNet("1.2.3.0/32").IsValid());
BOOST_CHECK(!CSubNet("1.2.3.0/33").IsValid());
BOOST_CHECK(CSubNet("1:2:3:4:5:6:7:8/0").IsValid());
BOOST_CHECK(CSubNet("1:2:3:4:5:6:7:8/33").IsValid());
BOOST_CHECK(!CSubNet("1:2:3:4:5:6:7:8/-1").IsValid());
BOOST_CHECK(CSubNet("1:2:3:4:5:6:7:8/128").IsValid());
BOOST_CHECK(!CSubNet("1:2:3:4:5:6:7:8/129").IsValid());
BOOST_CHECK(!CSubNet("fuzzy").IsValid());
//CNetAddr constructor test
BOOST_CHECK(CSubNet(CNetAddr("127.0.0.1")).IsValid());
BOOST_CHECK(CSubNet(CNetAddr("127.0.0.1")).Match(CNetAddr("127.0.0.1")));
BOOST_CHECK(!CSubNet(CNetAddr("127.0.0.1")).Match(CNetAddr("127.0.0.2")));
BOOST_CHECK(CSubNet(CNetAddr("127.0.0.1")).ToString() == "127.0.0.1/32");
BOOST_CHECK(CSubNet(CNetAddr("1:2:3:4:5:6:7:8")).IsValid());
BOOST_CHECK(CSubNet(CNetAddr("1:2:3:4:5:6:7:8")).Match(CNetAddr("1:2:3:4:5:6:7:8")));
BOOST_CHECK(!CSubNet(CNetAddr("1:2:3:4:5:6:7:8")).Match(CNetAddr("1:2:3:4:5:6:7:9")));
BOOST_CHECK(CSubNet(CNetAddr("1:2:3:4:5:6:7:8")).ToString() == "1:2:3:4:5:6:7:8/128");
CSubNet subnet = CSubNet("1.2.3.4/255.255.255.255");
BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.3.4/32");
subnet = CSubNet("1.2.3.4/255.255.255.254");
BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.3.4/31");
subnet = CSubNet("1.2.3.4/255.255.255.252");
BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.3.4/30");
subnet = CSubNet("1.2.3.4/255.255.255.248");
BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.3.0/29");
subnet = CSubNet("1.2.3.4/255.255.255.240");
BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.3.0/28");
subnet = CSubNet("1.2.3.4/255.255.255.224");
BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.3.0/27");
subnet = CSubNet("1.2.3.4/255.255.255.192");
BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.3.0/26");
subnet = CSubNet("1.2.3.4/255.255.255.128");
BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.3.0/25");
subnet = CSubNet("1.2.3.4/255.255.255.0");
BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.3.0/24");
subnet = CSubNet("1.2.3.4/255.255.254.0");
BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.2.0/23");
subnet = CSubNet("1.2.3.4/255.255.252.0");
BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.0.0/22");
subnet = CSubNet("1.2.3.4/255.255.248.0");
BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.0.0/21");
subnet = CSubNet("1.2.3.4/255.255.240.0");
BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.0.0/20");
subnet = CSubNet("1.2.3.4/255.255.224.0");
BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.0.0/19");
subnet = CSubNet("1.2.3.4/255.255.192.0");
BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.0.0/18");
subnet = CSubNet("1.2.3.4/255.255.128.0");
BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.0.0/17");
subnet = CSubNet("1.2.3.4/255.255.0.0");
BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.0.0/16");
subnet = CSubNet("1.2.3.4/255.254.0.0");
BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.0.0/15");
subnet = CSubNet("1.2.3.4/255.252.0.0");
BOOST_CHECK_EQUAL(subnet.ToString(), "1.0.0.0/14");
subnet = CSubNet("1.2.3.4/255.248.0.0");
BOOST_CHECK_EQUAL(subnet.ToString(), "1.0.0.0/13");
subnet = CSubNet("1.2.3.4/255.240.0.0");
BOOST_CHECK_EQUAL(subnet.ToString(), "1.0.0.0/12");
subnet = CSubNet("1.2.3.4/255.224.0.0");
BOOST_CHECK_EQUAL(subnet.ToString(), "1.0.0.0/11");
subnet = CSubNet("1.2.3.4/255.192.0.0");
BOOST_CHECK_EQUAL(subnet.ToString(), "1.0.0.0/10");
subnet = CSubNet("1.2.3.4/255.128.0.0");
BOOST_CHECK_EQUAL(subnet.ToString(), "1.0.0.0/9");
subnet = CSubNet("1.2.3.4/255.0.0.0");
BOOST_CHECK_EQUAL(subnet.ToString(), "1.0.0.0/8");
subnet = CSubNet("1.2.3.4/254.0.0.0");
BOOST_CHECK_EQUAL(subnet.ToString(), "0.0.0.0/7");
subnet = CSubNet("1.2.3.4/252.0.0.0");
BOOST_CHECK_EQUAL(subnet.ToString(), "0.0.0.0/6");
subnet = CSubNet("1.2.3.4/248.0.0.0");
BOOST_CHECK_EQUAL(subnet.ToString(), "0.0.0.0/5");
subnet = CSubNet("1.2.3.4/240.0.0.0");
BOOST_CHECK_EQUAL(subnet.ToString(), "0.0.0.0/4");
subnet = CSubNet("1.2.3.4/224.0.0.0");
BOOST_CHECK_EQUAL(subnet.ToString(), "0.0.0.0/3");
subnet = CSubNet("1.2.3.4/192.0.0.0");
BOOST_CHECK_EQUAL(subnet.ToString(), "0.0.0.0/2");
subnet = CSubNet("1.2.3.4/128.0.0.0");
BOOST_CHECK_EQUAL(subnet.ToString(), "0.0.0.0/1");
subnet = CSubNet("1.2.3.4/0.0.0.0");
BOOST_CHECK_EQUAL(subnet.ToString(), "0.0.0.0/0");
subnet = CSubNet("1:2:3:4:5:6:7:8/ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff");
BOOST_CHECK_EQUAL(subnet.ToString(), "1:2:3:4:5:6:7:8/128");
subnet = CSubNet("1:2:3:4:5:6:7:8/ffff:0000:0000:0000:0000:0000:0000:0000");
BOOST_CHECK_EQUAL(subnet.ToString(), "1::/16");
subnet = CSubNet("1:2:3:4:5:6:7:8/0000:0000:0000:0000:0000:0000:0000:0000");
BOOST_CHECK_EQUAL(subnet.ToString(), "::/0");
subnet = CSubNet("1.2.3.4/255.255.232.0");
BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.0.0/255.255.232.0");
subnet = CSubNet("1:2:3:4:5:6:7:8/ffff:ffff:ffff:fffe:ffff:ffff:ffff:ff0f");
BOOST_CHECK_EQUAL(subnet.ToString(), "1:2:3:4:5:6:7:8/ffff:ffff:ffff:fffe:ffff:ffff:ffff:ff0f");
}
BOOST_AUTO_TEST_CASE(netbase_getgroup)
{
BOOST_CHECK(CNetAddr("127.0.0.1").GetGroup() == boost::assign::list_of(0)); // Local -> !Routable()
BOOST_CHECK(CNetAddr("257.0.0.1").GetGroup() == boost::assign::list_of(0)); // !Valid -> !Routable()
BOOST_CHECK(CNetAddr("10.0.0.1").GetGroup() == boost::assign::list_of(0)); // RFC1918 -> !Routable()
BOOST_CHECK(CNetAddr("169.254.1.1").GetGroup() == boost::assign::list_of(0)); // RFC3927 -> !Routable()
BOOST_CHECK(CNetAddr("1.2.3.4").GetGroup() == boost::assign::list_of((unsigned char)NET_IPV4)(1)(2)); // IPv4
BOOST_CHECK(CNetAddr("::FFFF:0:102:304").GetGroup() == boost::assign::list_of((unsigned char)NET_IPV4)(1)(2)); // RFC6145
BOOST_CHECK(CNetAddr("64:FF9B::102:304").GetGroup() == boost::assign::list_of((unsigned char)NET_IPV4)(1)(2)); // RFC6052
BOOST_CHECK(CNetAddr("2002:102:304:9999:9999:9999:9999:9999").GetGroup() == boost::assign::list_of((unsigned char)NET_IPV4)(1)(2)); // RFC3964
BOOST_CHECK(CNetAddr("2001:0:9999:9999:9999:9999:FEFD:FCFB").GetGroup() == boost::assign::list_of((unsigned char)NET_IPV4)(1)(2)); // RFC4380
BOOST_CHECK(CNetAddr("FD87:D87E:EB43:edb1:8e4:3588:e546:35ca").GetGroup() == boost::assign::list_of((unsigned char)NET_TOR)(239)); // Tor
BOOST_CHECK(CNetAddr("2001:470:abcd:9999:9999:9999:9999:9999").GetGroup() == boost::assign::list_of((unsigned char)NET_IPV6)(32)(1)(4)(112)(175)); //he.net
BOOST_CHECK(CNetAddr("2001:2001:9999:9999:9999:9999:9999:9999").GetGroup() == boost::assign::list_of((unsigned char)NET_IPV6)(32)(1)(32)(1)); //IPv6
}
BOOST_AUTO_TEST_SUITE_END()
|
/*
* This file belongs to the Galois project, a C++ library for exploiting parallelism.
* The code is being released under the terms of the 3-Clause BSD License (a
* copy is located in LICENSE.txt at the top-level directory).
*
* Copyright (C) 2018, The University of Texas at Austin. All rights reserved.
* UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS
* SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF
* PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF
* DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH
* RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances
* shall University be liable for incidental, special, indirect, direct or
* consequential damages or loss of profits, interruption of business, or
* related expenses which may arise from use of Software or Documentation,
* including but not limited to those resulting from defects in Software and/or
* Documentation, or loss or inaccuracy of data of any kind.
*/
/**
* @file SyncStructures.cpp
*
* Contains implementations of the bitvector status setter/getter functions
*/
#include <galois/runtime/SyncStructures.h>
using namespace galois::runtime; // for easy access to BITVECTOR_STATUS
bool galois::runtime::src_invalid(BITVECTOR_STATUS bv_flag) {
return (bv_flag == BITVECTOR_STATUS::SRC_INVALID ||
bv_flag == BITVECTOR_STATUS::BOTH_INVALID);
}
bool galois::runtime::dst_invalid(BITVECTOR_STATUS bv_flag) {
return (bv_flag == BITVECTOR_STATUS::DST_INVALID ||
bv_flag == BITVECTOR_STATUS::BOTH_INVALID);
}
void galois::runtime::make_src_invalid(BITVECTOR_STATUS* bv_flag) {
switch (*bv_flag) {
case NONE_INVALID:
*bv_flag = BITVECTOR_STATUS::SRC_INVALID;
break;
case DST_INVALID:
*bv_flag = BITVECTOR_STATUS::BOTH_INVALID;
break;
case SRC_INVALID:
case BOTH_INVALID:
break;
}
}
void galois::runtime::make_dst_invalid(BITVECTOR_STATUS* bv_flag) {
switch (*bv_flag) {
case NONE_INVALID:
*bv_flag = BITVECTOR_STATUS::DST_INVALID;
break;
case SRC_INVALID:
*bv_flag = BITVECTOR_STATUS::BOTH_INVALID;
break;
case DST_INVALID:
case BOTH_INVALID:
break;
}
}
|
/* The copyright in this software is being made available under the BSD
* License, included below. This software may be subject to other third party
* and contributor rights, including patent rights, and no such rights are
* granted under this license.
*
* Copyright (c) 2010-2020, ITU/ISO/IEC
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
/** \file EncApp.cpp
\brief Encoder application class
*/
#include <list>
#include <fstream>
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <iomanip>
#include "EncApp.h"
#include "EncoderLib/AnnexBwrite.h"
#include "EncoderLib/EncLibCommon.h"
using namespace std;
//! \ingroup EncoderApp
//! \{
// ====================================================================================================================
// Constructor / destructor / initialization / destroy
// ====================================================================================================================
EncApp::EncApp( fstream& bitStream, EncLibCommon* encLibCommon )
: m_cEncLib( encLibCommon )
, m_bitstream( bitStream )
{
m_iFrameRcvd = 0;
m_totalBytes = 0;
m_essentialBytes = 0;
#if JVET_O0756_CALCULATE_HDRMETRICS
m_metricTime = std::chrono::milliseconds(0);
#endif
m_numEncoded = 0;
m_flush = false;
}
EncApp::~EncApp()
{
}
void EncApp::xInitLibCfg()
{
#if JVET_Q0814_DPB
VPS& vps = *m_cEncLib.getVPS();
vps.m_targetOlsIdx = m_targetOlsIdx;
#else
VPS vps;
#endif
vps.setMaxLayers( m_maxLayers );
if (vps.getMaxLayers() > 1)
{
vps.setVPSId(1); //JVET_P0205 vps_video_parameter_set_id shall be greater than 0 for multi-layer coding
}
else
{
vps.setVPSId(0);
vps.setEachLayerIsAnOlsFlag(1); // If vps_max_layers_minus1 is equal to 0,
// the value of each_layer_is_an_ols_flag is inferred to be equal to 1.
// Otherwise, when vps_all_independent_layers_flag is equal to 0,
// the value of each_layer_is_an_ols_flag is inferred to be equal to 0.
}
vps.setMaxSubLayers(m_maxSublayers);
if (vps.getMaxLayers() > 1 && vps.getMaxSubLayers() > 1)
{
vps.setAllLayersSameNumSublayersFlag(m_allLayersSameNumSublayersFlag);
}
if (vps.getMaxLayers() > 1)
{
vps.setAllIndependentLayersFlag(m_allIndependentLayersFlag);
if (!vps.getAllIndependentLayersFlag())
{
vps.setEachLayerIsAnOlsFlag(0);
}
}
for (int i = 0; i < vps.getMaxLayers(); i++)
{
vps.setGeneralLayerIdx( m_layerId[i], i );
vps.setLayerId(i, m_layerId[i]);
if (i > 0 && !vps.getAllIndependentLayersFlag())
{
vps.setIndependentLayerFlag( i, m_numRefLayers[i] ? false : true );
if (!vps.getIndependentLayerFlag(i))
{
for (int j = 0, k = 0; j < i; j++)
{
if (m_refLayerIdxStr[i].find(to_string(j)) != std::string::npos)
{
vps.setDirectRefLayerFlag(i, j, true);
vps.setInterLayerRefIdc( i, j, k );
vps.setDirectRefLayerIdx(i, k++, j);
}
else
{
vps.setDirectRefLayerFlag(i, j, false);
}
}
}
}
}
if (vps.getMaxLayers() > 1)
{
if (vps.getAllIndependentLayersFlag())
{
vps.setEachLayerIsAnOlsFlag(m_eachLayerIsAnOlsFlag);
if (vps.getEachLayerIsAnOlsFlag() == 0)
{
vps.setOlsModeIdc(2); // When vps_all_independent_layers_flag is equal to 1 and each_layer_is_an_ols_flag is equal to 0, the value of ols_mode_idc is inferred to be equal to 2
}
}
if (!vps.getEachLayerIsAnOlsFlag())
{
if (!vps.getAllIndependentLayersFlag())
{
vps.setOlsModeIdc(m_olsModeIdc);
}
if (vps.getOlsModeIdc() == 2)
{
vps.setNumOutputLayerSets(m_numOutputLayerSets);
for (int i = 1; i < vps.getNumOutputLayerSets(); i++)
{
for (int j = 0; j < vps.getMaxLayers(); j++)
{
if (m_olsOutputLayerStr[i].find(to_string(j)) != std::string::npos)
{
vps.setOlsOutputLayerFlag(i, j, 1);
}
else
{
vps.setOlsOutputLayerFlag(i, j, 0);
}
}
}
}
}
}
#if JVET_Q0786_PTL_only
CHECK( m_numPtlsInVps == 0, "There has to be at least one PTL structure in the VPS." );
vps.setNumPtls ( m_numPtlsInVps );
vps.setPtPresentFlag (0, 1);
for (int i = 0; i < vps.getNumPtls(); i++)
{
if( i > 0 )
vps.setPtPresentFlag (i, 0);
vps.setPtlMaxTemporalId (i, vps.getMaxSubLayers() - 1);
}
for (int i = 0; i < vps.getNumOutputLayerSets(); i++)
{
vps.setOlsPtlIdx (i, m_olsPtlIdx[i]);
}
std::vector<ProfileTierLevel> ptls;
ptls.resize(vps.getNumPtls());
// PTL0 shall be the same as the one signalled in the SPS
ptls[0].setLevelIdc ( m_level );
ptls[0].setProfileIdc ( m_profile);
ptls[0].setTierFlag ( m_levelTier );
ptls[0].setNumSubProfile ( m_numSubProfile );
for (int i = 0; i < m_numSubProfile; i++)
{
ptls[0].setSubProfileIdc (i, m_subProfile[i]);
}
for(int i = 1; i < vps.getNumPtls(); i++)
{
ptls[i].setLevelIdc (m_levelPtl[i]);
}
vps.setProfileTierLevel(ptls);
#endif
vps.setVPSExtensionFlag ( false );
#if !JVET_Q0814_DPB
m_cEncLib.setVPS(&vps);
#endif
m_cEncLib.setProfile ( m_profile);
m_cEncLib.setLevel ( m_levelTier, m_level);
m_cEncLib.setNumSubProfile ( m_numSubProfile );
for (int i = 0; i < m_numSubProfile; i++)
{
m_cEncLib.setSubProfile(i, m_subProfile[i]);
}
m_cEncLib.setProgressiveSourceFlag ( m_progressiveSourceFlag);
m_cEncLib.setInterlacedSourceFlag ( m_interlacedSourceFlag);
m_cEncLib.setNonPackedConstraintFlag ( m_nonPackedConstraintFlag);
#if JVET_Q0114_CONSTRAINT_FLAGS
m_cEncLib.setNonProjectedConstraintFlag ( m_nonProjectedConstraintFlag );
m_cEncLib.setNoResChangeInClvsConstraintFlag ( m_noResChangeInClvsConstraintFlag );
m_cEncLib.setOneTilePerPicConstraintFlag ( m_oneTilePerPicConstraintFlag );
m_cEncLib.setOneSlicePerPicConstraintFlag ( m_oneSlicePerPicConstraintFlag );
m_cEncLib.setOneSubpicPerPicConstraintFlag ( m_oneSubpicPerPicConstraintFlag );
#endif
m_cEncLib.setFrameOnlyConstraintFlag ( m_frameOnlyConstraintFlag);
m_cEncLib.setIntraConstraintFlag ( m_intraConstraintFlag );
m_cEncLib.setPrintMSEBasedSequencePSNR ( m_printMSEBasedSequencePSNR);
m_cEncLib.setPrintFrameMSE ( m_printFrameMSE);
m_cEncLib.setPrintHexPsnr(m_printHexPsnr);
m_cEncLib.setPrintSequenceMSE ( m_printSequenceMSE);
m_cEncLib.setCabacZeroWordPaddingEnabled ( m_cabacZeroWordPaddingEnabled );
m_cEncLib.setFrameRate ( m_iFrameRate );
m_cEncLib.setFrameSkip ( m_FrameSkip );
m_cEncLib.setTemporalSubsampleRatio ( m_temporalSubsampleRatio );
m_cEncLib.setSourceWidth ( m_iSourceWidth );
m_cEncLib.setSourceHeight ( m_iSourceHeight );
m_cEncLib.setConformanceWindow ( m_confWinLeft / SPS::getWinUnitX( m_InputChromaFormatIDC ), m_confWinRight / SPS::getWinUnitX( m_InputChromaFormatIDC ), m_confWinTop / SPS::getWinUnitY( m_InputChromaFormatIDC ), m_confWinBottom / SPS::getWinUnitY( m_InputChromaFormatIDC ) );
m_cEncLib.setScalingRatio ( m_scalingRatioHor, m_scalingRatioVer );
m_cEncLib.setRPREnabled ( m_rprEnabled );
m_cEncLib.setSwitchPocPeriod ( m_switchPocPeriod );
m_cEncLib.setUpscaledOutput ( m_upscaledOutput );
m_cEncLib.setFramesToBeEncoded ( m_framesToBeEncoded );
//====== SPS constraint flags =======
m_cEncLib.setIntraOnlyConstraintFlag ( m_intraConstraintFlag );
m_cEncLib.setMaxBitDepthConstraintIdc ( m_bitDepthConstraint - 8 );
m_cEncLib.setMaxChromaFormatConstraintIdc ( m_chromaFormatConstraint );
m_cEncLib.setFrameConstraintFlag ( m_bFrameConstraintFlag );
m_cEncLib.setNoQtbttDualTreeIntraConstraintFlag ( !m_dualTree );
m_cEncLib.setNoPartitionConstraintsOverrideConstraintFlag ( !m_SplitConsOverrideEnabledFlag );
m_cEncLib.setNoSaoConstraintFlag ( !m_bUseSAO );
m_cEncLib.setNoAlfConstraintFlag ( !m_alf );
#if JVET_Q0795_CCALF
m_cEncLib.setNoAlfConstraintFlag ( !m_ccalf );
#endif
m_cEncLib.setNoRefWraparoundConstraintFlag ( m_bNoRefWraparoundConstraintFlag );
m_cEncLib.setNoTemporalMvpConstraintFlag ( m_TMVPModeId ? false : true );
m_cEncLib.setNoSbtmvpConstraintFlag ( m_SubPuMvpMode ? false : true );
m_cEncLib.setNoAmvrConstraintFlag ( m_bNoAmvrConstraintFlag );
m_cEncLib.setNoBdofConstraintFlag ( !m_BIO );
m_cEncLib.setNoDmvrConstraintFlag ( !m_DMVR );
m_cEncLib.setNoCclmConstraintFlag ( m_LMChroma ? false : true );
m_cEncLib.setNoMtsConstraintFlag ( (m_MTS || m_MTSImplicit) ? false : true );
m_cEncLib.setNoSbtConstraintFlag ( !m_SBT );
m_cEncLib.setNoAffineMotionConstraintFlag ( !m_Affine );
m_cEncLib.setNoBcwConstraintFlag ( !m_bcw );
m_cEncLib.setNoIbcConstraintFlag ( m_IBCMode ? false : true );
m_cEncLib.setNoCiipConstraintFlag ( !m_ciip );
m_cEncLib.setNoFPelMmvdConstraintFlag ( !(m_MMVD && m_allowDisFracMMVD) );
#if !JVET_Q0806
m_cEncLib.setNoTriangleConstraintFlag ( !m_Triangle );
#else
m_cEncLib.setNoGeoConstraintFlag ( !m_Geo );
#endif
m_cEncLib.setNoLadfConstraintFlag ( !m_LadfEnabed );
m_cEncLib.setNoTransformSkipConstraintFlag ( !m_useTransformSkip );
#if JVET_Q0089_SLICE_LOSSLESS_CODING_CHROMA_BDPCM
m_cEncLib.setNoBDPCMConstraintFlag ( !m_useBDPCM );
#else
m_cEncLib.setNoBDPCMConstraintFlag ( m_useBDPCM == 0 );
#endif
m_cEncLib.setNoJointCbCrConstraintFlag (!m_JointCbCrMode);
m_cEncLib.setNoQpDeltaConstraintFlag ( m_bNoQpDeltaConstraintFlag );
m_cEncLib.setNoDepQuantConstraintFlag ( !m_depQuantEnabledFlag);
m_cEncLib.setNoSignDataHidingConstraintFlag ( !m_signDataHidingEnabledFlag );
m_cEncLib.setNoTrailConstraintFlag ( m_iIntraPeriod == 1 );
m_cEncLib.setNoStsaConstraintFlag ( m_iIntraPeriod == 1 || !xHasNonZeroTemporalID() );
m_cEncLib.setNoRaslConstraintFlag ( m_iIntraPeriod == 1 || !xHasLeadingPicture() );
m_cEncLib.setNoRadlConstraintFlag ( m_iIntraPeriod == 1 || !xHasLeadingPicture() );
m_cEncLib.setNoIdrConstraintFlag ( false ); // Not yet possible to encode bitstream starting with a GDR picture
m_cEncLib.setNoCraConstraintFlag ( m_iDecodingRefreshType != 1 );
m_cEncLib.setNoGdrConstraintFlag ( false ); // Not yet possible to encode GDR using config parameters
m_cEncLib.setNoApsConstraintFlag ( !m_alf && !m_lmcsEnabled && m_useScalingListId == SCALING_LIST_OFF);
//====== Coding Structure ========
m_cEncLib.setIntraPeriod ( m_iIntraPeriod );
m_cEncLib.setDecodingRefreshType ( m_iDecodingRefreshType );
m_cEncLib.setGOPSize ( m_iGOPSize );
m_cEncLib.setDrapPeriod ( m_drapPeriod );
m_cEncLib.setReWriteParamSets ( m_rewriteParamSets );
m_cEncLib.setRPLList0 ( m_RPLList0);
m_cEncLib.setRPLList1 ( m_RPLList1);
m_cEncLib.setIDRRefParamListPresent ( m_idrRefParamList );
m_cEncLib.setGopList ( m_GOPList );
for(int i = 0; i < MAX_TLAYER; i++)
{
m_cEncLib.setNumReorderPics ( m_numReorderPics[i], i );
m_cEncLib.setMaxDecPicBuffering ( m_maxDecPicBuffering[i], i );
}
for( uint32_t uiLoop = 0; uiLoop < MAX_TLAYER; ++uiLoop )
{
m_cEncLib.setLambdaModifier ( uiLoop, m_adLambdaModifier[ uiLoop ] );
}
m_cEncLib.setIntraLambdaModifier ( m_adIntraLambdaModifier );
m_cEncLib.setIntraQpFactor ( m_dIntraQpFactor );
m_cEncLib.setBaseQP ( m_iQP );
#if X0038_LAMBDA_FROM_QP_CAPABILITY
m_cEncLib.setIntraQPOffset ( m_intraQPOffset );
m_cEncLib.setLambdaFromQPEnable ( m_lambdaFromQPEnable );
#endif
m_cEncLib.setChromaQpMappingTableParams (m_chromaQpMappingTableParams);
m_cEncLib.setPad ( m_aiPad );
m_cEncLib.setAccessUnitDelimiter ( m_AccessUnitDelimiter );
#if JVET_Q0775_PH_IN_SH
m_cEncLib.setEnablePictureHeaderInSliceHeader ( m_enablePictureHeaderInSliceHeader );
#endif
m_cEncLib.setMaxTempLayer ( m_maxTempLayer );
//===== Slice ========
//====== Loop/Deblock Filter ========
m_cEncLib.setLoopFilterDisable ( m_bLoopFilterDisable );
m_cEncLib.setLoopFilterOffsetInPPS ( m_loopFilterOffsetInPPS );
m_cEncLib.setLoopFilterBetaOffset ( m_loopFilterBetaOffsetDiv2 );
m_cEncLib.setLoopFilterTcOffset ( m_loopFilterTcOffsetDiv2 );
#if JVET_Q0121_DEBLOCKING_CONTROL_PARAMETERS
m_cEncLib.setLoopFilterCbBetaOffset ( m_loopFilterCbBetaOffsetDiv2 );
m_cEncLib.setLoopFilterCbTcOffset ( m_loopFilterCbTcOffsetDiv2 );
m_cEncLib.setLoopFilterCrBetaOffset ( m_loopFilterCrBetaOffsetDiv2 );
m_cEncLib.setLoopFilterCrTcOffset ( m_loopFilterCrTcOffsetDiv2 );
#endif
#if W0038_DB_OPT
m_cEncLib.setDeblockingFilterMetric ( m_deblockingFilterMetric );
#else
m_cEncLib.setDeblockingFilterMetric ( m_DeblockingFilterMetric );
#endif
//====== Motion search ========
m_cEncLib.setDisableIntraPUsInInterSlices ( m_bDisableIntraPUsInInterSlices );
m_cEncLib.setMotionEstimationSearchMethod ( m_motionEstimationSearchMethod );
m_cEncLib.setSearchRange ( m_iSearchRange );
m_cEncLib.setBipredSearchRange ( m_bipredSearchRange );
m_cEncLib.setClipForBiPredMeEnabled ( m_bClipForBiPredMeEnabled );
m_cEncLib.setFastMEAssumingSmootherMVEnabled ( m_bFastMEAssumingSmootherMVEnabled );
m_cEncLib.setMinSearchWindow ( m_minSearchWindow );
m_cEncLib.setRestrictMESampling ( m_bRestrictMESampling );
//====== Quality control ========
m_cEncLib.setMaxDeltaQP ( m_iMaxDeltaQP );
m_cEncLib.setCuQpDeltaSubdiv ( m_cuQpDeltaSubdiv );
m_cEncLib.setCuChromaQpOffsetSubdiv ( m_cuChromaQpOffsetSubdiv );
m_cEncLib.setChromaCbQpOffset ( m_cbQpOffset );
m_cEncLib.setChromaCrQpOffset ( m_crQpOffset );
m_cEncLib.setChromaCbQpOffsetDualTree ( m_cbQpOffsetDualTree );
m_cEncLib.setChromaCrQpOffsetDualTree ( m_crQpOffsetDualTree );
m_cEncLib.setChromaCbCrQpOffset ( m_cbCrQpOffset );
m_cEncLib.setChromaCbCrQpOffsetDualTree ( m_cbCrQpOffsetDualTree );
#if ER_CHROMA_QP_WCG_PPS
m_cEncLib.setWCGChromaQpControl ( m_wcgChromaQpControl );
#endif
#if W0038_CQP_ADJ
m_cEncLib.setSliceChromaOffsetQpIntraOrPeriodic ( m_sliceChromaQpOffsetPeriodicity, m_sliceChromaQpOffsetIntraOrPeriodic );
#endif
m_cEncLib.setChromaFormatIdc ( m_chromaFormatIDC );
m_cEncLib.setUseAdaptiveQP ( m_bUseAdaptiveQP );
m_cEncLib.setQPAdaptationRange ( m_iQPAdaptationRange );
#if ENABLE_QPA
m_cEncLib.setUsePerceptQPA ( m_bUsePerceptQPA && !m_bUseAdaptiveQP );
m_cEncLib.setUseWPSNR ( m_bUseWPSNR );
#endif
m_cEncLib.setExtendedPrecisionProcessingFlag ( m_extendedPrecisionProcessingFlag );
m_cEncLib.setHighPrecisionOffsetsEnabledFlag ( m_highPrecisionOffsetsEnabledFlag );
m_cEncLib.setWeightedPredictionMethod( m_weightedPredictionMethod );
//====== Tool list ========
#if SHARP_LUMA_DELTA_QP
m_cEncLib.setLumaLevelToDeltaQPControls ( m_lumaLevelToDeltaQPMapping );
#endif
#if X0038_LAMBDA_FROM_QP_CAPABILITY
m_cEncLib.setDeltaQpRD( (m_costMode==COST_LOSSLESS_CODING) ? 0 : m_uiDeltaQpRD );
#else
m_cEncLib.setDeltaQpRD ( m_uiDeltaQpRD );
#endif
m_cEncLib.setFastDeltaQp ( m_bFastDeltaQP );
m_cEncLib.setUseASR ( m_bUseASR );
m_cEncLib.setUseHADME ( m_bUseHADME );
m_cEncLib.setdQPs ( m_aidQP );
m_cEncLib.setUseRDOQ ( m_useRDOQ );
m_cEncLib.setUseRDOQTS ( m_useRDOQTS );
#if T0196_SELECTIVE_RDOQ
m_cEncLib.setUseSelectiveRDOQ ( m_useSelectiveRDOQ );
#endif
m_cEncLib.setRDpenalty ( m_rdPenalty );
m_cEncLib.setCTUSize ( m_uiCTUSize );
#if JVET_Q0119_CLEANUPS
m_cEncLib.setSubPicInfoPresentFlag ( m_subPicInfoPresentFlag );
if(m_subPicInfoPresentFlag)
#else
m_cEncLib.setSubPicPresentFlag ( m_subPicPresentFlag );
if(m_subPicPresentFlag)
#endif
{
m_cEncLib.setNumSubPics ( m_numSubPics );
for (int i = 0; i < m_numSubPics; i++)
{
m_cEncLib.setSubPicCtuTopLeftX ( m_subPicCtuTopLeftX[i], i );
m_cEncLib.setSubPicCtuTopLeftY ( m_subPicCtuTopLeftY[i], i );
m_cEncLib.setSubPicWidth ( m_subPicWidth[i], i );
m_cEncLib.setSubPicHeight ( m_subPicHeight[i], i );
m_cEncLib.setSubPicTreatedAsPicFlag ( m_subPicTreatedAsPicFlag[i], i );
m_cEncLib.setLoopFilterAcrossSubpicEnabledFlag ( m_loopFilterAcrossSubpicEnabledFlag[i], i );
}
}
#if JVET_Q0119_CLEANUPS
m_cEncLib.setSubPicIdMappingExplicitlySignalledFlag ( m_subPicIdMappingExplicitlySignalledFlag );
if (m_subPicIdMappingExplicitlySignalledFlag)
{
m_cEncLib.setSubPicIdMappingInSpsFlag ( m_subPicIdMappingInSpsFlag );
if(m_subPicIdMappingInSpsFlag)
#else
m_cEncLib.setSubPicIdPresentFlag ( m_subPicIdPresentFlag );
if (m_subPicIdPresentFlag)
{
m_cEncLib.setSubPicIdSignallingPresentFlag ( m_subPicIdSignallingPresentFlag );
if(m_subPicIdSignallingPresentFlag)
#endif
{
m_cEncLib.setSubPicIdLen ( m_subPicIdLen );
for (int i = 0; i < m_numSubPics; i++)
{
m_cEncLib.setSubPicId ( m_subPicId[i], i );
}
}
}
m_cEncLib.setUseSplitConsOverride ( m_SplitConsOverrideEnabledFlag );
m_cEncLib.setMinQTSizes ( m_uiMinQT );
m_cEncLib.setMaxMTTHierarchyDepth ( m_uiMaxMTTHierarchyDepth, m_uiMaxMTTHierarchyDepthI, m_uiMaxMTTHierarchyDepthIChroma );
#if JVET_Q0330_BLOCK_PARTITION
m_cEncLib.setMaxBTSizes ( m_uiMaxBT );
m_cEncLib.setMaxTTSizes ( m_uiMaxTT );
#endif
m_cEncLib.setDualITree ( m_dualTree );
m_cEncLib.setLFNST ( m_LFNST );
m_cEncLib.setUseFastLFNST ( m_useFastLFNST );
m_cEncLib.setSubPuMvpMode ( m_SubPuMvpMode );
m_cEncLib.setAffine ( m_Affine );
m_cEncLib.setAffineType ( m_AffineType );
m_cEncLib.setPROF ( m_PROF );
m_cEncLib.setBIO (m_BIO);
m_cEncLib.setUseLMChroma ( m_LMChroma );
m_cEncLib.setHorCollocatedChromaFlag ( m_horCollocatedChromaFlag );
m_cEncLib.setVerCollocatedChromaFlag ( m_verCollocatedChromaFlag );
m_cEncLib.setIntraMTS ( m_MTS & 1 );
m_cEncLib.setInterMTS ( ( m_MTS >> 1 ) & 1 );
m_cEncLib.setMTSIntraMaxCand ( m_MTSIntraMaxCand );
m_cEncLib.setMTSInterMaxCand ( m_MTSInterMaxCand );
m_cEncLib.setImplicitMTS ( m_MTSImplicit );
m_cEncLib.setUseSBT ( m_SBT );
m_cEncLib.setSBTFast64WidthTh ( m_SBTFast64WidthTh );
m_cEncLib.setUseCompositeRef ( m_compositeRefEnabled );
m_cEncLib.setUseSMVD ( m_SMVD );
m_cEncLib.setUseBcw ( m_bcw );
m_cEncLib.setUseBcwFast ( m_BcwFast );
#if LUMA_ADAPTIVE_DEBLOCKING_FILTER_QP_OFFSET
m_cEncLib.setUseLadf ( m_LadfEnabed );
if ( m_LadfEnabed )
{
m_cEncLib.setLadfNumIntervals ( m_LadfNumIntervals);
for ( int k = 0; k < m_LadfNumIntervals; k++ )
{
m_cEncLib.setLadfQpOffset( m_LadfQpOffset[k], k );
m_cEncLib.setLadfIntervalLowerBound(m_LadfIntervalLowerBound[k], k);
}
}
#endif
m_cEncLib.setUseCiip ( m_ciip );
#if !JVET_Q0806
m_cEncLib.setUseTriangle ( m_Triangle );
#else
m_cEncLib.setUseGeo ( m_Geo );
#endif
m_cEncLib.setUseHashME ( m_HashME );
m_cEncLib.setAllowDisFracMMVD ( m_allowDisFracMMVD );
m_cEncLib.setUseAffineAmvr ( m_AffineAmvr );
m_cEncLib.setUseAffineAmvrEncOpt ( m_AffineAmvrEncOpt );
m_cEncLib.setDMVR ( m_DMVR );
m_cEncLib.setMMVD ( m_MMVD );
m_cEncLib.setMmvdDisNum (m_MmvdDisNum);
m_cEncLib.setRGBFormatFlag(m_rgbFormat);
m_cEncLib.setUseColorTrans(m_useColorTrans);
m_cEncLib.setPLTMode ( m_PLTMode );
m_cEncLib.setJointCbCr ( m_JointCbCrMode );
m_cEncLib.setIBCMode ( m_IBCMode );
m_cEncLib.setIBCLocalSearchRangeX ( m_IBCLocalSearchRangeX );
m_cEncLib.setIBCLocalSearchRangeY ( m_IBCLocalSearchRangeY );
m_cEncLib.setIBCHashSearch ( m_IBCHashSearch );
m_cEncLib.setIBCHashSearchMaxCand ( m_IBCHashSearchMaxCand );
m_cEncLib.setIBCHashSearchRange4SmallBlk ( m_IBCHashSearchRange4SmallBlk );
m_cEncLib.setIBCFastMethod ( m_IBCFastMethod );
m_cEncLib.setUseWrapAround ( m_wrapAround );
m_cEncLib.setWrapAroundOffset ( m_wrapAroundOffset );
// ADD_NEW_TOOL : (encoder app) add setting of tool enabling flags and associated parameters here
m_cEncLib.setLoopFilterAcrossVirtualBoundariesDisabledFlag ( m_loopFilterAcrossVirtualBoundariesDisabledFlag );
m_cEncLib.setNumVerVirtualBoundaries ( m_numVerVirtualBoundaries );
m_cEncLib.setNumHorVirtualBoundaries ( m_numHorVirtualBoundaries );
for( unsigned i = 0; i < m_numVerVirtualBoundaries; i++ )
{
m_cEncLib.setVirtualBoundariesPosX ( m_virtualBoundariesPosX[ i ], i );
}
for( unsigned i = 0; i < m_numHorVirtualBoundaries; i++ )
{
m_cEncLib.setVirtualBoundariesPosY ( m_virtualBoundariesPosY[ i ], i );
}
m_cEncLib.setMaxCUWidth ( m_uiCTUSize );
m_cEncLib.setMaxCUHeight ( m_uiCTUSize );
#if JVET_Q0468_Q0469_MIN_LUMA_CB_AND_MIN_QT_FIX
m_cEncLib.setLog2MinCodingBlockSize ( m_log2MinCuSize );
#else
m_cEncLib.setMaxCodingDepth ( m_uiMaxCodingDepth );
m_cEncLib.setLog2DiffMaxMinCodingBlockSize ( m_uiLog2DiffMaxMinCodingBlockSize );
#endif
m_cEncLib.setLog2MaxTbSize ( m_log2MaxTbSize );
m_cEncLib.setUseEncDbOpt(m_encDbOpt);
m_cEncLib.setUseFastLCTU ( m_useFastLCTU );
m_cEncLib.setFastInterSearchMode ( m_fastInterSearchMode );
m_cEncLib.setUseEarlyCU ( m_bUseEarlyCU );
m_cEncLib.setUseFastDecisionForMerge ( m_useFastDecisionForMerge );
m_cEncLib.setUseCbfFastMode ( m_bUseCbfFastMode );
m_cEncLib.setUseEarlySkipDetection ( m_useEarlySkipDetection );
m_cEncLib.setUseFastMerge ( m_useFastMrg );
m_cEncLib.setUsePbIntraFast ( m_usePbIntraFast );
m_cEncLib.setUseAMaxBT ( m_useAMaxBT );
m_cEncLib.setUseE0023FastEnc ( m_e0023FastEnc );
m_cEncLib.setUseContentBasedFastQtbt ( m_contentBasedFastQtbt );
m_cEncLib.setUseNonLinearAlfLuma ( m_useNonLinearAlfLuma );
m_cEncLib.setUseNonLinearAlfChroma ( m_useNonLinearAlfChroma );
m_cEncLib.setMaxNumAlfAlternativesChroma ( m_maxNumAlfAlternativesChroma );
m_cEncLib.setUseMRL ( m_MRL );
m_cEncLib.setUseMIP ( m_MIP );
m_cEncLib.setUseFastMIP ( m_useFastMIP );
m_cEncLib.setFastLocalDualTreeMode ( m_fastLocalDualTreeMode );
m_cEncLib.setCrossComponentPredictionEnabledFlag ( m_crossComponentPredictionEnabledFlag );
m_cEncLib.setUseReconBasedCrossCPredictionEstimate ( m_reconBasedCrossCPredictionEstimate );
#if !JVET_Q0441_SAO_MOD_12_BIT
m_cEncLib.setLog2SaoOffsetScale ( CHANNEL_TYPE_LUMA , m_log2SaoOffsetScale[CHANNEL_TYPE_LUMA] );
m_cEncLib.setLog2SaoOffsetScale ( CHANNEL_TYPE_CHROMA, m_log2SaoOffsetScale[CHANNEL_TYPE_CHROMA] );
#endif
m_cEncLib.setUseTransformSkip ( m_useTransformSkip );
m_cEncLib.setUseTransformSkipFast ( m_useTransformSkipFast );
m_cEncLib.setUseChromaTS ( m_useChromaTS && m_useTransformSkip);
m_cEncLib.setUseBDPCM ( m_useBDPCM );
m_cEncLib.setTransformSkipRotationEnabledFlag ( m_transformSkipRotationEnabledFlag );
m_cEncLib.setTransformSkipContextEnabledFlag ( m_transformSkipContextEnabledFlag );
m_cEncLib.setPersistentRiceAdaptationEnabledFlag ( m_persistentRiceAdaptationEnabledFlag );
m_cEncLib.setCabacBypassAlignmentEnabledFlag ( m_cabacBypassAlignmentEnabledFlag );
m_cEncLib.setLog2MaxTransformSkipBlockSize ( m_log2MaxTransformSkipBlockSize );
for (uint32_t signallingModeIndex = 0; signallingModeIndex < NUMBER_OF_RDPCM_SIGNALLING_MODES; signallingModeIndex++)
{
m_cEncLib.setRdpcmEnabledFlag ( RDPCMSignallingMode(signallingModeIndex), m_rdpcmEnabledFlag[signallingModeIndex]);
}
m_cEncLib.setFastUDIUseMPMEnabled ( m_bFastUDIUseMPMEnabled );
m_cEncLib.setFastMEForGenBLowDelayEnabled ( m_bFastMEForGenBLowDelayEnabled );
m_cEncLib.setUseBLambdaForNonKeyLowDelayPictures ( m_bUseBLambdaForNonKeyLowDelayPictures );
m_cEncLib.setUseISP ( m_ISP );
m_cEncLib.setUseFastISP ( m_useFastISP );
// set internal bit-depth and constants
for (uint32_t channelType = 0; channelType < MAX_NUM_CHANNEL_TYPE; channelType++)
{
m_cEncLib.setBitDepth((ChannelType)channelType, m_internalBitDepth[channelType]);
m_cEncLib.setInputBitDepth((ChannelType)channelType, m_inputBitDepth[channelType]);
}
m_cEncLib.setMaxNumMergeCand ( m_maxNumMergeCand );
m_cEncLib.setMaxNumAffineMergeCand ( m_maxNumAffineMergeCand );
#if !JVET_Q0806
m_cEncLib.setMaxNumTriangleCand ( m_maxNumTriangleCand );
#else
m_cEncLib.setMaxNumGeoCand ( m_maxNumGeoCand );
#endif
m_cEncLib.setMaxNumIBCMergeCand ( m_maxNumIBCMergeCand );
//====== Weighted Prediction ========
m_cEncLib.setUseWP ( m_useWeightedPred );
m_cEncLib.setWPBiPred ( m_useWeightedBiPred );
#if JVET_Q0297_MER
//====== Parallel Merge Estimation ========
m_cEncLib.setLog2ParallelMergeLevelMinus2(m_log2ParallelMergeLevel - 2);
#endif
//====== Tiles and Slices ========
m_cEncLib.setNoPicPartitionFlag( !m_picPartitionFlag );
if( m_picPartitionFlag )
{
m_cEncLib.setTileColWidths( m_tileColumnWidth );
m_cEncLib.setTileRowHeights( m_tileRowHeight );
m_cEncLib.setRectSliceFlag( !m_rasterSliceFlag );
m_cEncLib.setNumSlicesInPic( m_numSlicesInPic );
m_cEncLib.setTileIdxDeltaPresentFlag( m_tileIdxDeltaPresentFlag );
m_cEncLib.setRectSlices( m_rectSlices );
m_cEncLib.setRasterSliceSizes( m_rasterSliceSize );
m_cEncLib.setLFCrossTileBoundaryFlag( !m_disableLFCrossTileBoundaryFlag );
m_cEncLib.setLFCrossSliceBoundaryFlag( !m_disableLFCrossSliceBoundaryFlag );
}
else
{
m_cEncLib.setRectSliceFlag( true );
m_cEncLib.setNumSlicesInPic( 1 );
m_cEncLib.setTileIdxDeltaPresentFlag( 0 );
m_cEncLib.setLFCrossTileBoundaryFlag( true );
m_cEncLib.setLFCrossSliceBoundaryFlag( true );
}
//====== Sub-picture and Slices ========
m_cEncLib.setSingleSlicePerSubPicFlagFlag ( m_singleSlicePerSubPicFlag );
m_cEncLib.setUseSAO ( m_bUseSAO );
m_cEncLib.setTestSAODisableAtPictureLevel ( m_bTestSAODisableAtPictureLevel );
m_cEncLib.setSaoEncodingRate ( m_saoEncodingRate );
m_cEncLib.setSaoEncodingRateChroma ( m_saoEncodingRateChroma );
m_cEncLib.setMaxNumOffsetsPerPic ( m_maxNumOffsetsPerPic);
m_cEncLib.setSaoCtuBoundary ( m_saoCtuBoundary);
m_cEncLib.setSaoGreedyMergeEnc ( m_saoGreedyMergeEnc);
m_cEncLib.setIntraSmoothingDisabledFlag (!m_enableIntraReferenceSmoothing );
m_cEncLib.setDecodedPictureHashSEIType ( m_decodedPictureHashSEIType );
#if HEVC_SEI
m_cEncLib.setRecoveryPointSEIEnabled ( m_recoveryPointSEIEnabled );
#endif
m_cEncLib.setDependentRAPIndicationSEIEnabled ( m_drapPeriod > 0 );
m_cEncLib.setBufferingPeriodSEIEnabled ( m_bufferingPeriodSEIEnabled );
m_cEncLib.setPictureTimingSEIEnabled ( m_pictureTimingSEIEnabled );
m_cEncLib.setFrameFieldInfoSEIEnabled ( m_frameFieldInfoSEIEnabled );
m_cEncLib.setBpDeltasGOPStructure ( m_bpDeltasGOPStructure );
m_cEncLib.setDecodingUnitInfoSEIEnabled ( m_decodingUnitInfoSEIEnabled );
m_cEncLib.setHrdParametersPresentFlag ( m_hrdParametersPresentFlag );
m_cEncLib.setFramePackingArrangementSEIEnabled ( m_framePackingSEIEnabled );
m_cEncLib.setFramePackingArrangementSEIType ( m_framePackingSEIType );
m_cEncLib.setFramePackingArrangementSEIId ( m_framePackingSEIId );
m_cEncLib.setFramePackingArrangementSEIQuincunx ( m_framePackingSEIQuincunx );
m_cEncLib.setFramePackingArrangementSEIInterpretation ( m_framePackingSEIInterpretation );
m_cEncLib.setErpSEIEnabled ( m_erpSEIEnabled );
m_cEncLib.setErpSEICancelFlag ( m_erpSEICancelFlag );
m_cEncLib.setErpSEIPersistenceFlag ( m_erpSEIPersistenceFlag );
m_cEncLib.setErpSEIGuardBandFlag ( m_erpSEIGuardBandFlag );
m_cEncLib.setErpSEIGuardBandType ( m_erpSEIGuardBandType );
m_cEncLib.setErpSEILeftGuardBandWidth ( m_erpSEILeftGuardBandWidth );
m_cEncLib.setErpSEIRightGuardBandWidth ( m_erpSEIRightGuardBandWidth );
m_cEncLib.setSphereRotationSEIEnabled ( m_sphereRotationSEIEnabled );
m_cEncLib.setSphereRotationSEICancelFlag ( m_sphereRotationSEICancelFlag );
m_cEncLib.setSphereRotationSEIPersistenceFlag ( m_sphereRotationSEIPersistenceFlag );
m_cEncLib.setSphereRotationSEIYaw ( m_sphereRotationSEIYaw );
m_cEncLib.setSphereRotationSEIPitch ( m_sphereRotationSEIPitch );
m_cEncLib.setSphereRotationSEIRoll ( m_sphereRotationSEIRoll );
m_cEncLib.setOmniViewportSEIEnabled ( m_omniViewportSEIEnabled );
m_cEncLib.setOmniViewportSEIId ( m_omniViewportSEIId );
m_cEncLib.setOmniViewportSEICancelFlag ( m_omniViewportSEICancelFlag );
m_cEncLib.setOmniViewportSEIPersistenceFlag ( m_omniViewportSEIPersistenceFlag );
m_cEncLib.setOmniViewportSEICntMinus1 ( m_omniViewportSEICntMinus1 );
m_cEncLib.setOmniViewportSEIAzimuthCentre ( m_omniViewportSEIAzimuthCentre );
m_cEncLib.setOmniViewportSEIElevationCentre ( m_omniViewportSEIElevationCentre );
m_cEncLib.setOmniViewportSEITiltCentre ( m_omniViewportSEITiltCentre );
m_cEncLib.setOmniViewportSEIHorRange ( m_omniViewportSEIHorRange );
m_cEncLib.setOmniViewportSEIVerRange ( m_omniViewportSEIVerRange );
m_cEncLib.setRwpSEIEnabled (m_rwpSEIEnabled);
m_cEncLib.setRwpSEIRwpCancelFlag (m_rwpSEIRwpCancelFlag);
m_cEncLib.setRwpSEIRwpPersistenceFlag (m_rwpSEIRwpPersistenceFlag);
m_cEncLib.setRwpSEIConstituentPictureMatchingFlag (m_rwpSEIConstituentPictureMatchingFlag);
m_cEncLib.setRwpSEINumPackedRegions (m_rwpSEINumPackedRegions);
m_cEncLib.setRwpSEIProjPictureWidth (m_rwpSEIProjPictureWidth);
m_cEncLib.setRwpSEIProjPictureHeight (m_rwpSEIProjPictureHeight);
m_cEncLib.setRwpSEIPackedPictureWidth (m_rwpSEIPackedPictureWidth);
m_cEncLib.setRwpSEIPackedPictureHeight (m_rwpSEIPackedPictureHeight);
m_cEncLib.setRwpSEIRwpTransformType (m_rwpSEIRwpTransformType);
m_cEncLib.setRwpSEIRwpGuardBandFlag (m_rwpSEIRwpGuardBandFlag);
m_cEncLib.setRwpSEIProjRegionWidth (m_rwpSEIProjRegionWidth);
m_cEncLib.setRwpSEIProjRegionHeight (m_rwpSEIProjRegionHeight);
m_cEncLib.setRwpSEIRwpSEIProjRegionTop (m_rwpSEIRwpSEIProjRegionTop);
m_cEncLib.setRwpSEIProjRegionLeft (m_rwpSEIProjRegionLeft);
m_cEncLib.setRwpSEIPackedRegionWidth (m_rwpSEIPackedRegionWidth);
m_cEncLib.setRwpSEIPackedRegionHeight (m_rwpSEIPackedRegionHeight);
m_cEncLib.setRwpSEIPackedRegionTop (m_rwpSEIPackedRegionTop);
m_cEncLib.setRwpSEIPackedRegionLeft (m_rwpSEIPackedRegionLeft);
m_cEncLib.setRwpSEIRwpLeftGuardBandWidth (m_rwpSEIRwpLeftGuardBandWidth);
m_cEncLib.setRwpSEIRwpRightGuardBandWidth (m_rwpSEIRwpRightGuardBandWidth);
m_cEncLib.setRwpSEIRwpTopGuardBandHeight (m_rwpSEIRwpTopGuardBandHeight);
m_cEncLib.setRwpSEIRwpBottomGuardBandHeight (m_rwpSEIRwpBottomGuardBandHeight);
m_cEncLib.setRwpSEIRwpGuardBandNotUsedForPredFlag (m_rwpSEIRwpGuardBandNotUsedForPredFlag);
m_cEncLib.setRwpSEIRwpGuardBandType (m_rwpSEIRwpGuardBandType);
m_cEncLib.setGcmpSEIEnabled ( m_gcmpSEIEnabled );
m_cEncLib.setGcmpSEICancelFlag ( m_gcmpSEICancelFlag );
m_cEncLib.setGcmpSEIPersistenceFlag ( m_gcmpSEIPersistenceFlag );
m_cEncLib.setGcmpSEIPackingType ( (uint8_t)m_gcmpSEIPackingType );
m_cEncLib.setGcmpSEIMappingFunctionType ( (uint8_t)m_gcmpSEIMappingFunctionType );
m_cEncLib.setGcmpSEIFaceIndex ( m_gcmpSEIFaceIndex );
m_cEncLib.setGcmpSEIFaceRotation ( m_gcmpSEIFaceRotation );
m_cEncLib.setGcmpSEIFunctionCoeffU ( m_gcmpSEIFunctionCoeffU );
m_cEncLib.setGcmpSEIFunctionUAffectedByVFlag ( m_gcmpSEIFunctionUAffectedByVFlag );
m_cEncLib.setGcmpSEIFunctionCoeffV ( m_gcmpSEIFunctionCoeffV );
m_cEncLib.setGcmpSEIFunctionVAffectedByUFlag ( m_gcmpSEIFunctionVAffectedByUFlag );
m_cEncLib.setGcmpSEIGuardBandFlag ( m_gcmpSEIGuardBandFlag );
m_cEncLib.setGcmpSEIGuardBandBoundaryType ( m_gcmpSEIGuardBandBoundaryType );
m_cEncLib.setGcmpSEIGuardBandSamplesMinus1 ( (uint8_t)m_gcmpSEIGuardBandSamplesMinus1 );
m_cEncLib.setSubpicureLevelInfoSEIEnabled (m_subpicureLevelInfoSEIEnabled);
m_cEncLib.setSampleAspectRatioInfoSEIEnabled (m_sampleAspectRatioInfoSEIEnabled);
m_cEncLib.setSariCancelFlag (m_sariCancelFlag);
m_cEncLib.setSariPersistenceFlag (m_sariPersistenceFlag);
m_cEncLib.setSariAspectRatioIdc (m_sariAspectRatioIdc);
m_cEncLib.setSariSarWidth (m_sariSarWidth);
m_cEncLib.setSariSarHeight (m_sariSarHeight);
m_cEncLib.setMCTSEncConstraint ( m_MCTSEncConstraint);
m_cEncLib.setMasteringDisplaySEI ( m_masteringDisplay );
#if U0033_ALTERNATIVE_TRANSFER_CHARACTERISTICS_SEI
m_cEncLib.setSEIAlternativeTransferCharacteristicsSEIEnable ( m_preferredTransferCharacteristics>=0 );
m_cEncLib.setSEIPreferredTransferCharacteristics ( uint8_t(m_preferredTransferCharacteristics) );
#endif
// film grain charcteristics
m_cEncLib.setFilmGrainCharactersticsSEIEnabled (m_fgcSEIEnabled);
m_cEncLib.setFilmGrainCharactersticsSEICancelFlag (m_fgcSEICancelFlag);
m_cEncLib.setFilmGrainCharactersticsSEIPersistenceFlag (m_fgcSEIPersistenceFlag);
m_cEncLib.setFilmGrainCharactersticsSEIModelID ((uint8_t)m_fgcSEIModelID);
m_cEncLib.setFilmGrainCharactersticsSEISepColourDescPresent (m_fgcSEISepColourDescPresentFlag);
m_cEncLib.setFilmGrainCharactersticsSEIBlendingModeID ((uint8_t)m_fgcSEIBlendingModeID);
m_cEncLib.setFilmGrainCharactersticsSEILog2ScaleFactor ((uint8_t)m_fgcSEILog2ScaleFactor);
for (int i = 0; i < MAX_NUM_COMPONENT; i++) {
m_cEncLib.setFGCSEICompModelPresent (m_fgcSEICompModelPresent[i], i);
}
// content light level
m_cEncLib.setCLLSEIEnabled (m_cllSEIEnabled);
m_cEncLib.setCLLSEIMaxContentLightLevel ((uint16_t)m_cllSEIMaxContentLevel);
m_cEncLib.setCLLSEIMaxPicAvgLightLevel ((uint16_t)m_cllSEIMaxPicAvgLevel);
// ambient viewing enviornment
m_cEncLib.setAmbientViewingEnvironmentSEIEnabled (m_aveSEIEnabled);
m_cEncLib.setAmbientViewingEnvironmentSEIIlluminance (m_aveSEIAmbientIlluminance);
m_cEncLib.setAmbientViewingEnvironmentSEIAmbientLightX ((uint16_t)m_aveSEIAmbientLightX);
m_cEncLib.setAmbientViewingEnvironmentSEIAmbientLightY ((uint16_t)m_aveSEIAmbientLightY);
// content colour volume SEI
m_cEncLib.setCcvSEIEnabled (m_ccvSEIEnabled);
m_cEncLib.setCcvSEICancelFlag (m_ccvSEICancelFlag);
m_cEncLib.setCcvSEIPersistenceFlag (m_ccvSEIPersistenceFlag);
m_cEncLib.setCcvSEIEnabled (m_ccvSEIEnabled);
m_cEncLib.setCcvSEICancelFlag (m_ccvSEICancelFlag);
m_cEncLib.setCcvSEIPersistenceFlag (m_ccvSEIPersistenceFlag);
m_cEncLib.setCcvSEIPrimariesPresentFlag (m_ccvSEIPrimariesPresentFlag);
m_cEncLib.setCcvSEIMinLuminanceValuePresentFlag (m_ccvSEIMinLuminanceValuePresentFlag);
m_cEncLib.setCcvSEIMaxLuminanceValuePresentFlag (m_ccvSEIMaxLuminanceValuePresentFlag);
m_cEncLib.setCcvSEIAvgLuminanceValuePresentFlag (m_ccvSEIAvgLuminanceValuePresentFlag);
for(int i = 0; i < MAX_NUM_COMPONENT; i++) {
m_cEncLib.setCcvSEIPrimariesX (m_ccvSEIPrimariesX[i], i);
m_cEncLib.setCcvSEIPrimariesY (m_ccvSEIPrimariesY[i], i);
}
m_cEncLib.setCcvSEIMinLuminanceValue (m_ccvSEIMinLuminanceValue);
m_cEncLib.setCcvSEIMaxLuminanceValue (m_ccvSEIMaxLuminanceValue);
m_cEncLib.setCcvSEIAvgLuminanceValue (m_ccvSEIAvgLuminanceValue);
m_cEncLib.setEntropyCodingSyncEnabledFlag ( m_entropyCodingSyncEnabledFlag );
m_cEncLib.setTMVPModeId ( m_TMVPModeId );
m_cEncLib.setSliceLevelRpl ( m_sliceLevelRpl );
m_cEncLib.setSliceLevelDblk ( m_sliceLevelDblk );
m_cEncLib.setSliceLevelSao ( m_sliceLevelSao );
#if JVET_Q0819_PH_CHANGES
m_cEncLib.setSliceLevelWp ( m_sliceLevelWp );
m_cEncLib.setSliceLevelDeltaQp ( m_sliceLevelDeltaQp );
#endif
m_cEncLib.setSliceLevelAlf ( m_sliceLevelAlf );
#if !JVET_Q0482_REMOVE_CONSTANT_PARAMS
m_cEncLib.setConstantSliceHeaderParamsEnabledFlag ( m_constantSliceHeaderParamsEnabledFlag );
m_cEncLib.setPPSDepQuantEnabledIdc ( m_PPSDepQuantEnabledIdc );
m_cEncLib.setPPSRefPicListSPSIdc0 ( m_PPSRefPicListSPSIdc0 );
m_cEncLib.setPPSRefPicListSPSIdc1 ( m_PPSRefPicListSPSIdc1 );
m_cEncLib.setPPSMvdL1ZeroIdc ( m_PPSMvdL1ZeroIdc );
m_cEncLib.setPPSCollocatedFromL0Idc ( m_PPSCollocatedFromL0Idc );
m_cEncLib.setPPSSixMinusMaxNumMergeCandPlus1 ( m_PPSSixMinusMaxNumMergeCandPlus1 );
#endif
#if !JVET_Q0806
#if !JVET_Q0482_REMOVE_CONSTANT_PARAMS
m_cEncLib.setPPSMaxNumMergeCandMinusMaxNumTriangleCandPlus1 ( m_PPSMaxNumMergeCandMinusMaxNumTriangleCandPlus1 );
#endif
#else
#if !JVET_Q0482_REMOVE_CONSTANT_PARAMS
m_cEncLib.setPPSMaxNumMergeCandMinusMaxNumGeoCandPlus1 ( m_PPSMaxNumMergeCandMinusMaxNumGeoCandPlus1 );
#endif
#endif
m_cEncLib.setUseScalingListId ( m_useScalingListId );
m_cEncLib.setScalingListFileName ( m_scalingListFileName );
m_cEncLib.setDisableScalingMatrixForLfnstBlks ( m_disableScalingMatrixForLfnstBlks);
m_cEncLib.setDepQuantEnabledFlag ( m_depQuantEnabledFlag);
m_cEncLib.setSignDataHidingEnabledFlag ( m_signDataHidingEnabledFlag);
m_cEncLib.setUseRateCtrl ( m_RCEnableRateControl );
m_cEncLib.setTargetBitrate ( m_RCTargetBitrate );
m_cEncLib.setKeepHierBit ( m_RCKeepHierarchicalBit );
m_cEncLib.setLCULevelRC ( m_RCLCULevelRC );
m_cEncLib.setUseLCUSeparateModel ( m_RCUseLCUSeparateModel );
m_cEncLib.setInitialQP ( m_RCInitialQP );
m_cEncLib.setForceIntraQP ( m_RCForceIntraQP );
#if U0132_TARGET_BITS_SATURATION
m_cEncLib.setCpbSaturationEnabled ( m_RCCpbSaturationEnabled );
m_cEncLib.setCpbSize ( m_RCCpbSize );
m_cEncLib.setInitialCpbFullness ( m_RCInitialCpbFullness );
#endif
m_cEncLib.setCostMode ( m_costMode );
m_cEncLib.setUseRecalculateQPAccordingToLambda ( m_recalculateQPAccordingToLambda );
m_cEncLib.setDecodingParameterSetEnabled ( m_decodingParameterSetEnabled );
#if HEVC_SEI
m_cEncLib.setActiveParameterSetsSEIEnabled ( m_activeParameterSetsSEIEnabled );
#endif
m_cEncLib.setVuiParametersPresentFlag ( m_vuiParametersPresentFlag );
m_cEncLib.setAspectRatioInfoPresentFlag ( m_aspectRatioInfoPresentFlag);
m_cEncLib.setAspectRatioIdc ( m_aspectRatioIdc );
m_cEncLib.setSarWidth ( m_sarWidth );
m_cEncLib.setSarHeight ( m_sarHeight );
m_cEncLib.setColourDescriptionPresentFlag ( m_colourDescriptionPresentFlag );
m_cEncLib.setColourPrimaries ( m_colourPrimaries );
m_cEncLib.setTransferCharacteristics ( m_transferCharacteristics );
m_cEncLib.setMatrixCoefficients ( m_matrixCoefficients );
m_cEncLib.setChromaLocInfoPresentFlag ( m_chromaLocInfoPresentFlag );
m_cEncLib.setChromaSampleLocTypeTopField ( m_chromaSampleLocTypeTopField );
m_cEncLib.setChromaSampleLocTypeBottomField ( m_chromaSampleLocTypeBottomField );
m_cEncLib.setChromaSampleLocType ( m_chromaSampleLocType );
m_cEncLib.setOverscanInfoPresentFlag ( m_overscanInfoPresentFlag );
m_cEncLib.setOverscanAppropriateFlag ( m_overscanAppropriateFlag );
m_cEncLib.setVideoFullRangeFlag ( m_videoFullRangeFlag );
m_cEncLib.setEfficientFieldIRAPEnabled ( m_bEfficientFieldIRAPEnabled );
m_cEncLib.setHarmonizeGopFirstFieldCoupleEnabled ( m_bHarmonizeGopFirstFieldCoupleEnabled );
m_cEncLib.setSummaryOutFilename ( m_summaryOutFilename );
m_cEncLib.setSummaryPicFilenameBase ( m_summaryPicFilenameBase );
m_cEncLib.setSummaryVerboseness ( m_summaryVerboseness );
m_cEncLib.setIMV ( m_ImvMode );
m_cEncLib.setIMV4PelFast ( m_Imv4PelFast );
m_cEncLib.setDecodeBitstream ( 0, m_decodeBitstreams[0] );
m_cEncLib.setDecodeBitstream ( 1, m_decodeBitstreams[1] );
m_cEncLib.setSwitchPOC ( m_switchPOC );
m_cEncLib.setSwitchDQP ( m_switchDQP );
m_cEncLib.setFastForwardToPOC ( m_fastForwardToPOC );
m_cEncLib.setForceDecodeBitstream1 ( m_forceDecodeBitstream1 );
m_cEncLib.setStopAfterFFtoPOC ( m_stopAfterFFtoPOC );
m_cEncLib.setBs2ModPOCAndType ( m_bs2ModPOCAndType );
m_cEncLib.setDebugCTU ( m_debugCTU );
#if ENABLE_SPLIT_PARALLELISM
m_cEncLib.setNumSplitThreads ( m_numSplitThreads );
m_cEncLib.setForceSingleSplitThread ( m_forceSplitSequential );
#endif
m_cEncLib.setUseALF ( m_alf );
#if JVET_Q0795_CCALF
m_cEncLib.setUseCCALF ( m_ccalf );
m_cEncLib.setCCALFQpThreshold ( m_ccalfQpThreshold );
#endif
m_cEncLib.setLmcs ( m_lmcsEnabled );
m_cEncLib.setReshapeSignalType ( m_reshapeSignalType );
m_cEncLib.setReshapeIntraCMD ( m_intraCMD );
m_cEncLib.setReshapeCW ( m_reshapeCW );
m_cEncLib.setReshapeCSoffset ( m_CSoffset );
#if JVET_O0756_CALCULATE_HDRMETRICS
for (int i=0; i<hdrtoolslib::NB_REF_WHITE; i++)
{
m_cEncLib.setWhitePointDeltaE (i, m_whitePointDeltaE[i] );
}
m_cEncLib.setMaxSampleValue (m_maxSampleValue);
m_cEncLib.setSampleRange (m_sampleRange);
m_cEncLib.setColorPrimaries (m_colorPrimaries);
m_cEncLib.setEnableTFunctionLUT (m_enableTFunctionLUT);
for (int i=0; i<2; i++)
{
m_cEncLib.setChromaLocation (i, m_chromaLocation);
m_cEncLib.setChromaUPFilter (m_chromaUPFilter);
}
m_cEncLib.setCropOffsetLeft (m_cropOffsetLeft);
m_cEncLib.setCropOffsetTop (m_cropOffsetTop);
m_cEncLib.setCropOffsetRight (m_cropOffsetRight);
m_cEncLib.setCropOffsetBottom (m_cropOffsetBottom);
m_cEncLib.setCalculateHdrMetrics (m_calculateHdrMetrics);
#endif
m_cEncLib.setGopBasedTemporalFilterEnabled(m_gopBasedTemporalFilterEnabled);
m_cEncLib.setNumRefLayers ( m_numRefLayers );
}
void EncApp::xCreateLib( std::list<PelUnitBuf*>& recBufList, const int layerId )
{
// Video I/O
m_cVideoIOYuvInputFile.open( m_inputFileName, false, m_inputBitDepth, m_MSBExtendedBitDepth, m_internalBitDepth ); // read mode
#if EXTENSION_360_VIDEO
m_cVideoIOYuvInputFile.skipFrames(m_FrameSkip, m_inputFileWidth, m_inputFileHeight, m_InputChromaFormatIDC);
#else
const int sourceHeight = m_isField ? m_iSourceHeightOrg : m_iSourceHeight;
m_cVideoIOYuvInputFile.skipFrames(m_FrameSkip, m_iSourceWidth - m_aiPad[0], sourceHeight - m_aiPad[1], m_InputChromaFormatIDC);
#endif
if (!m_reconFileName.empty())
{
if (m_packedYUVMode && ((m_outputBitDepth[CH_L] != 10 && m_outputBitDepth[CH_L] != 12)
|| ((m_iSourceWidth & (1 + (m_outputBitDepth[CH_L] & 3))) != 0)))
{
EXIT ("Invalid output bit-depth or image width for packed YUV output, aborting\n");
}
if (m_packedYUVMode && (m_chromaFormatIDC != CHROMA_400) && ((m_outputBitDepth[CH_C] != 10 && m_outputBitDepth[CH_C] != 12)
|| (((m_iSourceWidth / SPS::getWinUnitX (m_chromaFormatIDC)) & (1 + (m_outputBitDepth[CH_C] & 3))) != 0)))
{
EXIT ("Invalid chroma output bit-depth or image width for packed YUV output, aborting\n");
}
std::string reconFileName = m_reconFileName;
if( m_reconFileName.compare( "/dev/null" ) && (m_maxLayers > 1) )
{
size_t pos = reconFileName.find_last_of('.');
if (pos != string::npos)
{
reconFileName.insert( pos, std::to_string( layerId ) );
}
else
{
reconFileName.append( std::to_string( layerId ) );
}
}
m_cVideoIOYuvReconFile.open( reconFileName, true, m_outputBitDepth, m_outputBitDepth, m_internalBitDepth ); // write mode
}
// create the encoder
m_cEncLib.create( layerId );
// create the output buffer
for( int i = 0; i < (m_iGOPSize + 1 + (m_isField ? 1 : 0)); i++ )
{
recBufList.push_back( new PelUnitBuf );
}
}
void EncApp::xDestroyLib()
{
// Video I/O
m_cVideoIOYuvInputFile.close();
m_cVideoIOYuvReconFile.close();
// Neo Decoder
m_cEncLib.destroy();
}
void EncApp::xInitLib(bool isFieldCoding)
{
m_cEncLib.init(isFieldCoding, this );
}
// ====================================================================================================================
// Public member functions
// ====================================================================================================================
void EncApp::createLib( const int layerIdx )
{
const int sourceHeight = m_isField ? m_iSourceHeightOrg : m_iSourceHeight;
UnitArea unitArea( m_chromaFormatIDC, Area( 0, 0, m_iSourceWidth, sourceHeight ) );
m_orgPic = new PelStorage;
m_trueOrgPic = new PelStorage;
m_orgPic->create( unitArea );
m_trueOrgPic->create( unitArea );
if( !m_bitstream.is_open() )
{
m_bitstream.open( m_bitstreamFileName.c_str(), fstream::binary | fstream::out );
if( !m_bitstream )
{
EXIT( "Failed to open bitstream file " << m_bitstreamFileName.c_str() << " for writing\n" );
}
}
// initialize internal class & member variables and VPS
xInitLibCfg();
const int layerId = m_cEncLib.getVPS() == nullptr ? 0 : m_cEncLib.getVPS()->getLayerId( layerIdx );
xCreateLib( m_recBufList, layerId );
xInitLib( m_isField );
printChromaFormat();
#if EXTENSION_360_VIDEO
m_ext360 = new TExt360AppEncTop( *this, m_cEncLib.getGOPEncoder()->getExt360Data(), *( m_cEncLib.getGOPEncoder() ), *m_orgPic );
#endif
if( m_gopBasedTemporalFilterEnabled )
{
m_temporalFilter.init( m_FrameSkip, m_inputBitDepth, m_MSBExtendedBitDepth, m_internalBitDepth, m_iSourceWidth, m_iSourceHeight,
m_aiPad, m_bClipInputVideoToRec709Range, m_inputFileName, m_chromaFormatIDC,
m_inputColourSpaceConvert, m_iQP, m_gopBasedTemporalFilterStrengths,
m_gopBasedTemporalFilterFutureReference );
}
}
void EncApp::destroyLib()
{
printf( "\nLayerId %2d", m_cEncLib.getLayerId() );
m_cEncLib.printSummary( m_isField );
// delete used buffers in encoder class
m_cEncLib.deletePicBuffer();
for( auto &p : m_recBufList )
{
delete p;
}
m_recBufList.clear();
xDestroyLib();
if( m_bitstream.is_open() )
{
m_bitstream.close();
}
m_orgPic->destroy();
m_trueOrgPic->destroy();
delete m_trueOrgPic;
delete m_orgPic;
#if EXTENSION_360_VIDEO
delete m_ext360;
#endif
printRateSummary();
}
bool EncApp::encodePrep( bool& eos )
{
// main encoder loop
const InputColourSpaceConversion ipCSC = m_inputColourSpaceConvert;
const InputColourSpaceConversion snrCSC = ( !m_snrInternalColourSpace ) ? m_inputColourSpaceConvert : IPCOLOURSPACE_UNCHANGED;
// read input YUV file
#if EXTENSION_360_VIDEO
if( m_ext360->isEnabled() )
{
m_ext360->read( m_cVideoIOYuvInputFile, *m_orgPic, *m_trueOrgPic, ipCSC );
}
else
{
m_cVideoIOYuvInputFile.read( *m_orgPic, *m_trueOrgPic, ipCSC, m_aiPad, m_InputChromaFormatIDC, m_bClipInputVideoToRec709Range );
}
#else
m_cVideoIOYuvInputFile.read( *m_orgPic, *m_trueOrgPic, ipCSC, m_aiPad, m_InputChromaFormatIDC, m_bClipInputVideoToRec709Range );
#endif
if( m_gopBasedTemporalFilterEnabled )
{
m_temporalFilter.filter( m_orgPic, m_iFrameRcvd );
}
// increase number of received frames
m_iFrameRcvd++;
eos = ( m_isField && ( m_iFrameRcvd == ( m_framesToBeEncoded >> 1 ) ) ) || ( !m_isField && ( m_iFrameRcvd == m_framesToBeEncoded ) );
// if end of file (which is only detected on a read failure) flush the encoder of any queued pictures
if( m_cVideoIOYuvInputFile.isEof() )
{
m_flush = true;
eos = true;
m_iFrameRcvd--;
m_cEncLib.setFramesToBeEncoded( m_iFrameRcvd );
}
bool keepDoing = false;
// call encoding function for one frame
if( m_isField )
{
keepDoing = m_cEncLib.encodePrep( eos, m_flush ? 0 : m_orgPic, m_flush ? 0 : m_trueOrgPic, snrCSC, m_recBufList, m_numEncoded, m_isTopFieldFirst );
}
else
{
keepDoing = m_cEncLib.encodePrep( eos, m_flush ? 0 : m_orgPic, m_flush ? 0 : m_trueOrgPic, snrCSC, m_recBufList, m_numEncoded );
}
return keepDoing;
}
bool EncApp::encode()
{
const InputColourSpaceConversion snrCSC = ( !m_snrInternalColourSpace ) ? m_inputColourSpaceConvert : IPCOLOURSPACE_UNCHANGED;
bool keepDoing = false;
// call encoding function for one frame
if( m_isField )
{
keepDoing = m_cEncLib.encode( snrCSC, m_recBufList, m_numEncoded, m_isTopFieldFirst );
}
else
{
keepDoing = m_cEncLib.encode( snrCSC, m_recBufList, m_numEncoded );
}
#if JVET_O0756_CALCULATE_HDRMETRICS
m_metricTime = m_cEncLib.getMetricTime();
#endif
// output when the entire GOP was proccessed
if( !keepDoing )
{
// write bistream to file if necessary
if( m_numEncoded > 0 )
{
xWriteOutput( m_numEncoded, m_recBufList );
}
// temporally skip frames
if( m_temporalSubsampleRatio > 1 )
{
#if EXTENSION_360_VIDEO
m_cVideoIOYuvInputFile.skipFrames( m_temporalSubsampleRatio - 1, m_inputFileWidth, m_inputFileHeight, m_InputChromaFormatIDC );
#else
const int sourceHeight = m_isField ? m_iSourceHeightOrg : m_iSourceHeight;
m_cVideoIOYuvInputFile.skipFrames( m_temporalSubsampleRatio - 1, m_iSourceWidth - m_aiPad[0], sourceHeight - m_aiPad[1], m_InputChromaFormatIDC );
#endif
}
}
return keepDoing;
}
// ====================================================================================================================
// Protected member functions
// ====================================================================================================================
/**
Write access units to output file.
\param bitstreamFile target bitstream file
\param iNumEncoded number of encoded frames
\param accessUnits list of access units to be written
*/
void EncApp::xWriteOutput( int iNumEncoded, std::list<PelUnitBuf*>& recBufList )
{
const InputColourSpaceConversion ipCSC = (!m_outputInternalColourSpace) ? m_inputColourSpaceConvert : IPCOLOURSPACE_UNCHANGED;
std::list<PelUnitBuf*>::iterator iterPicYuvRec = recBufList.end();
int i;
for ( i = 0; i < iNumEncoded; i++ )
{
--iterPicYuvRec;
}
if (m_isField)
{
//Reinterlace fields
for ( i = 0; i < iNumEncoded/2; i++ )
{
const PelUnitBuf* pcPicYuvRecTop = *(iterPicYuvRec++);
const PelUnitBuf* pcPicYuvRecBottom = *(iterPicYuvRec++);
if (!m_reconFileName.empty())
{
m_cVideoIOYuvReconFile.write( *pcPicYuvRecTop, *pcPicYuvRecBottom,
ipCSC,
false, // TODO: m_packedYUVMode,
m_confWinLeft, m_confWinRight, m_confWinTop, m_confWinBottom, NUM_CHROMA_FORMAT, m_isTopFieldFirst );
}
}
}
else
{
for ( i = 0; i < iNumEncoded; i++ )
{
const PelUnitBuf* pcPicYuvRec = *(iterPicYuvRec++);
if (!m_reconFileName.empty())
{
if( m_cEncLib.isRPREnabled() && m_cEncLib.getUpscaledOutput() )
{
const SPS& sps = *m_cEncLib.getSPS( 0 );
const PPS& pps = *m_cEncLib.getPPS( ( sps.getMaxPicWidthInLumaSamples() != pcPicYuvRec->get( COMPONENT_Y ).width || sps.getMaxPicHeightInLumaSamples() != pcPicYuvRec->get( COMPONENT_Y ).height ) ? ENC_PPS_ID_RPR : 0 );
m_cVideoIOYuvReconFile.writeUpscaledPicture( sps, pps, *pcPicYuvRec, ipCSC, m_packedYUVMode, m_cEncLib.getUpscaledOutput(), NUM_CHROMA_FORMAT, m_bClipOutputVideoToRec709Range );
}
else
{
m_cVideoIOYuvReconFile.write( pcPicYuvRec->get( COMPONENT_Y ).width, pcPicYuvRec->get( COMPONENT_Y ).height, *pcPicYuvRec, ipCSC, m_packedYUVMode,
m_confWinLeft, m_confWinRight, m_confWinTop, m_confWinBottom, NUM_CHROMA_FORMAT, m_bClipOutputVideoToRec709Range );
}
}
}
}
}
void EncApp::outputAU( const AccessUnit& au )
{
const vector<uint32_t>& stats = writeAnnexB(m_bitstream, au);
rateStatsAccum(au, stats);
m_bitstream.flush();
}
/**
*
*/
void EncApp::rateStatsAccum(const AccessUnit& au, const std::vector<uint32_t>& annexBsizes)
{
AccessUnit::const_iterator it_au = au.begin();
vector<uint32_t>::const_iterator it_stats = annexBsizes.begin();
for (; it_au != au.end(); it_au++, it_stats++)
{
switch ((*it_au)->m_nalUnitType)
{
case NAL_UNIT_CODED_SLICE_TRAIL:
case NAL_UNIT_CODED_SLICE_STSA:
case NAL_UNIT_CODED_SLICE_IDR_W_RADL:
case NAL_UNIT_CODED_SLICE_IDR_N_LP:
case NAL_UNIT_CODED_SLICE_CRA:
case NAL_UNIT_CODED_SLICE_GDR:
case NAL_UNIT_CODED_SLICE_RADL:
case NAL_UNIT_CODED_SLICE_RASL:
case NAL_UNIT_DPS:
case NAL_UNIT_VPS:
case NAL_UNIT_SPS:
case NAL_UNIT_PPS:
case NAL_UNIT_PH:
case NAL_UNIT_PREFIX_APS:
case NAL_UNIT_SUFFIX_APS:
m_essentialBytes += *it_stats;
break;
default:
break;
}
m_totalBytes += *it_stats;
}
}
void EncApp::printRateSummary()
{
double time = (double) m_iFrameRcvd / m_iFrameRate * m_temporalSubsampleRatio;
msg( DETAILS,"Bytes written to file: %u (%.3f kbps)\n", m_totalBytes, 0.008 * m_totalBytes / time );
if (m_summaryVerboseness > 0)
{
msg(DETAILS, "Bytes for SPS/PPS/APS/Slice (Incl. Annex B): %u (%.3f kbps)\n", m_essentialBytes, 0.008 * m_essentialBytes / time);
}
}
void EncApp::printChromaFormat()
{
if( g_verbosity >= DETAILS )
{
std::cout << std::setw(43) << "Input ChromaFormatIDC = ";
switch (m_InputChromaFormatIDC)
{
case CHROMA_400: std::cout << " 4:0:0"; break;
case CHROMA_420: std::cout << " 4:2:0"; break;
case CHROMA_422: std::cout << " 4:2:2"; break;
case CHROMA_444: std::cout << " 4:4:4"; break;
default:
THROW( "invalid chroma fomat");
}
std::cout << std::endl;
std::cout << std::setw(43) << "Output (internal) ChromaFormatIDC = ";
switch (m_cEncLib.getChromaFormatIdc())
{
case CHROMA_400: std::cout << " 4:0:0"; break;
case CHROMA_420: std::cout << " 4:2:0"; break;
case CHROMA_422: std::cout << " 4:2:2"; break;
case CHROMA_444: std::cout << " 4:4:4"; break;
default:
THROW( "invalid chroma fomat");
}
std::cout << "\n" << std::endl;
}
}
//! \}
|
#pragma once
#include <fea/config.hpp>
#include <fea/rendering/tilechunk.hpp>
#include <unordered_map>
#include <functional>
namespace fea
{
using TileId = int32_t;
struct FEA_API TileDefinition
{
TileDefinition(const glm::uvec2& texPos, TileId next = -1, uint32_t ticks = 0);
glm::uvec2 mTileTexPosition;
TileId mNextTile;
uint32_t mTicksUntilChange;
};
class FEA_API TileMap
{
struct AnimatedTile
{
AnimatedTile(TileId next, uint32_t timeLeft);
TileId mNext;
uint32_t mTimeLeft;
};
public:
TileMap(uint32_t gridWidth, uint32_t gridHeight, uint32_t tileWidth = 16, uint32_t tileHeight = 16, float textureTileWidth = 0.25f, float textureTileHeight = 0.25f , uint32_t chunkWidth = 32, uint32_t chunkHeight = 32);
void setPosition(const glm::vec2& position);
const glm::vec2& getPosition() const;
void translate(const glm::vec2& amount);
std::vector<const TileChunk*> getTileChunks() const;
void setTexture(const Texture& texture);
const Texture& getTexture() const;
void addTileDefinition(TileId id, const TileDefinition& tileDef);
void setTile(const glm::uvec2& pos, TileId id, int32_t orientation = NORMAL);
void unsetTile(const glm::uvec2& pos);
void fill(TileId id);
void setTileColor(const glm::uvec2& pos, const fea::Color& color);
void clear();
glm::uvec2 getTileByCoordinates(const glm::vec2& coordinates) const;
bool isOutOfBounds(const glm::uvec2& pos) const;
glm::uvec2 getTileSize() const;
glm::uvec2 getGridSize() const;
glm::uvec2 getTileMapSize() const;
void tick();
void setOpacity(float opacity);
float getOpacity() const;
void setRotation(float rotation);
float getRotation() const;
void rotate(float amount);
void setScale(const glm::vec2& scale);
const glm::vec2& getScale() const;
void scale(const glm::vec2& amount);
void setOrigin(const glm::vec2& origin);
const glm::vec2& getOrigin() const;
void setParallax(const glm::vec2& parallax);
const glm::vec2& getParallax() const;
void setColor(const Color& color);
Color getColor() const;
private:
glm::vec2 mPosition;
glm::uvec2 mChunkGridSize;
glm::uvec2 mChunkSize;
glm::uvec2 mTileSize;
glm::uvec2 mGridSize;
glm::vec2 mTextureTileSize;
std::vector<TileChunk> mChunks;
const Texture* mTexture;
std::unordered_map<TileId, TileDefinition> mTileDefs;
std::unordered_map<glm::uvec2, AnimatedTile> mAnimatedTiles;
};
/** @addtogroup Render2D
*@{
* @struct TileDefinition
* @class TileMap
*@}
***
* @struct TileDefinition
* @brief Data container describing a type of tile.
*
* Tile definition contains information about how a tile should be displayed and animated. The display information is coordinates of the tile texture.
*
* Animation works by simply switching to a different tile definition after a set amount of ticks. For instance, if a water animation involving two different tile images of water is needed, two tile definitions, one for each desired texture must be created. They are then setup so that the first tile switches to the other after a desired amount of ticks, and the second tile switches to the first. This will naturally create a cyclic animation.
*
* The animation data consists of the name of the next tile definition to switch to, and the amount of ticks it will take until the change is performed.
***
* @fn TileDefinition::TileDefinition(const glm::uvec2& texPos, TileId next = "", uint32_t ticks = 0)
* @brief Construct a TileDefinition.
* @param texPos Coordinates of the subrectangle to use as texture.
* @param next TileDefinition to change to. Only needed if the tile is animated.
* @param ticks Amount of ticks until the tile is changed. Only needed if the tile is animated.
***
* @var TileDefinition::mTileTexPosition
* @brief Coordinates describing the position of the subrect of the texture to use for this tile. For example if the map tile in the upper left corner is to be used, this variable should be (0,0). If the tile next to it is to be used, it should be (1,0).
***
* @var TileDefinition::mNextTile
* @brief If the tile is meant to be animated, this should be set to the name of the tile to switch to.
***
* @var TileDefinition::mTicksUntilChange
* @brief The amount of ticks to display this tile before it is changed to the one defined using TileDefinition::mNextTile.
***
* @class TileMap
* @brief Represents a graphical tile map with tiles that can be set freely and animated.
*
* Both the size of the grid and the individual tiles is customisable.
*
* This class is not a TileMap and can therefore not be rendered directly. It internally manages TileChunk instances which the whole tilemap is divided into. These have to be sent to the renderer for rendering. The size of the tile chunks is customisable.
***
* @fn TileMap::TileMap(uint32_t gridWidth, uint32_t gridHeight, uint32_t tileWidth = 16, uint32_t tileHeight = 16, float textureTileWidth = 0.25f, float textureTileHeight = 0.25f , uint32_t chunkWidth = 32, uint32_t chunkHeight = 32)
* @brief Construct a TileMap.
*
* Assert/undefined behavior when any of the input values are zero or below.
* @param gridWidth Amount of tiles on the X axis.
* @param gridHeight Amount of tiles on the Y axis.
* @param tileWidth Width of a single tile displayed on the screen in pixels with no scaling.
* @param tileHeight Height of a single tile displayed on the screen in pixels with no scaling.
* @param textureTileWidth Width of a tile in the texture image. Measured in percent of total texture width.
* @param textureTileHeight Height of a tile in the texture image. Measured in percent of total texture height.
* @param chunkWidth How many tiles on the X axis makes up a TileChunk.
* @param chunkHeight How many tiles on the Y axis makes up a TileChunk.
***
* @fn void TileMap::setPosition(const glm::vec2& position)
* @brief Set the position.
* @param position Vector containing the position.
***
* @fn const glm::vec2& TileMap::getPosition() const
* @brief Get the position.
* @return Vector containing the position.
***
* @fn void TileMap::translate(const glm::vec2& amount)
* @brief Move the TileMap using a vector.
* @param amount Vector containing the amount to move.
***
* @fn void TileMap::setOrigin(const glm::vec2& position)
* @brief Set the origin point of the TileMap, using a vector.
*
* The origin serves as the center point. This is where the object will be centered and all rotation and scaling will happen around this point. Also, if the position is set, the origin will be equivalent to that position.
* @param position Position to set the origin to.
***
* @fn const glm::vec2& TileMap::getOrigin() const
* @brief Get the origin point of the TileMap.
* @return Vector containing the origin.
***
* @fn void TileMap::setRotation(const float amount)
* @brief Set the rotation.
* @param rotation Rotation angle in radians.
***
* @fn float TileMap::getRotation() const
* @brief Get the current rotation.
* @return The rotation.
***
* @fn void TileMap::rotate(const float amount)
* @brief Rotate the TileMap a specific amount.
* @param amount Amount in radians to rotate the TileMap.
***
* @fn void TileMap::setScale(const glm::vec2& scale)
* @brief Set the scale factor using a vector.
* @param scale Vector containing the scale factor.
***
* @fn const glm::vec2& TileMap::getScale() const
* @brief Get the current scale.
* @return Vector containing the scale.
***
* @fn void TileMap::scale(const glm::vec2& amount)
* @brief Scale the TileMap using a vector.
* @param amount Scale factor.
***
* @fn void TileMap::setParallax(const glm::vec2& parallax)
* @brief Set the parallax factor for each x and y axis separately.
*
* The factor determines how much the drawable moves relative to the camera.
* A value of 1.0f is neutral, 0.5f is twice as slowly and 2.0f is twice as fast.
* @param parallax Parallax factor.
***
* @fn glm::vec2 TileMap::getParallax() const
* @brief Get the parallax factors as a vector.
* @return Parallax factor.
***
* @fn void TileMap::setOpacity(float opacity)
* @brief Set the opacity.
*
* Assert/undefined behavior if the values is not within the range of [0.0f,1.0f].
* @param opacity Opacity.
***
* @fn float TileMap::getOpacity() const
* @brief Get the opacity.
* @return Opacity.
***
* @fn Color TileMap::getColor() const
* @brief Get the color.
* @return The color of the drawable.
***
* @fn void TileMap::setColor(const Color& color)
* @brief Set the color.
* @param color Color to set to.
***
* @fn const std::vector<TileChunk>& TileMap::getTileChunks() const
* @brief Get a list of all TileChunk instances making up the TileMap.
*
* This function is what is used to render the TileMap. The list of the TileChunk instances can be iterated through, to pass the content to the rendered.
* @return List of tile chunks.
***
* @fn void TileMap::setTexture(const Texture& texture)
* @brief Set the texture to use.
* @param texture Texture.
***
* @fn const Texture& TileMap::getTexture() const
* @brief Get the current texture.
* @return Texture.
***
* @fn void TileMap::addTileDefinition(TileId id, const TileDefinition& tileDef)
* @brief Add a new tile definition.
*
* Before a tile is set, its type has to be registered with the TileMap using this function. It can then be accessed through the given id.
* @param id Id of the tile to add.
* @param tileDef Tile definition.
***
* @fn void TileMap::setTile(const glm::uvec2& position, TileId id, int32_t orientation = NORMAL)
* @brief Set a tile at the given coordinate.
*
* The tile can optionally be given a bitmask representing an orientation. In other words, several values can be provided using the | operator. Only one rotation can be given at a time. The possible orientation values are: V_FLIP, H_FLIP, ROT_90, ROT_180, ROT_270 and PRESERVE. V_FLIP and H_FLIP represent vertical and horizontal flipping of the tile respectively and the ROT_* values describe rotation to varios degrees. The PRESERVE flag preserves any previous orientation and must not be given along with other flags.
*
* Assert/undefined behavior when coordinates are outside the range of the tilemap, if tile name doesn't exist, or if the PRESERVE flag is passed with other values.
* @param position Coordinate of the tile to set,
* @param id Id of the tile definition to change it to.
* @param orientation Orientation of the tile.
***
* @fn void TileMap::unsetTile(const glm::uvec2& pos)
* @brief Set a tile to be transparent.
*
* This is the default state of tiles.
* Assert/undefined behavior when coordinates are outside the range of the tilemap.
* @param pos Coordinate of the tile to unset.
***
* @fn void TileMap::fill(TileId id)
* @brief Fill the whole tile map with a single tile type.
*
* Assert/undefined behavior when tile type doesn't exist.
* @param id Id of the tile to fill with.
***
* @fn void TileMap::setTileColor(const glm::uvec2& pos, const fea::Color& color)
* @brief Set the color shade of a tile.
*
* Assert/undefined behavior when tile is out of bounds.
* @param pos Location of the tile to colorize.
* @param color Color.
***
* @fn void TileMap::clear();
* @brief Clear the tile map of all tiles.
***
* @fn glm::uvec2 TileMap::getTileByCoordinates(const glm::vec2& coordinates) const
* @brief Get the tile coordinates for the given pixel coordinate on the TileMap.
*
* Assert/undefined behavior if coordinate is not within the bounds of the tilemap.
* @param coordinates Coordinate to check at.
* @return Tile coordinates.
***
* @fn bool TileMap::isOutOfBounds(const glm::uvec2& position) const
* @brief Checks if a tile is out of bounds.
* @param position Coordinate.
* @return True if the given tile coordinate is not within the tile grid.
***
* @fn void TileMap::tick()
* @brief Advance the animation clock by one step.
*
* This function needs to be called once every frame for the animations to work properly
***
* @fn glm::uvec2 TileMap::getTileSize() const
* @brief Get the size of a single tile.
* @return The tile size.
***
* @fn glm::uvec2 TileMap::getGridSize() const
* @brief Get the dimensions of the grid in tiles.
* @return The size of the grid.
***
* @fn glm::uvec2 TileMap::getTileMapSize() const
* @brief Get the total size of the whole tilemap.
*
* This will return the size of a single tile multiplied with the tile grid dimensions.
* @return Total size of the tilemap.
***/
}
|
/*=========================================================================
Program: Visualization Toolkit
Module: vtkOpenGLShaderCache.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkOpenGLShaderCache.h"
#include "vtk_glew.h"
#include "vtkObjectFactory.h"
#include "vtkOpenGLError.h"
#include "vtkOpenGLRenderWindow.h"
#include "vtkShader.h"
#include "vtkShaderProgram.h"
#include "vtkOpenGLHelper.h"
#include <cmath>
#include <sstream>
#include "vtksys/MD5.h"
class vtkOpenGLShaderCache::Private
{
public:
vtksysMD5* md5;
// map of hash to shader program structs
std::map<std::string, vtkShaderProgram *> ShaderPrograms;
Private()
{
md5 = vtksysMD5_New();
}
~Private()
{
vtksysMD5_Delete(this->md5);
}
//-----------------------------------------------------------------------------
void ComputeMD5(const char* content,
const char* content2,
const char* content3,
std::string &hash)
{
unsigned char digest[16];
char md5Hash[33];
md5Hash[32] = '\0';
vtksysMD5_Initialize(this->md5);
if (content)
{
vtksysMD5_Append(this->md5,
reinterpret_cast<const unsigned char *>(content),
(int)strlen(content));
}
if (content2)
{
vtksysMD5_Append(this->md5,
reinterpret_cast<const unsigned char *>(content2),
(int)strlen(content2));
}
if (content3)
{
vtksysMD5_Append(this->md5,
reinterpret_cast<const unsigned char *>(content3),
(int)strlen(content3));
}
vtksysMD5_Finalize(this->md5, digest);
vtksysMD5_DigestToHex(digest, md5Hash);
hash = md5Hash;
}
};
// ----------------------------------------------------------------------------
vtkStandardNewMacro(vtkOpenGLShaderCache);
// ----------------------------------------------------------------------------
vtkOpenGLShaderCache::vtkOpenGLShaderCache() : Internal(new Private)
{
this->LastShaderBound = nullptr;
this->OpenGLMajorVersion = 0;
this->OpenGLMinorVersion = 0;
}
// ----------------------------------------------------------------------------
vtkOpenGLShaderCache::~vtkOpenGLShaderCache()
{
typedef std::map<std::string,vtkShaderProgram*>::const_iterator SMapIter;
SMapIter iter = this->Internal->ShaderPrograms.begin();
for ( ; iter != this->Internal->ShaderPrograms.end(); ++iter)
{
iter->second->Delete();
}
delete this->Internal;
}
// perform System and Output replacements
unsigned int vtkOpenGLShaderCache::ReplaceShaderValues(
std::string &VSSource,
std::string &FSSource,
std::string &GSSource)
{
// first handle renaming any Fragment shader inputs
// if we have a geometry shader. By default fragment shaders
// assume their inputs come from a Vertex Shader. When we
// have a Geometry shader we rename the frament shader inputs
// to come from the geometry shader
if (!GSSource.empty())
{
vtkShaderProgram::Substitute(FSSource,"VSOut","GSOut");
}
#ifdef GL_ES_VERSION_3_0
std::string version = "#version 300 es\n";
#else
if (!this->OpenGLMajorVersion)
{
this->OpenGLMajorVersion = 3;
this->OpenGLMinorVersion = 2;
glGetIntegerv(GL_MAJOR_VERSION, & this->OpenGLMajorVersion);
glGetIntegerv(GL_MINOR_VERSION, & this->OpenGLMinorVersion);
}
std::string version = "#version 150\n";
if (this->OpenGLMajorVersion == 3 && this->OpenGLMinorVersion == 1)
{
version = "#version 140\n";
}
#endif
vtkShaderProgram::Substitute(VSSource,"//VTK::System::Dec",
version +
"#ifndef GL_ES\n"
"#define highp\n"
"#define mediump\n"
"#define lowp\n"
"#endif // GL_ES\n"
"#define attribute in\n" // to be safe
"#define varying out\n" // to be safe
);
vtkShaderProgram::Substitute(FSSource,"//VTK::System::Dec",
version +
"#ifdef GL_ES\n"
"#ifdef GL_FRAGMENT_PRECISION_HIGH\n"
"precision highp float;\n"
"precision highp sampler2D;\n"
"precision highp sampler3D;\n"
"#else\n"
"precision mediump float;\n"
"precision mediump sampler2D;\n"
"precision mediump sampler3D;\n"
"#endif\n"
"#define texelFetchBuffer texelFetch\n"
"#define texture1D texture\n"
"#define texture2D texture\n"
"#define texture3D texture\n"
"#else // GL_ES\n"
"#define highp\n"
"#define mediump\n"
"#define lowp\n"
"#if __VERSION__ == 150\n"
"#define texelFetchBuffer texelFetch\n"
"#define texture1D texture\n"
"#define texture2D texture\n"
"#define texture3D texture\n"
"#endif\n"
"#endif // GL_ES\n"
"#define varying in\n" // to be safe
);
vtkShaderProgram::Substitute(GSSource,"//VTK::System::Dec",
version +
"#ifdef GL_ES\n"
"#ifdef GL_FRAGMENT_PRECISION_HIGH\n"
"precision highp float;\n"
"#else\n"
"precision mediump float;\n"
"#endif\n"
"#else // GL_ES\n"
"#define highp\n"
"#define mediump\n"
"#define lowp\n"
"#endif // GL_ES\n"
);
unsigned int count = 0;
std::string fragDecls;
bool done = false;
while (!done)
{
std::ostringstream src;
std::ostringstream dst;
src << "gl_FragData[" << count << "]";
// this naming has to match the bindings
// in vtkOpenGLShaderProgram.cxx
dst << "fragOutput" << count;
done = !vtkShaderProgram::Substitute(FSSource, src.str(),dst.str());
if (!done)
{
#ifdef GL_ES_VERSION_3_0
src.str("");
src.clear();
src << count;
fragDecls += "layout(location = " + src.str() + ") ";
#endif
fragDecls += "out vec4 " + dst.str() + ";\n";
count++;
}
}
vtkShaderProgram::Substitute(FSSource,"//VTK::Output::Dec",fragDecls);
return count;
}
vtkShaderProgram *vtkOpenGLShaderCache::ReadyShaderProgram(
std::map<vtkShader::Type,vtkShader *> shaders,
vtkTransformFeedback *cap)
{
std::string VSSource = shaders[vtkShader::Vertex]->GetSource();
std::string FSSource = shaders[vtkShader::Fragment]->GetSource();
std::string GSSource = shaders[vtkShader::Geometry]->GetSource();
unsigned int count =
this->ReplaceShaderValues(VSSource,FSSource,GSSource);
shaders[vtkShader::Vertex]->SetSource(VSSource);
shaders[vtkShader::Fragment]->SetSource(FSSource);
shaders[vtkShader::Geometry]->SetSource(GSSource);
vtkShaderProgram *shader = this->GetShaderProgram(shaders);
shader->SetNumberOfOutputs(count);
return this->ReadyShaderProgram(shader, cap);
}
// return nullptr if there is an issue
vtkShaderProgram *vtkOpenGLShaderCache::ReadyShaderProgram(
const char *vertexCode, const char *fragmentCode, const char *geometryCode,
vtkTransformFeedback *cap)
{
// perform system wide shader replacements
// desktops to not use precision statements
std::string VSSource = vertexCode;
std::string FSSource = fragmentCode;
std::string GSSource = geometryCode;
unsigned int count =
this->ReplaceShaderValues(VSSource,FSSource,GSSource);
vtkShaderProgram *shader =
this->GetShaderProgram(
VSSource.c_str(), FSSource.c_str(), GSSource.c_str());
shader->SetNumberOfOutputs(count);
return this->ReadyShaderProgram(shader, cap);
}
// return nullptr if there is an issue
vtkShaderProgram *vtkOpenGLShaderCache::ReadyShaderProgram(
vtkShaderProgram *shader, vtkTransformFeedback *cap)
{
if (!shader)
{
return nullptr;
}
if (shader->GetTransformFeedback() != cap)
{
this->ReleaseCurrentShader();
shader->ReleaseGraphicsResources(nullptr);
shader->SetTransformFeedback(cap);
}
// compile if needed
if (!shader->GetCompiled() && !shader->CompileShader())
{
return nullptr;
}
// bind if needed
if (!this->BindShader(shader))
{
return nullptr;
}
return shader;
}
vtkShaderProgram *vtkOpenGLShaderCache::GetShaderProgram(
std::map<vtkShader::Type,vtkShader *> shaders)
{
// compute the MD5 and the check the map
std::string result;
this->Internal->ComputeMD5(
shaders[vtkShader::Vertex]->GetSource().c_str(),
shaders[vtkShader::Fragment]->GetSource().c_str(),
shaders[vtkShader::Geometry]->GetSource().c_str(), result);
// does it already exist?
typedef std::map<std::string,vtkShaderProgram*>::const_iterator SMapIter;
SMapIter found = this->Internal->ShaderPrograms.find(result);
if (found == this->Internal->ShaderPrograms.end())
{
// create one
vtkShaderProgram *sps = vtkShaderProgram::New();
sps->SetVertexShader(shaders[vtkShader::Vertex]);
sps->SetFragmentShader(shaders[vtkShader::Fragment]);
sps->SetGeometryShader(shaders[vtkShader::Geometry]);
sps->SetMD5Hash(result); // needed?
this->Internal->ShaderPrograms.insert(std::make_pair(result, sps));
return sps;
}
else
{
return found->second;
}
}
vtkShaderProgram *vtkOpenGLShaderCache::GetShaderProgram(
const char *vertexCode,
const char *fragmentCode,
const char *geometryCode)
{
// compute the MD5 and the check the map
std::string result;
this->Internal->ComputeMD5(vertexCode, fragmentCode, geometryCode, result);
// does it already exist?
typedef std::map<std::string,vtkShaderProgram*>::const_iterator SMapIter;
SMapIter found = this->Internal->ShaderPrograms.find(result);
if (found == this->Internal->ShaderPrograms.end())
{
// create one
vtkShaderProgram *sps = vtkShaderProgram::New();
sps->GetVertexShader()->SetSource(vertexCode);
sps->GetFragmentShader()->SetSource(fragmentCode);
if (geometryCode != nullptr)
{
sps->GetGeometryShader()->SetSource(geometryCode);
}
sps->SetMD5Hash(result); // needed?
this->Internal->ShaderPrograms.insert(std::make_pair(result, sps));
return sps;
}
else
{
return found->second;
}
}
void vtkOpenGLShaderCache::ReleaseGraphicsResources(vtkWindow *win)
{
// NOTE:
// In the current implementation as of October 26th, if a shader
// program is created by ShaderCache then it should make sure
// that it releases the graphics resources used by these programs.
// It is not wisely for callers to do that since then they would
// have to loop over all the programs were in use and invoke
// release graphics resources individually.
this->ReleaseCurrentShader();
typedef std::map<std::string,vtkShaderProgram*>::const_iterator SMapIter;
SMapIter iter = this->Internal->ShaderPrograms.begin();
for ( ; iter != this->Internal->ShaderPrograms.end(); ++iter)
{
iter->second->ReleaseGraphicsResources(win);
}
this->OpenGLMajorVersion = 0;
}
void vtkOpenGLShaderCache::ReleaseCurrentShader()
{
// release prior shader
if (this->LastShaderBound)
{
this->LastShaderBound->Release();
this->LastShaderBound = nullptr;
}
}
int vtkOpenGLShaderCache::BindShader(vtkShaderProgram* shader)
{
if (this->LastShaderBound == shader)
{
return 1;
}
// release prior shader
if (this->LastShaderBound)
{
this->LastShaderBound->Release();
}
shader->Bind();
this->LastShaderBound = shader;
return 1;
}
// ----------------------------------------------------------------------------
void vtkOpenGLShaderCache::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
}
|
// Copyright 2013 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/objects/keys.h"
#include "src/api/api-arguments-inl.h"
#include "src/execution/isolate-inl.h"
#include "src/handles/handles-inl.h"
#include "src/heap/factory.h"
#include "src/objects/api-callbacks.h"
#include "src/objects/elements-inl.h"
#include "src/objects/field-index-inl.h"
#include "src/objects/hash-table-inl.h"
#include "src/objects/module-inl.h"
#include "src/objects/objects-inl.h"
#include "src/objects/ordered-hash-table-inl.h"
#include "src/objects/property-descriptor.h"
#include "src/objects/prototype.h"
#include "src/utils/identity-map.h"
#include "src/zone/zone-hashmap.h"
namespace v8 {
namespace internal {
#define RETURN_NOTHING_IF_NOT_SUCCESSFUL(call) \
do { \
if (!(call)) return Nothing<bool>(); \
} while (false)
#define RETURN_FAILURE_IF_NOT_SUCCESSFUL(call) \
do { \
ExceptionStatus status_enum_result = (call); \
if (!status_enum_result) return status_enum_result; \
} while (false)
namespace {
static bool ContainsOnlyValidKeys(Handle<FixedArray> array) {
int len = array->length();
for (int i = 0; i < len; i++) {
Object e = array->get(i);
if (!(e.IsName() || e.IsNumber())) return false;
}
return true;
}
static int AddKey(Object key, Handle<FixedArray> combined_keys,
Handle<DescriptorArray> descs, int nof_descriptors,
int target) {
for (InternalIndex i : InternalIndex::Range(nof_descriptors)) {
if (descs->GetKey(i) == key) return 0;
}
combined_keys->set(target, key);
return 1;
}
static Handle<FixedArray> CombineKeys(Isolate* isolate,
Handle<FixedArray> own_keys,
Handle<FixedArray> prototype_chain_keys,
Handle<JSReceiver> receiver,
bool may_have_elements) {
int prototype_chain_keys_length = prototype_chain_keys->length();
if (prototype_chain_keys_length == 0) return own_keys;
Map map = receiver->map();
int nof_descriptors = map.NumberOfOwnDescriptors();
if (nof_descriptors == 0 && !may_have_elements) return prototype_chain_keys;
Handle<DescriptorArray> descs(map.instance_descriptors(), isolate);
int own_keys_length = own_keys.is_null() ? 0 : own_keys->length();
Handle<FixedArray> combined_keys = isolate->factory()->NewFixedArray(
own_keys_length + prototype_chain_keys_length);
if (own_keys_length != 0) {
own_keys->CopyTo(0, *combined_keys, 0, own_keys_length);
}
int target_keys_length = own_keys_length;
for (int i = 0; i < prototype_chain_keys_length; i++) {
target_keys_length += AddKey(prototype_chain_keys->get(i), combined_keys,
descs, nof_descriptors, target_keys_length);
}
return FixedArray::ShrinkOrEmpty(isolate, combined_keys, target_keys_length);
}
} // namespace
// static
MaybeHandle<FixedArray> KeyAccumulator::GetKeys(
Handle<JSReceiver> object, KeyCollectionMode mode, PropertyFilter filter,
GetKeysConversion keys_conversion, bool is_for_in, bool skip_indices) {
Isolate* isolate = object->GetIsolate();
FastKeyAccumulator accumulator(isolate, object, mode, filter, is_for_in,
skip_indices);
return accumulator.GetKeys(keys_conversion);
}
Handle<FixedArray> KeyAccumulator::GetKeys(GetKeysConversion convert) {
if (keys_.is_null()) {
return isolate_->factory()->empty_fixed_array();
}
if (mode_ == KeyCollectionMode::kOwnOnly &&
keys_->map() == ReadOnlyRoots(isolate_).fixed_array_map()) {
return Handle<FixedArray>::cast(keys_);
}
USE(ContainsOnlyValidKeys);
Handle<FixedArray> result =
OrderedHashSet::ConvertToKeysArray(isolate(), keys(), convert);
DCHECK(ContainsOnlyValidKeys(result));
if (try_prototype_info_cache_ && !first_prototype_map_.is_null()) {
PrototypeInfo::cast(first_prototype_map_->prototype_info())
.set_prototype_chain_enum_cache(*result);
Map::GetOrCreatePrototypeChainValidityCell(
Handle<Map>(receiver_->map(), isolate_), isolate_);
DCHECK(first_prototype_map_->IsPrototypeValidityCellValid());
}
return result;
}
Handle<OrderedHashSet> KeyAccumulator::keys() {
return Handle<OrderedHashSet>::cast(keys_);
}
ExceptionStatus KeyAccumulator::AddKey(Object key, AddKeyConversion convert) {
return AddKey(handle(key, isolate_), convert);
}
ExceptionStatus KeyAccumulator::AddKey(Handle<Object> key,
AddKeyConversion convert) {
if (filter_ == PRIVATE_NAMES_ONLY) {
if (!key->IsSymbol()) return ExceptionStatus::kSuccess;
if (!Symbol::cast(*key).is_private_name()) return ExceptionStatus::kSuccess;
} else if (key->IsSymbol()) {
if (filter_ & SKIP_SYMBOLS) return ExceptionStatus::kSuccess;
if (Symbol::cast(*key).is_private()) return ExceptionStatus::kSuccess;
} else if (filter_ & SKIP_STRINGS) {
return ExceptionStatus::kSuccess;
}
if (IsShadowed(key)) return ExceptionStatus::kSuccess;
if (keys_.is_null()) {
keys_ = OrderedHashSet::Allocate(isolate_, 16).ToHandleChecked();
}
uint32_t index;
if (convert == CONVERT_TO_ARRAY_INDEX && key->IsString() &&
Handle<String>::cast(key)->AsArrayIndex(&index)) {
key = isolate_->factory()->NewNumberFromUint(index);
}
MaybeHandle<OrderedHashSet> new_set_candidate =
OrderedHashSet::Add(isolate(), keys(), key);
Handle<OrderedHashSet> new_set;
if (!new_set_candidate.ToHandle(&new_set)) {
THROW_NEW_ERROR_RETURN_VALUE(
isolate_, NewRangeError(MessageTemplate::kTooManyProperties),
ExceptionStatus::kException);
}
if (*new_set != *keys_) {
// The keys_ Set is converted directly to a FixedArray in GetKeys which can
// be left-trimmer. Hence the previous Set should not keep a pointer to the
// new one.
keys_->set(OrderedHashSet::NextTableIndex(), Smi::zero());
keys_ = new_set;
}
return ExceptionStatus::kSuccess;
}
ExceptionStatus KeyAccumulator::AddKeys(Handle<FixedArray> array,
AddKeyConversion convert) {
int add_length = array->length();
for (int i = 0; i < add_length; i++) {
Handle<Object> current(array->get(i), isolate_);
RETURN_FAILURE_IF_NOT_SUCCESSFUL(AddKey(current, convert));
}
return ExceptionStatus::kSuccess;
}
ExceptionStatus KeyAccumulator::AddKeys(Handle<JSObject> array_like,
AddKeyConversion convert) {
DCHECK(array_like->IsJSArray() || array_like->HasSloppyArgumentsElements());
ElementsAccessor* accessor = array_like->GetElementsAccessor();
return accessor->AddElementsToKeyAccumulator(array_like, this, convert);
}
MaybeHandle<FixedArray> FilterProxyKeys(KeyAccumulator* accumulator,
Handle<JSProxy> owner,
Handle<FixedArray> keys,
PropertyFilter filter) {
if (filter == ALL_PROPERTIES) {
// Nothing to do.
return keys;
}
Isolate* isolate = accumulator->isolate();
int store_position = 0;
for (int i = 0; i < keys->length(); ++i) {
Handle<Name> key(Name::cast(keys->get(i)), isolate);
if (key->FilterKey(filter)) continue; // Skip this key.
if (filter & ONLY_ENUMERABLE) {
PropertyDescriptor desc;
Maybe<bool> found =
JSProxy::GetOwnPropertyDescriptor(isolate, owner, key, &desc);
MAYBE_RETURN(found, MaybeHandle<FixedArray>());
if (!found.FromJust()) continue;
if (!desc.enumerable()) {
accumulator->AddShadowingKey(key);
continue;
}
}
// Keep this key.
if (store_position != i) {
keys->set(store_position, *key);
}
store_position++;
}
return FixedArray::ShrinkOrEmpty(isolate, keys, store_position);
}
// Returns "nothing" in case of exception, "true" on success.
Maybe<bool> KeyAccumulator::AddKeysFromJSProxy(Handle<JSProxy> proxy,
Handle<FixedArray> keys) {
// Postpone the enumerable check for for-in to the ForInFilter step.
if (!is_for_in_) {
ASSIGN_RETURN_ON_EXCEPTION_VALUE(
isolate_, keys, FilterProxyKeys(this, proxy, keys, filter_),
Nothing<bool>());
if (mode_ == KeyCollectionMode::kOwnOnly) {
// If we collect only the keys from a JSProxy do not sort or deduplicate.
keys_ = keys;
return Just(true);
}
}
RETURN_NOTHING_IF_NOT_SUCCESSFUL(
AddKeys(keys, is_for_in_ ? CONVERT_TO_ARRAY_INDEX : DO_NOT_CONVERT));
return Just(true);
}
Maybe<bool> KeyAccumulator::CollectKeys(Handle<JSReceiver> receiver,
Handle<JSReceiver> object) {
// Proxies have no hidden prototype and we should not trigger the
// [[GetPrototypeOf]] trap on the last iteration when using
// AdvanceFollowingProxies.
if (mode_ == KeyCollectionMode::kOwnOnly && object->IsJSProxy()) {
MAYBE_RETURN(CollectOwnJSProxyKeys(receiver, Handle<JSProxy>::cast(object)),
Nothing<bool>());
return Just(true);
}
PrototypeIterator::WhereToEnd end = mode_ == KeyCollectionMode::kOwnOnly
? PrototypeIterator::END_AT_NON_HIDDEN
: PrototypeIterator::END_AT_NULL;
for (PrototypeIterator iter(isolate_, object, kStartAtReceiver, end);
!iter.IsAtEnd();) {
// Start the shadow checks only after the first prototype has added
// shadowing keys.
if (HasShadowingKeys()) skip_shadow_check_ = false;
Handle<JSReceiver> current =
PrototypeIterator::GetCurrent<JSReceiver>(iter);
Maybe<bool> result = Just(false); // Dummy initialization.
if (current->IsJSProxy()) {
result = CollectOwnJSProxyKeys(receiver, Handle<JSProxy>::cast(current));
} else {
DCHECK(current->IsJSObject());
result = CollectOwnKeys(receiver, Handle<JSObject>::cast(current));
}
MAYBE_RETURN(result, Nothing<bool>());
if (!result.FromJust()) break; // |false| means "stop iterating".
// Iterate through proxies but ignore access checks for the ALL_CAN_READ
// case on API objects for OWN_ONLY keys handled in CollectOwnKeys.
if (!iter.AdvanceFollowingProxiesIgnoringAccessChecks()) {
return Nothing<bool>();
}
if (!last_non_empty_prototype_.is_null() &&
*last_non_empty_prototype_ == *current) {
break;
}
}
return Just(true);
}
bool KeyAccumulator::HasShadowingKeys() { return !shadowing_keys_.is_null(); }
bool KeyAccumulator::IsShadowed(Handle<Object> key) {
if (!HasShadowingKeys() || skip_shadow_check_) return false;
return shadowing_keys_->Has(isolate_, key);
}
void KeyAccumulator::AddShadowingKey(Object key,
AllowHeapAllocation* allow_gc) {
if (mode_ == KeyCollectionMode::kOwnOnly) return;
AddShadowingKey(handle(key, isolate_));
}
void KeyAccumulator::AddShadowingKey(Handle<Object> key) {
if (mode_ == KeyCollectionMode::kOwnOnly) return;
if (shadowing_keys_.is_null()) {
shadowing_keys_ = ObjectHashSet::New(isolate_, 16);
}
shadowing_keys_ = ObjectHashSet::Add(isolate(), shadowing_keys_, key);
}
namespace {
void TrySettingEmptyEnumCache(JSReceiver object) {
Map map = object.map();
DCHECK_EQ(kInvalidEnumCacheSentinel, map.EnumLength());
if (!map.OnlyHasSimpleProperties()) return;
if (map.IsJSProxyMap()) return;
if (map.NumberOfEnumerableProperties() > 0) return;
DCHECK(object.IsJSObject());
map.SetEnumLength(0);
}
bool CheckAndInitalizeEmptyEnumCache(JSReceiver object) {
if (object.map().EnumLength() == kInvalidEnumCacheSentinel) {
TrySettingEmptyEnumCache(object);
}
if (object.map().EnumLength() != 0) return false;
DCHECK(object.IsJSObject());
return !JSObject::cast(object).HasEnumerableElements();
}
} // namespace
void FastKeyAccumulator::Prepare() {
DisallowHeapAllocation no_gc;
// Directly go for the fast path for OWN_ONLY keys.
if (mode_ == KeyCollectionMode::kOwnOnly) return;
// Fully walk the prototype chain and find the last prototype with keys.
is_receiver_simple_enum_ = false;
has_empty_prototype_ = true;
only_own_has_simple_elements_ =
!receiver_->map().IsCustomElementsReceiverMap();
JSReceiver last_prototype;
may_have_elements_ = MayHaveElements(*receiver_);
for (PrototypeIterator iter(isolate_, *receiver_); !iter.IsAtEnd();
iter.Advance()) {
JSReceiver current = iter.GetCurrent<JSReceiver>();
if (!may_have_elements_ || only_own_has_simple_elements_) {
if (MayHaveElements(current)) {
may_have_elements_ = true;
only_own_has_simple_elements_ = false;
}
}
bool has_no_properties = CheckAndInitalizeEmptyEnumCache(current);
if (has_no_properties) continue;
last_prototype = current;
has_empty_prototype_ = false;
}
// Check if we should try to create/use prototype info cache.
try_prototype_info_cache_ = TryPrototypeInfoCache(receiver_);
if (has_prototype_info_cache_) return;
if (has_empty_prototype_) {
is_receiver_simple_enum_ =
receiver_->map().EnumLength() != kInvalidEnumCacheSentinel &&
!JSObject::cast(*receiver_).HasEnumerableElements();
} else if (!last_prototype.is_null()) {
last_non_empty_prototype_ = handle(last_prototype, isolate_);
}
}
namespace {
Handle<FixedArray> ReduceFixedArrayTo(Isolate* isolate,
Handle<FixedArray> array, int length) {
DCHECK_LE(length, array->length());
if (array->length() == length) return array;
return isolate->factory()->CopyFixedArrayUpTo(array, length);
}
// Initializes and directly returns the enume cache. Users of this function
// have to make sure to never directly leak the enum cache.
Handle<FixedArray> GetFastEnumPropertyKeys(Isolate* isolate,
Handle<JSObject> object) {
Handle<Map> map(object->map(), isolate);
Handle<FixedArray> keys(map->instance_descriptors().enum_cache().keys(),
isolate);
// Check if the {map} has a valid enum length, which implies that it
// must have a valid enum cache as well.
int enum_length = map->EnumLength();
if (enum_length != kInvalidEnumCacheSentinel) {
DCHECK(map->OnlyHasSimpleProperties());
DCHECK_LE(enum_length, keys->length());
DCHECK_EQ(enum_length, map->NumberOfEnumerableProperties());
isolate->counters()->enum_cache_hits()->Increment();
return ReduceFixedArrayTo(isolate, keys, enum_length);
}
// Determine the actual number of enumerable properties of the {map}.
enum_length = map->NumberOfEnumerableProperties();
// Check if there's already a shared enum cache on the {map}s
// DescriptorArray with sufficient number of entries.
if (enum_length <= keys->length()) {
if (map->OnlyHasSimpleProperties()) map->SetEnumLength(enum_length);
isolate->counters()->enum_cache_hits()->Increment();
return ReduceFixedArrayTo(isolate, keys, enum_length);
}
Handle<DescriptorArray> descriptors =
Handle<DescriptorArray>(map->instance_descriptors(), isolate);
isolate->counters()->enum_cache_misses()->Increment();
// Create the keys array.
int index = 0;
bool fields_only = true;
keys = isolate->factory()->NewFixedArray(enum_length);
for (InternalIndex i : map->IterateOwnDescriptors()) {
DisallowHeapAllocation no_gc;
PropertyDetails details = descriptors->GetDetails(i);
if (details.IsDontEnum()) continue;
Object key = descriptors->GetKey(i);
if (key.IsSymbol()) continue;
keys->set(index, key);
if (details.location() != kField) fields_only = false;
index++;
}
DCHECK_EQ(index, keys->length());
// Optionally also create the indices array.
Handle<FixedArray> indices = isolate->factory()->empty_fixed_array();
if (fields_only) {
indices = isolate->factory()->NewFixedArray(enum_length);
index = 0;
for (InternalIndex i : map->IterateOwnDescriptors()) {
DisallowHeapAllocation no_gc;
PropertyDetails details = descriptors->GetDetails(i);
if (details.IsDontEnum()) continue;
Object key = descriptors->GetKey(i);
if (key.IsSymbol()) continue;
DCHECK_EQ(kData, details.kind());
DCHECK_EQ(kField, details.location());
FieldIndex field_index = FieldIndex::ForDescriptor(*map, i);
indices->set(index, Smi::FromInt(field_index.GetLoadByFieldIndex()));
index++;
}
DCHECK_EQ(index, indices->length());
}
DescriptorArray::InitializeOrChangeEnumCache(descriptors, isolate, keys,
indices);
if (map->OnlyHasSimpleProperties()) map->SetEnumLength(enum_length);
return keys;
}
template <bool fast_properties>
MaybeHandle<FixedArray> GetOwnKeysWithElements(Isolate* isolate,
Handle<JSObject> object,
GetKeysConversion convert,
bool skip_indices) {
Handle<FixedArray> keys;
ElementsAccessor* accessor = object->GetElementsAccessor();
if (fast_properties) {
keys = GetFastEnumPropertyKeys(isolate, object);
} else {
// TODO(cbruni): preallocate big enough array to also hold elements.
keys = KeyAccumulator::GetOwnEnumPropertyKeys(isolate, object);
}
MaybeHandle<FixedArray> result;
if (skip_indices) {
result = keys;
} else {
result =
accessor->PrependElementIndices(object, keys, convert, ONLY_ENUMERABLE);
}
if (FLAG_trace_for_in_enumerate) {
PrintF("| strings=%d symbols=0 elements=%u || prototypes>=1 ||\n",
keys->length(), result.ToHandleChecked()->length() - keys->length());
}
return result;
}
} // namespace
MaybeHandle<FixedArray> FastKeyAccumulator::GetKeys(
GetKeysConversion keys_conversion) {
// TODO(v8:9401): We should extend the fast path of KeyAccumulator::GetKeys to
// also use fast path even when filter = SKIP_SYMBOLS. We used to pass wrong
// filter to use fast path in cases where we tried to verify all properties
// are enumerable. However these checks weren't correct and passing the wrong
// filter led to wrong behaviour.
if (filter_ == ENUMERABLE_STRINGS) {
Handle<FixedArray> keys;
if (GetKeysFast(keys_conversion).ToHandle(&keys)) {
return keys;
}
if (isolate_->has_pending_exception()) return MaybeHandle<FixedArray>();
}
if (try_prototype_info_cache_) {
return GetKeysWithPrototypeInfoCache(keys_conversion);
}
return GetKeysSlow(keys_conversion);
}
MaybeHandle<FixedArray> FastKeyAccumulator::GetKeysFast(
GetKeysConversion keys_conversion) {
bool own_only = has_empty_prototype_ || mode_ == KeyCollectionMode::kOwnOnly;
Map map = receiver_->map();
if (!own_only || map.IsCustomElementsReceiverMap()) {
return MaybeHandle<FixedArray>();
}
// From this point on we are certain to only collect own keys.
DCHECK(receiver_->IsJSObject());
Handle<JSObject> object = Handle<JSObject>::cast(receiver_);
// Do not try to use the enum-cache for dict-mode objects.
if (map.is_dictionary_map()) {
return GetOwnKeysWithElements<false>(isolate_, object, keys_conversion,
skip_indices_);
}
int enum_length = receiver_->map().EnumLength();
if (enum_length == kInvalidEnumCacheSentinel) {
Handle<FixedArray> keys;
// Try initializing the enum cache and return own properties.
if (GetOwnKeysWithUninitializedEnumCache().ToHandle(&keys)) {
if (FLAG_trace_for_in_enumerate) {
PrintF("| strings=%d symbols=0 elements=0 || prototypes>=1 ||\n",
keys->length());
}
is_receiver_simple_enum_ =
object->map().EnumLength() != kInvalidEnumCacheSentinel;
return keys;
}
}
// The properties-only case failed because there were probably elements on the
// receiver.
return GetOwnKeysWithElements<true>(isolate_, object, keys_conversion,
skip_indices_);
}
MaybeHandle<FixedArray>
FastKeyAccumulator::GetOwnKeysWithUninitializedEnumCache() {
Handle<JSObject> object = Handle<JSObject>::cast(receiver_);
// Uninitalized enum cache
Map map = object->map();
if (object->elements() != ReadOnlyRoots(isolate_).empty_fixed_array() &&
object->elements() !=
ReadOnlyRoots(isolate_).empty_slow_element_dictionary()) {
// Assume that there are elements.
return MaybeHandle<FixedArray>();
}
int number_of_own_descriptors = map.NumberOfOwnDescriptors();
if (number_of_own_descriptors == 0) {
map.SetEnumLength(0);
return isolate_->factory()->empty_fixed_array();
}
// We have no elements but possibly enumerable property keys, hence we can
// directly initialize the enum cache.
Handle<FixedArray> keys = GetFastEnumPropertyKeys(isolate_, object);
if (is_for_in_) return keys;
// Do not leak the enum cache as it might end up as an elements backing store.
return isolate_->factory()->CopyFixedArray(keys);
}
MaybeHandle<FixedArray> FastKeyAccumulator::GetKeysSlow(
GetKeysConversion keys_conversion) {
KeyAccumulator accumulator(isolate_, mode_, filter_);
accumulator.set_is_for_in(is_for_in_);
accumulator.set_skip_indices(skip_indices_);
accumulator.set_last_non_empty_prototype(last_non_empty_prototype_);
accumulator.set_may_have_elements(may_have_elements_);
accumulator.set_first_prototype_map(first_prototype_map_);
accumulator.set_try_prototype_info_cache(try_prototype_info_cache_);
MAYBE_RETURN(accumulator.CollectKeys(receiver_, receiver_),
MaybeHandle<FixedArray>());
return accumulator.GetKeys(keys_conversion);
}
MaybeHandle<FixedArray> FastKeyAccumulator::GetKeysWithPrototypeInfoCache(
GetKeysConversion keys_conversion) {
Handle<FixedArray> own_keys;
if (may_have_elements_) {
MaybeHandle<FixedArray> maybe_own_keys;
if (receiver_->map().is_dictionary_map()) {
maybe_own_keys = GetOwnKeysWithElements<false>(
isolate_, Handle<JSObject>::cast(receiver_), keys_conversion,
skip_indices_);
} else {
maybe_own_keys = GetOwnKeysWithElements<true>(
isolate_, Handle<JSObject>::cast(receiver_), keys_conversion,
skip_indices_);
}
ASSIGN_RETURN_ON_EXCEPTION(isolate_, own_keys, maybe_own_keys, FixedArray);
} else {
own_keys = KeyAccumulator::GetOwnEnumPropertyKeys(
isolate_, Handle<JSObject>::cast(receiver_));
}
Handle<FixedArray> prototype_chain_keys;
if (has_prototype_info_cache_) {
prototype_chain_keys =
handle(FixedArray::cast(
PrototypeInfo::cast(first_prototype_map_->prototype_info())
.prototype_chain_enum_cache()),
isolate_);
} else {
KeyAccumulator accumulator(isolate_, mode_, filter_);
accumulator.set_is_for_in(is_for_in_);
accumulator.set_skip_indices(skip_indices_);
accumulator.set_last_non_empty_prototype(last_non_empty_prototype_);
accumulator.set_may_have_elements(may_have_elements_);
accumulator.set_receiver(receiver_);
accumulator.set_first_prototype_map(first_prototype_map_);
accumulator.set_try_prototype_info_cache(try_prototype_info_cache_);
MAYBE_RETURN(accumulator.CollectKeys(first_prototype_, first_prototype_),
MaybeHandle<FixedArray>());
prototype_chain_keys = accumulator.GetKeys(keys_conversion);
}
Handle<FixedArray> result = CombineKeys(
isolate_, own_keys, prototype_chain_keys, receiver_, may_have_elements_);
if (is_for_in_ && own_keys.is_identical_to(result)) {
// Don't leak the enumeration cache without the receiver since it might get
// trimmed otherwise.
return isolate_->factory()->CopyFixedArrayUpTo(result, result->length());
}
return result;
}
bool FastKeyAccumulator::MayHaveElements(JSReceiver receiver) {
if (!receiver.IsJSObject()) return true;
JSObject object = JSObject::cast(receiver);
if (object.HasEnumerableElements()) return true;
if (object.HasIndexedInterceptor()) return true;
return false;
}
bool FastKeyAccumulator::TryPrototypeInfoCache(Handle<JSReceiver> receiver) {
if (may_have_elements_ && !only_own_has_simple_elements_) return false;
Handle<JSObject> object = Handle<JSObject>::cast(receiver);
if (!object->HasFastProperties()) return false;
if (object->HasNamedInterceptor()) return false;
if (object->IsAccessCheckNeeded() &&
!isolate_->MayAccess(handle(isolate_->context(), isolate_), object)) {
return false;
}
HeapObject prototype = receiver->map().prototype();
if (prototype.is_null()) return false;
if (!prototype.map().is_prototype_map() ||
!prototype.map().prototype_info().IsPrototypeInfo()) {
return false;
}
first_prototype_ = handle(JSReceiver::cast(prototype), isolate_);
Handle<Map> map(prototype.map(), isolate_);
first_prototype_map_ = map;
has_prototype_info_cache_ = map->IsPrototypeValidityCellValid() &&
PrototypeInfo::cast(map->prototype_info())
.prototype_chain_enum_cache()
.IsFixedArray();
return true;
}
namespace {
enum IndexedOrNamed { kIndexed, kNamed };
V8_WARN_UNUSED_RESULT ExceptionStatus FilterForEnumerableProperties(
Handle<JSReceiver> receiver, Handle<JSObject> object,
Handle<InterceptorInfo> interceptor, KeyAccumulator* accumulator,
Handle<JSObject> result, IndexedOrNamed type) {
DCHECK(result->IsJSArray() || result->HasSloppyArgumentsElements());
ElementsAccessor* accessor = result->GetElementsAccessor();
size_t length = accessor->GetCapacity(*result, result->elements());
for (InternalIndex entry : InternalIndex::Range(length)) {
if (!accessor->HasEntry(*result, entry)) continue;
// args are invalid after args.Call(), create a new one in every iteration.
PropertyCallbackArguments args(accumulator->isolate(), interceptor->data(),
*receiver, *object, Just(kDontThrow));
Handle<Object> element = accessor->Get(result, entry);
Handle<Object> attributes;
if (type == kIndexed) {
uint32_t number;
CHECK(element->ToUint32(&number));
attributes = args.CallIndexedQuery(interceptor, number);
} else {
CHECK(element->IsName());
attributes =
args.CallNamedQuery(interceptor, Handle<Name>::cast(element));
}
if (!attributes.is_null()) {
int32_t value;
CHECK(attributes->ToInt32(&value));
if ((value & DONT_ENUM) == 0) {
RETURN_FAILURE_IF_NOT_SUCCESSFUL(
accumulator->AddKey(element, DO_NOT_CONVERT));
}
}
}
return ExceptionStatus::kSuccess;
}
// Returns |true| on success, |nothing| on exception.
Maybe<bool> CollectInterceptorKeysInternal(Handle<JSReceiver> receiver,
Handle<JSObject> object,
Handle<InterceptorInfo> interceptor,
KeyAccumulator* accumulator,
IndexedOrNamed type) {
Isolate* isolate = accumulator->isolate();
PropertyCallbackArguments enum_args(isolate, interceptor->data(), *receiver,
*object, Just(kDontThrow));
Handle<JSObject> result;
if (!interceptor->enumerator().IsUndefined(isolate)) {
if (type == kIndexed) {
result = enum_args.CallIndexedEnumerator(interceptor);
} else {
DCHECK_EQ(type, kNamed);
result = enum_args.CallNamedEnumerator(interceptor);
}
}
RETURN_VALUE_IF_SCHEDULED_EXCEPTION(isolate, Nothing<bool>());
if (result.is_null()) return Just(true);
if ((accumulator->filter() & ONLY_ENUMERABLE) &&
!interceptor->query().IsUndefined(isolate)) {
RETURN_NOTHING_IF_NOT_SUCCESSFUL(FilterForEnumerableProperties(
receiver, object, interceptor, accumulator, result, type));
} else {
RETURN_NOTHING_IF_NOT_SUCCESSFUL(accumulator->AddKeys(
result, type == kIndexed ? CONVERT_TO_ARRAY_INDEX : DO_NOT_CONVERT));
}
return Just(true);
}
Maybe<bool> CollectInterceptorKeys(Handle<JSReceiver> receiver,
Handle<JSObject> object,
KeyAccumulator* accumulator,
IndexedOrNamed type) {
Isolate* isolate = accumulator->isolate();
if (type == kIndexed) {
if (!object->HasIndexedInterceptor()) return Just(true);
} else {
if (!object->HasNamedInterceptor()) return Just(true);
}
Handle<InterceptorInfo> interceptor(type == kIndexed
? object->GetIndexedInterceptor()
: object->GetNamedInterceptor(),
isolate);
if ((accumulator->filter() & ONLY_ALL_CAN_READ) &&
!interceptor->all_can_read()) {
return Just(true);
}
return CollectInterceptorKeysInternal(receiver, object, interceptor,
accumulator, type);
}
} // namespace
Maybe<bool> KeyAccumulator::CollectOwnElementIndices(
Handle<JSReceiver> receiver, Handle<JSObject> object) {
if (filter_ & SKIP_STRINGS || skip_indices_) return Just(true);
ElementsAccessor* accessor = object->GetElementsAccessor();
RETURN_NOTHING_IF_NOT_SUCCESSFUL(
accessor->CollectElementIndices(object, this));
return CollectInterceptorKeys(receiver, object, this, kIndexed);
}
namespace {
template <bool skip_symbols>
base::Optional<int> CollectOwnPropertyNamesInternal(
Handle<JSObject> object, KeyAccumulator* keys,
Handle<DescriptorArray> descs, int start_index, int limit) {
AllowHeapAllocation allow_gc;
int first_skipped = -1;
PropertyFilter filter = keys->filter();
KeyCollectionMode mode = keys->mode();
for (InternalIndex i : InternalIndex::Range(start_index, limit)) {
bool is_shadowing_key = false;
PropertyDetails details = descs->GetDetails(i);
if ((details.attributes() & filter) != 0) {
if (mode == KeyCollectionMode::kIncludePrototypes) {
is_shadowing_key = true;
} else {
continue;
}
}
if (filter & ONLY_ALL_CAN_READ) {
if (details.kind() != kAccessor) continue;
Object accessors = descs->GetStrongValue(i);
if (!accessors.IsAccessorInfo()) continue;
if (!AccessorInfo::cast(accessors).all_can_read()) continue;
}
Name key = descs->GetKey(i);
if (skip_symbols == key.IsSymbol()) {
if (first_skipped == -1) first_skipped = i.as_int();
continue;
}
if (key.FilterKey(keys->filter())) continue;
if (is_shadowing_key) {
// This might allocate, but {key} is not used afterwards.
keys->AddShadowingKey(key, &allow_gc);
continue;
} else {
if (keys->AddKey(key, DO_NOT_CONVERT) != ExceptionStatus::kSuccess) {
return base::Optional<int>();
}
}
}
return first_skipped;
}
template <class T>
Handle<FixedArray> GetOwnEnumPropertyDictionaryKeys(Isolate* isolate,
KeyCollectionMode mode,
KeyAccumulator* accumulator,
Handle<JSObject> object,
T raw_dictionary) {
Handle<T> dictionary(raw_dictionary, isolate);
if (dictionary->NumberOfElements() == 0) {
return isolate->factory()->empty_fixed_array();
}
int length = dictionary->NumberOfEnumerableProperties();
Handle<FixedArray> storage = isolate->factory()->NewFixedArray(length);
T::CopyEnumKeysTo(isolate, dictionary, storage, mode, accumulator);
return storage;
}
} // namespace
Maybe<bool> KeyAccumulator::CollectOwnPropertyNames(Handle<JSReceiver> receiver,
Handle<JSObject> object) {
if (filter_ == ENUMERABLE_STRINGS) {
Handle<FixedArray> enum_keys;
if (object->HasFastProperties()) {
enum_keys = KeyAccumulator::GetOwnEnumPropertyKeys(isolate_, object);
// If the number of properties equals the length of enumerable properties
// we do not have to filter out non-enumerable ones
Map map = object->map();
int nof_descriptors = map.NumberOfOwnDescriptors();
if (enum_keys->length() != nof_descriptors) {
if (map.prototype(isolate_) != ReadOnlyRoots(isolate_).null_value()) {
AllowHeapAllocation allow_gc;
Handle<DescriptorArray> descs =
Handle<DescriptorArray>(map.instance_descriptors(), isolate_);
for (InternalIndex i : InternalIndex::Range(nof_descriptors)) {
PropertyDetails details = descs->GetDetails(i);
if (!details.IsDontEnum()) continue;
this->AddShadowingKey(descs->GetKey(i), &allow_gc);
}
}
}
} else if (object->IsJSGlobalObject()) {
enum_keys = GetOwnEnumPropertyDictionaryKeys(
isolate_, mode_, this, object,
JSGlobalObject::cast(*object).global_dictionary());
} else {
enum_keys = GetOwnEnumPropertyDictionaryKeys(
isolate_, mode_, this, object, object->property_dictionary());
}
if (object->IsJSModuleNamespace()) {
// Simulate [[GetOwnProperty]] for establishing enumerability, which
// throws for uninitialized exports.
for (int i = 0, n = enum_keys->length(); i < n; ++i) {
Handle<String> key(String::cast(enum_keys->get(i)), isolate_);
if (Handle<JSModuleNamespace>::cast(object)
->GetExport(isolate(), key)
.is_null()) {
return Nothing<bool>();
}
}
}
RETURN_NOTHING_IF_NOT_SUCCESSFUL(AddKeys(enum_keys, DO_NOT_CONVERT));
} else {
if (object->HasFastProperties()) {
int limit = object->map().NumberOfOwnDescriptors();
Handle<DescriptorArray> descs(object->map().instance_descriptors(),
isolate_);
// First collect the strings,
base::Optional<int> first_symbol =
CollectOwnPropertyNamesInternal<true>(object, this, descs, 0, limit);
// then the symbols.
RETURN_NOTHING_IF_NOT_SUCCESSFUL(first_symbol);
if (first_symbol.value() != -1) {
RETURN_NOTHING_IF_NOT_SUCCESSFUL(CollectOwnPropertyNamesInternal<false>(
object, this, descs, first_symbol.value(), limit));
}
} else if (object->IsJSGlobalObject()) {
RETURN_NOTHING_IF_NOT_SUCCESSFUL(GlobalDictionary::CollectKeysTo(
handle(JSGlobalObject::cast(*object).global_dictionary(), isolate_),
this));
} else {
RETURN_NOTHING_IF_NOT_SUCCESSFUL(NameDictionary::CollectKeysTo(
handle(object->property_dictionary(), isolate_), this));
}
}
// Add the property keys from the interceptor.
return CollectInterceptorKeys(receiver, object, this, kNamed);
}
ExceptionStatus KeyAccumulator::CollectPrivateNames(Handle<JSReceiver> receiver,
Handle<JSObject> object) {
DCHECK_EQ(mode_, KeyCollectionMode::kOwnOnly);
if (object->HasFastProperties()) {
int limit = object->map().NumberOfOwnDescriptors();
Handle<DescriptorArray> descs(object->map().instance_descriptors(),
isolate_);
CollectOwnPropertyNamesInternal<false>(object, this, descs, 0, limit);
} else if (object->IsJSGlobalObject()) {
RETURN_FAILURE_IF_NOT_SUCCESSFUL(GlobalDictionary::CollectKeysTo(
handle(JSGlobalObject::cast(*object).global_dictionary(), isolate_),
this));
} else {
RETURN_FAILURE_IF_NOT_SUCCESSFUL(NameDictionary::CollectKeysTo(
handle(object->property_dictionary(), isolate_), this));
}
return ExceptionStatus::kSuccess;
}
Maybe<bool> KeyAccumulator::CollectAccessCheckInterceptorKeys(
Handle<AccessCheckInfo> access_check_info, Handle<JSReceiver> receiver,
Handle<JSObject> object) {
if (!skip_indices_) {
MAYBE_RETURN((CollectInterceptorKeysInternal(
receiver, object,
handle(InterceptorInfo::cast(
access_check_info->indexed_interceptor()),
isolate_),
this, kIndexed)),
Nothing<bool>());
}
MAYBE_RETURN(
(CollectInterceptorKeysInternal(
receiver, object,
handle(InterceptorInfo::cast(access_check_info->named_interceptor()),
isolate_),
this, kNamed)),
Nothing<bool>());
return Just(true);
}
// Returns |true| on success, |false| if prototype walking should be stopped,
// |nothing| if an exception was thrown.
Maybe<bool> KeyAccumulator::CollectOwnKeys(Handle<JSReceiver> receiver,
Handle<JSObject> object) {
// Check access rights if required.
if (object->IsAccessCheckNeeded() &&
!isolate_->MayAccess(handle(isolate_->context(), isolate_), object)) {
// The cross-origin spec says that [[Enumerate]] shall return an empty
// iterator when it doesn't have access...
if (mode_ == KeyCollectionMode::kIncludePrototypes) {
return Just(false);
}
// ...whereas [[OwnPropertyKeys]] shall return allowlisted properties.
DCHECK_EQ(KeyCollectionMode::kOwnOnly, mode_);
Handle<AccessCheckInfo> access_check_info;
{
DisallowHeapAllocation no_gc;
AccessCheckInfo maybe_info = AccessCheckInfo::Get(isolate_, object);
if (!maybe_info.is_null()) {
access_check_info = handle(maybe_info, isolate_);
}
}
// We always have both kinds of interceptors or none.
if (!access_check_info.is_null() &&
access_check_info->named_interceptor() != Object()) {
MAYBE_RETURN(CollectAccessCheckInterceptorKeys(access_check_info,
receiver, object),
Nothing<bool>());
return Just(false);
}
filter_ = static_cast<PropertyFilter>(filter_ | ONLY_ALL_CAN_READ);
}
if (filter_ & PRIVATE_NAMES_ONLY) {
RETURN_NOTHING_IF_NOT_SUCCESSFUL(CollectPrivateNames(receiver, object));
return Just(true);
}
if (may_have_elements_) {
MAYBE_RETURN(CollectOwnElementIndices(receiver, object), Nothing<bool>());
}
MAYBE_RETURN(CollectOwnPropertyNames(receiver, object), Nothing<bool>());
return Just(true);
}
// static
Handle<FixedArray> KeyAccumulator::GetOwnEnumPropertyKeys(
Isolate* isolate, Handle<JSObject> object) {
if (object->HasFastProperties()) {
return GetFastEnumPropertyKeys(isolate, object);
} else if (object->IsJSGlobalObject()) {
return GetOwnEnumPropertyDictionaryKeys(
isolate, KeyCollectionMode::kOwnOnly, nullptr, object,
JSGlobalObject::cast(*object).global_dictionary());
} else {
return GetOwnEnumPropertyDictionaryKeys(
isolate, KeyCollectionMode::kOwnOnly, nullptr, object,
object->property_dictionary());
}
}
namespace {
class NameComparator {
public:
explicit NameComparator(Isolate* isolate) : isolate_(isolate) {}
bool operator()(uint32_t hash1, uint32_t hash2, const Handle<Name>& key1,
const Handle<Name>& key2) const {
return Name::Equals(isolate_, key1, key2);
}
private:
Isolate* isolate_;
};
} // namespace
// ES6 #sec-proxy-object-internal-methods-and-internal-slots-ownpropertykeys
// Returns |true| on success, |nothing| in case of exception.
Maybe<bool> KeyAccumulator::CollectOwnJSProxyKeys(Handle<JSReceiver> receiver,
Handle<JSProxy> proxy) {
STACK_CHECK(isolate_, Nothing<bool>());
if (filter_ == PRIVATE_NAMES_ONLY) {
RETURN_NOTHING_IF_NOT_SUCCESSFUL(NameDictionary::CollectKeysTo(
handle(proxy->property_dictionary(), isolate_), this));
return Just(true);
}
// 1. Let handler be the value of the [[ProxyHandler]] internal slot of O.
Handle<Object> handler(proxy->handler(), isolate_);
// 2. If handler is null, throw a TypeError exception.
// 3. Assert: Type(handler) is Object.
if (proxy->IsRevoked()) {
isolate_->Throw(*isolate_->factory()->NewTypeError(
MessageTemplate::kProxyRevoked, isolate_->factory()->ownKeys_string()));
return Nothing<bool>();
}
// 4. Let target be the value of the [[ProxyTarget]] internal slot of O.
Handle<JSReceiver> target(JSReceiver::cast(proxy->target()), isolate_);
// 5. Let trap be ? GetMethod(handler, "ownKeys").
Handle<Object> trap;
ASSIGN_RETURN_ON_EXCEPTION_VALUE(
isolate_, trap,
Object::GetMethod(Handle<JSReceiver>::cast(handler),
isolate_->factory()->ownKeys_string()),
Nothing<bool>());
// 6. If trap is undefined, then
if (trap->IsUndefined(isolate_)) {
// 6a. Return target.[[OwnPropertyKeys]]().
return CollectOwnJSProxyTargetKeys(proxy, target);
}
// 7. Let trapResultArray be Call(trap, handler, «target»).
Handle<Object> trap_result_array;
Handle<Object> args[] = {target};
ASSIGN_RETURN_ON_EXCEPTION_VALUE(
isolate_, trap_result_array,
Execution::Call(isolate_, trap, handler, arraysize(args), args),
Nothing<bool>());
// 8. Let trapResult be ? CreateListFromArrayLike(trapResultArray,
// «String, Symbol»).
Handle<FixedArray> trap_result;
ASSIGN_RETURN_ON_EXCEPTION_VALUE(
isolate_, trap_result,
Object::CreateListFromArrayLike(isolate_, trap_result_array,
ElementTypes::kStringAndSymbol),
Nothing<bool>());
// 9. If trapResult contains any duplicate entries, throw a TypeError
// exception. Combine with step 18
// 18. Let uncheckedResultKeys be a new List which is a copy of trapResult.
Zone set_zone(isolate_->allocator(), ZONE_NAME);
const int kPresent = 1;
const int kGone = 0;
using ZoneHashMapImpl =
base::TemplateHashMapImpl<Handle<Name>, int, NameComparator,
ZoneAllocationPolicy>;
ZoneHashMapImpl unchecked_result_keys(
ZoneHashMapImpl::kDefaultHashMapCapacity, NameComparator(isolate_),
ZoneAllocationPolicy(&set_zone));
int unchecked_result_keys_size = 0;
for (int i = 0; i < trap_result->length(); ++i) {
Handle<Name> key(Name::cast(trap_result->get(i)), isolate_);
auto entry = unchecked_result_keys.LookupOrInsert(key, key->Hash());
if (entry->value != kPresent) {
entry->value = kPresent;
unchecked_result_keys_size++;
} else {
// found dupes, throw exception
isolate_->Throw(*isolate_->factory()->NewTypeError(
MessageTemplate::kProxyOwnKeysDuplicateEntries));
return Nothing<bool>();
}
}
// 10. Let extensibleTarget be ? IsExtensible(target).
Maybe<bool> maybe_extensible = JSReceiver::IsExtensible(target);
MAYBE_RETURN(maybe_extensible, Nothing<bool>());
bool extensible_target = maybe_extensible.FromJust();
// 11. Let targetKeys be ? target.[[OwnPropertyKeys]]().
Handle<FixedArray> target_keys;
ASSIGN_RETURN_ON_EXCEPTION_VALUE(isolate_, target_keys,
JSReceiver::OwnPropertyKeys(target),
Nothing<bool>());
// 12, 13. (Assert)
// 14. Let targetConfigurableKeys be an empty List.
// To save memory, we're re-using target_keys and will modify it in-place.
Handle<FixedArray> target_configurable_keys = target_keys;
// 15. Let targetNonconfigurableKeys be an empty List.
Handle<FixedArray> target_nonconfigurable_keys =
isolate_->factory()->NewFixedArray(target_keys->length());
int nonconfigurable_keys_length = 0;
// 16. Repeat, for each element key of targetKeys:
for (int i = 0; i < target_keys->length(); ++i) {
// 16a. Let desc be ? target.[[GetOwnProperty]](key).
PropertyDescriptor desc;
Maybe<bool> found = JSReceiver::GetOwnPropertyDescriptor(
isolate_, target, handle(target_keys->get(i), isolate_), &desc);
MAYBE_RETURN(found, Nothing<bool>());
// 16b. If desc is not undefined and desc.[[Configurable]] is false, then
if (found.FromJust() && !desc.configurable()) {
// 16b i. Append key as an element of targetNonconfigurableKeys.
target_nonconfigurable_keys->set(nonconfigurable_keys_length,
target_keys->get(i));
nonconfigurable_keys_length++;
// The key was moved, null it out in the original list.
target_keys->set(i, Smi::zero());
} else {
// 16c. Else,
// 16c i. Append key as an element of targetConfigurableKeys.
// (No-op, just keep it in |target_keys|.)
}
}
// 17. If extensibleTarget is true and targetNonconfigurableKeys is empty,
// then:
if (extensible_target && nonconfigurable_keys_length == 0) {
// 17a. Return trapResult.
return AddKeysFromJSProxy(proxy, trap_result);
}
// 18. (Done in step 9)
// 19. Repeat, for each key that is an element of targetNonconfigurableKeys:
for (int i = 0; i < nonconfigurable_keys_length; ++i) {
Object raw_key = target_nonconfigurable_keys->get(i);
Handle<Name> key(Name::cast(raw_key), isolate_);
// 19a. If key is not an element of uncheckedResultKeys, throw a
// TypeError exception.
auto found = unchecked_result_keys.Lookup(key, key->Hash());
if (found == nullptr || found->value == kGone) {
isolate_->Throw(*isolate_->factory()->NewTypeError(
MessageTemplate::kProxyOwnKeysMissing, key));
return Nothing<bool>();
}
// 19b. Remove key from uncheckedResultKeys.
found->value = kGone;
unchecked_result_keys_size--;
}
// 20. If extensibleTarget is true, return trapResult.
if (extensible_target) {
return AddKeysFromJSProxy(proxy, trap_result);
}
// 21. Repeat, for each key that is an element of targetConfigurableKeys:
for (int i = 0; i < target_configurable_keys->length(); ++i) {
Object raw_key = target_configurable_keys->get(i);
if (raw_key.IsSmi()) continue; // Zapped entry, was nonconfigurable.
Handle<Name> key(Name::cast(raw_key), isolate_);
// 21a. If key is not an element of uncheckedResultKeys, throw a
// TypeError exception.
auto found = unchecked_result_keys.Lookup(key, key->Hash());
if (found == nullptr || found->value == kGone) {
isolate_->Throw(*isolate_->factory()->NewTypeError(
MessageTemplate::kProxyOwnKeysMissing, key));
return Nothing<bool>();
}
// 21b. Remove key from uncheckedResultKeys.
found->value = kGone;
unchecked_result_keys_size--;
}
// 22. If uncheckedResultKeys is not empty, throw a TypeError exception.
if (unchecked_result_keys_size != 0) {
DCHECK_GT(unchecked_result_keys_size, 0);
isolate_->Throw(*isolate_->factory()->NewTypeError(
MessageTemplate::kProxyOwnKeysNonExtensible));
return Nothing<bool>();
}
// 23. Return trapResult.
return AddKeysFromJSProxy(proxy, trap_result);
}
Maybe<bool> KeyAccumulator::CollectOwnJSProxyTargetKeys(
Handle<JSProxy> proxy, Handle<JSReceiver> target) {
// TODO(cbruni): avoid creating another KeyAccumulator
Handle<FixedArray> keys;
ASSIGN_RETURN_ON_EXCEPTION_VALUE(
isolate_, keys,
KeyAccumulator::GetKeys(
target, KeyCollectionMode::kOwnOnly, ALL_PROPERTIES,
GetKeysConversion::kConvertToString, is_for_in_, skip_indices_),
Nothing<bool>());
Maybe<bool> result = AddKeysFromJSProxy(proxy, keys);
return result;
}
#undef RETURN_NOTHING_IF_NOT_SUCCESSFUL
#undef RETURN_FAILURE_IF_NOT_SUCCESSFUL
} // namespace internal
} // namespace v8
|
/*
* Qt4 bitcoin GUI.
*
* W.J. van der Laan 2011-2012
* The BitToken Developers 2011-2013
*/
#include "walletview.h"
#include "bitcoingui.h"
#include "transactiontablemodel.h"
#include "addressbookpage.h"
#include "sendcoinsdialog.h"
#include "signverifymessagedialog.h"
#include "clientmodel.h"
#include "walletmodel.h"
#include "optionsmodel.h"
#include "transactionview.h"
#include "overviewpage.h"
#include "askpassphrasedialog.h"
#include "ui_interface.h"
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QAction>
#if QT_VERSION < 0x050000
#include <QDesktopServices>
#else
#include <QStandardPaths>
#endif
#include <QFileDialog>
#include <QPushButton>
WalletView::WalletView(QWidget *parent, BitcoinGUI *_gui):
QStackedWidget(parent),
gui(_gui),
clientModel(0),
walletModel(0)
{
// Create tabs
overviewPage = new OverviewPage();
transactionsPage = new QWidget(this);
QVBoxLayout *vbox = new QVBoxLayout();
QHBoxLayout *hbox_buttons = new QHBoxLayout();
transactionView = new TransactionView(this);
vbox->addWidget(transactionView);
QPushButton *exportButton = new QPushButton(tr("&Export"), this);
exportButton->setToolTip(tr("Export the data in the current tab to a file"));
#ifndef Q_OS_MAC // Icons on push buttons are very uncommon on Mac
exportButton->setIcon(QIcon(":/icons/export"));
#endif
hbox_buttons->addStretch();
hbox_buttons->addWidget(exportButton);
vbox->addLayout(hbox_buttons);
transactionsPage->setLayout(vbox);
addressBookPage = new AddressBookPage(AddressBookPage::ForEditing, AddressBookPage::SendingTab);
receiveCoinsPage = new AddressBookPage(AddressBookPage::ForEditing, AddressBookPage::ReceivingTab);
sendCoinsPage = new SendCoinsDialog(gui);
signVerifyMessageDialog = new SignVerifyMessageDialog(gui);
addWidget(overviewPage);
addWidget(transactionsPage);
addWidget(addressBookPage);
addWidget(receiveCoinsPage);
addWidget(sendCoinsPage);
// Clicking on a transaction on the overview page simply sends you to transaction history page
connect(overviewPage, SIGNAL(transactionClicked(QModelIndex)), this, SLOT(gotoHistoryPage()));
connect(overviewPage, SIGNAL(transactionClicked(QModelIndex)), transactionView, SLOT(focusTransaction(QModelIndex)));
// Double-clicking on a transaction on the transaction history page shows details
connect(transactionView, SIGNAL(doubleClicked(QModelIndex)), transactionView, SLOT(showDetails()));
// Clicking on "Send Coins" in the address book sends you to the send coins tab
connect(addressBookPage, SIGNAL(sendCoins(QString)), this, SLOT(gotoSendCoinsPage(QString)));
// Clicking on "Verify Message" in the address book opens the verify message tab in the Sign/Verify Message dialog
connect(addressBookPage, SIGNAL(verifyMessage(QString)), this, SLOT(gotoVerifyMessageTab(QString)));
// Clicking on "Sign Message" in the receive coins page opens the sign message tab in the Sign/Verify Message dialog
connect(receiveCoinsPage, SIGNAL(signMessage(QString)), this, SLOT(gotoSignMessageTab(QString)));
// Clicking on "Export" allows to export the transaction list
connect(exportButton, SIGNAL(clicked()), transactionView, SLOT(exportClicked()));
gotoOverviewPage();
}
WalletView::~WalletView()
{
}
void WalletView::setBitcoinGUI(BitcoinGUI *gui)
{
this->gui = gui;
}
void WalletView::setClientModel(ClientModel *clientModel)
{
this->clientModel = clientModel;
if (clientModel)
{
overviewPage->setClientModel(clientModel);
addressBookPage->setOptionsModel(clientModel->getOptionsModel());
receiveCoinsPage->setOptionsModel(clientModel->getOptionsModel());
}
}
void WalletView::setWalletModel(WalletModel *walletModel)
{
this->walletModel = walletModel;
if (walletModel)
{
// Receive and report messages from wallet thread
connect(walletModel, SIGNAL(message(QString,QString,unsigned int)), gui, SLOT(message(QString,QString,unsigned int)));
// Put transaction list in tabs
transactionView->setModel(walletModel);
overviewPage->setWalletModel(walletModel);
addressBookPage->setModel(walletModel->getAddressTableModel());
receiveCoinsPage->setModel(walletModel->getAddressTableModel());
sendCoinsPage->setModel(walletModel);
signVerifyMessageDialog->setModel(walletModel);
setEncryptionStatus();
connect(walletModel, SIGNAL(encryptionStatusChanged(int)), gui, SLOT(setEncryptionStatus(int)));
// Balloon pop-up for new transaction
connect(walletModel->getTransactionTableModel(), SIGNAL(rowsInserted(QModelIndex,int,int)),
this, SLOT(incomingTransaction(QModelIndex,int,int)));
// Ask for passphrase if needed
connect(walletModel, SIGNAL(requireUnlock()), this, SLOT(unlockWallet()));
}
}
void WalletView::incomingTransaction(const QModelIndex& parent, int start, int /*end*/)
{
// Prevent balloon-spam when initial block download is in progress
if(!walletModel || !clientModel || clientModel->inInitialBlockDownload())
return;
TransactionTableModel *ttm = walletModel->getTransactionTableModel();
QString date = ttm->index(start, TransactionTableModel::Date, parent).data().toString();
qint64 amount = ttm->index(start, TransactionTableModel::Amount, parent).data(Qt::EditRole).toULongLong();
QString type = ttm->index(start, TransactionTableModel::Type, parent).data().toString();
QString address = ttm->index(start, TransactionTableModel::ToAddress, parent).data().toString();
gui->incomingTransaction(date, walletModel->getOptionsModel()->getDisplayUnit(), amount, type, address);
}
void WalletView::gotoOverviewPage()
{
gui->getOverviewAction()->setChecked(true);
setCurrentWidget(overviewPage);
}
void WalletView::gotoHistoryPage()
{
gui->getHistoryAction()->setChecked(true);
setCurrentWidget(transactionsPage);
}
void WalletView::gotoAddressBookPage()
{
gui->getAddressBookAction()->setChecked(true);
setCurrentWidget(addressBookPage);
}
void WalletView::gotoReceiveCoinsPage()
{
gui->getReceiveCoinsAction()->setChecked(true);
setCurrentWidget(receiveCoinsPage);
}
void WalletView::gotoSendCoinsPage(QString addr)
{
gui->getSendCoinsAction()->setChecked(true);
setCurrentWidget(sendCoinsPage);
if (!addr.isEmpty())
sendCoinsPage->setAddress(addr);
}
void WalletView::gotoSignMessageTab(QString addr)
{
// call show() in showTab_SM()
signVerifyMessageDialog->showTab_SM(true);
if (!addr.isEmpty())
signVerifyMessageDialog->setAddress_SM(addr);
}
void WalletView::gotoVerifyMessageTab(QString addr)
{
// call show() in showTab_VM()
signVerifyMessageDialog->showTab_VM(true);
if (!addr.isEmpty())
signVerifyMessageDialog->setAddress_VM(addr);
}
bool WalletView::handleURI(const QString& strURI)
{
// URI has to be valid
if (sendCoinsPage->handleURI(strURI))
{
gotoSendCoinsPage();
return true;
}
else
return false;
}
void WalletView::showOutOfSyncWarning(bool fShow)
{
overviewPage->showOutOfSyncWarning(fShow);
}
void WalletView::setEncryptionStatus()
{
gui->setEncryptionStatus(walletModel->getEncryptionStatus());
}
void WalletView::encryptWallet(bool status)
{
if(!walletModel)
return;
AskPassphraseDialog dlg(status ? AskPassphraseDialog::Encrypt : AskPassphraseDialog::Decrypt, this);
dlg.setModel(walletModel);
dlg.exec();
setEncryptionStatus();
}
void WalletView::backupWallet()
{
#if QT_VERSION < 0x050000
QString saveDir = QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation);
#else
QString saveDir = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation);
#endif
QString filename = QFileDialog::getSaveFileName(this, tr("Backup Wallet"), saveDir, tr("Wallet Data (*.dat)"));
if (!filename.isEmpty()) {
if (!walletModel->backupWallet(filename)) {
gui->message(tr("Backup Failed"), tr("There was an error trying to save the wallet data to the new location."),
CClientUIInterface::MSG_ERROR);
}
else
gui->message(tr("Backup Successful"), tr("The wallet data was successfully saved to the new location."),
CClientUIInterface::MSG_INFORMATION);
}
}
void WalletView::changePassphrase()
{
AskPassphraseDialog dlg(AskPassphraseDialog::ChangePass, this);
dlg.setModel(walletModel);
dlg.exec();
}
void WalletView::unlockWallet()
{
if(!walletModel)
return;
// Unlock wallet when requested by wallet model
if (walletModel->getEncryptionStatus() == WalletModel::Locked)
{
AskPassphraseDialog dlg(AskPassphraseDialog::Unlock, this);
dlg.setModel(walletModel);
dlg.exec();
}
}
|
#include "drw_textcodec.h"
#include <sstream>
#include <iomanip>
#include <algorithm>
#include <cstring>
#include <iconv.h>
#include "../drw_base.h"
#include "drw_cptables.h"
#include "drw_cptable932.h"
#include "drw_cptable936.h"
#include "drw_cptable949.h"
#include "drw_cptable950.h"
DRW_TextCodec::DRW_TextCodec() {
version = DRW::AC1021;
conv = new DRW_Converter(NULL, 0);
}
DRW_TextCodec::~DRW_TextCodec() {
delete conv;
}
void DRW_TextCodec::setVersion(int v, bool dxfFormat){
if (v == DRW::AC1009 || v == DRW::AC1006) {
version = DRW::AC1009;
cp = "ANSI_1252";
setCodePage(&cp, dxfFormat);
} else if (v == DRW::AC1012 || v == DRW::AC1014
|| v == DRW::AC1015 || v == DRW::AC1018) {
version = DRW::AC1015;
// if (cp.empty()) { //codepage not set, initialize
cp = "ANSI_1252";
setCodePage(&cp, dxfFormat);
// }
} else {
version = DRW::AC1021;
if (dxfFormat)
cp = "UTF-8";//RLZ: can be UCS2 or UTF-16 16bits per char
else
cp = "UTF-16";//RLZ: can be UCS2 or UTF-16 16bits per char
setCodePage(&cp, dxfFormat);
}
}
void DRW_TextCodec::setVersion(std::string *v, bool dxfFormat){
std::string versionStr = *v;
if (versionStr == "AC1009" || versionStr == "AC1006") {
setVersion(DRW::AC1009, dxfFormat);
} else if (versionStr == "AC1012" || versionStr == "AC1014"
|| versionStr == "AC1015" || versionStr == "AC1018") {
setVersion(DRW::AC1015, dxfFormat);
}
setVersion(DRW::AC1021, dxfFormat);
}
void DRW_TextCodec::setCodePage(std::string *c, bool dxfFormat){
static int min_ver = 10;
min_ver = std::min(min_ver, version);
cp = correctCodePage(*c);
delete conv;
if (version == DRW::AC1009 || version == DRW::AC1015) {
if (cp == "ANSI_874")
conv = new DRW_ConvTable(DRW_Table874, CPLENGHTCOMMON);
else if (cp == "ANSI_932")
conv = new DRW_Conv932Table(DRW_Table932, DRW_LeadTable932,
DRW_DoubleTable932, CPLENGHT932);
else if (cp == "ANSI_936")
conv = new DRW_ConvDBCSTable(DRW_Table936, DRW_LeadTable936,
DRW_DoubleTable936, CPLENGHT936);
else if (cp == "ANSI_949")
conv = new DRW_ConvDBCSTable(DRW_Table949, DRW_LeadTable949,
DRW_DoubleTable949, CPLENGHT949);
else if (cp == "ANSI_950")
conv = new DRW_ConvDBCSTable(DRW_Table950, DRW_LeadTable950,
DRW_DoubleTable950, CPLENGHT950);
else if (cp == "ANSI_1250")
conv = new DRW_ConvTable(DRW_Table1250, CPLENGHTCOMMON);
else if (cp == "ANSI_1251")
conv = new DRW_ConvTable(DRW_Table1251, CPLENGHTCOMMON);
else if (cp == "ANSI_1253")
conv = new DRW_ConvTable(DRW_Table1253, CPLENGHTCOMMON);
else if (cp == "ANSI_1254")
conv = new DRW_ConvTable(DRW_Table1254, CPLENGHTCOMMON);
else if (cp == "ANSI_1255")
conv = new DRW_ConvTable(DRW_Table1255, CPLENGHTCOMMON);
else if (cp == "ANSI_1256")
conv = new DRW_ConvTable(DRW_Table1256, CPLENGHTCOMMON);
else if (cp == "ANSI_1257")
conv = new DRW_ConvTable(DRW_Table1257, CPLENGHTCOMMON);
else if (cp == "ANSI_1258")
conv = new DRW_ConvTable(DRW_Table1258, CPLENGHTCOMMON);
else if (cp == "UTF-8") { //DXF older than 2007 are write in win codepages
cp = "ANSI_1252";
conv = new DRW_ExtConverter("SJIS");
} else {
conv = new DRW_ExtConverter("SJIS");
}
} else {
if (min_ver <= DRW::AC1018) {
conv = new DRW_ExtConverter("SJIS");
} else {
if (dxfFormat)
conv = new DRW_Converter(NULL, 0);//utf16 to utf8
else
conv = new DRW_ConvUTF16();//utf16 to utf8
}
}
}
std::string DRW_TextCodec::toUtf8(std::string s) {
return conv->toUtf8(&s);
}
std::string DRW_TextCodec::fromUtf8(std::string s) {
return conv->fromUtf8(&s);
}
std::string DRW_Converter::toUtf8(std::string *s) {
std::string result;
int j = 0;
unsigned int i= 0;
for (i=0; i < s->length(); i++) {
unsigned char c = s->at(i);
if (c < 0x80) { //ascii check for /U+????
if (c == '\\' && i+6 < s->length() && s->at(i+1) == 'U' && s->at(i+2) == '+') {
result += s->substr(j,i-j);
result += encodeText(s->substr(i,7));
i +=6;
j = i+1;
}
} else if (c < 0xE0 ) {//2 bits
i++;
} else if (c < 0xF0 ) {//3 bits
i +=2;
} else if (c < 0xF8 ) {//4 bits
i +=3;
}
}
result += s->substr(j);
return result;
}
std::string DRW_ConvTable::fromUtf8(std::string *s) {
std::string result;
bool notFound;
int code;
int j = 0;
for (unsigned int i=0; i < s->length(); i++) {
unsigned char c = s->at(i);
if (c > 0x7F) { //need to decode
result += s->substr(j,i-j);
std::string part1 = s->substr(i,4);
int l;
code = decodeNum(part1, &l);
j = i+l;
i = j - 1;
notFound = true;
for (int k=0; k<cpLenght; k++){
if(table[k] == code) {
result += CPOFFSET + k; //translate from table
notFound = false;
break;
}
}
if (notFound)
result += decodeText(code);
}
}
result += s->substr(j);
return result;
}
std::string DRW_ConvTable::toUtf8(std::string *s) {
std::string res;
std::string::iterator it;
for ( it=s->begin() ; it < s->end(); ++it ) {
unsigned char c = *it;
if (c < 0x80) {
//check for \U+ encoded text
if (c == '\\') {
if (it+6 < s->end() && *(it+1) == 'U' && *(it+2) == '+') {
res += encodeText(std::string(it, it+7));
it +=6;
} else {
res +=c; //no \U+ encoded text write
}
} else
res +=c; //c!='\' ascii char write
} else {//end c < 0x80
res += encodeNum(table[c-0x80]); //translate from table
}
} //end for
return res;
}
std::string DRW_Converter::encodeText(std::string stmp){
int code;
#if defined(__APPLE__)
int Succeeded = sscanf (&( stmp.substr(3,4)[0]), "%x", &code );
if ( !Succeeded || Succeeded == EOF )
code = 0;
#else
std::istringstream sd(stmp.substr(3,4));
sd >> std::hex >> code;
#endif
return encodeNum(code);
}
std::string DRW_Converter::decodeText(int c){
std::string res = "\\U+";
std::string num;
#if defined(__APPLE__)
std::string str(16, '\0');
snprintf (&(str[0]), 16, "%04X", c );
num = str;
#else
std::stringstream ss;
ss << std::uppercase << std::setfill('0') << std::setw(4) << std::hex << c;
ss >> num;
#endif
res += num;
return res;
}
std::string DRW_Converter::encodeNum(int c){
unsigned char ret[5];
if (c < 128) { // 0-7F US-ASCII 7 bits
ret[0] = c;
ret[1] = 0;
} else if (c < 0x800) { //80-07FF 2 bytes
ret[0] = 0xC0 | (c >> 6);
ret[1] = 0x80 | (c & 0x3f);
ret[2] = 0;
} else if (c< 0x10000) { //800-FFFF 3 bytes
ret[0] = 0xe0 | (c >> 12);
ret[1] = 0x80 | ((c >> 6) & 0x3f);
ret[2] = 0x80 | (c & 0x3f);
ret[3] = 0;
} else { //10000-10FFFF 4 bytes
ret[0] = 0xf0 | (c >> 18);
ret[1] = 0x80 | ((c >> 12) & 0x3f);
ret[2] = 0x80 | ((c >> 6) & 0x3f);
ret[3] = 0x80 | (c & 0x3f);
ret[4] = 0;
}
return std::string((char*)ret);
}
/** 's' is a string with at least 4 bytes lenght
** returned 'b' is byte lenght of encoded char: 2,3 or 4
**/
int DRW_Converter::decodeNum(std::string s, int *b){
int code= 0;
unsigned char c = s.at(0);
if ( (c& 0xE0) == 0xC0) { //2 bytes
code = ( c&0x1F)<<6;
code = (s.at(1) &0x3F) | code;
*b = 2;
} else if ( (c& 0xF0) == 0xE0) { //3 bytes
code = ( c&0x0F)<<12;
code = ((s.at(1) &0x3F)<<6) | code;
code = (s.at(2) &0x3F) | code;
*b = 3;
} else if ( (c& 0xF8) == 0xF0) { //4 bytes
code = ( c&0x07)<<18;
code = ((s.at(1) &0x3F)<<12) | code;
code = ((s.at(2) &0x3F)<<6) | code;
code = (s.at(3) &0x3F) | code;
*b = 4;
}
return code;
}
std::string DRW_ConvDBCSTable::fromUtf8(std::string *s) {
std::string result;
bool notFound;
int code;
int j = 0;
for (unsigned int i=0; i < s->length(); i++) {
unsigned char c = s->at(i);
if (c > 0x7F) { //need to decode
result += s->substr(j,i-j);
std::string part1 = s->substr(i,4);
int l;
code = decodeNum(part1, &l);
j = i+l;
i = j - 1;
notFound = true;
for (int k=0; k<cpLenght; k++){
if(doubleTable[k][1] == code) {
int data = doubleTable[k][0];
char d[3];
d[0] = data >> 8;
d[1] = data & 0xFF;
d[2]= '\0';
result += d; //translate from table
notFound = false;
break;
}
}
if (notFound)
result += decodeText(code);
} //direct conversion
}
result += s->substr(j);
return result;
}
std::string DRW_ConvDBCSTable::toUtf8(std::string *s) {
std::string res;
std::string::iterator it;
for ( it=s->begin() ; it < s->end(); ++it ) {
bool notFound = true;
unsigned char c = *it;
if (c < 0x80) {
notFound = false;
//check for \U+ encoded text
if (c == '\\') {
if (it+6 < s->end() && *(it+1) == 'U' && *(it+2) == '+') {
res += encodeText(std::string(it, it+7));
it +=6;
} else {
res +=c; //no \U+ encoded text write
}
} else
res +=c; //c!='\' ascii char write
} else if(c == 0x80 ){//1 byte table
notFound = false;
res += encodeNum(0x20AC);//euro sign
} else {//2 bytes
++it;
int code = (c << 8) | (unsigned char )(*it);
int sta = leadTable[c-0x81];
int end = leadTable[c-0x80];
for (int k=sta; k<end; k++){
if(doubleTable[k][0] == code) {
res += encodeNum(doubleTable[k][1]); //translate from table
notFound = false;
break;
}
}
}
//not found
if (notFound) res += encodeNum(NOTFOUND936);
} //end for
return res;
}
std::string DRW_Conv932Table::fromUtf8(std::string *s) {
std::string result;
bool notFound;
int code;
int j = 0;
for (unsigned int i=0; i < s->length(); i++) {
unsigned char c = s->at(i);
if (c > 0x7F) { //need to decode
result += s->substr(j,i-j);
std::string part1 = s->substr(i,4);
int l;
code = decodeNum(part1, &l);
j = i+l;
i = j - 1;
notFound = true;
// 1 byte table
if (code > 0xff60 && code < 0xFFA0) {
result += code - CPOFFSET932; //translate from table
notFound = false;
}
if (notFound && ( code<0xF8 || (code>0x390 && code<0x542) ||
(code>0x200F && code<0x9FA1) || code>0xF928 )) {
for (int k=0; k<cpLenght; k++){
if(doubleTable[k][1] == code) {
int data = doubleTable[k][0];
char d[3];
d[0] = data >> 8;
d[1] = data & 0xFF;
d[2]= '\0';
result += d; //translate from table
notFound = false;
break;
}
}
}
if (notFound)
result += decodeText(code);
} //direct conversion
}
result += s->substr(j);
return result;
}
std::string DRW_Conv932Table::toUtf8(std::string *s) {
std::string res;
std::string::iterator it;
for ( it=s->begin() ; it < s->end(); ++it ) {
bool notFound = true;
unsigned char c = *it;
if (c < 0x80) {
notFound = false;
//check for \U+ encoded text
if (c == '\\') {
if (it+6 < s->end() && *(it+1) == 'U' && *(it+2) == '+') {
res += encodeText(std::string(it, it+7));
it +=6;
} else {
res +=c; //no \U+ encoded text write
}
} else
res +=c; //c!='\' ascii char write
} else if(c > 0xA0 && c < 0xE0 ){//1 byte table
notFound = false;
res += encodeNum(c + CPOFFSET932); //translate from table
} else {//2 bytes
++it;
int code = (c << 8) | (unsigned char )(*it);
int sta;
int end=0;
if (c > 0x80 && c < 0xA0) {
sta = DRW_LeadTable932[c-0x81];
end = DRW_LeadTable932[c-0x80];
} else if (c > 0xDF && c < 0xFD){
sta = DRW_LeadTable932[c-0xC1];
end = DRW_LeadTable932[c-0xC0];
}
if (end > 0) {
for (int k=sta; k<end; k++){
if(DRW_DoubleTable932[k][0] == code) {
res += encodeNum(DRW_DoubleTable932[k][1]); //translate from table
notFound = false;
break;
}
}
}
}
//not found
if (notFound) res += encodeNum(NOTFOUND932);
} //end for
return res;
}
std::string DRW_ConvUTF16::fromUtf8(std::string *s){
DRW_UNUSED(s);
//RLZ: to be writen (only needed for write dwg 2007+)
return std::string();
}
std::string DRW_ConvUTF16::toUtf8(std::string *s){//RLZ: pending to write
std::string res;
std::string::iterator it;
for ( it=s->begin() ; it < s->end(); ++it ) {
unsigned char c1 = *it;
unsigned char c2 = *(++it);
duint16 ch = (c2 <<8) | c1;
res +=encodeNum(ch);
} //end for
return res;
}
std::string DRW_ExtConverter::convertByiconv(const char *in_encode,
const char *out_encode,
const std::string *s) {
const int BUF_SIZE = 1000;
static char in_buf[BUF_SIZE], out_buf[BUF_SIZE];
const char *in_ptr = in_buf;
char *out_ptr = out_buf;
strncpy(in_buf, s->c_str(), BUF_SIZE);
iconv_t ic;
ic = iconv_open(out_encode, in_encode);
size_t il = BUF_SIZE-1, ol = BUF_SIZE-1;
iconv(ic , &in_ptr, &il, &out_ptr, &ol);
iconv_close(ic);
return std::string(out_buf);
}
std::string DRW_ExtConverter::fromUtf8(std::string *s){
return convertByiconv("UTF8", this->encoding, s);
}
std::string DRW_ExtConverter::toUtf8(std::string *s){
return convertByiconv(this->encoding, "UTF8", s);
}
std::string DRW_TextCodec::correctCodePage(const std::string& s) {
//stringstream cause crash in OS/X, bug#3597944
std::string cp=s;
transform(cp.begin(), cp.end(), cp.begin(), toupper);
//Latin/Thai
if (cp=="ANSI_874" || cp=="CP874" || cp=="ISO8859-11" || cp=="TIS-620") {
return "ANSI_874";
//Central Europe and Eastern Europe
} else if (cp=="ANSI_1250" || cp=="CP1250" || cp=="ISO8859-2") {
return "ANSI_1250";
//Cyrillic script
} else if (cp=="ANSI_1251" || cp=="CP1251" || cp=="ISO8859-5" || cp=="KOI8-R" ||
cp=="KOI8-U" || cp=="IBM 866") {
return "ANSI_1251";
//Western Europe
} else if (cp=="ANSI_1252" || cp=="CP1252" || cp=="LATIN1" || cp=="ISO-8859-1" ||
cp=="CP819" || cp=="CSISO" || cp=="IBM819" || cp=="ISO_8859-1" || cp=="APPLE ROMAN" ||
cp=="ISO8859-1" || cp=="ISO8859-15" || cp=="ISO-IR-100" || cp=="L1" || cp=="IBM 850") {
return "ANSI_1252";
//Greek
} else if (cp=="ANSI_1253" || cp=="CP1253" || cp=="iso8859-7") {
return "ANSI_1253";
//Turkish
} else if (cp=="ANSI_1254" || cp=="CP1254" || cp=="iso8859-9" || cp=="iso8859-3") {
return "ANSI_1254";
//Hebrew
} else if (cp=="ANSI_1255" || cp=="CP1255" || cp=="iso8859-8") {
return "ANSI_1255";
//Arabic
} else if (cp=="ANSI_1256" || cp=="CP1256" || cp=="ISO8859-6") {
return "ANSI_1256";
//Baltic
} else if (cp=="ANSI_1257" || cp=="CP1257" || cp=="ISO8859-4" || cp=="ISO8859-10" || cp=="ISO8859-13") {
return "ANSI_1257";
//Vietnamese
} else if (cp=="ANSI_1258" || cp=="CP1258") {
return "ANSI_1258";
//Japanese
} else if (cp=="ANSI_932" || cp=="SHIFT-JIS" || cp=="SHIFT_JIS" || cp=="CSSHIFTJIS" ||
cp=="CSWINDOWS31J" || cp=="MS_KANJI" || cp=="X-MS-CP932" || cp=="X-SJIS" ||
cp=="EUCJP" || cp=="EUC-JP" || cp=="CSEUCPKDFMTJAPANESE" || cp=="X-EUC" ||
cp=="X-EUC-JP" || cp=="JIS7") {
return "ANSI_932";
//Chinese PRC GBK (XGB) simplified
} else if (cp=="ANSI_936" || cp=="GBK" || cp=="GB2312" || cp=="CHINESE" || cp=="CN-GB" ||
cp=="CSGB2312" || cp=="CSGB231280" || cp=="CSISO58BG231280" ||
cp=="GB_2312-80" || cp=="GB231280" || cp=="GB2312-80" ||
cp=="ISO-IR-58" || cp=="GB18030") {
return "ANSI_936";
//Korean
} else if (cp=="ANSI_949" || cp=="EUCKR") {
return "ANSI_949";
//Chinese Big5 (Taiwan, Hong Kong SAR)
} else if (cp=="ANSI_950" || cp=="BIG5" || cp=="CN-BIG5" || cp=="CSBIG5" ||
cp=="X-X-BIG5" || cp=="BIG5-HKSCS") {
return "ANSI_950";
//celtic
/* } else if (cp=="ISO8859-14") {
return "ISO8859-14";
} else if (cp=="TSCII") {
return "TSCII"; //tamil
}*/
} else if (cp=="UTF-8" || cp=="UTF8" || cp=="UTF8-BIT") {
return "UTF-8";
} else if (cp=="UTF-16" || cp=="UTF16" || cp=="UTF16-BIT") {
return "UTF-16";
}
return "ANSI_1252";
}
|
/*
Copyright (c) 2002-2009 Tampere University.
This file is part of TTA-Based Codesign Environment (TCE).
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
/**
* @file AddressSpaceCheck.hh
*
* Implementation of AddressSpaceCheck class.
*
* @author Viljami Korhonen 2007 (viljami.korhonen-no.spam-tut.fi)
* @note rating: red
*/
#include <string>
#include "AddressSpaceCheck.hh"
#include "FunctionUnit.hh"
#include "HWOperation.hh"
#include "Machine.hh"
#include "Operation.hh"
#include "OperationPool.hh"
#include "TCEString.hh"
#include "MachineCheckResults.hh"
using namespace TTAMachine;
/**
* The constructor.
*
* @param operationPool operation pool to search the operations for
*/
AddressSpaceCheck::AddressSpaceCheck(OperationPool& operationPool) :
MachineCheck("Address space check."),
operationPool_(operationPool) {
}
/**
* The destructor.
*/
AddressSpaceCheck::~AddressSpaceCheck() {
}
/**
* Checks that if the FUs' operations access memory,
* there is a memory address space available for them.
*
* @param mach Machine to be checked.
* @param results Check results.
* @return True if the check passed
*/
bool
AddressSpaceCheck::check(
const TTAMachine::Machine& mach,
MachineCheckResults& results) const {
Machine::FunctionUnitNavigator FUs = mach.functionUnitNavigator();
for (int i = 0; i < FUs.count(); i++) {
FunctionUnit* unit = FUs.item(i);
if (unit->addressSpace() != NULL) {
continue;
}
for (int j = 0; j < unit->operationCount(); ++j) {
Operation& op =
operationPool_.operation(unit->operation(j)->name().c_str());
// skip any Nulloperations because the check is done elsewhere
if (&op == &NullOperation::instance()) {
continue;
}
if (op.usesMemory() && unit->addressSpace() == NULL) {
results.addError(*this,
std::string("operation ") + op.name() + " accesses memory" +
" but the memory address space was not set.");
return false;
}
}
} // end for all FUs
return true;
}
|
#include <stdio.h>
#include "Logger.h"
#include "GEngine.h"
#include "colors.h"
#include "GShaderProgram.h"
#include "GShaderProgramManager.h"
#include "GShaderVariableHandle.h"
#include "GVertexBufferObject.h"
#include "GPrimativeFactory.h"
#include "GLight_T.h"
using glw::GReturnCode::GLW_SUCCESS;
using glw::GReturnCode::GLW_FAIL;
using glw::engine::GEngine;
using glw::engine::glsl::GShaderProgram;
using glw::engine::glsl::GShaderProgramId;
using glw::engine::glsl::GShaderProgramManager;
using glw::engine::glsl::GLight_T;
using glw::engine::glsl::GShaderVariableHandle;
using glw::engine::buffers::GVertexBufferObject;
using glw::engine::buffers::GPrimativeFactory;
using glw::engine::buffers::GArrayVertex;
using glw::engine::buffers::GArrayVec3;
using glw::engine::buffers::GArrayVec2;
using glw::engine::buffers::GArrayVBO;
namespace
{
const char * TRG = "MAIN";
const char * __CLASSNAME__ = "main";
GEngine engine;
GShaderProgramManager shaderProgramManager;
GShaderProgramId LIGHTING_PROGRAM;
GArrayVBO vbos;
GCamera camera(glm::vec3(0, 0, 5), glm::vec3(), glm::vec3(0,0,-1), glm::vec3(0, 1, 0));
GLight_T light = { glm::vec3(5, 5, 5), glw::WHITE, glm::vec3(1, 25, 100) };
glm::vec3 ambientColor = glw::BLACK;
}
GReturnCode loop()
{
// (calculations should be done in a different thread)
// Update the camera
camera.update(0.1f, 0.9f);
// Update the engine with the camera
engine.setCamera(camera);
// Rotate the sphere
vbos[0].m_theta += 0.01f;
// Rotate the second VBO around the sphere using quaternions
vbos[1].m_pos = glm::quat(1, 0, 0.001f, 0) * vbos[1].m_pos;
// Set the scene clear color
engine.setClearColor(ambientColor);
// Clear the scene
engine.clearAll();
// Set the 3D perspective
engine.load3DPerspective();
// Load the shader program we want to draw with
shaderProgramManager.loadProgram(LIGHTING_PROGRAM);
// Draw the sphere VBO
shaderProgramManager.drawVBOs(vbos);
return GLW_SUCCESS;
}
GReturnCode initShaderPrograms()
{
GReturnCode success = GLW_SUCCESS;
LINFO(TRG, "Initialising GLSL shader programs...");
// Add a new program to the manager
if (GLW_SUCCESS == shaderProgramManager.addNewProgram(
"../shaders/phong.vert", // Vertex shader
"../shaders/phong.frag", // Fragment shader
engine.getModelMat(), // Pass the engine's model matrix
engine.getViewMat(), // Pass the engine's view matrix
engine.getProjMat(), // Pass the engine's proj. matrix
LIGHTING_PROGRAM)) // Supply the id container
{
// Get the shader program we have just created
GShaderProgram * shaderProgram = shaderProgramManager.getProgram(LIGHTING_PROGRAM);
// Check the program has been created
if (NULL != shaderProgram)
{
if(shaderProgram->isValid())
{
// Set the variable handle for our textures
if (GLW_FAIL == shaderProgram->setTexHandle())
{
success = GLW_FAIL;
}
// Add a global light properties //
if (GLW_FAIL == shaderProgram->addHandle(GShaderVariableHandle(VAR_LIGHT_POSITION,
&light.pos)))
{
success = GLW_FAIL;
}
if (GLW_FAIL == shaderProgram->addHandle(GShaderVariableHandle(VAR_LIGHT_COLOR,
&light.color)))
{
success = GLW_FAIL;
}
if (GLW_FAIL == shaderProgram->addHandle(GShaderVariableHandle(VAR_LIGHT_PROPERTIES,
&light.brightness_specscale_shinniness)))
{
success = GLW_FAIL;
}
if (GLW_FAIL == shaderProgram->addHandle(GShaderVariableHandle(VAR_EYE_POSITION,
engine.getEyePos())))
{
success = GLW_FAIL;
}
if (GLW_FAIL == shaderProgram->addHandle(GShaderVariableHandle(VAR_AMBIENT_COLOR,
&ambientColor)))
{
success = GLW_FAIL;
}
}
else
{
success = GLW_FAIL;
LERROR(TRG, "LIGHTING_PROGRAM is not valid",
__FILE__, __LINE__, __CLASSNAME__, __func__);
}
}
else
{
success = GLW_FAIL;
LERROR(TRG, "LIGHTING_PROGRAM is NULL",
__FILE__, __LINE__, __CLASSNAME__, __func__);
}
}
else
{
success = GLW_FAIL;
LERROR(TRG, "Failed to add LIGHTING_PROGRAM",
__FILE__, __LINE__, __CLASSNAME__, __func__);
}
return success;
}
GReturnCode initVBOs()
{
GReturnCode success = GLW_SUCCESS;
LINFO(TRG, "Initialising VBOs...");
// Create array containers
GArrayVertex o;
GArrayVec3 v, c, n, t;
GArrayVec2 uv;
LINFO(TRG, "Generating Sphere...");
// Generate an array of vec3s for a sphere
GPrimativeFactory::sphere(v, 200, 200);
// Create the texture coordinates for a sphere
GPrimativeFactory::sphereicalUVs(uv, v);
// Pack the vec3s and texture coords into a vertex array
GPrimativeFactory::packObject(o, v, uv);
// Create a new VBO with our new vertex array
vbos.push_back(
GVertexBufferObject(
o, // Supply the vertex array
glm::vec3(), // World position
glm::vec3(0, 1, 0), // Rotation axis
glm::radians(0.0f), // Rotation angle
glm::vec3(1, 0, 0), // Pre-rotation axis
glm::radians(90.0f), // Pre-rotation angle
glm::vec3(1), // Scale vector
"../textures/mars.jpg") // Texture file
);
// Create a new VBO with our new vertex array
vbos.push_back(
GVertexBufferObject(
o, // Supply the vertex array
glm::vec3(4, 0, 0), // World position
glm::vec3(0, 1, 0), // Rotation axis
glm::radians(0.0f), // Rotation angle
glm::vec3(1, 0, 0), // Pre-rotation axis
glm::radians(90.0f), // Pre-rotation angle
glm::vec3(0.1f), // Scale vector
"../textures/151.bmp") // Texture file
);
return success;
}
GReturnCode init()
{
GReturnCode success = GLW_SUCCESS;
// SHADER PROGRAM SETUP //
success = initShaderPrograms();
// MESH SETUP //
if (GLW_SUCCESS == success)
{
success = initVBOs();
}
return success;
}
void mouse_button_callback(GLFWwindow* window, int button, int action, int mods)
{
if (action == GLFW_PRESS)
{
switch (button)
{
case GLFW_MOUSE_BUTTON_LEFT:
LINFO(TRG, "User left click");
break;
}
}
}
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
if (action == GLFW_PRESS || action == GLFW_REPEAT)
{
switch (key)
{
case GLFW_KEY_A:
camera.applyForceLeft();
break;
case GLFW_KEY_D:
camera.applyForceRight();
break;
case GLFW_KEY_W:
camera.applyForceForward();
break;
case GLFW_KEY_S:
camera.applyForceBackward();
break;
case GLFW_KEY_Q:
camera.applyForceDown();
break;
case GLFW_KEY_E:
camera.applyForceUp();
break;
case GLFW_KEY_ESCAPE:
LINFO(TRG, "User triggered terminatation.");
glfwSetWindowShouldClose(window, GL_TRUE);
break;
}
}
}
int main()
{
LSTARTLOGGER("../logs/GLW");
LINFO(TRG, "Program started.");
// Set the clear colour of the scene
engine.setClearColor(ambientColor);
// Set the window size
engine.setWindowSize(glm::vec2(1280,720));
// Set the callbacks for the engine, and run
engine.run(loop, init, key_callback, mouse_button_callback);
LINFO(TRG, "Program exit.");
LENDLOGGER();
return 0;
}
|
/*
Copyright (c) 2015-2016 Advanced Micro Devices, Inc. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
/* HIT_START
* BUILD: %t %s ../../test_common.cpp
* RUN: %t
* HIT_END
*/
// TODO - bug if run both back-to-back, once fixed should just need one command line
#include "test_common.h"
#include <malloc.h>
__global__ void Inc(float* Ad) {
int tx = threadIdx.x + blockIdx.x * blockDim.x;
Ad[tx] = Ad[tx] + float(1);
}
template <typename T>
void doMemCopy(size_t numElements, int offset, T* A, T* Bh, T* Bd, bool internalRegister) {
A = A + offset;
numElements -= offset;
size_t sizeBytes = numElements * sizeof(T);
if (internalRegister) {
HIPCHECK(hipHostRegister(A, sizeBytes, 0));
}
// Reset
for (size_t i = 0; i < numElements; i++) {
A[i] = float(i);
Bh[i] = 0.0f;
}
HIPCHECK(hipMemset(Bd, 13.0f, sizeBytes));
//
HIPCHECK(hipMemcpy(Bd, A, sizeBytes, hipMemcpyHostToDevice));
HIPCHECK(hipMemcpy(Bh, Bd, sizeBytes, hipMemcpyDeviceToHost));
// Make sure the copy worked
for (size_t i = 0; i < numElements; i++) {
if (Bh[i] != A[i]) {
printf("mismatch at Bh[%zu]=%f, A[%zu]=%f\n", i, Bh[i], i, A[i]);
failed("mismatch");
};
}
if (internalRegister) {
HIPCHECK(hipHostUnregister(A));
}
}
int main(int argc, char* argv[]) {
HipTest::parseStandardArguments(argc, argv, true);
const size_t size = N * sizeof(float);
if (p_tests & 0x1) {
float *A, **Ad;
int num_devices;
HIPCHECK(hipGetDeviceCount(&num_devices));
Ad = new float*[num_devices];
A = (float*)malloc(size);
HIPCHECK(hipHostRegister(A, size, 0));
for (int i = 0; i < N; i++) {
A[i] = float(1);
}
for (int i = 0; i < num_devices; i++) {
HIPCHECK(hipSetDevice(i));
HIPCHECK(hipHostGetDevicePointer((void**)&Ad[i], A, 0));
}
// Reference the registered device pointer Ad from inside the kernel:
for (int i = 0; i < num_devices; i++) {
HIPCHECK(hipSetDevice(i));
hipLaunchKernelGGL(Inc, dim3(N / 512), dim3(512), 0, 0, Ad[i]);
HIPCHECK(hipDeviceSynchronize());
}
HIPASSERT(A[10] == 1.0f + float(num_devices));
HIPCHECK(hipHostUnregister(A));
free(A);
delete [] Ad;
}
if (p_tests & 0x6) {
// Sensitize HIP bug if device does not match where the memory was registered.
HIPCHECK(hipSetDevice(0));
float* A = (float*)malloc(size);
// Copy to B, this should be optimal pinned malloc copy:
// Note we are using the host pointer here:
float *Bh, *Bd;
Bh = (float*)malloc(size);
HIPCHECK(hipMalloc(&Bd, size));
// TODO - set to 128
#define OFFSETS_TO_TRY 128
assert(N > OFFSETS_TO_TRY);
if (p_tests & 0x2) {
for (size_t i = 0; i < OFFSETS_TO_TRY; i++) {
doMemCopy(N, i, A, Bh, Bd, true /*internalRegister*/);
}
}
if (p_tests & 0x4) {
HIPCHECK(hipHostRegister(A, size, 0));
for (size_t i = 0; i < OFFSETS_TO_TRY; i++) {
doMemCopy(N, i, A, Bh, Bd, false /*internalRegister*/);
}
HIPCHECK(hipHostUnregister(A));
}
free(A);
free(Bh);
hipFree(Bd);
}
passed();
}
|
/******************************************************************************
* ____ _ _____ *
* / ___| / \ | ___| C++ *
* | | / _ \ | |_ Actor *
* | |___ / ___ \| _| Framework *
* \____/_/ \_|_| *
* *
* Copyright 2011-2018 Dominik Charousset *
* *
* Distributed under the terms and conditions of the BSD 3-Clause License or *
* (at your option) under the terms and conditions of the Boost Software *
* License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. *
* *
* If you did not receive a copy of the license files, see *
* http://opensource.org/licenses/BSD-3-Clause and *
* http://www.boost.org/LICENSE_1_0.txt. *
******************************************************************************/
#pragma once
#include <deque>
#include <vector>
#include <cstdint>
#include <cstddef>
#include "caf/actor_control_block.hpp"
#include "caf/downstream_msg.hpp"
#include "caf/fwd.hpp"
#include "caf/logger.hpp"
#include "caf/stream_aborter.hpp"
#include "caf/stream_slot.hpp"
#include "caf/system_messages.hpp"
#include "caf/detail/type_traits.hpp"
#include "caf/meta/type_name.hpp"
namespace caf {
/// State for a single path to a sink of a `downstream_manager`.
class outbound_path {
public:
// -- member types -----------------------------------------------------------
/// Propagates graceful shutdowns.
using regular_shutdown = downstream_msg::close;
/// Propagates errors.
using irregular_shutdown = downstream_msg::forced_close;
/// Stores batches until receiving corresponding ACKs.
using cache_type = std::deque<std::pair<int64_t, downstream_msg::batch>>;
// -- constants --------------------------------------------------------------
/// Stream aborter flag to monitor a path.
static constexpr const auto aborter_type = stream_aborter::sink_aborter;
// -- constructors, destructors, and assignment operators --------------------
/// Constructs a pending path for given slot and handle.
outbound_path(stream_slot sender_slot, strong_actor_ptr receiver_hdl);
~outbound_path();
// -- downstream communication -----------------------------------------------
/// Sends an `open_stream_msg` handshake.
static void emit_open(local_actor* self, stream_slot slot,
strong_actor_ptr to, message handshake_data,
stream_priority prio);
/// Sends a `downstream_msg::batch` on this path. Decrements `open_credit` by
/// `xs_size` and increments `next_batch_id` by 1.
void emit_batch(local_actor* self, int32_t xs_size, message xs);
template <class Iterator>
Iterator emit_batches_impl(local_actor* self, Iterator i, Iterator e,
bool force_underfull) {
CAF_LOG_TRACE(CAF_ARG(force_underfull));
CAF_ASSERT(desired_batch_size > 0);
using type = detail::decay_t<decltype(*i)>;
// Ship full batches.
while (std::distance(i, e) >= desired_batch_size) {
std::vector<type> tmp{std::make_move_iterator(i),
std::make_move_iterator(i + desired_batch_size)};
emit_batch(self, desired_batch_size, make_message(std::move(tmp)));
i += desired_batch_size;
}
// Ship underful batch only if `force_underful` is set.
if (i != e && force_underfull) {
std::vector<type> tmp{std::make_move_iterator(i),
std::make_move_iterator(e)};
auto tmp_size = static_cast<int32_t>(tmp.size());
emit_batch(self, tmp_size, make_message(std::move(tmp)));
return e;
}
return i;
}
/// Calls `emit_batch` for each chunk in the cache, whereas each chunk is of
/// size `desired_batch_size`. Does nothing for pending paths.
template <class T>
void emit_batches(local_actor* self, std::vector<T>& cache,
bool force_underfull) {
CAF_LOG_TRACE(CAF_ARG(slots) << CAF_ARG(open_credit) << CAF_ARG(cache)
<< CAF_ARG(force_underfull));
if (pending())
return;
CAF_ASSERT(open_credit >= 0);
CAF_ASSERT(desired_batch_size > 0);
CAF_ASSERT(cache.size() <= std::numeric_limits<int32_t>::max());
auto first = cache.begin();
auto last = first + std::min(open_credit,
static_cast<int32_t>(cache.size()));
if (first == last)
return;
auto i = emit_batches_impl(self, first, last, force_underfull);
if (i == cache.end()) {
cache.clear();
} else if (i != first) {
cache.erase(first, i);
}
}
/// Sends a `downstream_msg::close` on this path.
void emit_regular_shutdown(local_actor* self);
/// Sends a `downstream_msg::forced_close` on this path.
void emit_irregular_shutdown(local_actor* self, error reason);
/// Sends a `downstream_msg::forced_close`.
static void emit_irregular_shutdown(local_actor* self, stream_slots slots,
const strong_actor_ptr& hdl,
error reason);
// -- properties -------------------------------------------------------------
/// Returns whether this path is pending, i.e., didn't receive an `ack_open`
/// yet.
bool pending() const noexcept {
return slots.receiver == invalid_stream_slot;
}
/// Returns whether no pending ACKs exist.
bool clean() const noexcept {
return next_batch_id == next_ack_id;
}
void set_desired_batch_size(int32_t value) noexcept;
// -- member variables -------------------------------------------------------
/// Slot IDs for sender (self) and receiver (hdl).
stream_slots slots;
/// Handle to the sink.
strong_actor_ptr hdl;
/// Next expected batch ID.
int64_t next_batch_id;
/// Currently available credit on this path.
int32_t open_credit;
/// Ideal batch size. Configured by the sink.
int32_t desired_batch_size;
/// ID of the first unacknowledged batch. Note that CAF uses accumulative
/// ACKs, i.e., receiving an ACK with a higher ID is not an error.
int64_t next_ack_id;
/// Stores the maximum capacity of the downstream actor.
int32_t max_capacity;
/// Stores whether an outbound path is marked for removal. The
/// `downstream_manger` no longer sends new batches to a closing path, but
/// buffered batches are still shipped. The owning `stream_manager` removes
/// the path when receiving an `upstream_msg::ack_batch` and no pending
/// batches for this path exist.
bool closing;
};
/// @relates outbound_path
template <class Inspector>
typename Inspector::result_type inspect(Inspector& f, outbound_path& x) {
return f(meta::type_name("outbound_path"), x.slots, x.hdl, x.next_batch_id,
x.open_credit, x.desired_batch_size, x.next_ack_id);
}
} // namespace caf
|
/*
Copyright (c) 2008-2009 nemesis Developers Association. All rights reserved.
Governed by the nemesis License 3.0 the full text of which is contained in
the file License.txt included in nemesis binary and source code distribution
packages.
*/
#include "System.h"
#include "Main/GraphicUserInterface.h"
#include "Common/SecurityToken.h"
#include "NewSecurityTokenKeyfileDialog.h"
#include "SecurityTokenKeyfilesDialog.h"
namespace nemesis
{
SecurityTokenKeyfilesDialog::SecurityTokenKeyfilesDialog (wxWindow* parent, bool selectionMode)
: SecurityTokenKeyfilesDialogBase (parent)
{
if (selectionMode)
SetTitle (LangString["SELECT_TOKEN_KEYFILES"]);
list <int> colPermilles;
SecurityTokenKeyfileListCtrl->InsertColumn (ColumnSecurityTokenSlotId, LangString["TOKEN_SLOT_ID"], wxLIST_FORMAT_CENTER, 1);
colPermilles.push_back (102);
SecurityTokenKeyfileListCtrl->InsertColumn (ColumnSecurityTokenLabel, LangString["TOKEN_NAME"], wxLIST_FORMAT_LEFT, 1);
colPermilles.push_back (368);
SecurityTokenKeyfileListCtrl->InsertColumn (ColumnSecurityTokenKeyfileLabel, LangString["TOKEN_DATA_OBJECT_LABEL"], wxLIST_FORMAT_LEFT, 1);
colPermilles.push_back (529);
FillSecurityTokenKeyfileListCtrl();
Gui->SetListCtrlWidth (SecurityTokenKeyfileListCtrl, 65);
Gui->SetListCtrlHeight (SecurityTokenKeyfileListCtrl, 16);
Gui->SetListCtrlColumnWidths (SecurityTokenKeyfileListCtrl, colPermilles);
Fit();
Layout();
Center();
DeleteButton->Disable();
ExportButton->Disable();
OKButton->Disable();
OKButton->SetDefault();
}
void SecurityTokenKeyfilesDialog::FillSecurityTokenKeyfileListCtrl ()
{
wxBusyCursor busy;
SecurityTokenKeyfileListCtrl->DeleteAllItems();
SecurityTokenKeyfileList = SecurityToken::GetAvailableKeyfiles();
size_t i = 0;
foreach (const SecurityTokenKeyfile &key, SecurityTokenKeyfileList)
{
vector <wstring> fields (SecurityTokenKeyfileListCtrl->GetColumnCount());
fields[ColumnSecurityTokenSlotId] = StringConverter::ToWide ((uint64) key.SlotId);
fields[ColumnSecurityTokenLabel] = key.Token.Label;
fields[ColumnSecurityTokenKeyfileLabel] = key.Id;
Gui->AppendToListCtrl (SecurityTokenKeyfileListCtrl, fields, 0, &SecurityTokenKeyfileList[i++]);
}
}
void SecurityTokenKeyfilesDialog::OnDeleteButtonClick (wxCommandEvent& event)
{
try
{
if (!Gui->AskYesNo (LangString["CONFIRM_SEL_FILES_DELETE"]))
return;
wxBusyCursor busy;
foreach (long item, Gui->GetListCtrlSelectedItems (SecurityTokenKeyfileListCtrl))
{
SecurityToken::DeleteKeyfile (*reinterpret_cast <SecurityTokenKeyfile *> (SecurityTokenKeyfileListCtrl->GetItemData (item)));
}
FillSecurityTokenKeyfileListCtrl();
}
catch (exception &e)
{
Gui->ShowError (e);
}
}
void SecurityTokenKeyfilesDialog::OnExportButtonClick (wxCommandEvent& event)
{
try
{
foreach (long item, Gui->GetListCtrlSelectedItems (SecurityTokenKeyfileListCtrl))
{
SecurityTokenKeyfile *keyfile = reinterpret_cast <SecurityTokenKeyfile *> (SecurityTokenKeyfileListCtrl->GetItemData (item));
FilePathList files = Gui->SelectFiles (this, wxEmptyString, true);
if (!files.empty())
{
wxBusyCursor busy;
vector <byte> keyfileData;
SecurityToken::GetKeyfileData (*keyfile, keyfileData);
BufferPtr keyfileDataBuf (&keyfileData.front(), keyfileData.size());
finally_do_arg (BufferPtr, keyfileDataBuf, { finally_arg.Erase(); });
File keyfile;
keyfile.Open (*files.front(), File::CreateWrite);
keyfile.Write (keyfileDataBuf);
}
else
break;
Gui->ShowInfo ("KEYFILE_EXPORTED");
}
}
catch (exception &e)
{
Gui->ShowError (e);
}
}
void SecurityTokenKeyfilesDialog::OnImportButtonClick (wxCommandEvent& event)
{
try
{
FilePathList keyfilePaths = Gui->SelectFiles (this, LangString["SELECT_KEYFILES"], false);
if (keyfilePaths.empty())
return;
FilePath keyfilePath = *keyfilePaths.front();
File keyfile;
keyfile.Open (keyfilePath, File::OpenRead, File::ShareReadWrite, File::PreserveTimestamps);
if (keyfile.Length() > 0)
{
vector <byte> keyfileData (keyfile.Length());
BufferPtr keyfileDataBuf (&keyfileData.front(), keyfileData.size());
keyfile.ReadCompleteBuffer (keyfileDataBuf);
finally_do_arg (BufferPtr, keyfileDataBuf, { finally_arg.Erase(); });
NewSecurityTokenKeyfileDialog newKeyfileDialog (this, keyfilePath.ToBaseName());
if (newKeyfileDialog.ShowModal() == wxID_OK)
{
wxBusyCursor busy;
SecurityToken::CreateKeyfile (newKeyfileDialog.GetSelectedSlotId(), keyfileData, StringConverter::ToSingle (newKeyfileDialog.GetKeyfileName()));
FillSecurityTokenKeyfileListCtrl();
}
}
else
throw InsufficientData (SRC_POS, keyfilePath);
}
catch (exception &e)
{
Gui->ShowError (e);
}
}
void SecurityTokenKeyfilesDialog::OnListItemDeselected (wxListEvent& event)
{
if (SecurityTokenKeyfileListCtrl->GetSelectedItemCount() == 0)
{
DeleteButton->Disable();
ExportButton->Disable();
OKButton->Disable();
}
}
void SecurityTokenKeyfilesDialog::OnListItemSelected (wxListEvent& event)
{
if (event.GetItem().GetData() != (wxUIntPtr) nullptr)
{
DeleteButton->Enable();
ExportButton->Enable();
OKButton->Enable();
}
}
void SecurityTokenKeyfilesDialog::OnOKButtonClick ()
{
foreach (long item, Gui->GetListCtrlSelectedItems (SecurityTokenKeyfileListCtrl))
{
SecurityTokenKeyfile *key = reinterpret_cast <SecurityTokenKeyfile *> (SecurityTokenKeyfileListCtrl->GetItemData (item));
SelectedSecurityTokenKeyfilePaths.push_back (*key);
}
EndModal (wxID_OK);
}
}
|
// Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
#include "extern/beatsaber-hook/shared/utils/byref.hpp"
// Including type: UnityEngine.ProBuilder.ProBuilderMesh
#include "UnityEngine/ProBuilder/ProBuilderMesh.hpp"
// Including type: UnityEngine.Vector4
#include "UnityEngine/Vector4.hpp"
// Including type: UnityEngine.Vector2
#include "UnityEngine/Vector2.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "extern/beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Begin forward declares
// Forward declaring namespace: System
namespace System {
// Forward declaring type: Func`2<T, TResult>
template<typename T, typename TResult>
class Func_2;
}
// Forward declaring namespace: UnityEngine::ProBuilder
namespace UnityEngine::ProBuilder {
// Forward declaring type: Face
class Face;
}
// Completed forward declares
// Type namespace: UnityEngine.ProBuilder
namespace UnityEngine::ProBuilder {
// Forward declaring type: <>c
class $$c;
}
#include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
NEED_NO_BOX(UnityEngine::ProBuilder::ProBuilderMesh::$$c);
DEFINE_IL2CPP_ARG_TYPE(UnityEngine::ProBuilder::ProBuilderMesh::$$c*, "UnityEngine.ProBuilder", "ProBuilderMesh/<>c");
// Type namespace: UnityEngine.ProBuilder
namespace UnityEngine::ProBuilder {
// Size: 0x10
#pragma pack(push, 1)
// Autogenerated type: UnityEngine.ProBuilder.ProBuilderMesh/UnityEngine.ProBuilder.<>c
// [TokenAttribute] Offset: FFFFFFFF
// [CompilerGeneratedAttribute] Offset: FFFFFFFF
class ProBuilderMesh::$$c : public ::Il2CppObject {
public:
// Get static field: static public readonly UnityEngine.ProBuilder.ProBuilderMesh/UnityEngine.ProBuilder.<>c <>9
static UnityEngine::ProBuilder::ProBuilderMesh::$$c* _get_$$9();
// Set static field: static public readonly UnityEngine.ProBuilder.ProBuilderMesh/UnityEngine.ProBuilder.<>c <>9
static void _set_$$9(UnityEngine::ProBuilder::ProBuilderMesh::$$c* value);
// Get static field: static public System.Func`2<UnityEngine.Vector4,UnityEngine.Vector2> <>9__102_0
static System::Func_2<UnityEngine::Vector4, UnityEngine::Vector2>* _get_$$9__102_0();
// Set static field: static public System.Func`2<UnityEngine.Vector4,UnityEngine.Vector2> <>9__102_0
static void _set_$$9__102_0(System::Func_2<UnityEngine::Vector4, UnityEngine::Vector2>* value);
// Get static field: static public System.Func`2<UnityEngine.Vector4,UnityEngine.Vector2> <>9__102_1
static System::Func_2<UnityEngine::Vector4, UnityEngine::Vector2>* _get_$$9__102_1();
// Set static field: static public System.Func`2<UnityEngine.Vector4,UnityEngine.Vector2> <>9__102_1
static void _set_$$9__102_1(System::Func_2<UnityEngine::Vector4, UnityEngine::Vector2>* value);
// Get static field: static public System.Func`2<UnityEngine.ProBuilder.Face,System.Int32> <>9__110_0
static System::Func_2<UnityEngine::ProBuilder::Face*, int>* _get_$$9__110_0();
// Set static field: static public System.Func`2<UnityEngine.ProBuilder.Face,System.Int32> <>9__110_0
static void _set_$$9__110_0(System::Func_2<UnityEngine::ProBuilder::Face*, int>* value);
// Get static field: static public System.Func`2<UnityEngine.ProBuilder.Face,System.Int32> <>9__112_0
static System::Func_2<UnityEngine::ProBuilder::Face*, int>* _get_$$9__112_0();
// Set static field: static public System.Func`2<UnityEngine.ProBuilder.Face,System.Int32> <>9__112_0
static void _set_$$9__112_0(System::Func_2<UnityEngine::ProBuilder::Face*, int>* value);
// Get static field: static public System.Func`2<UnityEngine.ProBuilder.Face,UnityEngine.ProBuilder.Face> <>9__147_0
static System::Func_2<UnityEngine::ProBuilder::Face*, UnityEngine::ProBuilder::Face*>* _get_$$9__147_0();
// Set static field: static public System.Func`2<UnityEngine.ProBuilder.Face,UnityEngine.ProBuilder.Face> <>9__147_0
static void _set_$$9__147_0(System::Func_2<UnityEngine::ProBuilder::Face*, UnityEngine::ProBuilder::Face*>* value);
// static private System.Void .cctor()
// Offset: 0x1675A9C
static void _cctor();
// UnityEngine.Vector2 <SetUVs>b__102_0(UnityEngine.Vector4 x)
// Offset: 0x1675B08
UnityEngine::Vector2 $SetUVs$b__102_0(UnityEngine::Vector4 x);
// UnityEngine.Vector2 <SetUVs>b__102_1(UnityEngine.Vector4 x)
// Offset: 0x1675B98
UnityEngine::Vector2 $SetUVs$b__102_1(UnityEngine::Vector4 x);
// System.Int32 <get_indexCount>b__110_0(UnityEngine.ProBuilder.Face x)
// Offset: 0x1675C28
int $get_indexCount$b__110_0(UnityEngine::ProBuilder::Face* x);
// System.Int32 <get_triangleCount>b__112_0(UnityEngine.ProBuilder.Face x)
// Offset: 0x1675C4C
int $get_triangleCount$b__112_0(UnityEngine::ProBuilder::Face* x);
// UnityEngine.ProBuilder.Face <CopyFrom>b__147_0(UnityEngine.ProBuilder.Face x)
// Offset: 0x1675C70
UnityEngine::ProBuilder::Face* $CopyFrom$b__147_0(UnityEngine::ProBuilder::Face* x);
// public System.Void .ctor()
// Offset: 0x1675B00
// Implemented from: System.Object
// Base method: System.Void Object::.ctor()
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static ProBuilderMesh::$$c* New_ctor() {
static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::ProBuilder::ProBuilderMesh::$$c::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<ProBuilderMesh::$$c*, creationType>()));
}
}; // UnityEngine.ProBuilder.ProBuilderMesh/UnityEngine.ProBuilder.<>c
#pragma pack(pop)
}
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: UnityEngine::ProBuilder::ProBuilderMesh::$$c::_cctor
// Il2CppName: .cctor
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (*)()>(&UnityEngine::ProBuilder::ProBuilderMesh::$$c::_cctor)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(UnityEngine::ProBuilder::ProBuilderMesh::$$c*), ".cctor", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: UnityEngine::ProBuilder::ProBuilderMesh::$$c::$SetUVs$b__102_0
// Il2CppName: <SetUVs>b__102_0
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<UnityEngine::Vector2 (UnityEngine::ProBuilder::ProBuilderMesh::$$c::*)(UnityEngine::Vector4)>(&UnityEngine::ProBuilder::ProBuilderMesh::$$c::$SetUVs$b__102_0)> {
static const MethodInfo* get() {
static auto* x = &::il2cpp_utils::GetClassFromName("UnityEngine", "Vector4")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(UnityEngine::ProBuilder::ProBuilderMesh::$$c*), "<SetUVs>b__102_0", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{x});
}
};
// Writing MetadataGetter for method: UnityEngine::ProBuilder::ProBuilderMesh::$$c::$SetUVs$b__102_1
// Il2CppName: <SetUVs>b__102_1
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<UnityEngine::Vector2 (UnityEngine::ProBuilder::ProBuilderMesh::$$c::*)(UnityEngine::Vector4)>(&UnityEngine::ProBuilder::ProBuilderMesh::$$c::$SetUVs$b__102_1)> {
static const MethodInfo* get() {
static auto* x = &::il2cpp_utils::GetClassFromName("UnityEngine", "Vector4")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(UnityEngine::ProBuilder::ProBuilderMesh::$$c*), "<SetUVs>b__102_1", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{x});
}
};
// Writing MetadataGetter for method: UnityEngine::ProBuilder::ProBuilderMesh::$$c::$get_indexCount$b__110_0
// Il2CppName: <get_indexCount>b__110_0
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (UnityEngine::ProBuilder::ProBuilderMesh::$$c::*)(UnityEngine::ProBuilder::Face*)>(&UnityEngine::ProBuilder::ProBuilderMesh::$$c::$get_indexCount$b__110_0)> {
static const MethodInfo* get() {
static auto* x = &::il2cpp_utils::GetClassFromName("UnityEngine.ProBuilder", "Face")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(UnityEngine::ProBuilder::ProBuilderMesh::$$c*), "<get_indexCount>b__110_0", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{x});
}
};
// Writing MetadataGetter for method: UnityEngine::ProBuilder::ProBuilderMesh::$$c::$get_triangleCount$b__112_0
// Il2CppName: <get_triangleCount>b__112_0
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (UnityEngine::ProBuilder::ProBuilderMesh::$$c::*)(UnityEngine::ProBuilder::Face*)>(&UnityEngine::ProBuilder::ProBuilderMesh::$$c::$get_triangleCount$b__112_0)> {
static const MethodInfo* get() {
static auto* x = &::il2cpp_utils::GetClassFromName("UnityEngine.ProBuilder", "Face")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(UnityEngine::ProBuilder::ProBuilderMesh::$$c*), "<get_triangleCount>b__112_0", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{x});
}
};
// Writing MetadataGetter for method: UnityEngine::ProBuilder::ProBuilderMesh::$$c::$CopyFrom$b__147_0
// Il2CppName: <CopyFrom>b__147_0
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<UnityEngine::ProBuilder::Face* (UnityEngine::ProBuilder::ProBuilderMesh::$$c::*)(UnityEngine::ProBuilder::Face*)>(&UnityEngine::ProBuilder::ProBuilderMesh::$$c::$CopyFrom$b__147_0)> {
static const MethodInfo* get() {
static auto* x = &::il2cpp_utils::GetClassFromName("UnityEngine.ProBuilder", "Face")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(UnityEngine::ProBuilder::ProBuilderMesh::$$c*), "<CopyFrom>b__147_0", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{x});
}
};
// Writing MetadataGetter for method: UnityEngine::ProBuilder::ProBuilderMesh::$$c::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
|
/*
Copyright 2020 The OneFlow Authors. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "oneflow/core/graph/task_graph.h"
#include "oneflow/core/common/util.h"
#include "oneflow/core/graph/inplace_lbi_graph.h"
#include "oneflow/core/graph/id_serialization.h"
#include "oneflow/core/register/runtime_blob_desc.h"
#include "oneflow/core/job/global_for.h"
#include "oneflow/core/operator/variable_op.h"
#include "oneflow/core/graph/op_graph.h"
#include "oneflow/core/graph/normal_forward_compute_task_node.h"
#include "oneflow/core/graph/boxing_identity_task_node.h"
#include "oneflow/core/job/scope.h"
#include "oneflow/core/vm/symbol_storage.h"
#include "oneflow/core/job_rewriter/calculation_pass.h"
#include "oneflow/core/graph/boxing/sub_task_graph_builder_util.h"
#include "oneflow/core/graph/boxing/hierarchical_sub_task_graph_builder_impl.h"
#include "oneflow/core/graph/stream_index_getter_registry_manager.h"
namespace oneflow {
namespace {
bool IsInterfaceTask(const TaskNode* node) {
const auto* comp_task_node = dynamic_cast<const CompTaskNode*>(node);
if (comp_task_node == nullptr) { return false; }
auto op_type_case = comp_task_node->op()->op_conf().op_type_case();
return IsClassRegistered<int32_t, IsInterfaceOpConf4OpTypeCase>(op_type_case);
}
bool IsConnectToTickOp(const TaskNode* node) {
const auto* comp_task_node = dynamic_cast<const CompTaskNode*>(node);
if (comp_task_node == nullptr) { return false; }
const Operator* op = comp_task_node->op().get();
if (dynamic_cast<const VariableOp*>(op) != nullptr) { return true; }
return false;
}
bool IsOptimizerPassOp(const Operator* op) {
// NOTE(chengcheng): use scope::calculation_pass_name instead of area_id to not merge optimizer
// ops with fw/bw ops
if (!op->op_conf().has_scope_symbol_id()) {
// NOTE(chengcheng): Some system op insert to OpGraph may not set scope_symbol_id, it MUST NOT
// optimizer subgraph ops.
return false;
}
int64_t scope_symbol_id = op->op_conf().scope_symbol_id();
CHECK(Global<symbol::Storage<Scope>>::Get()->Has(scope_symbol_id))
<< " Error! op : \n " << op->op_conf().DebugString()
<< " has error scope_symbol_id = " << scope_symbol_id
<< " which cannot find in Global<symbol::Storage<Scope>>::Get()\n";
const Scope& scope = Global<symbol::Storage<Scope>>::Get()->Get(scope_symbol_id);
return scope.scope_proto().calculation_pass_name() == kOptimizerPass;
}
bool IsSubsetTickOpConf(const OperatorConf& op_conf) {
return op_conf.has_src_subset_tick_conf() || op_conf.has_dst_subset_tick_conf();
}
bool IsTickOpConf(const OperatorConf& conf) {
return IsClassRegistered<int32_t, IsTickTockOpTypeCase>(conf.op_type_case());
}
bool IsSpecialOpNotConsiderMergeInChain(const Operator* op) {
const OperatorConf& op_conf = op->op_conf();
if (op_conf.has_variable_conf() || op_conf.has_tick_conf() || op_conf.has_device_tick_conf()
|| op_conf.has_src_subset_tick_conf() || op_conf.has_dst_subset_tick_conf()
|| op_conf.has_source_tick_conf() || op_conf.has_sink_tick_conf()
|| op_conf.has_acc_tick_conf()) {
return true;
}
// NOTE(chengcheng): ONLY nccl_use_compute_stream = false will exclude optimizer pass ops
if (!Global<ResourceDesc, ForSession>::Get()->nccl_use_compute_stream()
&& IsOptimizerPassOp(op)) {
return true;
}
return false;
}
bool IsTaskNodeProducedResgtHasMultiRegstNum(const TaskNode* node) {
for (const auto& pair : node->produced_regsts()) {
if (pair.second->min_register_num() > 1) { return true; }
}
return false;
}
bool CanBeMergedInChain(const TaskNode* node) {
// ONLY the node which is NormalForward and in GPU and NOT variable can be merged.
if (IsTaskNodeProducedResgtHasMultiRegstNum(node)) { return false; }
const auto* fw_comp_node = dynamic_cast<const NormalForwardCompTaskNode*>(node);
if (fw_comp_node == nullptr) { return false; }
if (fw_comp_node->device_type() != DeviceType::kGPU) { return false; }
const Operator* op = fw_comp_node->op().get();
if (IsSpecialOpNotConsiderMergeInChain(op)) { return false; }
return true;
}
void TraverseConnectedSubGraphMergeInThisChain(TaskNode* this_node, const int64_t this_chain_id) {
CHECK_NE(this_chain_id, -1);
CHECK_EQ(this_node->chain_id(), -1);
// bfs search all node can be merged in this chain
HashSet<TaskNode*> visited_nodes;
std::queue<TaskNode*> queued_nodes;
queued_nodes.push(this_node);
visited_nodes.insert(this_node);
while (!queued_nodes.empty()) {
TaskNode* cur_node = queued_nodes.front();
queued_nodes.pop();
CHECK_EQ(cur_node->chain_id(), -1);
cur_node->set_chain_id(this_chain_id);
cur_node->ForEachNodeOnInOutEdge([&](TaskNode* next_node) {
if (visited_nodes.find(next_node) == visited_nodes.end() && CanBeMergedInChain(next_node)
&& this_node->GlobalWorkStreamId() == next_node->GlobalWorkStreamId()) {
if (next_node->chain_id() == -1) {
queued_nodes.push(next_node);
visited_nodes.insert(next_node);
} else {
CHECK_EQ(next_node->chain_id(), this_chain_id);
}
}
});
}
}
std::function<TaskNode*(const std::string&)> MakeGetterTaskNode4SoleOpName(
const HashSet<TaskNode*>& task_nodes) {
auto op_name2task_nodes = std::make_shared<HashMap<std::string, HashSet<TaskNode*>>>();
for (TaskNode* task_node : task_nodes) {
if (task_node->exec_gph().node_num() == 1) {
ExecNode* exec_node = task_node->exec_gph().SoleNode();
CHECK((*op_name2task_nodes)[exec_node->op()->op_name()].emplace(task_node).second);
}
}
return [op_name2task_nodes](const std::string& op_name) -> TaskNode* {
const auto& iter = op_name2task_nodes->find(op_name);
if (iter == op_name2task_nodes->end()) { return nullptr; }
if (iter->second.size() > 1) { return nullptr; }
return *iter->second.begin();
};
}
bool IsLbiOnTaskEdge(const TaskEdge* edge, const LogicalBlobId& lbi) {
for (const auto& regst_desc : edge->GetRegsts()) {
if (regst_desc->HasLbi(lbi)) { return true; }
}
return false;
}
std::function<bool(const LogicalBlobId&, const std::string&)>
MakePredicatorIsLbiAllConsumersReachable(
const std::function<const TaskNode*(const std::string&)>& TaskNode4SoleOpName,
const std::function<bool(const std::string&, const std::string&)>&
IsOpNameDataOrCtrlReachable) {
auto IsDataOrCtrlReachable = [IsOpNameDataOrCtrlReachable](const TaskNode* src_node,
const TaskNode* dst_node) -> bool {
if (src_node->chain_id() == dst_node->chain_id()
&& src_node->order_in_graph() <= dst_node->order_in_graph()) {
return true;
}
const CompTaskNode* comp_src_node = dynamic_cast<const CompTaskNode*>(src_node);
if (comp_src_node == nullptr) { return false; }
const CompTaskNode* comp_dst_node = dynamic_cast<const CompTaskNode*>(dst_node);
if (comp_dst_node == nullptr) { return false; }
return IsOpNameDataOrCtrlReachable(comp_src_node->op()->op_name(),
comp_dst_node->op()->op_name());
};
return [TaskNode4SoleOpName, IsDataOrCtrlReachable](const LogicalBlobId& lbi,
const std::string& op_name) -> bool {
const TaskNode* src_task_node = TaskNode4SoleOpName(lbi.op_name());
const TaskNode* dst_task_node = TaskNode4SoleOpName(op_name);
size_t out_edges_size = 0;
size_t reachable_out_edges_size = 0;
for (TaskEdge* out_edge : src_task_node->out_edges()) {
if (IsLbiOnTaskEdge(out_edge, lbi)) {
out_edges_size += 1;
reachable_out_edges_size += IsDataOrCtrlReachable(out_edge->dst_node(), dst_task_node);
}
}
return out_edges_size > 0 && out_edges_size == reachable_out_edges_size;
};
}
bool IsInplaceAllowed(
TaskNode* task_node, const std::vector<std::string>& bns,
const std::function<const TaskNode*(const std::string&)>& TaskNode4SoleOpName) {
if (task_node->exec_gph().node_num() != 1) { return false; }
const auto& exec_node = *task_node->exec_gph().SoleNode();
for (const auto& bn : bns) {
// TaskNode for bn is not nullptr if it's on the same device with `task_node`
if (TaskNode4SoleOpName(exec_node.op()->BnInOp2Lbi(bn).op_name()) == nullptr) { return false; }
const RegstDesc& regst_desc = *exec_node.RegstDesc4BnInOp(bn);
if (regst_desc.NumOfLbi() != 1) { return false; }
}
const BlobDesc* first_blob = nullptr;
for (const auto& bn : bns) {
const BlobDesc* blob_desc = exec_node.RegstDesc4BnInOp(bn)->SoleBlobDesc();
if (first_blob == nullptr) {
first_blob = blob_desc;
} else {
if (!(first_blob->shape().elem_cnt() == blob_desc->shape().elem_cnt()
&& first_blob->data_type() == blob_desc->data_type())) {
return false;
}
}
}
return true;
}
std::unique_ptr<BoxingLogger> CreateBoxingLogger() {
if (Global<ResourceDesc, ForSession>::Get()->enable_debug_mode()) {
return std::unique_ptr<BoxingLogger>(
new CsvBoxingLogger(StrCat("boxing/log/", GlobalJobDesc().job_id()) + ".csv"));
} else {
return std::unique_ptr<BoxingLogger>(new NullBoxingLogger());
}
}
Maybe<void> MakeGetterTaskNode4MachineId7ThrdId(
const std::vector<CompTaskNode*>& task_nodes,
std::function<Maybe<CompTaskNode*>(int64_t mchn_id, int64_t thrd_id)>* Getter) {
// ticks are shared within a machine/process
auto machine_id2task_node = std::make_shared<HashMap<int64_t, CompTaskNode*>>();
for (auto* task_node : task_nodes) {
machine_id2task_node->emplace(task_node->machine_id(), task_node);
}
*Getter = [machine_id2task_node](int64_t mchn_id, int64_t thrd_id) -> Maybe<CompTaskNode*> {
const auto& iter = machine_id2task_node->find(mchn_id);
CHECK_OR_RETURN(iter != machine_id2task_node->end());
return iter->second;
};
return Maybe<void>::Ok();
}
void GenSortedCompTaskNodes(const OpNode* op_node, std::vector<CompTaskNode*>* sorted_comp_tasks) {
int64_t parallel_idx = 0;
const ParallelDesc& parallel_desc = op_node->parallel_desc();
int64_t parallel_num = parallel_desc.parallel_num();
for (int64_t machine_id : parallel_desc.sorted_machine_ids()) {
for (int64_t dev_phy_id : parallel_desc.sorted_dev_phy_ids(machine_id)) {
CompTaskNode* comp_task_node = NewCompTaskNode4OpNode(op_node);
comp_task_node->set_machine_id(machine_id);
comp_task_node->mut_parallel_ctx()->set_parallel_id(parallel_idx++);
comp_task_node->mut_parallel_ctx()->set_parallel_num(parallel_num);
DeviceId::device_index_t device_index =
parallel_desc.device_type() == DeviceType::kCPU
? DeviceId::kCPUDeviceIndex
: static_cast<DeviceId::device_index_t>(dev_phy_id);
DeviceId device_id{static_cast<DeviceId::rank_t>(machine_id), parallel_desc.device_type(),
device_index};
StreamId::stream_index_t stream_index =
StreamIndexGetterRegistryManager::Get().StreamIndex4DeviceIdAndTaskType(
device_id, comp_task_node->GetTaskType());
comp_task_node->set_thrd_id(SerializeStreamIdToInt64(StreamId{device_id, stream_index}));
comp_task_node->set_op_node(op_node);
sorted_comp_tasks->push_back(comp_task_node);
}
}
}
bool IsConnectedLbisAllSameParallelDistribution(const OpEdge* op_edge) {
const OpNode* src_node = op_edge->src_node();
const OpNode* dst_node = op_edge->dst_node();
CHECK_GT(op_edge->lbis().size(), 0);
HashSet<bool> predicators;
for (const LogicalBlobId& lbi : op_edge->lbis()) {
const ParallelDistribution& src_parallel_distribution = src_node->ParallelDistribution4Lbi(lbi);
const ParallelDistribution& dst_parallel_distribution = dst_node->ParallelDistribution4Lbi(lbi);
predicators.insert(src_parallel_distribution == dst_parallel_distribution);
}
CHECK_EQ(predicators.size(), 1);
return *predicators.begin();
}
BldSubTskGphMthd GetMthdForBldSubTskGph(const OpEdge* op_edge) {
const OpNode* src_node = op_edge->src_node();
const OpNode* dst_node = op_edge->dst_node();
const ParallelDesc& src_pd = src_node->parallel_desc();
const ParallelDesc& dst_pd = dst_node->parallel_desc();
const OperatorConf& src_op_conf = src_node->op().op_conf();
const OperatorConf& dst_op_conf = dst_node->op().op_conf();
// WaitAndSendIds -> Reentrantlock
if (src_op_conf.has_wait_and_send_ids_conf() && dst_op_conf.has_reentrant_lock_conf()) {
CHECK_EQ(src_pd.parallel_num(), 1);
CHECK_EQ(dst_pd.parallel_num(), 1);
return &TaskGraph::BldSubTskGphByBoxing;
}
// *Tick -> *Tick
if (IsTickOpConf(src_op_conf) || IsTickOpConf(dst_op_conf)) {
if (src_op_conf.has_source_tick_conf()) {
CHECK(dst_op_conf.has_tick_conf());
CHECK_EQ(src_pd.parallel_num(), 1);
CHECK_EQ(dst_pd.parallel_num(), 1);
return &TaskGraph::BldSubTskGphByBoxing;
} else if (dst_op_conf.has_sink_tick_conf()) {
CHECK(src_op_conf.has_tick_conf() || src_op_conf.has_sink_tick_conf());
CHECK_EQ(src_pd.parallel_num(), 1);
CHECK_EQ(dst_pd.parallel_num(), 1);
return &TaskGraph::BldSubTskGphByBoxing;
} else if (IsSubsetTickOpConf(src_op_conf)) {
return &TaskGraph::BldSubTskGphBySrcSubsetConnect;
} else if (IsSubsetTickOpConf(dst_op_conf)) {
return &TaskGraph::BldSubTskGphByDstSubsetConnect;
} else if (IsTickOpConf(src_op_conf) && IsTickOpConf(dst_op_conf)) {
if (src_pd.parallel_num() == dst_pd.parallel_num()) {
return &TaskGraph::BldSubTskGphByOneToOne;
} else {
CHECK_EQ(src_pd.parallel_num(), 1);
return &TaskGraph::BldSubTskGphByBroadcastToBroadcast;
}
}
}
std::shared_ptr<CompTaskNode> src_comp_task(NewCompTaskNode4OpNode(src_node));
std::shared_ptr<CompTaskNode> dst_comp_task(NewCompTaskNode4OpNode(dst_node));
// NOTE(chengcheng): MUST use TaskType instead of OpTypeCase because may
// Multi-op correspoding to SAME TaskType such as:
// DistributeConcatOpConf and DistributeAddOpConf -> TaskType::kDistributeConcat
// DistributeSplitOpConf and DistributeCloneOpConf -> TaskType::kDistributeSplit
// * -> DistributeConcat
if (dst_comp_task->GetTaskType() == TaskType::kDistributeConcat) {
return &TaskGraph::BldSubTskGphByPartialInLbiConnect;
}
// DistributeSplit -> *
if (src_comp_task->GetTaskType() == TaskType::kDistributeSplit) {
return &TaskGraph::BldSubTskGphByPartialOutLbiConnect;
}
// NormalForward -> DecodeH2D
if (src_comp_task->GetTaskType() == TaskType::kNormalForward
&& dst_comp_task->GetTaskType() == TaskType::kDecodeH2D) {
return &TaskGraph::BldSubTskGphNormalForwardToDecodeH2D;
}
if (src_pd.parallel_num() == 1 && dst_pd.parallel_num() == 1) {
return &TaskGraph::BldSubTskGphByOneToOne;
}
// one to one
if (src_pd.parallel_num() == dst_pd.parallel_num() && *src_pd.hierarchy() == *dst_pd.hierarchy()
&& IsConnectedLbisAllSameParallelDistribution(op_edge)) {
return &TaskGraph::BldSubTskGphByOneToOne;
}
return &TaskGraph::BldSubTskGphByBoxing;
}
void ForEachOpGraphNecessaryCtrlEdge(
const OpGraph* op_graph, const std::function<void(const OpNode*, const OpNode*)>& Handler) {
auto IsOpGraphDataReachable = op_graph->MakePredicatorIsReachable();
op_graph->ForEachNode([&](OpNode* dst) {
for (const auto& ctrl_in_op_name : dst->op().op_conf().ctrl_in_op_name()) {
const OpNode* src = op_graph->OpNode4OpName(ctrl_in_op_name);
CHECK(!IsOpGraphDataReachable(dst, src));
if (!IsOpGraphDataReachable(src, dst)) {
CHECK(src->parallel_desc().EqualsOnlyForMachineAndDeviceIds(dst->parallel_desc()));
const Shape* src_time_shape = CHECK_JUST(src->op().GetOpTimeShape()).get();
const Shape* dst_time_shape = CHECK_JUST(dst->op().GetInputBlobFastestTimeShape()).get();
if (dst_time_shape == nullptr) {
dst_time_shape = CHECK_JUST(dst->op().GetOpTimeShape()).get();
}
CHECK_EQ(src_time_shape->elem_cnt(), dst_time_shape->elem_cnt());
Handler(src, dst);
}
}
});
}
} // namespace
TaskGraph::TaskGraph() {
OpGraph* op_graph = Global<OpGraph>::Get();
sub_tsk_gph_builder_ctx_.reset(new SubTskGphBuilderCtx(this));
boxing_logger_ = CreateBoxingLogger();
hierarchical_sub_tsk_gph_builder_.reset(new DispatchHierarchicalSubTskGphBuilder());
HashMap<const OpNode*, std::vector<CompTaskNode*>> op_node2sorted_comp_tasks;
op_graph->ForEachNode([&](const OpNode* op_node) {
std::vector<CompTaskNode*>* sorted_comp_tasks = &(op_node2sorted_comp_tasks[op_node]);
GenSortedCompTaskNodes(op_node, sorted_comp_tasks);
for (CompTaskNode* comp_task : *sorted_comp_tasks) { AddAllocatedNode(comp_task); }
});
op_graph->ForEachEdge([&](const OpEdge* op_edge) {
BldSubTskGphMthd method = GetMthdForBldSubTskGph(op_edge);
(this->*method)(op_edge, op_node2sorted_comp_tasks.at(op_edge->src_node()),
op_node2sorted_comp_tasks.at(op_edge->dst_node()));
});
ForEachOpGraphNecessaryCtrlEdge(op_graph, [&](const OpNode* src, const OpNode* dst) {
const auto& src_task_nodes = op_node2sorted_comp_tasks.at(src);
const auto& dst_task_nodes = op_node2sorted_comp_tasks.at(dst);
if (src->op().op_conf().has_src_subset_tick_conf()) {
UNIMPLEMENTED();
} else if (dst->op().op_conf().has_dst_subset_tick_conf()) {
UNIMPLEMENTED();
} else {
ConnectCtrlEdges(src_task_nodes, dst_task_nodes);
}
});
SetOrderInGraphForEachNode();
if (Global<ResourceDesc, ForSession>::Get()->enable_debug_mode()) { ToDotWithAutoFilePath(); }
}
TaskGraph::~TaskGraph() = default;
TaskEdge* TaskGraph::NewTaskEdgeWithLbi(const LogicalBlobId& lbi) {
TaskEdge* edge = NewEdge();
edge->AddLbi(lbi);
return edge;
}
TaskEdge* TaskGraph::NewTaskEdgeWithLbis(const std::vector<LogicalBlobId>& lbis) {
TaskEdge* edge = NewEdge();
edge->AddLbis(lbis);
return edge;
}
TaskNode* TaskGraph::GetProxyNode(TaskNode* src_node, const LogicalBlobId& lbi,
int64_t dst_machine_id, int64_t dst_mem_zone_id) {
int64_t src_mem_zone_id = src_node->MemZoneId121();
const ProxyKey key(src_node, lbi, dst_machine_id, dst_mem_zone_id);
if (proxy2node.find(key) != proxy2node.cend()) {
return proxy2node.at(key);
} else {
if (dst_machine_id == src_node->machine_id() && dst_mem_zone_id == src_mem_zone_id) {
proxy2node[key] = src_node;
return src_node;
} else if (Global<IDMgr>::Get()->IsGpuMemZone(dst_mem_zone_id)) {
TaskNode* proxy_on_dst_host =
GetProxyNode(src_node, lbi, dst_machine_id, Global<IDMgr>::Get()->CpuMemZoneId());
CopyHdTaskNode* copy_task = NewNode<CopyHdTaskNode>();
copy_task->Init(CopyHdOpConf::H2D, proxy_on_dst_host->machine_id(),
Global<IDMgr>::Get()->GetGpuPhyIdFromMemZoneId(dst_mem_zone_id), lbi);
Connect<TaskNode>(proxy_on_dst_host, NewTaskEdgeWithLbi(lbi), copy_task);
proxy2node[key] = copy_task;
return copy_task;
} else if (Global<IDMgr>::Get()->IsCpuMemZone(dst_mem_zone_id)) {
if (src_node->machine_id() == dst_machine_id) {
if (Global<IDMgr>::Get()->IsGpuMemZone(src_mem_zone_id)) {
CopyHdTaskNode* copy_task = NewNode<CopyHdTaskNode>();
copy_task->Init(CopyHdOpConf::D2H, src_node->machine_id(),
Global<IDMgr>::Get()->GetGpuPhyIdFromMemZoneId(src_mem_zone_id), lbi);
Connect<TaskNode>(src_node, NewTaskEdgeWithLbi(lbi), copy_task);
proxy2node[key] = copy_task;
return copy_task;
} else {
UNIMPLEMENTED();
}
} else {
TaskNode* proxy_on_src_host = GetProxyNode(src_node, lbi, src_node->machine_id(),
Global<IDMgr>::Get()->CpuMemZoneId());
CopyCommNetTaskNode* copy_comm_net_task = NewNode<CopyCommNetTaskNode>();
copy_comm_net_task->Init(dst_machine_id, lbi);
Connect<TaskNode>(proxy_on_src_host, NewTaskEdgeWithLbi(lbi), copy_comm_net_task);
proxy2node[key] = copy_comm_net_task;
return copy_comm_net_task;
}
} else {
UNIMPLEMENTED();
}
}
UNIMPLEMENTED();
return nullptr;
}
TaskNode* TaskGraph::GetProxyNode(TaskNode* src_node, const LogicalBlobId& lbi,
const ParallelDesc& dst_parallel_desc, int64_t dst_parallel_id) {
const int64_t dst_machine_id =
CHECK_JUST(dst_parallel_desc.MachineId4ParallelId(dst_parallel_id));
int64_t dst_mem_zone_id;
const IDMgr* id_mgr = Global<IDMgr>::Get();
if (dst_parallel_desc.device_type() == DeviceType::kCPU) {
dst_mem_zone_id = id_mgr->CpuMemZoneId();
} else if (dst_parallel_desc.device_type() == DeviceType::kGPU) {
const int64_t dst_dev_phy_id =
CHECK_JUST(dst_parallel_desc.DeviceId4ParallelId(dst_parallel_id));
dst_mem_zone_id = id_mgr->GpuMemZoneId(dst_dev_phy_id);
} else {
UNIMPLEMENTED();
}
return GetProxyNode(src_node, lbi, dst_machine_id, dst_mem_zone_id);
}
void TaskGraph::ConnectCtrlEdges(const std::vector<CompTaskNode*>& src_task_nodes,
const std::vector<CompTaskNode*>& dst_task_nodes) {
CHECK_EQ(src_task_nodes.size(), dst_task_nodes.size());
FOR_RANGE(int32_t, i, 0, src_task_nodes.size()) {
std::string regst_desc_name;
RegstDesc* ctrl_regst_desc =
src_task_nodes.at(i)->BuildCtrlRegstDesc(dst_task_nodes.at(i), ®st_desc_name);
TaskEdge* edge = NewEdge();
Connect<TaskNode>(src_task_nodes.at(i), edge, dst_task_nodes.at(i));
src_task_nodes.at(i)->BindEdgeWithProducedRegst(edge, regst_desc_name);
}
}
void TaskGraph::RemoveEmptyRegsts() {
ForEachNode([&](TaskNode* node) { node->EraseZeroSizeProducedBlob(); });
ForEachNode([&](TaskNode* node) { node->EraseZeroSizeConsumedRegst(); });
ForEachNode([&](TaskNode* node) { node->EraseZeroSizeProducedRegst(); });
ForEachNode([&](TaskNode* node) { node->UnbindBnWithEmptyRegst(); });
}
void TaskGraph::MergeChainAndAddOrderingCtrlEdgeInSameChain() {
MergeChain();
BuildCtrlRegstDescInSameChain();
}
void TaskGraph::SetOrderInGraphForEachNode() {
int64_t order_in_graph = 0;
auto SetOrderInGraph = [&](TaskNode* task_node) {
task_node->set_order_in_graph(order_in_graph);
ordered_task_nodes_.emplace_back(task_node);
++order_in_graph;
};
TopoForEachNode(SetOrderInGraph);
}
void TaskGraph::MergeChain() {
int64_t chain_id = 0;
for (auto* this_node : ordered_task_nodes_) {
// skip if this node has been set in a chain.
if (this_node->chain_id() != -1) { continue; }
CHECK_EQ(this_node->chain_id(), -1);
if (CanBeMergedInChain(this_node)) {
TraverseConnectedSubGraphMergeInThisChain(this_node, chain_id);
} else {
this_node->set_chain_id(chain_id);
}
++chain_id;
}
for (auto* node : ordered_task_nodes_) { CHECK_NE(node->chain_id(), -1); }
}
void TaskGraph::BuildCtrlRegstDescInSameChain() {
HashMap<int64_t, TaskNode*> chain_id2node;
for (auto* node : ordered_task_nodes_) {
if (IsConnectToTickOp(node)) { continue; }
int64_t chain_id = node->chain_id();
auto iter = chain_id2node.find(chain_id);
if (iter == chain_id2node.end()) {
CHECK(chain_id2node.emplace(chain_id, node).second);
} else {
TaskNode* src_node = iter->second;
TaskNode* dst_node = node;
std::string ctrl_regst_name;
bool build_ctrl_edge = src_node->BuildCtrlRegstDescIfNeed(dst_node, &ctrl_regst_name);
if (build_ctrl_edge) {
CHECK(!ctrl_regst_name.empty());
TaskEdge* edge = NewEdge();
Connect<TaskNode>(src_node, edge, dst_node);
src_node->BindEdgeWithProducedRegst(edge, ctrl_regst_name);
}
iter->second = dst_node;
}
}
}
void TaskGraph::GetInplaceOpBlobArgList(
InplaceObasInfo* obas_info, const HashSet<TaskNode*>& dev_nodes,
const std::function<const TaskNode*(const std::string&)>& TaskNode4OpName) const {
auto AddMutableInplaceArgPair = [&](TaskNode* node, const std::string& ibn,
const std::string& obn, const std::string& op_name) {
if (IsInplaceAllowed(node, {ibn, obn}, TaskNode4OpName)) {
auto* pair = obas_info->mut_inplace_oba_pairs.mutable_pair()->Add();
*pair->mutable_first() = GenOpBlobArg(op_name, ibn);
*pair->mutable_second() = GenOpBlobArg(op_name, obn);
}
};
auto AddConstInplaceArgPair = [&](TaskNode* node, const std::string& ibn, const std::string& obn,
const std::string& op_name) {
if (IsInplaceAllowed(node, {ibn, obn}, TaskNode4OpName)) {
auto* pair = obas_info->con_inplace_oba_pairs.mutable_pair()->Add();
*pair->mutable_first() = GenOpBlobArg(op_name, ibn);
*pair->mutable_second() = GenOpBlobArg(op_name, obn);
}
};
for (TaskNode* task_node : dev_nodes) {
if (task_node->exec_gph().node_num() != 1) { continue; }
const auto& op = *task_node->exec_gph().SoleNode()->op();
for (const std::string& ibn : op.input_bns()) {
if (op.InputBlobModifier4Ibn(ibn).is_mutable()) {
CHECK(IsInplaceAllowed(task_node, {ibn}, TaskNode4OpName));
*obas_info->mut_in_obas.mutable_oba()->Add() = GenOpBlobArg(op.op_name(), ibn);
}
}
for (const auto& pair : task_node->exec_gph().SoleNode()->mut_inplace_obn2ibn()) {
AddMutableInplaceArgPair(task_node, pair.second, pair.first, op.op_name());
}
for (const auto& pair : task_node->exec_gph().SoleNode()->con_inplace_obn2ibn()) {
AddConstInplaceArgPair(task_node, pair.second, pair.first, op.op_name());
}
}
}
void TaskGraph::GetSafeInplaceOpBlobArgList(
InplaceObasInfo* safe_obas_info, const HashSet<TaskNode*>& dev_nodes,
const std::function<bool(const std::string&, const std::string&)>& IsOpNameDataOrCtrlReachable)
const {
auto TaskNode4SoleOpName = MakeGetterTaskNode4SoleOpName(dev_nodes);
InplaceObasInfo obas_info;
GetInplaceOpBlobArgList(&obas_info, dev_nodes, TaskNode4SoleOpName);
auto Op4OpName = [&](const std::string& op_name) -> const Operator* {
return TaskNode4SoleOpName(op_name)->exec_gph().SoleNode()->op().get();
};
auto IsLbiAllConsumersReachable =
MakePredicatorIsLbiAllConsumersReachable(TaskNode4SoleOpName, IsOpNameDataOrCtrlReachable);
InplaceLbiGraph origin_graph(obas_info, Op4OpName);
InplaceLbiGraph safe_graph(*safe_obas_info, Op4OpName);
origin_graph.ComputeSafeInplaceObns(safe_obas_info, IsLbiAllConsumersReachable);
if (Global<ResourceDesc, ForSession>::Get()->enable_debug_mode()) {
origin_graph.ToDotWithFilePath(
JoinPath("dot", "InplaceLbiGraph", GlobalJobDesc().job_name() + "_origin.dot"));
safe_graph.ToDotWithFilePath(
JoinPath("dot", "InplaceLbiGraph", GlobalJobDesc().job_name() + "_safe.dot"));
}
}
void TaskGraph::SetTaskRegstInplaceInfo(const InplaceObasInfo& obas_info,
const HashSet<TaskNode*>& dev_nodes) const {
auto TaskNode4SoleOpName = MakeGetterTaskNode4SoleOpName(dev_nodes);
auto Op4OpName = [&](const std::string& op_name) -> const Operator* {
return TaskNode4SoleOpName(op_name)->exec_gph().SoleNode()->op().get();
};
InplaceLbiGraph inplace_gph(obas_info, Op4OpName);
inplace_gph.ForEachConnectedComponent([&](const HashSet<const InplaceLbiNode*>& inplace_nodes) {
for (const auto* inplace_node : inplace_nodes) {
if (inplace_node->in_edges().empty()) { continue; }
const auto* inplace_edge = inplace_node->SoleInEdge();
auto* exec_node = TaskNode4SoleOpName(inplace_edge->op().op_name())->exec_gph().SoleNode();
RegstDesc* in_regst = exec_node->RegstDesc4BnInOp(inplace_edge->ibn());
RegstDesc* out_regst = exec_node->RegstDesc4BnInOp(inplace_edge->obn());
out_regst->set_hint_inplace_consumed_regst_desc_id(in_regst->regst_desc_id());
}
});
}
void TaskGraph::ForEachGpuDeviceNodes(
const std::function<void(const HashSet<TaskNode*>& dev_nodes)>& Handler) const {
HashMap<std::pair<int64_t, int64_t>, HashSet<TaskNode*>> global_dev_phy_id2nodes;
ForEachNode([&](TaskNode* task_node) {
if (task_node->device_type() != DeviceType::kGPU) { return; }
int64_t dev_phy_id = Global<IDMgr>::Get()->GetGpuPhyIdFromThrdId(task_node->thrd_id());
global_dev_phy_id2nodes[{task_node->machine_id(), dev_phy_id}].emplace(task_node);
});
for (const auto& pair : global_dev_phy_id2nodes) { Handler(pair.second); }
}
void TaskGraph::EnableInplaceMemSharing(
const std::function<bool(const std::string&, const std::string&)>&
IsOpNameDataOrCtrlReachable) {
ForEachGpuDeviceNodes([&](const HashSet<TaskNode*>& dev_nodes) {
InplaceObasInfo safe_inplace_obas_info;
GetSafeInplaceOpBlobArgList(&safe_inplace_obas_info, dev_nodes, IsOpNameDataOrCtrlReachable);
SetTaskRegstInplaceInfo(safe_inplace_obas_info, dev_nodes);
});
}
#define DEFINE_BLD_SUB_TASK_GRAPH_METHOD(method_name) \
void TaskGraph::method_name BLD_SUB_TSK_GPH_MTHD_ARGS()
DEFINE_BLD_SUB_TASK_GRAPH_METHOD(BldSubTskGphByBoxing) {
const OpNode* src_op_node = op_edge->src_node();
const OpNode* dst_op_node = op_edge->dst_node();
for (const LogicalBlobId& lbi : op_edge->lbis()) {
std::vector<TaskNode*> in_nodes(sorted_src_comp_tasks.begin(), sorted_src_comp_tasks.end());
std::vector<TaskNode*> out_nodes;
out_nodes.reserve(sorted_dst_comp_tasks.size());
std::vector<std::vector<TaskNode*>> sorted_ctrl_tasks;
const ParallelDistribution& src_parallel_distribution =
src_op_node->ParallelDistribution4Lbi(lbi);
const ParallelDistribution& dst_parallel_distribution =
dst_op_node->ParallelDistribution4Lbi(lbi);
const ParallelDesc& src_parallel_desc = src_op_node->parallel_desc();
const ParallelDesc& dst_parallel_desc = dst_op_node->parallel_desc();
const BlobDesc& blob_desc = src_op_node->LogicalBlobDesc4Lbi(lbi);
auto status = CHECK_JUST(hierarchical_sub_tsk_gph_builder_->Build(
sub_tsk_gph_builder_ctx_.get(), in_nodes, &out_nodes, &sorted_ctrl_tasks, src_parallel_desc,
dst_parallel_desc, lbi, blob_desc, src_parallel_distribution, dst_parallel_distribution,
*(CHECK_JUST(src_op_node->op().GetOpTimeShape()).get())));
boxing_logger_->Log(*status, src_op_node->op().op_name(), dst_op_node->op().op_name(),
src_parallel_desc, dst_parallel_desc, src_parallel_distribution,
dst_parallel_distribution, lbi, blob_desc);
CHECK_EQ(out_nodes.size(), sorted_dst_comp_tasks.size());
FOR_RANGE(size_t, i, 0, out_nodes.size()) {
ConnectWithLbi(out_nodes.at(i), sorted_dst_comp_tasks.at(i), lbi);
}
if (!sorted_ctrl_tasks.empty()) {
CHECK_EQ(sorted_ctrl_tasks.size(), sorted_dst_comp_tasks.size());
FOR_RANGE(size_t, i, 0, sorted_dst_comp_tasks.size()) {
for (TaskNode* ctrl_node : sorted_ctrl_tasks.at(i)) {
std::string regst_desc_name;
ctrl_node->BuildCtrlRegstDesc(sorted_dst_comp_tasks.at(i), ®st_desc_name);
TaskEdge* edge = NewEdge();
Connect<TaskNode>(ctrl_node, edge, sorted_dst_comp_tasks.at(i));
ctrl_node->BindEdgeWithProducedRegst(edge, regst_desc_name);
}
}
}
}
}
DEFINE_BLD_SUB_TASK_GRAPH_METHOD(BldSubTskGphByOneToOne) {
CHECK_EQ(sorted_src_comp_tasks.size(), sorted_dst_comp_tasks.size());
FOR_RANGE(size_t, i, 0, sorted_src_comp_tasks.size()) {
for (const LogicalBlobId& lbi : op_edge->lbis()) {
BuildTaskPath(sorted_src_comp_tasks.at(i), sorted_dst_comp_tasks.at(i), lbi);
}
}
}
DEFINE_BLD_SUB_TASK_GRAPH_METHOD(BldSubTskGphByBroadcastToBroadcast) {
for (CompTaskNode* dst_node : sorted_dst_comp_tasks) {
CompTaskNode* nearest_src_node =
SubTskGphBuilderUtil::FindNearestNode(sorted_src_comp_tasks, dst_node);
CHECK_NOTNULL(nearest_src_node);
for (const LogicalBlobId& lbi : op_edge->lbis()) {
BuildTaskPath(nearest_src_node, dst_node, lbi);
}
}
}
DEFINE_BLD_SUB_TASK_GRAPH_METHOD(BldSubTskGphByPartialInLbiConnect) {
const Operator& src_op = op_edge->src_node()->op();
const Operator& dst_op = op_edge->dst_node()->op();
HashSet<LogicalBlobId> lbis;
for (const auto& obn : src_op.output_bns()) { lbis.insert(src_op.BnInOp2Lbi(obn)); }
CHECK_EQ(sorted_src_comp_tasks.size(), 1);
CHECK_EQ(dst_op.input_bns().size(), sorted_dst_comp_tasks.size());
FOR_RANGE(int, i, 0, sorted_dst_comp_tasks.size()) {
const auto& lbi = dst_op.BnInOp2Lbi(dst_op.input_bns().Get(i));
if (lbis.find(lbi) != lbis.end()) {
BuildTaskPath(sorted_src_comp_tasks.at(0), sorted_dst_comp_tasks.at(i), lbi);
}
}
}
DEFINE_BLD_SUB_TASK_GRAPH_METHOD(BldSubTskGphByPartialOutLbiConnect) {
const Operator& src_op = op_edge->src_node()->op();
const Operator& dst_op = op_edge->dst_node()->op();
HashSet<LogicalBlobId> lbis;
for (const auto& ibn : dst_op.input_bns()) { lbis.insert(dst_op.BnInOp2Lbi(ibn)); }
CHECK_EQ(sorted_dst_comp_tasks.size(), 1);
CHECK_EQ(src_op.output_bns().size(), sorted_src_comp_tasks.size());
FOR_RANGE(int, i, 0, sorted_src_comp_tasks.size()) {
const auto& lbi = src_op.BnInOp2Lbi(src_op.output_bns().Get(i));
if (lbis.find(lbi) != lbis.end()) {
BuildTaskPath(sorted_src_comp_tasks.at(i), sorted_dst_comp_tasks.at(0), lbi);
}
}
}
DEFINE_BLD_SUB_TASK_GRAPH_METHOD(BldSubTskGphBySrcSubsetConnect) {
std::function<Maybe<CompTaskNode*>(int64_t mchn_id, int64_t thrd_id)> TaskNode4MachineId7ThrdId;
CHECK_JUST(
MakeGetterTaskNode4MachineId7ThrdId(sorted_src_comp_tasks, &TaskNode4MachineId7ThrdId));
for (CompTaskNode* dst_task_node : sorted_dst_comp_tasks) {
CompTaskNode* src_task_node = CHECK_JUST(
TaskNode4MachineId7ThrdId(dst_task_node->machine_id(), dst_task_node->thrd_id()));
Connect<TaskNode>(src_task_node, NewTaskEdgeWithLbis(op_edge->lbis()), dst_task_node);
}
}
DEFINE_BLD_SUB_TASK_GRAPH_METHOD(BldSubTskGphByDstSubsetConnect) {
std::function<Maybe<CompTaskNode*>(int64_t mchn_id, int64_t thrd_id)> TaskNode4MachineId7ThrdId;
CHECK_JUST(
MakeGetterTaskNode4MachineId7ThrdId(sorted_dst_comp_tasks, &TaskNode4MachineId7ThrdId));
for (CompTaskNode* src_task_node : sorted_src_comp_tasks) {
CompTaskNode* dst_task_node = CHECK_JUST(
TaskNode4MachineId7ThrdId(src_task_node->machine_id(), src_task_node->thrd_id()));
Connect<TaskNode>(src_task_node, NewTaskEdgeWithLbis(op_edge->lbis()), dst_task_node);
}
}
DEFINE_BLD_SUB_TASK_GRAPH_METHOD(BldSubTskGphNormalForwardToDecodeH2D) {
CHECK_EQ(sorted_src_comp_tasks.size(), sorted_dst_comp_tasks.size());
FOR_RANGE(size_t, i, 0, sorted_src_comp_tasks.size()) {
CompTaskNode* src = sorted_src_comp_tasks.at(i);
CompTaskNode* dst = sorted_dst_comp_tasks.at(i);
for (const LogicalBlobId& lbi : op_edge->lbis()) { BuildTaskPath(src, dst, lbi); }
}
}
void TaskGraph::ConnectWithLbi(TaskNode* src_node, TaskNode* dst_node, const LogicalBlobId& lbi) {
if (src_node == dst_node) { return; }
for (TaskEdge* out_edge : src_node->out_edges()) {
TaskNode* out_node = out_edge->dst_node();
if (out_node == dst_node) {
out_edge->AddLbi(lbi);
return;
}
}
TaskEdge* connected_edge = NewEdge();
connected_edge->AddLbi(lbi);
Connect<TaskNode>(src_node, connected_edge, dst_node);
}
void TaskGraph::BuildTaskPath(TaskNode* src_node, TaskNode* dst_node, const LogicalBlobId& lbi) {
int64_t dst_machine_id = dst_node->machine_id();
int64_t dst_mem_zone_id = dst_node->MemZoneId121();
TaskNode* proxy_node = GetProxyNode(src_node, lbi, dst_machine_id, dst_mem_zone_id);
ConnectWithLbi(proxy_node, dst_node, lbi);
}
} // namespace oneflow
|
//============================================================================
// Copyright (c) Kitware, Inc.
// All rights reserved.
// See LICENSE.txt for details.
//
// This software is distributed WITHOUT ANY WARRANTY; without even
// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
// PURPOSE. See the above copyright notice for more information.
//============================================================================
#include <vtkm/cont/FieldRangeCompute.h>
#include <vtkm/cont/FieldRangeCompute.hxx>
#include <vtkm/cont/Algorithm.h>
namespace vtkm
{
namespace cont
{
//-----------------------------------------------------------------------------
VTKM_CONT
vtkm::cont::ArrayHandle<vtkm::Range> FieldRangeCompute(const vtkm::cont::DataSet& dataset,
const std::string& name,
vtkm::cont::Field::Association assoc)
{
return vtkm::cont::detail::FieldRangeComputeImpl(
dataset, name, assoc, VTKM_DEFAULT_TYPE_LIST_TAG());
}
//-----------------------------------------------------------------------------
VTKM_CONT
vtkm::cont::ArrayHandle<vtkm::Range> FieldRangeCompute(const vtkm::cont::MultiBlock& multiblock,
const std::string& name,
vtkm::cont::Field::Association assoc)
{
return vtkm::cont::detail::FieldRangeComputeImpl(
multiblock, name, assoc, VTKM_DEFAULT_TYPE_LIST_TAG());
}
}
} // namespace vtkm::cont
|
// (C) Copyright Jonathan Turkanis 2004
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt.)
// See http://www.boost.org/libs/iostreams for documentation.
#ifndef BOOST_IOSTREAMS_TEST_READ_BIDIRECTIONAL_HPP_INCLUDED
#define BOOST_IOSTREAMS_TEST_READ_BIDIRECTIONAL_HPP_INCLUDED
#include <fstream>
#include <boost/iostreams/combine.hpp>
#include <boost/iostreams/device/file.hpp>
#include <boost/iostreams/filtering_stream.hpp>
#include <boost/test/test_tools.hpp>
#include "detail/temp_file.hpp"
#include "detail/verification.hpp"
void read_bidirectional_test()
{
using namespace std;
using namespace boost;
using namespace boost::iostreams;
using namespace boost::iostreams::test;
test_file test;
{
test_file src;
temp_file dest; // Dummy.
filtering_stream<bidirectional> first(
combine(file_source(src.name()), file_sink(dest.name())), 0
);
ifstream second(test.name().c_str());
BOOST_CHECK_MESSAGE(
compare_streams_in_chars(first, second),
"failed reading from filtering_stream<bidirectional>"
"in chars with no buffer"
);
}
{
test_file src;
temp_file dest; // Dummy.
filtering_stream<bidirectional> first(
combine(file_source(src.name()), file_sink(dest.name())), 0
);
ifstream second(test.name().c_str());
BOOST_CHECK_MESSAGE(
compare_streams_in_chunks(first, second),
"failed reading from filtering_stream<bidirectional>"
"in chunks with no buffer"
);
}
{
test_file src;
temp_file dest; // Dummy.
filtering_stream<bidirectional> first(
combine(file_source(src.name()), file_sink(dest.name()))
);
ifstream second(test.name().c_str());
BOOST_CHECK_MESSAGE(
compare_streams_in_chars(first, second),
"failed reading from filtering_stream<bidirectional>"
"in chars with large buffer"
);
}
{
test_file src;
temp_file dest; // Dummy.
filtering_stream<bidirectional> first(
combine(file_source(src.name()), file_sink(dest.name()))
);
ifstream second(test.name().c_str());
BOOST_CHECK_MESSAGE(
compare_streams_in_chunks(first, second),
"failed reading from filtering_stream<bidirectional>"
"in chunks with large buffer"
);
}
}
#endif // #ifndef BOOST_IOSTREAMS_TEST_READ_BIDIRECTIONAL_HPP_INCLUDED
|
/*=========================================================================
Program: ParaView
Module: vtkPVClassNameInformation.cxx
Copyright (c) Kitware, Inc.
All rights reserved.
See Copyright.txt or http://www.paraview.org/HTML/Copyright.html for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkPVClassNameInformation.h"
#include "vtkClientServerStream.h"
#include "vtkObjectFactory.h"
vtkStandardNewMacro(vtkPVClassNameInformation);
//----------------------------------------------------------------------------
vtkPVClassNameInformation::vtkPVClassNameInformation()
{
this->VTKClassName = 0;
}
//----------------------------------------------------------------------------
vtkPVClassNameInformation::~vtkPVClassNameInformation()
{
this->SetVTKClassName(0);
}
//----------------------------------------------------------------------------
void vtkPVClassNameInformation::PrintSelf(ostream &os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
os << indent << "VTKClassName: "
<< (this->VTKClassName?this->VTKClassName:"(none)") << "\n";
}
//----------------------------------------------------------------------------
void vtkPVClassNameInformation::CopyFromObject(vtkObject* obj)
{
if(!obj)
{
vtkErrorMacro("Cannot get class name from NULL object.");
return;
}
this->SetVTKClassName(obj->GetClassName());
}
//----------------------------------------------------------------------------
void vtkPVClassNameInformation::AddInformation(vtkPVInformation* info)
{
if (vtkPVClassNameInformation::SafeDownCast(info))
{
this->SetVTKClassName(
vtkPVClassNameInformation::SafeDownCast(info)->GetVTKClassName());
}
}
//----------------------------------------------------------------------------
void
vtkPVClassNameInformation::CopyToStream(vtkClientServerStream* css)
{
css->Reset();
*css << vtkClientServerStream::Reply << this->VTKClassName
<< vtkClientServerStream::End;
}
//----------------------------------------------------------------------------
void
vtkPVClassNameInformation::CopyFromStream(const vtkClientServerStream* css)
{
const char* cname = 0;
css->GetArgument(0, 0, &cname);
this->SetVTKClassName(cname);
}
|
/***********************************************************************************************************************
* OpenStudio(R), Copyright (c) 2008-2017, Alliance for Sustainable Energy, LLC. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
* following conditions are met:
*
* (1) Redistributions of source code must retain the above copyright notice, this list of conditions and the following
* disclaimer.
*
* (2) Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
* following disclaimer in the documentation and/or other materials provided with the distribution.
*
* (3) Neither the name of the copyright holder nor the names of any contributors may be used to endorse or promote
* products derived from this software without specific prior written permission from the respective party.
*
* (4) Other than as required in clauses (1) and (2), distributions in any form of modifications or other derivative
* works may not use the "OpenStudio" trademark, "OS", "os", or any other confusingly similar designation without
* specific prior written permission from Alliance for Sustainable Energy, LLC.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER, THE UNITED STATES GOVERNMENT, OR ANY CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**********************************************************************************************************************/
#ifndef MODEL_FOUNDATIONKIVASETTINGS_IMPL_HPP
#define MODEL_FOUNDATIONKIVASETTINGS_IMPL_HPP
#include <vector>
#include "ModelAPI.hpp"
#include "ModelObject_Impl.hpp"
namespace openstudio {
namespace model {
namespace detail {
/** FoundationKivaSettings_Impl is a ModelObject_Impl that is the implementation class for FoundationKivaSettings.*/
class MODEL_API FoundationKivaSettings_Impl : public ModelObject_Impl {
public:
/** @name Constructors and Destructors */
//@{
FoundationKivaSettings_Impl(const IdfObject& idfObject,
Model_Impl* model,
bool keepHandle);
FoundationKivaSettings_Impl(const openstudio::detail::WorkspaceObject_Impl& other,
Model_Impl* model,
bool keepHandle);
FoundationKivaSettings_Impl(const FoundationKivaSettings_Impl& other,
Model_Impl* model,
bool keepHandle);
virtual ~FoundationKivaSettings_Impl() {}
//@}
/** @name Virtual Methods */
//@{
virtual boost::optional<ParentObject> parent() const override;
virtual const std::vector<std::string>& outputVariableNames() const override;
virtual IddObjectType iddObjectType() const override;
//@}
/** @name Getters */
//@{
double soilConductivity() const;
bool isSoilConductivityDefaulted() const;
double soilDensity() const;
bool isSoilDensityDefaulted() const;
double soilSpecificHeat() const;
bool isSoilSpecificHeatDefaulted() const;
double groundSolarAbsorptivity() const;
bool isGroundSolarAbsorptivityDefaulted() const;
double groundThermalAbsorptivity() const;
bool isGroundThermalAbsorptivityDefaulted() const;
double groundSurfaceRoughness() const;
bool isGroundSurfaceRoughnessDefaulted() const;
double farFieldWidth() const;
bool isFarFieldWidthDefaulted() const;
std::string deepGroundBoundaryCondition() const;
bool isDeepGroundBoundaryConditionAutoselected();
boost::optional<double> deepGroundDepth();
bool isDeepGroundDepthAutocalculated();
double minimumCellDimension() const;
bool isMinimumCellDimensionDefaulted() const;
double maximumCellGrowthCoefficient() const;
bool isMaximumCellGrowthCoefficientDefaulted() const;
std::string simulationTimestep() const;
bool isSimulationTimestepDefaulted() const;
//@}
/** @name Setters */
//@{
bool setSoilConductivity(double soilConductivity);
void resetSoilConductivity();
bool setSoilDensity(double soilDensity);
void resetSoilDensity();
bool setSoilSpecificHeat(double soilSpecificHeat);
void resetSoilSpecificHeat();
bool setGroundSolarAbsorptivity(double groundSolarAbsorptivity);
void resetGroundSolarAbsorptivity();
bool setGroundThermalAbsorptivity(double groundThermalAbsorptivity);
void resetGroundThermalAbsorptivity();
bool setGroundSurfaceRoughness(double groundSurfaceRoughness);
void resetGroundSurfaceRoughness();
bool setFarFieldWidth(double farFieldWidth);
void resetFarFieldWidth();
bool setDeepGroundBoundaryCondition(std::string deepGroundBoundaryCondition);
void resetDeepGroundBoundaryCondition();
bool setDeepGroundDepth(double deepGroundDepth);
void autocalculateDeepGroundDepth();
bool setMinimumCellDimension(double minimumCellDimension);
void resetMinimumCellDimension();
bool setMaximumCellGrowthCoefficient(double maximumCellGrowthCoefficient);
void resetMaximumCellGrowthCoefficient();
bool setSimulationTimestep(std::string simulationTimestep);
void resetSimulationTimestep();
//@}
/** @name Other */
//@{
//@}
protected:
private:
REGISTER_LOGGER("openstudio.model.FoundationKivaSettings");
};
} // detail
} // model
} // openstudio
#endif // MODEL_FOUNDATIONKIVASETTINGS_IMPL_HPP
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* MusicPlayer.hpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mrassokh <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/07/12 12:25:02 by mrassokh #+# #+# */
/* Updated: 2019/07/12 12:25:04 by mrassokh ### ########.fr */
/* */
/* ************************************************************************** */
#pragma once
#include <SDL.h>
#include <SDL_mixer.h>
#include "CustomException.hpp"
#include <map>
#include <string>
#include <iostream>
#include <memory>
#include <vector>
#define MUSIC_PLAYER MusicPlayer::getInstance()
typedef std::map<std::string, Mix_Music*> musicMap;
typedef std::map<std::string, Mix_Chunk*> soundMap;
typedef std::vector<Mix_Music*> musList;
class MusicPlayer
{
public:
static MusicPlayer &getInstance();
void setBinFolder(std::string const& aPath);
void initLoad();
void loadMusic(std::string const &musicName, std::string const &source);
void loadSound(std::string const &soundName, std::string const &source);
void clearMusicMap();
void clearSoundMap();
void playMusicInfinity(std::string const &musicName) const;
void playMusicOnce(std::string const &musicName);
void pauseMusic() const;
void unPauseMusic() const;
void playSound(std::string const &soundName) const;
private:
MusicPlayer();
MusicPlayer(MusicPlayer const & rhs) = delete;
MusicPlayer& operator=(MusicPlayer const & rhs) = delete;
~MusicPlayer();
musicMap mMusic;
soundMap mSound;
std::string mBinFolder;
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.