<commit_before>/*
 *  qimask.cpp
 *
 *  Created by Tobias Wood on 2015/09/22.
 *  Copyright (c) 2015 Tobias Wood.
 *
 *  This Source Code Form is subject to the terms of the Mozilla Public
 *  License, v. 2.0. If a copy of the MPL was not distributed with this
 *  file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 */

#include <iostream>
#include <string>
#include <complex>

#include "itkComplexToModulusImageFilter.h"
#include "itkOtsuThresholdImageFilter.h"
#include "itkVotingBinaryIterativeHoleFillingImageFilter.h"
#include "itkBinaryCrossStructuringElement.h"
#include "itkBinaryBallStructuringElement.h"
#include "itkBinaryErodeImageFilter.h"
#include "itkBinaryDilateImageFilter.h"

#include "Args.h"
#include "Types.h"
#include "Util.h"
#include "IO.h"
#include "Masking.h"

int main(int argc, char **argv) {
    args::ArgumentParser parser(
    "Generates masks in stages.\n"
    "Stage 1 - Otsu thresholding to generate binary mask\n"
    "Stage 2 - RATs (optional)\n"
    "Stage 3 - Hole filling (optional)\n"
    "http://github.com/spinicist/QUIT"
    );

    args::Positional<std::string> input_path(parser, "INPUT_FILE", "Input file");

    args::HelpFlag help(parser, "HELP", "Show this help menu", {'h', "help"});
    args::Flag     verbose(parser, "VERBOSE", "Print more information", {'v', "verbose"});
    args::ValueFlag<std::string> outarg(parser, "OUTPUT FILE", "Set output filename, default is input + _mask", {'o', "out"});
    args::ValueFlag<int> volume(parser, "VOLUME", "Choose volume to mask in multi-volume file. Default 1, -1 selects last volume", {'v', "volume"}, 0);
    args::Flag     is_complex(parser, "COMPLEX", "Input data is complex, take magnitude first", {'x', "complex"});
    args::ValueFlag<float> lower_threshold(parser, "LOWER THRESHOLD", "Specify lower intensity threshold for 1st stage, otherwise Otsu's method is used", {'l', "lower"}, 0.);
    args::ValueFlag<float> upper_threshold(parser, "UPPER THRESHOLD", "Specify upper intensity threshold for 1st stage, otherwise Otsu's method is used", {'u', "upper"}, std::numeric_limits<float>::infinity());
    args::ValueFlag<float> rats(parser, "RATS", "Perform the RATS step, argument is size threshold for connected component", {'r', "rats"}, 0.);
    args::ValueFlag<int> fillh_radius(parser, "FILL HOLES", "Fill holes in thresholded mask with radius N", {'F', "fillh"}, 0);
    args::Flag     run_bet(parser, "RUN BET", "Run the Brain Extraction Tool stage", {'B', "bet"});

    QI::ParseArgs(parser, argc, argv);

    if (verbose) std::cout << "Reading input image: " << QI::CheckPos(input_path) << std::endl;
    QI::SeriesF::Pointer vols = ITK_NULLPTR;
    if (is_complex) {
        vols = QI::ReadMagnitudeImage<QI::SeriesF>(QI::CheckPos(input_path));
    } else {
        vols = QI::ReadImage<QI::SeriesF>(QI::CheckPos(input_path));
    }

    std::string out_path;
    if (outarg.Get() == "") {
        out_path = QI::StripExt(input_path.Get()) + "_mask" + QI::OutExt();
    } else {
        out_path = outarg.Get();
    }

    // Extract one volume to process
    auto region = vols->GetLargestPossibleRegion();
    if (std::abs(volume.Get()) < region.GetSize()[3]) {
        int volume_to_get = (region.GetSize()[3] + volume.Get()) % region.GetSize()[3];
        if (verbose) std::cout << "Using volume " << volume_to_get << std::endl;
        region.GetModifiableIndex()[3] = volume_to_get;
    } else {
        std::cerr << "Specified volume was invalid: " << volume.Get() << std::endl;
        return EXIT_FAILURE;
    }
    region.GetModifiableSize()[3] = 0;
    auto vol = itk::ExtractImageFilter<QI::SeriesF, QI::VolumeF>::New();
    vol->SetExtractionRegion(region);
    vol->SetInput(vols);
    vol->SetDirectionCollapseToSubmatrix();
    vol->Update();
    QI::VolumeF::Pointer intensity_image = vol->GetOutput();
    intensity_image->DisconnectPipeline();

    /*
     *  Stage 1 - Otsu or Threshold
     */
    QI::VolumeI::Pointer mask_image = ITK_NULLPTR;
    if (lower_threshold || upper_threshold) {
        if (verbose) std::cout << "Thresholding range: " << lower_threshold.Get() << "-" << upper_threshold.Get() << std::endl;
        mask_image = QI::ThresholdMask(intensity_image, lower_threshold.Get(), upper_threshold.Get());
    } else {
        if (verbose) std::cout << "Generating Otsu mask" << std::endl;
        mask_image = QI::OtsuMask(intensity_image);
    }

    /*
     *  Stage 2 - RATS
     */
     if (rats) {
        typedef itk::BinaryBallStructuringElement<int, 3> TBall;
        typedef itk::BinaryErodeImageFilter<QI::VolumeI, QI::VolumeI, TBall> TErode;
        typedef itk::BinaryDilateImageFilter<QI::VolumeI, QI::VolumeI, TBall> TDilate;
        float mask_volume = std::numeric_limits<float>::infinity();
        float voxel_volume = QI::VoxelVolume(mask_image);
        std::cout << "Voxel volume: " << voxel_volume << std::endl;
        int radius = 0;
        QI::VolumeI::Pointer mask_rats;
        while (mask_volume > rats.Get()) {
            radius++;
            TBall ball;
            TBall::SizeType radii; radii.Fill(radius);
            ball.SetRadius(radii);
            ball.CreateStructuringElement();
            TErode::Pointer erode = TErode::New();
            erode->SetInput(mask_image);
            erode->SetForegroundValue(1);
            erode->SetBackgroundValue(0);
            erode->SetKernel(ball);
            erode->Update();
            std::vector<float> kept_sizes = QI::FindLabels(erode->GetOutput(), 0, 1, mask_rats);
            mask_volume = kept_sizes[0] * voxel_volume;
            auto dilate = TDilate::New();
            dilate->SetKernel(ball);
            dilate->SetInput(mask_rats);
            dilate->SetForegroundValue(1);
            dilate->SetBackgroundValue(0);
            dilate->Update();
            mask_rats = dilate->GetOutput();
            mask_rats->DisconnectPipeline();
            if (verbose) std::cout << "Ran RATS iteration, current radius: " << radius << " volume is: " << mask_volume << std::endl;
         }
         mask_image = mask_rats;
     }

    /*
     *  Stage 3 - Hole Filling
     */
    QI::VolumeI::Pointer finalMask = ITK_NULLPTR;
    if (fillh_radius) {
        if (verbose) std::cout << "Filling holes" << std::endl;
        auto fillHoles = itk::VotingBinaryIterativeHoleFillingImageFilter<QI::VolumeI>::New();
        itk::VotingBinaryIterativeHoleFillingImageFilter<QI::VolumeI>::InputSizeType radius;
        radius.Fill(fillh_radius.Get());
        fillHoles->SetInput(mask_image);
        fillHoles->SetRadius(radius);
        fillHoles->SetMajorityThreshold(2); // Corresponds to (rad^3-1)/2 + 2 threshold
        fillHoles->SetBackgroundValue(0);
        fillHoles->SetForegroundValue(1);
        fillHoles->SetMaximumNumberOfIterations(3);
        fillHoles->Update();
        mask_image = fillHoles->GetOutput();
        mask_image->DisconnectPipeline();
    }

    if (verbose) std::cout << "Saving mask to: " << out_path << std::endl;
    QI::WriteImage(mask_image, out_path);
    if (verbose) std::cout << "Finished." << std::endl;
    return EXIT_SUCCESS;
}

<commit_msg>BUG: Missing a verbose check.<commit_after>/*
 *  qimask.cpp
 *
 *  Created by Tobias Wood on 2015/09/22.
 *  Copyright (c) 2015 Tobias Wood.
 *
 *  This Source Code Form is subject to the terms of the Mozilla Public
 *  License, v. 2.0. If a copy of the MPL was not distributed with this
 *  file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 */

#include <iostream>
#include <string>
#include <complex>

#include "itkComplexToModulusImageFilter.h"
#include "itkOtsuThresholdImageFilter.h"
#include "itkVotingBinaryIterativeHoleFillingImageFilter.h"
#include "itkBinaryCrossStructuringElement.h"
#include "itkBinaryBallStructuringElement.h"
#include "itkBinaryErodeImageFilter.h"
#include "itkBinaryDilateImageFilter.h"

#include "Args.h"
#include "Types.h"
#include "Util.h"
#include "IO.h"
#include "Masking.h"

int main(int argc, char **argv) {
    args::ArgumentParser parser(
    "Generates masks in stages.\n"
    "Stage 1 - Otsu thresholding to generate binary mask\n"
    "Stage 2 - RATs (optional)\n"
    "Stage 3 - Hole filling (optional)\n"
    "http://github.com/spinicist/QUIT"
    );

    args::Positional<std::string> input_path(parser, "INPUT_FILE", "Input file");

    args::HelpFlag help(parser, "HELP", "Show this help menu", {'h', "help"});
    args::Flag     verbose(parser, "VERBOSE", "Print more information", {'v', "verbose"});
    args::ValueFlag<std::string> outarg(parser, "OUTPUT FILE", "Set output filename, default is input + _mask", {'o', "out"});
    args::ValueFlag<int> volume(parser, "VOLUME", "Choose volume to mask in multi-volume file. Default 1, -1 selects last volume", {'v', "volume"}, 0);
    args::Flag     is_complex(parser, "COMPLEX", "Input data is complex, take magnitude first", {'x', "complex"});
    args::ValueFlag<float> lower_threshold(parser, "LOWER THRESHOLD", "Specify lower intensity threshold for 1st stage, otherwise Otsu's method is used", {'l', "lower"}, 0.);
    args::ValueFlag<float> upper_threshold(parser, "UPPER THRESHOLD", "Specify upper intensity threshold for 1st stage, otherwise Otsu's method is used", {'u', "upper"}, std::numeric_limits<float>::infinity());
    args::ValueFlag<float> rats(parser, "RATS", "Perform the RATS step, argument is size threshold for connected component", {'r', "rats"}, 0.);
    args::ValueFlag<int> fillh_radius(parser, "FILL HOLES", "Fill holes in thresholded mask with radius N", {'F', "fillh"}, 0);
    args::Flag     run_bet(parser, "RUN BET", "Run the Brain Extraction Tool stage", {'B', "bet"});

    QI::ParseArgs(parser, argc, argv);

    if (verbose) std::cout << "Reading input image: " << QI::CheckPos(input_path) << std::endl;
    QI::SeriesF::Pointer vols = ITK_NULLPTR;
    if (is_complex) {
        vols = QI::ReadMagnitudeImage<QI::SeriesF>(QI::CheckPos(input_path));
    } else {
        vols = QI::ReadImage<QI::SeriesF>(QI::CheckPos(input_path));
    }

    std::string out_path;
    if (outarg.Get() == "") {
        out_path = QI::StripExt(input_path.Get()) + "_mask" + QI::OutExt();
    } else {
        out_path = outarg.Get();
    }

    // Extract one volume to process
    auto region = vols->GetLargestPossibleRegion();
    if (std::abs(volume.Get()) < region.GetSize()[3]) {
        int volume_to_get = (region.GetSize()[3] + volume.Get()) % region.GetSize()[3];
        if (verbose) std::cout << "Using volume " << volume_to_get << std::endl;
        region.GetModifiableIndex()[3] = volume_to_get;
    } else {
        std::cerr << "Specified volume was invalid: " << volume.Get() << std::endl;
        return EXIT_FAILURE;
    }
    region.GetModifiableSize()[3] = 0;
    auto vol = itk::ExtractImageFilter<QI::SeriesF, QI::VolumeF>::New();
    vol->SetExtractionRegion(region);
    vol->SetInput(vols);
    vol->SetDirectionCollapseToSubmatrix();
    vol->Update();
    QI::VolumeF::Pointer intensity_image = vol->GetOutput();
    intensity_image->DisconnectPipeline();

    /*
     *  Stage 1 - Otsu or Threshold
     */
    QI::VolumeI::Pointer mask_image = ITK_NULLPTR;
    if (lower_threshold || upper_threshold) {
        if (verbose) std::cout << "Thresholding range: " << lower_threshold.Get() << "-" << upper_threshold.Get() << std::endl;
        mask_image = QI::ThresholdMask(intensity_image, lower_threshold.Get(), upper_threshold.Get());
    } else {
        if (verbose) std::cout << "Generating Otsu mask" << std::endl;
        mask_image = QI::OtsuMask(intensity_image);
    }

    /*
     *  Stage 2 - RATS
     */
     if (rats) {
        typedef itk::BinaryBallStructuringElement<int, 3> TBall;
        typedef itk::BinaryErodeImageFilter<QI::VolumeI, QI::VolumeI, TBall> TErode;
        typedef itk::BinaryDilateImageFilter<QI::VolumeI, QI::VolumeI, TBall> TDilate;
        float mask_volume = std::numeric_limits<float>::infinity();
        float voxel_volume = QI::VoxelVolume(mask_image);
        if (verbose) std::cout << "Voxel volume: " << voxel_volume << std::endl;
        int radius = 0;
        QI::VolumeI::Pointer mask_rats;
        while (mask_volume > rats.Get()) {
            radius++;
            TBall ball;
            TBall::SizeType radii; radii.Fill(radius);
            ball.SetRadius(radii);
            ball.CreateStructuringElement();
            TErode::Pointer erode = TErode::New();
            erode->SetInput(mask_image);
            erode->SetForegroundValue(1);
            erode->SetBackgroundValue(0);
            erode->SetKernel(ball);
            erode->Update();
            std::vector<float> kept_sizes = QI::FindLabels(erode->GetOutput(), 0, 1, mask_rats);
            mask_volume = kept_sizes[0] * voxel_volume;
            auto dilate = TDilate::New();
            dilate->SetKernel(ball);
            dilate->SetInput(mask_rats);
            dilate->SetForegroundValue(1);
            dilate->SetBackgroundValue(0);
            dilate->Update();
            mask_rats = dilate->GetOutput();
            mask_rats->DisconnectPipeline();
            if (verbose) std::cout << "Ran RATS iteration, current radius: " << radius << " volume is: " << mask_volume << std::endl;
         }
         mask_image = mask_rats;
     }

    /*
     *  Stage 3 - Hole Filling
     */
    QI::VolumeI::Pointer finalMask = ITK_NULLPTR;
    if (fillh_radius) {
        if (verbose) std::cout << "Filling holes" << std::endl;
        auto fillHoles = itk::VotingBinaryIterativeHoleFillingImageFilter<QI::VolumeI>::New();
        itk::VotingBinaryIterativeHoleFillingImageFilter<QI::VolumeI>::InputSizeType radius;
        radius.Fill(fillh_radius.Get());
        fillHoles->SetInput(mask_image);
        fillHoles->SetRadius(radius);
        fillHoles->SetMajorityThreshold(2); // Corresponds to (rad^3-1)/2 + 2 threshold
        fillHoles->SetBackgroundValue(0);
        fillHoles->SetForegroundValue(1);
        fillHoles->SetMaximumNumberOfIterations(3);
        fillHoles->Update();
        mask_image = fillHoles->GetOutput();
        mask_image->DisconnectPipeline();
    }

    if (verbose) std::cout << "Saving mask to: " << out_path << std::endl;
    QI::WriteImage(mask_image, out_path);
    if (verbose) std::cout << "Finished." << std::endl;
    return EXIT_SUCCESS;
}

<|endoftext|>


<commit_before>#include "./constraint_updater.h"
#include <Eigen/Geometry>
#include <vector>
#include <string>
#include <memory>
#include "./placement.h"
#include "./shadow_constraint_drawer.h"
#include "./anchor_constraint_drawer.h"

ConstraintUpdater::ConstraintUpdater(
    int width, int height,
    std::shared_ptr<AnchorConstraintDrawer> anchorConstraintDrawer,
    std::shared_ptr<ShadowConstraintDrawer> connectorShadowDrawer,
    std::shared_ptr<ShadowConstraintDrawer> shadowConstraintDrawer)
  : width(width), height(height),
    anchorConstraintDrawer(anchorConstraintDrawer),
    connectorShadowDrawer(connectorShadowDrawer),
    shadowConstraintDrawer(shadowConstraintDrawer)
{
  labelShadowColor = Placement::labelShadowValue / 255.0f;
  connectorShadowColor = Placement::connectorShadowValue / 255.0f;
  anchorConstraintColor = Placement::anchorConstraintValue / 255.0f;
}

ConstraintUpdater::~ConstraintUpdater()
{
}

void ConstraintUpdater::drawConstraintRegionFor(
    Eigen::Vector2i anchorPosition, Eigen::Vector2i labelSize,
    Eigen::Vector2i lastAnchorPosition, Eigen::Vector2i lastLabelPosition,
    Eigen::Vector2i lastLabelSize)
{
  this->labelSize = labelSize.cast<float>();

  if (isConnectorShadowEnabled)
    addConnectorShadow(anchorPosition, lastAnchorPosition, lastLabelPosition);

  Eigen::Vector2f anchor = anchorPosition.cast<float>();
  Eigen::Vector2f lastHalfSize = 0.5f * lastLabelSize.cast<float>();
  addLabelShadow(anchor, lastLabelPosition, lastHalfSize);
}

void ConstraintUpdater::drawRegionsForAnchors(
    std::vector<Eigen::Vector2f> anchorPositions, Eigen::Vector2i labelSize)
{
  std::vector<float> positions(anchorPositions.size() * 2);
  size_t index = 0;
  for (auto &anchorPosition : anchorPositions)
  {
    positions[index++] = anchorPosition.x();
    positions[index++] = anchorPosition.y();
  }
  assert(positions.size() == index);

  anchorConstraintDrawer->update(positions);

  Eigen::Vector2f borderPixel(1.0f, 1.0f);
  Eigen::Vector2f constraintSize = borderPixel + labelSize.cast<float>();
  Eigen::Vector2f halfSize =
      constraintSize.cwiseQuotient(Eigen::Vector2f(width, height));

  anchorConstraintDrawer->draw(anchorConstraintColor, halfSize);
}

void ConstraintUpdater::clear()
{
  shadowConstraintDrawer->clear();

  sources.clear();
  starts.clear();
  ends.clear();

  anchors.clear();
  connectorStart.clear();
  connectorEnd.clear();
}

void ConstraintUpdater::finish()
{
  shadowConstraintDrawer->update(sources, starts, ends);
  connectorShadowDrawer->update(anchors, connectorStart, connectorEnd);

  Eigen::Vector2f borderPixel(2.0f, 2.0f);
  Eigen::Vector2f sizeWithBorder = labelSize.cast<float>() + borderPixel;
  Eigen::Vector2f halfSize =
      sizeWithBorder.cwiseQuotient(Eigen::Vector2f(width, height));

  shadowConstraintDrawer->draw(labelShadowColor, halfSize);
  connectorShadowDrawer->draw(connectorShadowColor, halfSize);
}

void ConstraintUpdater::setIsConnectorShadowEnabled(bool enabled)
{
  isConnectorShadowEnabled = enabled;
}

void ConstraintUpdater::addConnectorShadow(Eigen::Vector2i anchor,
                                           Eigen::Vector2i start,
                                           Eigen::Vector2i end)
{
  anchors.push_back(anchor.x());
  anchors.push_back(anchor.y());

  connectorStart.push_back(start.x());
  connectorStart.push_back(start.y());

  connectorEnd.push_back(end.x());
  connectorEnd.push_back(end.y());
}

void ConstraintUpdater::addLineShadow(Eigen::Vector2f source,
                                      Eigen::Vector2f start,
                                      Eigen::Vector2f end)
{
  sources.push_back(source.x());
  sources.push_back(source.y());

  starts.push_back(start.x());
  starts.push_back(start.y());

  ends.push_back(end.x());
  ends.push_back(end.y());
}

void ConstraintUpdater::addLabelShadow(Eigen::Vector2f anchor,
                                       Eigen::Vector2i lastLabelPosition,
                                       Eigen::Vector2f lastHalfSize)
{
  std::vector<Eigen::Vector2f> corners =
      getCornersFor(lastLabelPosition, lastHalfSize);
  std::vector<float> cornerAnchorDistances;
  for (auto corner : corners)
    cornerAnchorDistances.push_back((corner - anchor).squaredNorm());

  int maxIndex = std::distance(cornerAnchorDistances.begin(),
                               std::max_element(cornerAnchorDistances.begin(),
                                                cornerAnchorDistances.end()));

  // Just add a line shadow for two edges of the label.
  // The other two, which are connected to the farthest corner
  // would produce an area which is included in the first one.
  // The following table illustrates which lines must be drawn,
  // between which corners (given by index)
  //
  // maxIndex  line 1  line 2
  // 0         1 to 2  2 to 3
  // 1         2 to 3  3 to 0
  // 2         0 to 1  3 to 0
  // 3         0 to 1  1 to 2
  if (maxIndex == 2 || maxIndex == 3)
    addLineShadow(anchor, corners[0], corners[1]);

  if (maxIndex == 0 || maxIndex == 3)
    addLineShadow(anchor, corners[1], corners[2]);

  if (maxIndex == 0 || maxIndex == 1)
    addLineShadow(anchor, corners[2], corners[3]);

  if (maxIndex == 1 || maxIndex == 2)
    addLineShadow(anchor, corners[3], corners[0]);
}

std::vector<Eigen::Vector2f>
ConstraintUpdater::getCornersFor(Eigen::Vector2i position,
                                 Eigen::Vector2f halfSize)
{
  std::vector<Eigen::Vector2f> corners = {
    Eigen::Vector2f(position.x() + halfSize.x(), position.y() + halfSize.y()),
    Eigen::Vector2f(position.x() - halfSize.x(), position.y() + halfSize.y()),
    Eigen::Vector2f(position.x() - halfSize.x(), position.y() - halfSize.y()),
    Eigen::Vector2f(position.x() + halfSize.x(), position.y() - halfSize.y()),
  };

  return corners;
}

void ConstraintUpdater::save(std::string filename)
{
  anchorConstraintDrawer->saveBufferTo(filename);
}
<commit_msg>Increase anchor border size to 2.<commit_after>#include "./constraint_updater.h"
#include <Eigen/Geometry>
#include <vector>
#include <string>
#include <memory>
#include "./placement.h"
#include "./shadow_constraint_drawer.h"
#include "./anchor_constraint_drawer.h"

ConstraintUpdater::ConstraintUpdater(
    int width, int height,
    std::shared_ptr<AnchorConstraintDrawer> anchorConstraintDrawer,
    std::shared_ptr<ShadowConstraintDrawer> connectorShadowDrawer,
    std::shared_ptr<ShadowConstraintDrawer> shadowConstraintDrawer)
  : width(width), height(height),
    anchorConstraintDrawer(anchorConstraintDrawer),
    connectorShadowDrawer(connectorShadowDrawer),
    shadowConstraintDrawer(shadowConstraintDrawer)
{
  labelShadowColor = Placement::labelShadowValue / 255.0f;
  connectorShadowColor = Placement::connectorShadowValue / 255.0f;
  anchorConstraintColor = Placement::anchorConstraintValue / 255.0f;
}

ConstraintUpdater::~ConstraintUpdater()
{
}

void ConstraintUpdater::drawConstraintRegionFor(
    Eigen::Vector2i anchorPosition, Eigen::Vector2i labelSize,
    Eigen::Vector2i lastAnchorPosition, Eigen::Vector2i lastLabelPosition,
    Eigen::Vector2i lastLabelSize)
{
  this->labelSize = labelSize.cast<float>();

  if (isConnectorShadowEnabled)
    addConnectorShadow(anchorPosition, lastAnchorPosition, lastLabelPosition);

  Eigen::Vector2f anchor = anchorPosition.cast<float>();
  Eigen::Vector2f lastHalfSize = 0.5f * lastLabelSize.cast<float>();
  addLabelShadow(anchor, lastLabelPosition, lastHalfSize);
}

void ConstraintUpdater::drawRegionsForAnchors(
    std::vector<Eigen::Vector2f> anchorPositions, Eigen::Vector2i labelSize)
{
  std::vector<float> positions(anchorPositions.size() * 2);
  size_t index = 0;
  for (auto &anchorPosition : anchorPositions)
  {
    positions[index++] = anchorPosition.x();
    positions[index++] = anchorPosition.y();
  }
  assert(positions.size() == index);

  anchorConstraintDrawer->update(positions);

  Eigen::Vector2f borderPixel(2.0f, 2.0f);
  Eigen::Vector2f constraintSize = borderPixel + labelSize.cast<float>();
  Eigen::Vector2f halfSize =
      constraintSize.cwiseQuotient(Eigen::Vector2f(width, height));

  anchorConstraintDrawer->draw(anchorConstraintColor, halfSize);
}

void ConstraintUpdater::clear()
{
  shadowConstraintDrawer->clear();

  sources.clear();
  starts.clear();
  ends.clear();

  anchors.clear();
  connectorStart.clear();
  connectorEnd.clear();
}

void ConstraintUpdater::finish()
{
  shadowConstraintDrawer->update(sources, starts, ends);
  connectorShadowDrawer->update(anchors, connectorStart, connectorEnd);

  Eigen::Vector2f borderPixel(2.0f, 2.0f);
  Eigen::Vector2f sizeWithBorder = labelSize.cast<float>() + borderPixel;
  Eigen::Vector2f halfSize =
      sizeWithBorder.cwiseQuotient(Eigen::Vector2f(width, height));

  shadowConstraintDrawer->draw(labelShadowColor, halfSize);
  connectorShadowDrawer->draw(connectorShadowColor, halfSize);
}

void ConstraintUpdater::setIsConnectorShadowEnabled(bool enabled)
{
  isConnectorShadowEnabled = enabled;
}

void ConstraintUpdater::addConnectorShadow(Eigen::Vector2i anchor,
                                           Eigen::Vector2i start,
                                           Eigen::Vector2i end)
{
  anchors.push_back(anchor.x());
  anchors.push_back(anchor.y());

  connectorStart.push_back(start.x());
  connectorStart.push_back(start.y());

  connectorEnd.push_back(end.x());
  connectorEnd.push_back(end.y());
}

void ConstraintUpdater::addLineShadow(Eigen::Vector2f source,
                                      Eigen::Vector2f start,
                                      Eigen::Vector2f end)
{
  sources.push_back(source.x());
  sources.push_back(source.y());

  starts.push_back(start.x());
  starts.push_back(start.y());

  ends.push_back(end.x());
  ends.push_back(end.y());
}

void ConstraintUpdater::addLabelShadow(Eigen::Vector2f anchor,
                                       Eigen::Vector2i lastLabelPosition,
                                       Eigen::Vector2f lastHalfSize)
{
  std::vector<Eigen::Vector2f> corners =
      getCornersFor(lastLabelPosition, lastHalfSize);
  std::vector<float> cornerAnchorDistances;
  for (auto corner : corners)
    cornerAnchorDistances.push_back((corner - anchor).squaredNorm());

  int maxIndex = std::distance(cornerAnchorDistances.begin(),
                               std::max_element(cornerAnchorDistances.begin(),
                                                cornerAnchorDistances.end()));

  // Just add a line shadow for two edges of the label.
  // The other two, which are connected to the farthest corner
  // would produce an area which is included in the first one.
  // The following table illustrates which lines must be drawn,
  // between which corners (given by index)
  //
  // maxIndex  line 1  line 2
  // 0         1 to 2  2 to 3
  // 1         2 to 3  3 to 0
  // 2         0 to 1  3 to 0
  // 3         0 to 1  1 to 2
  if (maxIndex == 2 || maxIndex == 3)
    addLineShadow(anchor, corners[0], corners[1]);

  if (maxIndex == 0 || maxIndex == 3)
    addLineShadow(anchor, corners[1], corners[2]);

  if (maxIndex == 0 || maxIndex == 1)
    addLineShadow(anchor, corners[2], corners[3]);

  if (maxIndex == 1 || maxIndex == 2)
    addLineShadow(anchor, corners[3], corners[0]);
}

std::vector<Eigen::Vector2f>
ConstraintUpdater::getCornersFor(Eigen::Vector2i position,
                                 Eigen::Vector2f halfSize)
{
  std::vector<Eigen::Vector2f> corners = {
    Eigen::Vector2f(position.x() + halfSize.x(), position.y() + halfSize.y()),
    Eigen::Vector2f(position.x() - halfSize.x(), position.y() + halfSize.y()),
    Eigen::Vector2f(position.x() - halfSize.x(), position.y() - halfSize.y()),
    Eigen::Vector2f(position.x() + halfSize.x(), position.y() - halfSize.y()),
  };

  return corners;
}

void ConstraintUpdater::save(std::string filename)
{
  anchorConstraintDrawer->saveBufferTo(filename);
}
<|endoftext|>


<commit_before>#include <Bull/Render/Context/GlContext.hpp>
#include <Bull/Render/Context/GlFunctions.hpp>
#include <Bull/Render/Target/RenderTarget.hpp>

namespace Bull
{
    RenderTarget::~RenderTarget() = default;

    void RenderTarget::clear(Uint8 red, Uint8 green, Uint8 blue, Uint8 alpha)
    {
        setActive();

        gl::clearColor(static_cast<float>(red)   / 255.f,
                       static_cast<float>(green) / 255.f,
                       static_cast<float>(blue)  / 255.f,
                       static_cast<float>(alpha) / 255.f);

        gl::clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    }

    void RenderTarget::clear(const Color& color)
    {
        clear(color.red, color.green, color.blue, color.alpha);
    }

    void RenderTarget::setActive(bool active)
    {
        if(m_context)
        {
            m_context->setActive(active);
        }
    }

    void RenderTarget::setViewport(const Viewport& viewport)
    {
        setActive();

        m_currentViewport = viewport;

        gl::viewport(m_currentViewport.x, m_currentViewport.y, m_currentViewport.width, m_currentViewport.height);
    }

    const Viewport& RenderTarget::getViewport() const
    {
        return m_currentViewport;
    }

    void RenderTarget::resetViewport()
    {
        setViewport(getDefaultViewport());
    }

    const ContextSettings& RenderTarget::getSettings() const
    {
        if(m_context)
        {
            return m_context->getSettings();
        }

        return ContextSettings::Empty;
    }
}
<commit_msg>[Render/RenderTarget] Clear stencil buffer if enable<commit_after>#include <Bull/Render/Context/GlContext.hpp>
#include <Bull/Render/Context/GlFunctions.hpp>
#include <Bull/Render/Target/RenderTarget.hpp>

namespace Bull
{
    RenderTarget::~RenderTarget() = default;

    void RenderTarget::clear(Uint8 red, Uint8 green, Uint8 blue, Uint8 alpha)
    {
        setActive();

        gl::clearColor(static_cast<float>(red)   / 255.f,
                       static_cast<float>(green) / 255.f,
                       static_cast<float>(blue)  / 255.f,
                       static_cast<float>(alpha) / 255.f);

        gl::clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        if(gl::isEnabled(GL_STENCIL_TEST))
        {
            gl::clear(GL_STENCIL_BUFFER_BIT);
        }
    }

    void RenderTarget::clear(const Color& color)
    {
        clear(color.red, color.green, color.blue, color.alpha);
    }

    void RenderTarget::setActive(bool active)
    {
        if(m_context)
        {
            m_context->setActive(active);
        }
    }

    void RenderTarget::setViewport(const Viewport& viewport)
    {
        setActive();

        m_currentViewport = viewport;

        gl::viewport(m_currentViewport.x, m_currentViewport.y, m_currentViewport.width, m_currentViewport.height);
    }

    const Viewport& RenderTarget::getViewport() const
    {
        return m_currentViewport;
    }

    void RenderTarget::resetViewport()
    {
        setViewport(getDefaultViewport());
    }

    const ContextSettings& RenderTarget::getSettings() const
    {
        if(m_context)
        {
            return m_context->getSettings();
        }

        return ContextSettings::Empty;
    }
}
<|endoftext|>


<commit_before>#pragma once

#include <vector>
#include <string>
#include <functional>
#include <Engine/Entity/Entity.hpp>
#include <imgui.h>

namespace Component {
    class Animation;
    class Physics;
    class Mesh;
    class Lens;
    class Material;
    class DirectionalLight;
    class PointLight;
    class SpotLight;
    class Listener;
    class Script;
    class SoundSource;
    class ParticleEmitter;
}

namespace GUI {
    /// Used to edit an entity.
    class EntityEditor {
        public:
            /// Create new entity editor.
            EntityEditor();

            /// Destructor.
            ~EntityEditor();

            /// Show the editor.
            void Show();

            /// Set the entity to edit.
            /**
             * @param entity The entity to edit.
             */
            void SetEntity(Entity* entity);

            /// Checks if the editor is showing this entity.
            /**
             * @param entity The entity to check.
             * @return Is it showing.
             */
            bool ShowsEntity(Entity* entity);

            /// Get whether the window is visible.
            /**
             * @return Whether the window is visible.
             */
            bool IsVisible() const;

            /// Set whether the window should be visible.
            /**
             * @param visible Whether the window should be visible.
             */
            void SetVisible(bool visible);

        private:
            template<typename type> void AddEditor(const std::string& name, std::function<void(type*)> editorFunction);
            template<typename type> void AddComponent(const std::string& name);
            template<typename type> void EditComponent(const std::string& name, std::function<void(type*)> editorFunction);

            // Editors
            void AnimationEditor(Component::Animation* animation);
            void PhysicsEditor(Component::Physics* physics);
            void MeshEditor(Component::Mesh* mesh);
            void LensEditor(Component::Lens* lens);
            void MaterialEditor(Component::Material* material);
            void DirectionalLightEditor(Component::DirectionalLight* directionalLight);
            void PointLightEditor(Component::PointLight* pointLight);
            void SpotLightEditor(Component::SpotLight* spotLight);
            void ListenerEditor(Component::Listener* listener);
            void ScriptEditor(Component::Script* script);
            void SoundSourceEditor(Component::SoundSource* soundSource);
            void ParticleEmitterEditor(Component::ParticleEmitter* particleEmitter);

            Entity* entity = nullptr;
            bool visible = false;
            char name[128];

            struct Editor {
                std::function<void()> addFunction;
                std::function<void()> editFunction;
            };
            std::vector<Editor> editors;
    };
}

template<typename type> void GUI::EntityEditor::AddEditor(const std::string& name, std::function<void(type*)> editorFunction) {
    Editor editor;
    editor.addFunction = std::bind(&EntityEditor::AddComponent<type>, this, name);
    editor.editFunction = std::bind(&EntityEditor::EditComponent<type>, this, name, editorFunction);
    editors.push_back(editor);
}

template<typename type> void GUI::EntityEditor::AddComponent(const std::string& name) {
    if (entity->GetComponent<type>() == nullptr)
        if (ImGui::Selectable(name.c_str()))
            entity->AddComponent<type>();
}

template<typename type> void GUI::EntityEditor::EditComponent(const std::string& name, std::function<void(type*)> editorFunction) {
    type* component = entity->GetComponent<type>();
    if (component != nullptr && ImGui::CollapsingHeader(name.c_str())) {
        editorFunction(component);

        if (ImGui::Button("Remove"))
            entity->KillComponent<type>();
    }
}
<commit_msg>Push component ID<commit_after>#pragma once

#include <vector>
#include <string>
#include <functional>
#include <Engine/Entity/Entity.hpp>
#include <imgui.h>

namespace Component {
    class Animation;
    class Physics;
    class Mesh;
    class Lens;
    class Material;
    class DirectionalLight;
    class PointLight;
    class SpotLight;
    class Listener;
    class Script;
    class SoundSource;
    class ParticleEmitter;
}

namespace GUI {
    /// Used to edit an entity.
    class EntityEditor {
        public:
            /// Create new entity editor.
            EntityEditor();

            /// Destructor.
            ~EntityEditor();

            /// Show the editor.
            void Show();

            /// Set the entity to edit.
            /**
             * @param entity The entity to edit.
             */
            void SetEntity(Entity* entity);

            /// Checks if the editor is showing this entity.
            /**
             * @param entity The entity to check.
             * @return Is it showing.
             */
            bool ShowsEntity(Entity* entity);

            /// Get whether the window is visible.
            /**
             * @return Whether the window is visible.
             */
            bool IsVisible() const;

            /// Set whether the window should be visible.
            /**
             * @param visible Whether the window should be visible.
             */
            void SetVisible(bool visible);

        private:
            template<typename type> void AddEditor(const std::string& name, std::function<void(type*)> editorFunction);
            template<typename type> void AddComponent(const std::string& name);
            template<typename type> void EditComponent(const std::string& name, std::function<void(type*)> editorFunction);

            // Editors
            void AnimationEditor(Component::Animation* animation);
            void PhysicsEditor(Component::Physics* physics);
            void MeshEditor(Component::Mesh* mesh);
            void LensEditor(Component::Lens* lens);
            void MaterialEditor(Component::Material* material);
            void DirectionalLightEditor(Component::DirectionalLight* directionalLight);
            void PointLightEditor(Component::PointLight* pointLight);
            void SpotLightEditor(Component::SpotLight* spotLight);
            void ListenerEditor(Component::Listener* listener);
            void ScriptEditor(Component::Script* script);
            void SoundSourceEditor(Component::SoundSource* soundSource);
            void ParticleEmitterEditor(Component::ParticleEmitter* particleEmitter);

            Entity* entity = nullptr;
            bool visible = false;
            char name[128];

            struct Editor {
                std::function<void()> addFunction;
                std::function<void()> editFunction;
            };
            std::vector<Editor> editors;
    };
}

template<typename type> void GUI::EntityEditor::AddEditor(const std::string& name, std::function<void(type*)> editorFunction) {
    Editor editor;
    editor.addFunction = std::bind(&EntityEditor::AddComponent<type>, this, name);
    editor.editFunction = std::bind(&EntityEditor::EditComponent<type>, this, name, editorFunction);
    editors.push_back(editor);
}

template<typename type> void GUI::EntityEditor::AddComponent(const std::string& name) {
    if (entity->GetComponent<type>() == nullptr)
        if (ImGui::Selectable(name.c_str()))
            entity->AddComponent<type>();
}

template<typename type> void GUI::EntityEditor::EditComponent(const std::string& name, std::function<void(type*)> editorFunction) {
    type* component = entity->GetComponent<type>();
    if (component != nullptr && ImGui::CollapsingHeader(name.c_str())) {
        ImGui::PushID(name.c_str());

        editorFunction(component);

        if (ImGui::Button("Remove"))
            entity->KillComponent<type>();

        ImGui::PopID();
    }
}
<|endoftext|>


<commit_before>// //////////////////////////////////////////////////////////////////////
// Import section
// //////////////////////////////////////////////////////////////////////
// STL
#include <fstream>
#include <string>
#include <vector>
#include <exception>
// Distribution
#include <simcrs/SIMCRS_Service.hpp>
// Dsim
#include <dsim/command/Simulator.hpp>
#include <dsim/service/Logger.hpp>

namespace DSIM {

  // //////////////////////////////////////////////////////////////////////
  void Simulator::simulate (SIMCRS::SIMCRS_Service& ioSIMCRS_Service) {

    try {

      // DEBUG
      DSIM_LOG_DEBUG ("The simulation is starting");

      // Airline code
      std::string lAirlineCode ("LH");

      // Number of passengers in the travelling group
      SIMCRS::PartySize_T lPartySize = 5;

      // Make a booking
      ioSIMCRS_Service.sell (lAirlineCode, lPartySize);

      // DEBUG
      DSIM_LOG_DEBUG ("The simulation has ended");

    } catch (const std::exception& lStdError) {
      DSIM_LOG_ERROR ("Error: " << lStdError.what());
      throw SimulationException();
    }
  }

}
<commit_msg>[Dev] Some small changes in the type definition.<commit_after>// //////////////////////////////////////////////////////////////////////
// Import section
// //////////////////////////////////////////////////////////////////////
// STL
#include <fstream>
#include <string>
#include <vector>
#include <exception>
// STDAIR
#include <stdair/STDAIR_Types.hpp>
// Distribution
#include <simcrs/SIMCRS_Service.hpp>
// Dsim
#include <dsim/command/Simulator.hpp>
#include <dsim/service/Logger.hpp>

namespace DSIM {

  // //////////////////////////////////////////////////////////////////////
  void Simulator::simulate (SIMCRS::SIMCRS_Service& ioSIMCRS_Service) {

    try {

      // DEBUG
      DSIM_LOG_DEBUG ("The simulation is starting");

      // Airline code
      stdair::AirlineCode_T lAirlineCode ("BA");

      // Number of passengers in the travelling group
      stdair::PartySize_T lPartySize = 5;

      // Make a booking
      ioSIMCRS_Service.sell (lAirlineCode, lPartySize);

      // DEBUG
      DSIM_LOG_DEBUG ("The simulation has ended");

    } catch (const std::exception& lStdError) {
      DSIM_LOG_ERROR ("Error: " << lStdError.what());
      throw SimulationException();
    }
  }

}
<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_comphelper.hxx"
#include <comphelper/componentmodule.hxx>

/** === begin UNO includes === **/
/** === end UNO includes === **/
#include <comphelper/sequence.hxx>
#include <osl/diagnose.h>

#include <vector>

//........................................................................
namespace comphelper
{
//........................................................................

    using namespace ::cppu;
    /** === being UNO using === **/
    using ::com::sun::star::uno::Sequence;
    using ::com::sun::star::uno::RuntimeException;
    using ::com::sun::star::uno::Reference;
    using ::com::sun::star::lang::XMultiServiceFactory;
    using ::com::sun::star::registry::XRegistryKey;
    using ::com::sun::star::uno::Exception;
    using ::com::sun::star::uno::XInterface;
    /** === end UNO using === **/

    typedef ::std::vector< ComponentDescription >   ComponentDescriptions;

    //=========================================================================
    //= OModuleImpl
    //=========================================================================
    /** implementation for <type>OModule</type>. not threadsafe, has to be guarded by it's owner
    */
    class OModuleImpl
    {
    public:
        ComponentDescriptions                           m_aRegisteredComponents;

        OModuleImpl();
        ~OModuleImpl();
    };

    //-------------------------------------------------------------------------
    OModuleImpl::OModuleImpl()
    {
    }

    //-------------------------------------------------------------------------
    OModuleImpl::~OModuleImpl()
    {
    }

    //=========================================================================
    //= OModule
    //=========================================================================
    //-------------------------------------------------------------------------
    OModule::OModule()
        :m_nClients( 0 )
        ,m_pImpl( 0 )
    {
    }

    OModule::~OModule() {}

    //-------------------------------------------------------------------------
    void OModule::registerClient( OModule::ClientAccess )
    {
        ::osl::MutexGuard aGuard(m_aMutex);
        if ( 1 == osl_incrementInterlockedCount( &m_nClients ) )
            onFirstClient();
    }

    //-------------------------------------------------------------------------
    void OModule::revokeClient( OModule::ClientAccess )
    {
        ::osl::MutexGuard aGuard(m_aMutex);
        if ( 0 == osl_decrementInterlockedCount( &m_nClients ) )
            onLastClient();
    }

    //--------------------------------------------------------------------------
    void OModule::onFirstClient()
    {
        OSL_PRECOND( !m_pImpl, "called out of sequence" );
        if ( !m_pImpl )
            m_pImpl = new OModuleImpl;
    }

    //--------------------------------------------------------------------------
    void OModule::onLastClient()
    {
        OSL_PRECOND( m_pImpl, "called out of sequence" );
        delete m_pImpl;
        m_pImpl = 0;
    }

    //--------------------------------------------------------------------------
    void OModule::registerImplementation( const ComponentDescription& _rComp )
    {
        ::osl::MutexGuard aGuard( m_aMutex );
        OSL_PRECOND( m_pImpl, "not initialized properly" );
        if ( !m_pImpl )
            throw RuntimeException();

        m_pImpl->m_aRegisteredComponents.push_back( _rComp );
    }

    //--------------------------------------------------------------------------
    void OModule::registerImplementation( const ::rtl::OUString& _rImplementationName, const ::com::sun::star::uno::Sequence< ::rtl::OUString >& _rServiceNames,
        ::cppu::ComponentFactoryFunc _pCreateFunction, FactoryInstantiation _pFactoryFunction )
    {
        ComponentDescription aComponent( _rImplementationName, _rServiceNames, ::rtl::OUString(), _pCreateFunction, _pFactoryFunction );
        registerImplementation( aComponent );
    }

    //--------------------------------------------------------------------------
    void* OModule::getComponentFactory( const sal_Char* _pImplementationName, void* _pServiceManager, void* /*_pRegistryKey*/ )
    {
        Reference< XInterface > xFactory( getComponentFactory(
            ::rtl::OUString::createFromAscii( _pImplementationName ),
            Reference< XMultiServiceFactory >( static_cast< XMultiServiceFactory* >( _pServiceManager ) )
        ) );
        return xFactory.get();
    }

    //--------------------------------------------------------------------------
    Reference< XInterface > OModule::getComponentFactory( const ::rtl::OUString& _rImplementationName,
        const Reference< XMultiServiceFactory >& /* _rxServiceManager */ )
    {
        Reference< XInterface > xReturn;

        for (   ComponentDescriptions::const_iterator component = m_pImpl->m_aRegisteredComponents.begin();
                component != m_pImpl->m_aRegisteredComponents.end();
                ++component
            )
        {
            if ( component->sImplementationName == _rImplementationName )
            {
                xReturn = component->pFactoryCreationFunc(
                    component->pComponentCreationFunc,
                    component->sImplementationName,
                    component->aSupportedServices,
                    NULL
                );
                if ( xReturn.is() )
                {
                    xReturn->acquire();
                    return xReturn.get();
                }
            }
        }

        return NULL;
    }

//........................................................................
} // namespace comphelper
//........................................................................

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>Revert "do not leak memory"<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_comphelper.hxx"
#include <comphelper/componentmodule.hxx>

/** === begin UNO includes === **/
/** === end UNO includes === **/
#include <comphelper/sequence.hxx>
#include <osl/diagnose.h>

#include <vector>

//........................................................................
namespace comphelper
{
//........................................................................

    using namespace ::cppu;
    /** === being UNO using === **/
    using ::com::sun::star::uno::Sequence;
    using ::com::sun::star::uno::RuntimeException;
    using ::com::sun::star::uno::Reference;
    using ::com::sun::star::lang::XMultiServiceFactory;
    using ::com::sun::star::registry::XRegistryKey;
    using ::com::sun::star::uno::Exception;
    using ::com::sun::star::uno::XInterface;
    /** === end UNO using === **/

    typedef ::std::vector< ComponentDescription >   ComponentDescriptions;

    //=========================================================================
    //= OModuleImpl
    //=========================================================================
    /** implementation for <type>OModule</type>. not threadsafe, has to be guarded by it's owner
    */
    class OModuleImpl
    {
    public:
        ComponentDescriptions                           m_aRegisteredComponents;

        OModuleImpl();
        ~OModuleImpl();
    };

    //-------------------------------------------------------------------------
    OModuleImpl::OModuleImpl()
    {
    }

    //-------------------------------------------------------------------------
    OModuleImpl::~OModuleImpl()
    {
    }

    //=========================================================================
    //= OModule
    //=========================================================================
    //-------------------------------------------------------------------------
    OModule::OModule()
        :m_nClients( 0 )
        ,m_pImpl( new OModuleImpl )
    {
    }

    OModule::~OModule() {}

    //-------------------------------------------------------------------------
    void OModule::registerClient( OModule::ClientAccess )
    {
        ::osl::MutexGuard aGuard(m_aMutex);
        if ( 1 == osl_incrementInterlockedCount( &m_nClients ) )
            onFirstClient();
    }

    //-------------------------------------------------------------------------
    void OModule::revokeClient( OModule::ClientAccess )
    {
        ::osl::MutexGuard aGuard(m_aMutex);
        if ( 0 == osl_decrementInterlockedCount( &m_nClients ) )
            onLastClient();
    }

    //--------------------------------------------------------------------------
    void OModule::onFirstClient()
    {
    }

    //--------------------------------------------------------------------------
    void OModule::onLastClient()
    {
    }

    //--------------------------------------------------------------------------
    void OModule::registerImplementation( const ComponentDescription& _rComp )
    {
        ::osl::MutexGuard aGuard( m_aMutex );
        if ( !m_pImpl )
            throw RuntimeException();

        m_pImpl->m_aRegisteredComponents.push_back( _rComp );
    }

    //--------------------------------------------------------------------------
    void OModule::registerImplementation( const ::rtl::OUString& _rImplementationName, const ::com::sun::star::uno::Sequence< ::rtl::OUString >& _rServiceNames,
        ::cppu::ComponentFactoryFunc _pCreateFunction, FactoryInstantiation _pFactoryFunction )
    {
        ComponentDescription aComponent( _rImplementationName, _rServiceNames, ::rtl::OUString(), _pCreateFunction, _pFactoryFunction );
        registerImplementation( aComponent );
    }

    //--------------------------------------------------------------------------
    void* OModule::getComponentFactory( const sal_Char* _pImplementationName, void* _pServiceManager, void* /*_pRegistryKey*/ )
    {
        Reference< XInterface > xFactory( getComponentFactory(
            ::rtl::OUString::createFromAscii( _pImplementationName ),
            Reference< XMultiServiceFactory >( static_cast< XMultiServiceFactory* >( _pServiceManager ) )
        ) );
        return xFactory.get();
    }

    //--------------------------------------------------------------------------
    Reference< XInterface > OModule::getComponentFactory( const ::rtl::OUString& _rImplementationName,
        const Reference< XMultiServiceFactory >& /* _rxServiceManager */ )
    {
        Reference< XInterface > xReturn;

        for (   ComponentDescriptions::const_iterator component = m_pImpl->m_aRegisteredComponents.begin();
                component != m_pImpl->m_aRegisteredComponents.end();
                ++component
            )
        {
            if ( component->sImplementationName == _rImplementationName )
            {
                xReturn = component->pFactoryCreationFunc(
                    component->pComponentCreationFunc,
                    component->sImplementationName,
                    component->aSupportedServices,
                    NULL
                );
                if ( xReturn.is() )
                {
                    xReturn->acquire();
                    return xReturn.get();
                }
            }
        }

        return NULL;
    }

//........................................................................
} // namespace comphelper
//........................................................................

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


<commit_before>//===--- Tools.cpp - Tools Implementations --------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//

#include "Tools.h"
#include "ToolChains.h"

#include "swift/Basic/LLVM.h"
#include "swift/Basic/Range.h"
#include "swift/Driver/Driver.h"
#include "swift/Driver/Job.h"
#include "swift/Driver/Options.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/Option/Arg.h"
#include "llvm/Option/ArgList.h"
#include "llvm/Support/Path.h"

using namespace swift::driver;
using namespace swift::driver::tools;
using namespace llvm::opt;

/// Swift Tool

std::unique_ptr<Job> Swift::constructJob(const JobAction &JA,
                                         std::unique_ptr<JobList> Inputs,
                                         std::unique_ptr<CommandOutput> Output,
                                         const ActionList &InputActions,
                                         const ArgList &Args,
                                         StringRef LinkingOutput) const {
  ArgStringList Arguments;

  const char *Exec = getToolChain().getDriver().getSwiftProgramPath();

  // Invoke ourselves in -frontend mode.
  Arguments.push_back("-frontend");

  Arguments.push_back("-target");
  std::string TripleStr = getToolChain().getTripleString();
  Arguments.push_back(Args.MakeArgString(TripleStr));

  const char *OutputOption = nullptr;
  switch (Output->getType()) {
  case types::TY_Object:
    OutputOption = "-c";
    break;
  case types::TY_RawSIL:
    OutputOption = "-emit-silgen";
    break;
  case types::TY_SIL:
    OutputOption = "-emit-sil";
    break;
  case types::TY_LLVM_IR:
    OutputOption = "-emit-ir";
    break;
  case types::TY_LLVM_BC:
    OutputOption = "-emit-bc";
    break;
  case types::TY_Nothing:
    // We were told to output nothing, so get the last mode option and use that.
    OutputOption =
      Args.getLastArg(options::OPT_modes_Group)->getSpelling().data();
    break;
  default:
    llvm_unreachable("Invalid output type");
  }

  assert(OutputOption != nullptr && "No output option specified!");

  Arguments.push_back(OutputOption);

  assert(Inputs->empty() &&
         "The Swift frontend does not expect to be fed any input Jobs!");
  assert(InputActions.size() == 1 &&
         "The Swift frontend expects exactly one input (the primary file)!");

  const InputAction *IA = dyn_cast<InputAction>(InputActions[0]);
  assert(IA && "Only InputActions can be passed as inputs!");
  const Arg &PrimaryInputArg = IA->getInputArg();
  bool FoundPrimaryInput = false;

  for (const Arg *A : make_range(Args.filtered_begin(options::OPT_INPUT),
                                 Args.filtered_end())) {
    Option Opt = A->getOption();
    if (A->getOption().matches(options::OPT_INPUT)) {
      // See if this input should be passed with -primary-file.
      if (!FoundPrimaryInput && PrimaryInputArg.getIndex() == A->getIndex()) {
        Arguments.push_back("-primary-file");
        FoundPrimaryInput = true;
      }
      Arguments.push_back(A->getValue());
    }
  }

  if (Args.hasArg(options::OPT_module_name)) {
    Args.AddLastArg(Arguments, options::OPT_module_name);
  } else if (const Arg *A = Args.getLastArgNoClaim(options::OPT_o)) {
      Arguments.push_back("-module-name");
      StringRef InferredModuleName = llvm::sys::path::stem(A->getValue());
      Arguments.push_back(Args.MakeArgString(InferredModuleName));
  }

  Args.AddLastArg(Arguments, options::OPT_g);

  // Pass the optimization level down to the frontend.
  Args.AddLastArg(Arguments, options::OPT_O_Group);

  // Set the SDK for the frontend.
  Args.AddLastArg(Arguments, options::OPT_sdk);

  // Pass through the values passed to -Xfrontend.
  Args.AddAllArgValues(Arguments, options::OPT_Xfrontend);

  Args.AddLastArg(Arguments, options::OPT_parse_as_library);

  Args.AddLastArg(Arguments, options::OPT_parse_sil);

  Args.AddLastArg(Arguments, options::OPT_parse_stdlib);

  // Add the output file argument if necessary.
  if (Output->getType() != types::TY_Nothing) {
    Arguments.push_back("-o");
    Arguments.push_back(Output->getFilename().data());
  } else if (Args.getLastArg(options::OPT_modes_Group)->getOption().matches(
               options::OPT_i)) {
    Args.AddLastArg(Arguments, options::OPT__DASH_DASH);
  }

  std::unique_ptr<Job> Cmd(new Command(JA, *this, std::move(Inputs),
                                       std::move(Output),
                                       Exec, Arguments));
  return Cmd;
}

/// Darwin Tools

llvm::Triple::ArchType darwin::getArchTypeForDarwinArchName(StringRef Arch) {
  return llvm::StringSwitch<llvm::Triple::ArchType>(Arch)
    .Cases("i386", "i486", "i486SX", "i586", "i686", llvm::Triple::x86)
    .Cases("pentium", "pentpro", "pentIIm3", "pentIIm5", "pentium4",
           llvm::Triple::x86)

    .Case("x86_64", llvm::Triple::x86_64)

    .Cases("arm", "armv4t", "armv5", "armv6", "armv6m", llvm::Triple::arm)
    .Cases("armv7", "armv7em", "armv7f", "armv7k", "armv7m", llvm::Triple::arm)
    .Cases("armv7s", "xscale", llvm::Triple::arm)

    .Default(llvm::Triple::UnknownArch);
}

void darwin::DarwinTool::anchor() {}

void darwin::DarwinTool::AddDarwinArch(const ArgList &Args,
                                       ArgStringList &CmdArgs) const {
  StringRef ArchName = getDarwinToolChain().getDarwinArchName(Args);

  CmdArgs.push_back("-arch");
  CmdArgs.push_back(Args.MakeArgString(ArchName));
}

std::unique_ptr<Job>
darwin::Linker::constructJob(const JobAction &JA,
                             std::unique_ptr<JobList> Inputs,
                             std::unique_ptr<CommandOutput> Output,
                             const ActionList &InputActions,
                             const ArgList &Args,
                             StringRef LinkingOutput) const {
  assert(Output->getType() == types::TY_Image && "Invalid linker output type.");
  ArgStringList Arguments;
  Arguments.push_back("-v");

  std::string Exec = getToolChain().getDriver().getProgramPath("ld",
                                                               getToolChain());

  std::unique_ptr<Job>Cmd (new Command(JA, *this, std::move(Inputs),
                                       std::move(Output),
                                       Args.MakeArgString(Exec), Arguments));
  return Cmd;
}
<commit_msg>[driver] Pass -serialize-diagnostics to the frontend, if requested.<commit_after>//===--- Tools.cpp - Tools Implementations --------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//

#include "Tools.h"
#include "ToolChains.h"

#include "swift/Basic/LLVM.h"
#include "swift/Basic/Range.h"
#include "swift/Driver/Driver.h"
#include "swift/Driver/Job.h"
#include "swift/Driver/Options.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/Option/Arg.h"
#include "llvm/Option/ArgList.h"
#include "llvm/Support/Path.h"

using namespace swift::driver;
using namespace swift::driver::tools;
using namespace llvm::opt;

/// Swift Tool

std::unique_ptr<Job> Swift::constructJob(const JobAction &JA,
                                         std::unique_ptr<JobList> Inputs,
                                         std::unique_ptr<CommandOutput> Output,
                                         const ActionList &InputActions,
                                         const ArgList &Args,
                                         StringRef LinkingOutput) const {
  ArgStringList Arguments;

  const char *Exec = getToolChain().getDriver().getSwiftProgramPath();

  // Invoke ourselves in -frontend mode.
  Arguments.push_back("-frontend");

  Arguments.push_back("-target");
  std::string TripleStr = getToolChain().getTripleString();
  Arguments.push_back(Args.MakeArgString(TripleStr));

  const char *OutputOption = nullptr;
  switch (Output->getType()) {
  case types::TY_Object:
    OutputOption = "-c";
    break;
  case types::TY_RawSIL:
    OutputOption = "-emit-silgen";
    break;
  case types::TY_SIL:
    OutputOption = "-emit-sil";
    break;
  case types::TY_LLVM_IR:
    OutputOption = "-emit-ir";
    break;
  case types::TY_LLVM_BC:
    OutputOption = "-emit-bc";
    break;
  case types::TY_Nothing:
    // We were told to output nothing, so get the last mode option and use that.
    OutputOption =
      Args.getLastArg(options::OPT_modes_Group)->getSpelling().data();
    break;
  default:
    llvm_unreachable("Invalid output type");
  }

  assert(OutputOption != nullptr && "No output option specified!");

  Arguments.push_back(OutputOption);

  assert(Inputs->empty() &&
         "The Swift frontend does not expect to be fed any input Jobs!");
  assert(InputActions.size() == 1 &&
         "The Swift frontend expects exactly one input (the primary file)!");

  const InputAction *IA = dyn_cast<InputAction>(InputActions[0]);
  assert(IA && "Only InputActions can be passed as inputs!");
  const Arg &PrimaryInputArg = IA->getInputArg();
  bool FoundPrimaryInput = false;

  for (const Arg *A : make_range(Args.filtered_begin(options::OPT_INPUT),
                                 Args.filtered_end())) {
    Option Opt = A->getOption();
    if (A->getOption().matches(options::OPT_INPUT)) {
      // See if this input should be passed with -primary-file.
      if (!FoundPrimaryInput && PrimaryInputArg.getIndex() == A->getIndex()) {
        Arguments.push_back("-primary-file");
        FoundPrimaryInput = true;
      }
      Arguments.push_back(A->getValue());
    }
  }

  if (Args.hasArg(options::OPT_module_name)) {
    Args.AddLastArg(Arguments, options::OPT_module_name);
  } else if (const Arg *A = Args.getLastArgNoClaim(options::OPT_o)) {
      Arguments.push_back("-module-name");
      StringRef InferredModuleName = llvm::sys::path::stem(A->getValue());
      Arguments.push_back(Args.MakeArgString(InferredModuleName));
  }

  Args.AddLastArg(Arguments, options::OPT_g);

  // Pass the optimization level down to the frontend.
  Args.AddLastArg(Arguments, options::OPT_O_Group);

  // Set the SDK for the frontend.
  Args.AddLastArg(Arguments, options::OPT_sdk);

  // Pass through the values passed to -Xfrontend.
  Args.AddAllArgValues(Arguments, options::OPT_Xfrontend);

  Args.AddLastArg(Arguments, options::OPT_parse_as_library);

  Args.AddLastArg(Arguments, options::OPT_parse_sil);

  Args.AddLastArg(Arguments, options::OPT_parse_stdlib);

  if (Args.hasArg(options::OPT_serialize_diagnostics)) {
    Arguments.push_back("-serialize-diagnostics");
    // TODO: pass -serialized-diagnostics-path with user-specified path,
    // if present. (This requires an output file map.)
  }

  // Add the output file argument if necessary.
  if (Output->getType() != types::TY_Nothing) {
    Arguments.push_back("-o");
    Arguments.push_back(Output->getFilename().data());
  } else if (Args.getLastArg(options::OPT_modes_Group)->getOption().matches(
               options::OPT_i)) {
    Args.AddLastArg(Arguments, options::OPT__DASH_DASH);
  }

  std::unique_ptr<Job> Cmd(new Command(JA, *this, std::move(Inputs),
                                       std::move(Output),
                                       Exec, Arguments));
  return Cmd;
}

/// Darwin Tools

llvm::Triple::ArchType darwin::getArchTypeForDarwinArchName(StringRef Arch) {
  return llvm::StringSwitch<llvm::Triple::ArchType>(Arch)
    .Cases("i386", "i486", "i486SX", "i586", "i686", llvm::Triple::x86)
    .Cases("pentium", "pentpro", "pentIIm3", "pentIIm5", "pentium4",
           llvm::Triple::x86)

    .Case("x86_64", llvm::Triple::x86_64)

    .Cases("arm", "armv4t", "armv5", "armv6", "armv6m", llvm::Triple::arm)
    .Cases("armv7", "armv7em", "armv7f", "armv7k", "armv7m", llvm::Triple::arm)
    .Cases("armv7s", "xscale", llvm::Triple::arm)

    .Default(llvm::Triple::UnknownArch);
}

void darwin::DarwinTool::anchor() {}

void darwin::DarwinTool::AddDarwinArch(const ArgList &Args,
                                       ArgStringList &CmdArgs) const {
  StringRef ArchName = getDarwinToolChain().getDarwinArchName(Args);

  CmdArgs.push_back("-arch");
  CmdArgs.push_back(Args.MakeArgString(ArchName));
}

std::unique_ptr<Job>
darwin::Linker::constructJob(const JobAction &JA,
                             std::unique_ptr<JobList> Inputs,
                             std::unique_ptr<CommandOutput> Output,
                             const ActionList &InputActions,
                             const ArgList &Args,
                             StringRef LinkingOutput) const {
  assert(Output->getType() == types::TY_Image && "Invalid linker output type.");
  ArgStringList Arguments;
  Arguments.push_back("-v");

  std::string Exec = getToolChain().getDriver().getProgramPath("ld",
                                                               getToolChain());

  std::unique_ptr<Job>Cmd (new Command(JA, *this, std::move(Inputs),
                                       std::move(Output),
                                       Args.MakeArgString(Exec), Arguments));
  return Cmd;
}
<|endoftext|>


<commit_before>/**
 * Analysis of registers that can be accessed by a BB
 *
 * This should produce a mapping between basic blocks and set of registers.
 *
 * It showcases the development of an Analysis.
 */

#define DEBUG_TYPE "reachable-integer-values"
#include "llvm/Support/Debug.h"

#include "ReachableIntegerValues.h"
#include "llvm/IR/Dominators.h"

#include <deque>

using namespace llvm;

ReachableIntegerValuesPass::ReachableIntegerValuesPass() : FunctionPass(ID) {}

bool ReachableIntegerValuesPass::runOnFunction(Function &F) {
  // The same instance of the analysis is created and registered, then used
  // repetitively, so we must clear its state each time we enter runOnFunction
  ReachableIntegerValuesMap.clear();

  // First compute sets of integer values defined for each Basic block
  ReachableIntegerValuesMapTy DefinedValuesMap;
  for (BasicBlock &BB : F) {
    auto &Values = DefinedValuesMap[&BB];
    for (Instruction &Inst : BB)
      if (Inst.getType()->isIntegerTy())
        Values.insert(&Inst);
  }

  // Second compute the reachable integer values

  // arguments and globals are always live
  auto &HeadValues = ReachableIntegerValuesMap[&F.getEntryBlock()];
  for (Argument &Arg : F.args())
    HeadValues.insert(&Arg);

  // then use dominance tree to merge relevant sets
  auto *Root =
      getAnalysis<DominatorTreeWrapperPass>().getDomTree().getRootNode();
  std::deque<decltype(Root)> NodesToProcess;
  NodesToProcess.push_back(Root);

  DEBUG(errs() << "In Function:\n" << F);

  while (not NodesToProcess.empty()) {
    auto *NodeToProcess = NodesToProcess.back();
    NodesToProcess.pop_back();
    DEBUG(errs() << "processing BB " << NodeToProcess->getBlock() << "\n");
    for (auto *Child : *NodeToProcess) {
      DEBUG(errs() << "updating dominated child " << Child->getBlock() << "\n");
      NodesToProcess.push_back(Child);
      {
        // add defined values to dominated nodes
        auto &Values = DefinedValuesMap[NodeToProcess->getBlock()];
        ReachableIntegerValuesMap[Child->getBlock()].insert(Values.begin(),
                                                            Values.end());
      }
      {
        // add inherited values from dominating node
        auto &Values = ReachableIntegerValuesMap[NodeToProcess->getBlock()];
        ReachableIntegerValuesMap[Child->getBlock()].insert(Values.begin(),
                                                            Values.end());
      }
    }
  }

  // An analysis should not modify its argument
  return false;
}

// This instructs the PassManager of the analyses required and preserved by
// this pass. The Pass Manager will schedule required passes earlier in the
// pipeline and make them available for this pass. Identifying the preserved
// analyses allows to save compile time by avoiding to recompute analysis when
// the results won't change.
// Analyses are read-only, so they generally preserve everything
// see
// http://llvm.org/docs/WritingAnLLVMPass.html#specifying-interactions-between-passes
void ReachableIntegerValuesPass::getAnalysisUsage(AnalysisUsage &Info) const {
  Info.addRequired<DominatorTreeWrapperPass>();
  Info.setPreservesAll();
}

ReachableIntegerValuesPass::ReachableIntegerValuesMapTy const &
ReachableIntegerValuesPass::getReachableIntegerValuesMap() const {
  return ReachableIntegerValuesMap;
}

char ReachableIntegerValuesPass::ID = 0;
static RegisterPass<ReachableIntegerValuesPass>
    X("reachable-integer-values",         // pass option
      "Compute Reachable Integer values", // pass description
      true,                               // does not modify the CFG
      true                                // and it's an analysis
      );
<commit_msg>MSVC compliance<commit_after>/**
 * Analysis of registers that can be accessed by a BB
 *
 * This should produce a mapping between basic blocks and set of registers.
 *
 * It showcases the development of an Analysis.
 */

#define DEBUG_TYPE "reachable-integer-values"
#include "llvm/Support/Debug.h"

#include "ReachableIntegerValues.h"
#include "llvm/IR/Dominators.h"

#include <deque>

using namespace llvm;

ReachableIntegerValuesPass::ReachableIntegerValuesPass() : FunctionPass(ID) {}

bool ReachableIntegerValuesPass::runOnFunction(Function &F) {
  // The same instance of the analysis is created and registered, then used
  // repetitively, so we must clear its state each time we enter runOnFunction
  ReachableIntegerValuesMap.clear();

  // First compute sets of integer values defined for each Basic block
  ReachableIntegerValuesMapTy DefinedValuesMap;
  for (BasicBlock &BB : F) {
    auto &Values = DefinedValuesMap[&BB];
    for (Instruction &Inst : BB)
      if (Inst.getType()->isIntegerTy())
        Values.insert(&Inst);
  }

  // Second compute the reachable integer values

  // arguments and globals are always live
  auto &HeadValues = ReachableIntegerValuesMap[&F.getEntryBlock()];
  for (Argument &Arg : F.args())
    HeadValues.insert(&Arg);

  // then use dominance tree to merge relevant sets
  auto *Root =
      getAnalysis<DominatorTreeWrapperPass>().getDomTree().getRootNode();
  std::deque<decltype(Root)> NodesToProcess;
  NodesToProcess.push_back(Root);

  DEBUG(errs() << "In Function:\n" << F);

  while (!NodesToProcess.empty()) {
    auto *NodeToProcess = NodesToProcess.back();
    NodesToProcess.pop_back();
    DEBUG(errs() << "processing BB " << NodeToProcess->getBlock() << "\n");
    for (auto *Child : *NodeToProcess) {
      DEBUG(errs() << "updating dominated child " << Child->getBlock() << "\n");
      NodesToProcess.push_back(Child);
      {
        // add defined values to dominated nodes
        auto &Values = DefinedValuesMap[NodeToProcess->getBlock()];
        ReachableIntegerValuesMap[Child->getBlock()].insert(Values.begin(),
                                                            Values.end());
      }
      {
        // add inherited values from dominating node
        auto &Values = ReachableIntegerValuesMap[NodeToProcess->getBlock()];
        ReachableIntegerValuesMap[Child->getBlock()].insert(Values.begin(),
                                                            Values.end());
      }
    }
  }

  // An analysis should not modify its argument
  return false;
}

// This instructs the PassManager of the analyses required and preserved by
// this pass. The Pass Manager will schedule required passes earlier in the
// pipeline and make them available for this pass. Identifying the preserved
// analyses allows to save compile time by avoiding to recompute analysis when
// the results won't change.
// Analyses are read-only, so they generally preserve everything
// see
// http://llvm.org/docs/WritingAnLLVMPass.html#specifying-interactions-between-passes
void ReachableIntegerValuesPass::getAnalysisUsage(AnalysisUsage &Info) const {
  Info.addRequired<DominatorTreeWrapperPass>();
  Info.setPreservesAll();
}

ReachableIntegerValuesPass::ReachableIntegerValuesMapTy const &
ReachableIntegerValuesPass::getReachableIntegerValuesMap() const {
  return ReachableIntegerValuesMap;
}

char ReachableIntegerValuesPass::ID = 0;
static RegisterPass<ReachableIntegerValuesPass>
    X("reachable-integer-values",         // pass option
      "Compute Reachable Integer values", // pass description
      true,                               // does not modify the CFG
      true                                // and it's an analysis
      );
<|endoftext|>


<commit_before>/**************************************************************************
 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * 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.                  *
$Log$
Revision 1.1  2006/03/28 14:54:48  arcelli
class for TOF alignment

author: Silvia Arcelli, arcelli@bo.infn.it
*/

#include <TBenchmark.h>
#include <Rtypes.h>
#include "TClonesArray.h"
#include "TObjString.h"
#include "AliLog.h"
#include "AliRun.h"
#include "AliModule.h"
#include "AliTOFAlignment.h"
#include "AliAlignObj.h"
#include "AliAlignObjAngles.h"
#include "AliCDBManager.h"
#include "AliCDBMetaData.h"
#include "AliCDBStorage.h"
#include "AliCDBId.h"
#include "AliCDBEntry.h"

ClassImp(AliTOFAlignment)

//_____________________________________________________________________________
AliTOFAlignment::AliTOFAlignment():TTask("AliTOFAlignment","") {
  //AliTOFalignment main Ctor

  fNTOFAlignObj=0;
  fTOFAlignObjArray=0x0;
}
//_____________________________________________________________________________
AliTOFAlignment::AliTOFAlignment(const AliTOFAlignment &t):TTask("AliTOFAlignment",""){
  //AliTOFAlignment copy Ctor

  fNTOFAlignObj=t.fNTOFAlignObj;
  fTOFAlignObjArray=t.fTOFAlignObjArray;

}

//_____________________________________________________________________________
void AliTOFAlignment::Smear( Float_t *tr, Float_t *rot){

  fTOFAlignObjArray = new TObjArray(kMaxAlignObj);
  Float_t dx, dy, dz;  // shifts
  Float_t dpsi, dtheta, dphi; // angular displacements
  TRandom *rnd   = new TRandom(1567);

  TString path;
  const char *SM71="/ALIC_1/B077_1/B071_"; //1-13
  const char *sm71="/BTO1_1";
  const char *SM74="/ALIC_1/B077_1/B074_"; //1-2
  const char *sm74="/BTO2_1";
  const char *SM75="/ALIC_1/B077_1/B075_"; //1-3
  const char *sm75="/BTO3_1";

  Int_t nSM71 = 13, nSM74=2, nSM75=3;
  AliAlignObj::ELayerID iLayer = AliAlignObj::kInvalidLayer;
  UShort_t iIndex=0; //dummy volume index
  //  AliAlignObj::ELayerID iLayer = AliAlignObj::kTOF;
  //  Int_t iIndex=1; //dummy volume index
  UShort_t dvoluid = AliAlignObj::LayerToVolUID(iLayer,iIndex); //dummy volume identity
  Int_t i;
  for (i = 1; i<=nSM71 ; i++) {

    dx = (rnd->Gaus(0.,1.))*tr[0]/nSM71;
    dy = (rnd->Gaus(0.,1.))*tr[1]/nSM71;
    dz = (rnd->Gaus(0.,1.))*tr[2]/nSM71;
    dpsi   = rot[0]/nSM71;
    dtheta = rot[1]/nSM71;
    dphi   = rot[2]/nSM71;

    path = SM71;
    path += i;
    path += sm71;
    AliAlignObjAngles *o =new AliAlignObjAngles(path, dvoluid, dx, dy, dz, dpsi, dtheta, dphi);
    fTOFAlignObjArray->Add(o);
  }

  for (i = 1; i<=nSM74 ; i++) {

    dx = (rnd->Gaus(0.,1.))*tr[0]/nSM74;
    dy = (rnd->Gaus(0.,1.))*tr[1]/nSM74;
    dz = (rnd->Gaus(0.,1.))*tr[2]/nSM74;
    dpsi   = rot[0]/nSM74;
    dtheta = rot[1]/nSM74;
    dphi   = rot[2]/nSM74;

    path = SM74;
    path += i;
    path += sm74;
    AliAlignObjAngles *o =new AliAlignObjAngles(path, dvoluid, dx, dy, dz, dpsi, dtheta, dphi);
    fTOFAlignObjArray->Add(o);
  }

  for (i = 1; i<=nSM75; i++) {

    dx = (rnd->Gaus(0.,1.))*tr[0]/nSM75;
    dy = (rnd->Gaus(0.,1.))*tr[1]/nSM75;
    dz = (rnd->Gaus(0.,1.))*tr[2]/nSM75;
    dpsi   = rot[0]/nSM75;
    dtheta = rot[1]/nSM75;
    dphi   = rot[2]/nSM75;

    path = SM75;
    path += i;
    path += sm75;
    AliAlignObjAngles *o =new AliAlignObjAngles(path, dvoluid, dx, dy, dz, dpsi, dtheta, dphi);
    fTOFAlignObjArray->Add(o);
  }
  fNTOFAlignObj=fTOFAlignObjArray->GetEntries();
  AliInfo(Form("Number of Alignable Volumes: %d",fNTOFAlignObj));
  delete rnd;
}

//_____________________________________________________________________________
void AliTOFAlignment::Align( Float_t *tr, Float_t *rot){

  fTOFAlignObjArray = new TObjArray(kMaxAlignObj);
  Float_t dx, dy, dz;  // shifts
  Float_t dpsi, dtheta, dphi; // angular displacements
  TString path;
  const char *SM71="/ALIC_1/B077_1/B071_"; //1-13
  const char *sm71="/BTO1_1";
  const char *SM74="/ALIC_1/B077_1/B074_"; //1-2
  const char *sm74="/BTO2_1";
  const char *SM75="/ALIC_1/B077_1/B075_"; //1-3
  const char *sm75="/BTO3_1";

  Int_t nSM71 = 13, nSM74=2, nSM75=3;
  AliAlignObj::ELayerID iLayer = AliAlignObj::kInvalidLayer;
  UShort_t iIndex=0; //dummy volume index
  //  AliAlignObj::ELayerID iLayer = AliAlignObj::kTOF;
  //  Int_t iIndex=1; //dummy volume index
  UShort_t dvoluid = AliAlignObj::LayerToVolUID(iLayer,iIndex); //dummy volume identity
  Int_t i;
  for (i = 1; i<=nSM71 ; i++) {

    dx = tr[0]/nSM71;
    dy = tr[1]/nSM71;
    dz = tr[2]/nSM71;
    dpsi   = rot[0]/nSM71;
    dtheta = rot[1]/nSM71;
    dphi   = rot[2]/nSM71;

    path = SM71;
    path += i;
    path += sm71;
    AliAlignObjAngles *o =new AliAlignObjAngles(path, dvoluid, dx, dy, dz, dpsi, dtheta, dphi);
    fTOFAlignObjArray->Add(o);
  }

  for (i = 1; i<=nSM74 ; i++) {

    dx = tr[0]/nSM74;
    dy = tr[1]/nSM74;
    dz = tr[2]/nSM74;
    dpsi   = rot[0]/nSM74;
    dtheta = rot[1]/nSM74;
    dphi   = rot[2]/nSM74;

    path = SM74;
    path += i;
    path += sm74;
    AliAlignObjAngles *o =new AliAlignObjAngles(path, dvoluid, dx, dy, dz, dpsi, dtheta, dphi);
    fTOFAlignObjArray->Add(o);
  }

  for (i = 1; i<=nSM75; i++) {

    dx = tr[0]/nSM75;
    dy = tr[1]/nSM75;
    dz = tr[2]/nSM75;
    dpsi   = rot[0]/nSM75;
    dtheta = rot[1]/nSM75;
    dphi   = rot[2]/nSM75;

    path = SM75;
    path += i;
    path += sm75;
    AliAlignObjAngles *o =new AliAlignObjAngles(path, dvoluid, dx, dy, dz, dpsi, dtheta, dphi);
    fTOFAlignObjArray->Add(o);
  }
  fNTOFAlignObj=fTOFAlignObjArray->GetEntries();
  AliInfo(Form("Number of Alignable Volumes: %d",fNTOFAlignObj));
  AliInfo("Sono nel cesso");
}
//_____________________________________________________________________________
void AliTOFAlignment::WriteParOnCDB(Char_t *sel, Int_t minrun, Int_t maxrun){
  AliCDBManager *man = AliCDBManager::Instance();
  if(!man->IsDefaultStorageSet())man->SetDefaultStorage("local://$ALICE_ROOT");
  Char_t *sel1 = "AlignPar" ;
  Char_t  out[100];
  sprintf(out,"%s/%s",sel,sel1);
  AliCDBId idTOFAlign(out,minrun,maxrun);
  AliCDBMetaData *mdTOFAlign = new AliCDBMetaData();
  mdTOFAlign->SetResponsible("TOF");
  AliInfo(Form("Number of Alignable Volumes: %d",fNTOFAlignObj));
  man->Put(fTOFAlignObjArray,idTOFAlign,mdTOFAlign);
}
//_____________________________________________________________________________
void AliTOFAlignment::ReadParFromCDB(Char_t *sel, Int_t nrun){
  AliCDBManager *man = AliCDBManager::Instance();
  if(!man->IsDefaultStorageSet())man->SetDefaultStorage("local://$ALICE_ROOT");
  Char_t *sel1 = "AlignPar" ;
  Char_t  out[100];
  sprintf(out,"%s/%s",sel,sel1);
  AliCDBEntry *entry = man->Get(out,nrun);
  fTOFAlignObjArray=(TObjArray*)entry->GetObject();
  fNTOFAlignObj=fTOFAlignObjArray->GetEntries();
  AliInfo(Form("Number of Alignable Volumes from CDB: %d",fNTOFAlignObj));

}
//_____________________________________________________________________________
void AliTOFAlignment::WriteSimParOnCDB(Char_t *sel, Int_t minrun, Int_t maxrun){
  AliCDBManager *man = AliCDBManager::Instance();
  if(!man->IsDefaultStorageSet())man->SetDefaultStorage("local://$ALICE_ROOT");
  Char_t *sel1 = "AlignSimPar" ;
  Char_t  out[100];
  sprintf(out,"%s/%s",sel,sel1);
  AliCDBId idTOFAlign(out,minrun,maxrun);
  AliCDBMetaData *mdTOFAlign = new AliCDBMetaData();
  mdTOFAlign->SetResponsible("TOF");
  AliInfo(Form("Number of Alignable Volumes: %d",fNTOFAlignObj));
  man->Put(fTOFAlignObjArray,idTOFAlign,mdTOFAlign);
}
//_____________________________________________________________________________
void AliTOFAlignment::ReadSimParFromCDB(Char_t *sel, Int_t nrun){
  AliCDBManager *man = AliCDBManager::Instance();
  if(!man->IsDefaultStorageSet())man->SetDefaultStorage("local://$ALICE_ROOT");
  Char_t *sel1 = "AlignSimPar" ;
  Char_t  out[100];
  sprintf(out,"%s/%s",sel,sel1);
  AliCDBEntry *entry = man->Get(out,nrun);
  fTOFAlignObjArray=(TObjArray*)entry->GetObject();
  fNTOFAlignObj=fTOFAlignObjArray->GetEntries();
  AliInfo(Form("Number of Alignable Volumes from CDB: %d",fNTOFAlignObj));

}
//_____________________________________________________________________________
void AliTOFAlignment::WriteOnCDBforDC(){
  AliCDBManager *man = AliCDBManager::Instance();
  if(!man->IsDefaultStorageSet())man->SetDefaultStorage("local://$ALICE_ROOT");
  AliCDBId idTOFAlign("TOF/Align/Data",0,0);
  AliCDBMetaData *mdTOFAlign = new AliCDBMetaData();
  mdTOFAlign->SetComment("Alignment objects for ideal geometry, i.e. applying them to TGeo has to leave geometry unchanged");
  mdTOFAlign->SetResponsible("TOF");
  AliInfo(Form("Number of Alignable Volumes: %d",fNTOFAlignObj));
  man->Put(fTOFAlignObjArray,idTOFAlign,mdTOFAlign);
}
//_____________________________________________________________________________
void AliTOFAlignment::ReadFromCDBforDC(){
  AliCDBManager *man = AliCDBManager::Instance();
  if(!man->IsDefaultStorageSet())man->SetDefaultStorage("local://$ALICE_ROOT");
  AliCDBEntry *entry = man->Get("TOF/Align/Data",0);
  fTOFAlignObjArray=(TObjArray*)entry->GetObject();
  fNTOFAlignObj=fTOFAlignObjArray->GetEntries();
  AliInfo(Form("Number of Alignable Volumes from CDB: %d",fNTOFAlignObj));

}
<commit_msg>Removing some junk printout<commit_after>/**************************************************************************
 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * 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.                  *
$Log$
Revision 1.2  2006/03/31 11:26:30  arcelli
 changing CDB Ids according to standard convention

Revision 1.1  2006/03/28 14:54:48  arcelli
class for TOF alignment

author: Silvia Arcelli, arcelli@bo.infn.it
*/

#include <TBenchmark.h>
#include <Rtypes.h>
#include "TClonesArray.h"
#include "TObjString.h"
#include "AliLog.h"
#include "AliRun.h"
#include "AliModule.h"
#include "AliTOFAlignment.h"
#include "AliAlignObj.h"
#include "AliAlignObjAngles.h"
#include "AliCDBManager.h"
#include "AliCDBMetaData.h"
#include "AliCDBStorage.h"
#include "AliCDBId.h"
#include "AliCDBEntry.h"

ClassImp(AliTOFAlignment)

//_____________________________________________________________________________
AliTOFAlignment::AliTOFAlignment():TTask("AliTOFAlignment","") {
  //AliTOFalignment main Ctor

  fNTOFAlignObj=0;
  fTOFAlignObjArray=0x0;
}
//_____________________________________________________________________________
AliTOFAlignment::AliTOFAlignment(const AliTOFAlignment &t):TTask("AliTOFAlignment",""){
  //AliTOFAlignment copy Ctor

  fNTOFAlignObj=t.fNTOFAlignObj;
  fTOFAlignObjArray=t.fTOFAlignObjArray;

}

//_____________________________________________________________________________
void AliTOFAlignment::Smear( Float_t *tr, Float_t *rot){

  fTOFAlignObjArray = new TObjArray(kMaxAlignObj);
  Float_t dx, dy, dz;  // shifts
  Float_t dpsi, dtheta, dphi; // angular displacements
  TRandom *rnd   = new TRandom(1567);

  TString path;
  const char *SM71="/ALIC_1/B077_1/B071_"; //1-13
  const char *sm71="/BTO1_1";
  const char *SM74="/ALIC_1/B077_1/B074_"; //1-2
  const char *sm74="/BTO2_1";
  const char *SM75="/ALIC_1/B077_1/B075_"; //1-3
  const char *sm75="/BTO3_1";

  Int_t nSM71 = 13, nSM74=2, nSM75=3;
  AliAlignObj::ELayerID iLayer = AliAlignObj::kInvalidLayer;
  UShort_t iIndex=0; //dummy volume index
  //  AliAlignObj::ELayerID iLayer = AliAlignObj::kTOF;
  //  Int_t iIndex=1; //dummy volume index
  UShort_t dvoluid = AliAlignObj::LayerToVolUID(iLayer,iIndex); //dummy volume identity
  Int_t i;
  for (i = 1; i<=nSM71 ; i++) {

    dx = (rnd->Gaus(0.,1.))*tr[0]/nSM71;
    dy = (rnd->Gaus(0.,1.))*tr[1]/nSM71;
    dz = (rnd->Gaus(0.,1.))*tr[2]/nSM71;
    dpsi   = rot[0]/nSM71;
    dtheta = rot[1]/nSM71;
    dphi   = rot[2]/nSM71;

    path = SM71;
    path += i;
    path += sm71;
    AliAlignObjAngles *o =new AliAlignObjAngles(path, dvoluid, dx, dy, dz, dpsi, dtheta, dphi);
    fTOFAlignObjArray->Add(o);
  }

  for (i = 1; i<=nSM74 ; i++) {

    dx = (rnd->Gaus(0.,1.))*tr[0]/nSM74;
    dy = (rnd->Gaus(0.,1.))*tr[1]/nSM74;
    dz = (rnd->Gaus(0.,1.))*tr[2]/nSM74;
    dpsi   = rot[0]/nSM74;
    dtheta = rot[1]/nSM74;
    dphi   = rot[2]/nSM74;

    path = SM74;
    path += i;
    path += sm74;
    AliAlignObjAngles *o =new AliAlignObjAngles(path, dvoluid, dx, dy, dz, dpsi, dtheta, dphi);
    fTOFAlignObjArray->Add(o);
  }

  for (i = 1; i<=nSM75; i++) {

    dx = (rnd->Gaus(0.,1.))*tr[0]/nSM75;
    dy = (rnd->Gaus(0.,1.))*tr[1]/nSM75;
    dz = (rnd->Gaus(0.,1.))*tr[2]/nSM75;
    dpsi   = rot[0]/nSM75;
    dtheta = rot[1]/nSM75;
    dphi   = rot[2]/nSM75;

    path = SM75;
    path += i;
    path += sm75;
    AliAlignObjAngles *o =new AliAlignObjAngles(path, dvoluid, dx, dy, dz, dpsi, dtheta, dphi);
    fTOFAlignObjArray->Add(o);
  }
  fNTOFAlignObj=fTOFAlignObjArray->GetEntries();
  AliInfo(Form("Number of Alignable Volumes: %d",fNTOFAlignObj));
  delete rnd;
}

//_____________________________________________________________________________
void AliTOFAlignment::Align( Float_t *tr, Float_t *rot){

  fTOFAlignObjArray = new TObjArray(kMaxAlignObj);
  Float_t dx, dy, dz;  // shifts
  Float_t dpsi, dtheta, dphi; // angular displacements
  TString path;
  const char *SM71="/ALIC_1/B077_1/B071_"; //1-13
  const char *sm71="/BTO1_1";
  const char *SM74="/ALIC_1/B077_1/B074_"; //1-2
  const char *sm74="/BTO2_1";
  const char *SM75="/ALIC_1/B077_1/B075_"; //1-3
  const char *sm75="/BTO3_1";

  Int_t nSM71 = 13, nSM74=2, nSM75=3;
  AliAlignObj::ELayerID iLayer = AliAlignObj::kInvalidLayer;
  UShort_t iIndex=0; //dummy volume index
  //  AliAlignObj::ELayerID iLayer = AliAlignObj::kTOF;
  //  Int_t iIndex=1; //dummy volume index
  UShort_t dvoluid = AliAlignObj::LayerToVolUID(iLayer,iIndex); //dummy volume identity
  Int_t i;
  for (i = 1; i<=nSM71 ; i++) {

    dx = tr[0]/nSM71;
    dy = tr[1]/nSM71;
    dz = tr[2]/nSM71;
    dpsi   = rot[0]/nSM71;
    dtheta = rot[1]/nSM71;
    dphi   = rot[2]/nSM71;

    path = SM71;
    path += i;
    path += sm71;
    AliAlignObjAngles *o =new AliAlignObjAngles(path, dvoluid, dx, dy, dz, dpsi, dtheta, dphi);
    fTOFAlignObjArray->Add(o);
  }

  for (i = 1; i<=nSM74 ; i++) {

    dx = tr[0]/nSM74;
    dy = tr[1]/nSM74;
    dz = tr[2]/nSM74;
    dpsi   = rot[0]/nSM74;
    dtheta = rot[1]/nSM74;
    dphi   = rot[2]/nSM74;

    path = SM74;
    path += i;
    path += sm74;
    AliAlignObjAngles *o =new AliAlignObjAngles(path, dvoluid, dx, dy, dz, dpsi, dtheta, dphi);
    fTOFAlignObjArray->Add(o);
  }

  for (i = 1; i<=nSM75; i++) {

    dx = tr[0]/nSM75;
    dy = tr[1]/nSM75;
    dz = tr[2]/nSM75;
    dpsi   = rot[0]/nSM75;
    dtheta = rot[1]/nSM75;
    dphi   = rot[2]/nSM75;

    path = SM75;
    path += i;
    path += sm75;
    AliAlignObjAngles *o =new AliAlignObjAngles(path, dvoluid, dx, dy, dz, dpsi, dtheta, dphi);
    fTOFAlignObjArray->Add(o);
  }
  fNTOFAlignObj=fTOFAlignObjArray->GetEntries();
  AliInfo(Form("Number of Alignable Volumes: %d",fNTOFAlignObj));
}
//_____________________________________________________________________________
void AliTOFAlignment::WriteParOnCDB(Char_t *sel, Int_t minrun, Int_t maxrun){
  AliCDBManager *man = AliCDBManager::Instance();
  if(!man->IsDefaultStorageSet())man->SetDefaultStorage("local://$ALICE_ROOT");
  Char_t *sel1 = "AlignPar" ;
  Char_t  out[100];
  sprintf(out,"%s/%s",sel,sel1);
  AliCDBId idTOFAlign(out,minrun,maxrun);
  AliCDBMetaData *mdTOFAlign = new AliCDBMetaData();
  mdTOFAlign->SetResponsible("TOF");
  AliInfo(Form("Number of Alignable Volumes: %d",fNTOFAlignObj));
  man->Put(fTOFAlignObjArray,idTOFAlign,mdTOFAlign);
}
//_____________________________________________________________________________
void AliTOFAlignment::ReadParFromCDB(Char_t *sel, Int_t nrun){
  AliCDBManager *man = AliCDBManager::Instance();
  if(!man->IsDefaultStorageSet())man->SetDefaultStorage("local://$ALICE_ROOT");
  Char_t *sel1 = "AlignPar" ;
  Char_t  out[100];
  sprintf(out,"%s/%s",sel,sel1);
  AliCDBEntry *entry = man->Get(out,nrun);
  fTOFAlignObjArray=(TObjArray*)entry->GetObject();
  fNTOFAlignObj=fTOFAlignObjArray->GetEntries();
  AliInfo(Form("Number of Alignable Volumes from CDB: %d",fNTOFAlignObj));

}
//_____________________________________________________________________________
void AliTOFAlignment::WriteSimParOnCDB(Char_t *sel, Int_t minrun, Int_t maxrun){
  AliCDBManager *man = AliCDBManager::Instance();
  if(!man->IsDefaultStorageSet())man->SetDefaultStorage("local://$ALICE_ROOT");
  Char_t *sel1 = "AlignSimPar" ;
  Char_t  out[100];
  sprintf(out,"%s/%s",sel,sel1);
  AliCDBId idTOFAlign(out,minrun,maxrun);
  AliCDBMetaData *mdTOFAlign = new AliCDBMetaData();
  mdTOFAlign->SetResponsible("TOF");
  AliInfo(Form("Number of Alignable Volumes: %d",fNTOFAlignObj));
  man->Put(fTOFAlignObjArray,idTOFAlign,mdTOFAlign);
}
//_____________________________________________________________________________
void AliTOFAlignment::ReadSimParFromCDB(Char_t *sel, Int_t nrun){
  AliCDBManager *man = AliCDBManager::Instance();
  if(!man->IsDefaultStorageSet())man->SetDefaultStorage("local://$ALICE_ROOT");
  Char_t *sel1 = "AlignSimPar" ;
  Char_t  out[100];
  sprintf(out,"%s/%s",sel,sel1);
  AliCDBEntry *entry = man->Get(out,nrun);
  fTOFAlignObjArray=(TObjArray*)entry->GetObject();
  fNTOFAlignObj=fTOFAlignObjArray->GetEntries();
  AliInfo(Form("Number of Alignable Volumes from CDB: %d",fNTOFAlignObj));

}
//_____________________________________________________________________________
void AliTOFAlignment::WriteOnCDBforDC(){
  AliCDBManager *man = AliCDBManager::Instance();
  if(!man->IsDefaultStorageSet())man->SetDefaultStorage("local://$ALICE_ROOT");
  AliCDBId idTOFAlign("TOF/Align/Data",0,0);
  AliCDBMetaData *mdTOFAlign = new AliCDBMetaData();
  mdTOFAlign->SetComment("Alignment objects for ideal geometry, i.e. applying them to TGeo has to leave geometry unchanged");
  mdTOFAlign->SetResponsible("TOF");
  AliInfo(Form("Number of Alignable Volumes: %d",fNTOFAlignObj));
  man->Put(fTOFAlignObjArray,idTOFAlign,mdTOFAlign);
}
//_____________________________________________________________________________
void AliTOFAlignment::ReadFromCDBforDC(){
  AliCDBManager *man = AliCDBManager::Instance();
  if(!man->IsDefaultStorageSet())man->SetDefaultStorage("local://$ALICE_ROOT");
  AliCDBEntry *entry = man->Get("TOF/Align/Data",0);
  fTOFAlignObjArray=(TObjArray*)entry->GetObject();
  fNTOFAlignObj=fTOFAlignObjArray->GetEntries();
  AliInfo(Form("Number of Alignable Volumes from CDB: %d",fNTOFAlignObj));

}
<|endoftext|>