<commit_before>#include "stdafx.hpp"

#include <functional>

#include "CppUnitTest.h"
#include "..\TestUtilities\TestUtilities.hpp"
#include "..\TestUtilities\QuantityComparisons.hpp"
#include "..\TestUtilities\GeometryComparisons.hpp"
#include "..\TestUtilities\Algebra.hpp"

#include "..\Quantities\Dimensionless.hpp"
#include "..\Quantities\Quantities.hpp"
#include "..\Quantities\SI.hpp"
#include "..\Quantities\Constants.hpp"
#include "..\Quantities\UK.hpp"
#include "..\Quantities\BIPM.hpp"
#include "..\Quantities\Astronomy.hpp"
#include "..\Geometry\R3Element.hpp"
#include "..\Geometry\Grassmann.hpp"
#include "..\Quantities\ElementaryFunctions.hpp"

using namespace Microsoft::VisualStudio::CppUnitTestFramework;

namespace Principia {
namespace GeometryTests
{
using namespace Geometry;
using namespace Quantities;
using namespace SI;
using namespace UK;
using namespace BIPM;
using namespace Astronomy;
using namespace Constants;
using namespace TestUtilities;

TEST_CLASS(GeometryTests)
{
 public:
  struct World;
  TEST_METHOD(Dumb3Vector) {
    R3Element<Speed> nullVector(0 * Metre / Second,
                                0 * Metre / Second,
                                0 * Metre / Second);
    R3Element<Speed> u(1 * Metre / Second,
                       120 * Kilo(Metre) / Hour,
                       -SpeedOfLight);
    R3Element<Speed> v(-20 * Knot,
                       2 * π * AstronomicalUnit / JulianYear,
                       1 * Admiralty::NauticalMile / Hour);
    R3Element<Speed> w(-1 * Mile / Hour, -2 * Foot / Second, -3 * Knot);
    R3Element<Speed> a(88 * Mile / Hour, 300 * Metre / Second, 46 * Knot);
    AssertEqual((e * Dimensionless(42)) * v, e * (Dimensionless(42) * v));
    TestVectorSpace<R3Element<Speed>,
                    Dimensionless>(nullVector, u, v, w, Dimensionless(0),
                                   Dimensionless(1), e, Dimensionless(42));
    TestAlternatingBilinearMap(Cross<Speed, Speed>, u,
                               v, w, a, Dimensionless(42));
    TestSymmetricPositiveDefiniteBilinearMap(Dot<Speed, Speed>,
                                             u, v, w, a, Dimensionless(42));
  }

  TEST_METHOD(SpecialOrthogonalLieAlgebra) {
    R3Element<Dimensionless> u(3, -42, 0);
    R3Element<Dimensionless> v(-π, -e, -1);
    R3Element<Dimensionless> w(2, 2, 2);
    R3Element<Dimensionless> a(1.2, 2.3, 3.4);
    TestLieBracket(Commutator<Dimensionless, Dimensionless, World>,
                   Bivector<Dimensionless, World>(u),
                   Bivector<Dimensionless, World>(v),
                   Bivector<Dimensionless, World>(w),
                   Bivector<Dimensionless, World>(a), Dimensionless(0.42));
  }

  TEST_METHOD(VectorSpaces) {
    R3Element<Length> nullDisplacement(0 * Metre, 0 * Metre, 0 * Metre);
    R3Element<Length> u(3 * Metre, -42 * Metre, 0 * Metre);
    R3Element<Length> v(-π * Metre, -e * Metre, -1 * Metre);
    R3Element<Length> w(2 * Metre, 2 * Metre, 2 * Metre);
    R3Element<Length> a(1 * Inch, 2 * Foot, 3 * Admiralty::Fathom);
    {
      std::function<Area(Vector<Length, World>,
                         Vector<Length, World>)> vectorInnerProduct =
      [](Vector<Length, World> a, Vector<Length, World> b) {
        return InnerProduct(a, b);
      };
      std::function<Area(Bivector<Length, World>,
                         Bivector<Length, World>)> bivectorInnerProduct =
      [](Bivector<Length, World> a, Bivector<Length, World> b) {
        return InnerProduct(a, b);
      };
      std::function<Area(Trivector<Length, World>,
                         Trivector<Length, World>)> trivectorInnerProduct =
      [](Trivector<Length, World> a, Trivector<Length, World> b) {
        return InnerProduct(a, b);
      };
      TestInnerProductSpace(vectorInnerProduct,
                            Vector<Length, World>(nullDisplacement),
                            Vector<Length, World>(u), Vector<Length, World>(v),
                            Vector<Length, World>(w), Vector<Length, World>(a),
                            Dimensionless(0), Dimensionless(1), Sqrt(163),
                            -Sqrt(2));
      TestInnerProductSpace(bivectorInnerProduct,
                            Bivector<Length, World>(nullDisplacement),
                            Bivector<Length, World>(u),
                            Bivector<Length, World>(v),
                            Bivector<Length, World>(w),
                            Bivector<Length, World>(a),
                            Dimensionless(0), Dimensionless(1), Sqrt(163),
                            -Sqrt(2));
      TestInnerProductSpace(trivectorInnerProduct,
                            Trivector<Length, World>(nullDisplacement.x),
                            Trivector<Length, World>(u.y),
                            Trivector<Length, World>(v.z),
                            Trivector<Length, World>(w.x),
                            Trivector<Length, World>(a.y),
                            Dimensionless(0), Dimensionless(1), Sqrt(163),
                            -Sqrt(2));
    }
    {
      std::function<Dimensionless(Vector<Dimensionless, World>,
                                  Vector<Dimensionless, World>)>
      vectorInnerProduct = [](Vector<Dimensionless, World> a,
                              Vector<Dimensionless, World> b) {
        return InnerProduct(a, b);
      };
      std::function<Dimensionless(Bivector<Dimensionless, World>,
                                  Bivector<Dimensionless, World>)>
      bivectorInnerProduct = [](Bivector<Dimensionless, World> a,
                                Bivector<Dimensionless, World> b) {
        return InnerProduct(a, b);
      };
      std::function<Dimensionless(Trivector<Dimensionless, World>,
                                  Trivector<Dimensionless, World>)>
      trivectorInnerProduct = [](Trivector<Dimensionless, World> a,
                                 Trivector<Dimensionless, World> b) {
        return InnerProduct(a, b);
      };
      TestInnerProductSpace(vectorInnerProduct,
                            Vector<Dimensionless,
                                   World>(nullDisplacement / Metre),
                            Vector<Dimensionless, World>(u / Metre),
                            Vector<Dimensionless, World>(v / Metre),
                            Vector<Dimensionless, World>(w / Metre),
                            Vector<Dimensionless, World>(a / Metre),
                            Dimensionless(0), Dimensionless(1), Sqrt(163),
                            -Sqrt(2));
      TestInnerProductSpace(bivectorInnerProduct,
                            Bivector<Dimensionless,
                                     World>(nullDisplacement / Metre),
                            Bivector<Dimensionless, World>(u / Metre),
                            Bivector<Dimensionless, World>(v / Metre),
                            Bivector<Dimensionless, World>(w / Metre),
                            Bivector<Dimensionless, World>(a / Metre),
                            Dimensionless(0), Dimensionless(1), Sqrt(163),
                            -Sqrt(2));
      TestInnerProductSpace(trivectorInnerProduct,
                            Trivector<Dimensionless,
                                      World>(nullDisplacement.x / Metre),
                            Trivector<Dimensionless, World>(u.y / Metre),
                            Trivector<Dimensionless, World>(v.z / Metre),
                            Trivector<Dimensionless, World>(w.x / Metre),
                            Trivector<Dimensionless, World>(a.y / Metre),
                            Dimensionless(0), Dimensionless(1), Sqrt(163),
                            -Sqrt(2));
    }
  }
};
}  // namespace GeometryTests
}  // namespace Principia
<commit_msg>Tiny test.<commit_after>#include "stdafx.hpp"

#include <functional>

#include "CppUnitTest.h"
#include "..\TestUtilities\TestUtilities.hpp"
#include "..\TestUtilities\QuantityComparisons.hpp"
#include "..\TestUtilities\GeometryComparisons.hpp"
#include "..\TestUtilities\Algebra.hpp"

#include "..\Quantities\Dimensionless.hpp"
#include "..\Quantities\Quantities.hpp"
#include "..\Quantities\SI.hpp"
#include "..\Quantities\Constants.hpp"
#include "..\Quantities\UK.hpp"
#include "..\Quantities\BIPM.hpp"
#include "..\Quantities\Astronomy.hpp"
#include "..\Geometry\R3Element.hpp"
#include "..\Geometry\Grassmann.hpp"
#include "..\Quantities\ElementaryFunctions.hpp"

using namespace Microsoft::VisualStudio::CppUnitTestFramework;

namespace Principia {
namespace GeometryTests
{
using namespace Geometry;
using namespace Quantities;
using namespace SI;
using namespace UK;
using namespace BIPM;
using namespace Astronomy;
using namespace Constants;
using namespace TestUtilities;

TEST_CLASS(GeometryTests)
{
 public:
  struct World;
  TEST_METHOD(Dumb3Vector) {
    R3Element<Speed> nullVector(0 * Metre / Second,
                                0 * Metre / Second,
                                0 * Metre / Second);
    R3Element<Speed> u(1 * Metre / Second,
                       120 * Kilo(Metre) / Hour,
                       -SpeedOfLight);
    R3Element<Speed> v(-20 * Knot,
                       2 * π * AstronomicalUnit / JulianYear,
                       1 * Admiralty::NauticalMile / Hour);
    R3Element<Speed> w(-1 * Mile / Hour, -2 * Foot / Second, -3 * Knot);
    R3Element<Speed> a(88 * Mile / Hour, 300 * Metre / Second, 46 * Knot);
    AssertEqual((e * Dimensionless(42)) * v, e * (Dimensionless(42) * v));
    TestVectorSpace<R3Element<Speed>,
                    Dimensionless>(nullVector, u, v, w, Dimensionless(0),
                                   Dimensionless(1), e, Dimensionless(42));
    TestAlternatingBilinearMap(Cross<Speed, Speed>, u,
                               v, w, a, Dimensionless(42));
    TestSymmetricPositiveDefiniteBilinearMap(Dot<Speed, Speed>,
                                             u, v, w, a, Dimensionless(42));
  }

  TEST_METHOD(SpecialOrthogonalLieAlgebra) {
    R3Element<Dimensionless> u(3, -42, 0);
    R3Element<Dimensionless> v(-π, -e, -1);
    R3Element<Dimensionless> w(2, 2, 2);
    R3Element<Dimensionless> a(1.2, 2.3, 3.4);
    TestLieBracket(Commutator<Dimensionless, Dimensionless, World>,
                   Bivector<Dimensionless, World>(u),
                   Bivector<Dimensionless, World>(v),
                   Bivector<Dimensionless, World>(w),
                   Bivector<Dimensionless, World>(a), Dimensionless(0.42));
  }

  TEST_METHOD(VectorSpaces) {
    R3Element<Length> nullDisplacement(0 * Metre, 0 * Metre, 0 * Metre);
    R3Element<Length> u(3 * Metre, -42 * Metre, 0 * Metre);
    R3Element<Length> v(-π * Metre, -e * Metre, -1 * Metre);
    R3Element<Length> w(2 * Metre, 2 * Metre, 2 * Metre);
    R3Element<Length> a(1 * Inch, 2 * Foot, 3 * Admiralty::Fathom);
    {
      std::function<Area(Vector<Length, World>,
                         Vector<Length, World>)> vectorInnerProduct =
      [](Vector<Length, World> a, Vector<Length, World> b) {
        return InnerProduct(a, b);
      };
      std::function<Area(Bivector<Length, World>,
                         Bivector<Length, World>)> bivectorInnerProduct =
      [](Bivector<Length, World> a, Bivector<Length, World> b) {
        return InnerProduct(a, b);
      };
      std::function<Area(Trivector<Length, World>,
                         Trivector<Length, World>)> trivectorInnerProduct =
      [](Trivector<Length, World> a, Trivector<Length, World> b) {
        return InnerProduct(a, b);
      };
      TestInnerProductSpace(vectorInnerProduct,
                            Vector<Length, World>(nullDisplacement),
                            Vector<Length, World>(u), Vector<Length, World>(v),
                            Vector<Length, World>(w), Vector<Length, World>(a),
                            Dimensionless(0), Dimensionless(1), Sqrt(163),
                            -Sqrt(2));
      TestInnerProductSpace(bivectorInnerProduct,
                            Bivector<Length, World>(nullDisplacement),
                            Bivector<Length, World>(u),
                            Bivector<Length, World>(v),
                            Bivector<Length, World>(w),
                            Bivector<Length, World>(a),
                            Dimensionless(0), Dimensionless(1), Sqrt(163),
                            -Sqrt(2));
      TestInnerProductSpace(trivectorInnerProduct,
                            Trivector<Length, World>(nullDisplacement.x),
                            Trivector<Length, World>(u.y),
                            Trivector<Length, World>(v.z),
                            Trivector<Length, World>(w.x),
                            Trivector<Length, World>(a.y),
                            Dimensionless(0), Dimensionless(1), Sqrt(163),
                            -Sqrt(2));
    }
    {
      std::function<Dimensionless(Vector<Dimensionless, World>,
                                  Vector<Dimensionless, World>)>
      vectorInnerProduct = [](Vector<Dimensionless, World> a,
                              Vector<Dimensionless, World> b) {
        return InnerProduct(a, b);
      };
      std::function<Dimensionless(Bivector<Dimensionless, World>,
                                  Bivector<Dimensionless, World>)>
      bivectorInnerProduct = [](Bivector<Dimensionless, World> a,
                                Bivector<Dimensionless, World> b) {
        return InnerProduct(a, b);
      };
      std::function<Dimensionless(Trivector<Dimensionless, World>,
                                  Trivector<Dimensionless, World>)>
      trivectorInnerProduct = [](Trivector<Dimensionless, World> a,
                                 Trivector<Dimensionless, World> b) {
        return InnerProduct(a, b);
      };
      TestInnerProductSpace(vectorInnerProduct,
                            Vector<Dimensionless,
                                   World>(nullDisplacement / Metre),
                            Vector<Dimensionless, World>(u / Metre),
                            Vector<Dimensionless, World>(v / Metre),
                            Vector<Dimensionless, World>(w / Metre),
                            Vector<Dimensionless, World>(a / Metre),
                            Dimensionless(0), Dimensionless(1), Sqrt(163),
                            -Sqrt(2));
      TestInnerProductSpace(bivectorInnerProduct,
                            Bivector<Dimensionless,
                                     World>(nullDisplacement / Metre),
                            Bivector<Dimensionless, World>(u / Metre),
                            Bivector<Dimensionless, World>(v / Metre),
                            Bivector<Dimensionless, World>(w / Metre),
                            Bivector<Dimensionless, World>(a / Metre),
                            Dimensionless(0), Dimensionless(1), Sqrt(163),
                            -Sqrt(2));
      TestInnerProductSpace(trivectorInnerProduct,
                            Trivector<Dimensionless,
                                      World>(nullDisplacement.x / Metre),
                            Trivector<Dimensionless, World>(u.y / Metre),
                            Trivector<Dimensionless, World>(v.z / Metre),
                            Trivector<Dimensionless, World>(w.x / Metre),
                            Trivector<Dimensionless, World>(a.y / Metre),
                            Dimensionless(0), Dimensionless(1), Sqrt(163),
                            -Sqrt(2));
    }
  }
  TEST_METHOD(GrassmannAlgebra) {
    R3Element<Dimensionless> u(3, -42, 0);
    R3Element<Dimensionless> v(-π, -e, -1);
    R3Element<Dimensionless> w(2, 2, 2);
    R3Element<Dimensionless> a(1.2, 2.3, 3.4);
    std::function<Bivector<Dimensionless,
                           World>(Vector<Dimensionless, World>,
                                  Vector<Dimensionless, World>)> vectorWedge =
      [](Vector<Dimensionless, World> a, Vector<Dimensionless, World> b) {
        return Wedge(a, b);
      };
    TestAlternatingBilinearMap(vectorWedge, Vector<Dimensionless, World>(u),
                               Vector<Dimensionless, World>(u),
                               Vector<Dimensionless, World>(u),
                               Vector<Dimensionless, World>(u),
                               Dimensionless(6 * 9));
  }
};
}  // namespace GeometryTests
}  // namespace Principia
<|endoftext|>


<commit_before>// Copyright 2011-2012 Google
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "base/hash.h"
#include "base/map-util.h"
#include "base/stl_util.h"
#include "base/random.h"
#include "constraint_solver/constraint_solveri.h"
#include "constraint_solver/constraint_solver.h"

DEFINE_int32(vsize, 5, "Number of variables");
DEFINE_int32(csize, 5, "Number of variables");
DEFINE_int32(slack, 4, "Slack in cardinalities");
DEFINE_int32(seed, 1, "Random seed");

namespace operations_research {
extern Constraint* Gcc(Solver* const solver,
                       const std::vector<IntVar*>& vars,
                       int64 first_domain_value,
                       const std::vector<int>& min_occurrences,
                       const std::vector<int>& max_occurrences);

int64 TestGcc(int vsize, int csize, int slack, int seed, bool use_gcc) {
  if (vsize > csize + slack) {
    LOG(INFO) << "Cannot create problem";
    return 0;
  }
  ACMRandom rgen(seed); // defines a random generator

  std::vector<int> card_min(csize, 0);
  std::vector<int> card_max(csize, 0);
  for (int i = 0; i< vsize - slack; ++i) {
    const int index = rgen.Uniform(csize);
    card_min[index]++;
    card_max[index]++;
  }
  for (int i = 0; i < slack; ++i) {
    const int index = rgen.Uniform(csize);
    card_max[index]++;
  }

  LOG(INFO) << (use_gcc ? "Gcc constraint:" : "Distribute constraint:");
  LOG(INFO) << "  - num variables = " << vsize;
  LOG(INFO) << "  - num values = " << csize;
  LOG(INFO) << "  - slack = " << slack;
  LOG(INFO) << "  - seed = " << seed;
  Solver solver("TestGcc");
  std::vector<IntVar*> vars;
  solver.MakeIntVarArray(vsize, 0, csize - 1, &vars);
  Constraint* const gcc = use_gcc ?
                          Gcc(&solver, vars, 0, card_min, card_max) :
                          solver.MakeDistribute(vars, card_min, card_max);
  solver.AddConstraint(gcc);
  DecisionBuilder* const db = solver.MakePhase(vars,
                                               Solver::CHOOSE_FIRST_UNBOUND,
                                               Solver::ASSIGN_MIN_VALUE);

  LOG(INFO) << "Start search";
  CycleTimer t;
  t.Start();
  solver.NewSearch(db);
  int counter = 0;
  while(solver.NextSolution()) {
    counter++;
  }
  solver.EndSearch();
  t.Stop();

  LOG(INFO) << "test time : " << t.GetInUsec() << " micro seconds";
  LOG(INFO) << "Found " << counter << " solutions";
  return counter;
}
}  // namespace operations_research

int main(int argc, char** argv) {
  google::ParseCommandLineFlags(&argc, &argv, true);
  CHECK_EQ(operations_research::TestGcc(FLAGS_vsize,
                                        FLAGS_csize,
                                        FLAGS_slack,
                                        FLAGS_seed,
                                        false),
           operations_research::TestGcc(FLAGS_vsize,
                                        FLAGS_csize,
                                        FLAGS_slack,
                                        FLAGS_seed,
                                        true));
  return 0;
}
<commit_msg>improve example<commit_after>// Copyright 2011-2012 Google
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "base/hash.h"
#include "base/map-util.h"
#include "base/stl_util.h"
#include "base/random.h"
#include "constraint_solver/constraint_solveri.h"
#include "constraint_solver/constraint_solver.h"

DEFINE_int32(vsize, 5, "Number of variables");
DEFINE_int32(csize, 5, "Number of variables");
DEFINE_int32(slack, 4, "Slack in cardinalities");
DEFINE_int32(seed, 1, "Random seed");

namespace operations_research {
extern Constraint* Gcc(Solver* const solver,
                       const std::vector<IntVar*>& vars,
                       int64 first_domain_value,
                       const std::vector<int>& min_occurrences,
                       const std::vector<int>& max_occurrences);

int64 TestGcc(int vsize, int csize, int slack, int seed, bool use_gcc) {
  if (vsize > csize + slack) {
    LOG(INFO) << "Cannot create problem";
    return 0;
  }
  ACMRandom rgen(seed); // defines a random generator

  std::vector<int> card_min(csize, 0);
  std::vector<int> card_max(csize, 0);
  for (int i = 0; i< vsize - slack; ++i) {
    const int index = rgen.Uniform(csize);
    card_min[index]++;
    card_max[index]++;
  }
  for (int i = 0; i < 2 * slack; ++i) {
    card_max[rgen.Uniform(csize)]++;
  }

  LOG(INFO) << (use_gcc ? "Gcc constraint:" : "Distribute constraint:");
  LOG(INFO) << "  - num variables = " << vsize;
  LOG(INFO) << "  - num values = " << csize;
  LOG(INFO) << "  - slack = " << slack;
  LOG(INFO) << "  - seed = " << seed;

  Solver solver("TestGcc");
  std::vector<IntVar*> vars;
  solver.MakeIntVarArray(vsize, 0, csize - 1, &vars);
  Constraint* const gcc = use_gcc ?
                          Gcc(&solver, vars, 0, card_min, card_max) :
                          solver.MakeDistribute(vars, card_min, card_max);
  solver.AddConstraint(gcc);
  DecisionBuilder* const db = solver.MakePhase(vars,
                                               Solver::CHOOSE_FIRST_UNBOUND,
                                               Solver::ASSIGN_MIN_VALUE);

  LOG(INFO) << "Start search";
  CycleTimer t;
  t.Start();
  solver.NewSearch(db);
  int counter = 0;
  while(solver.NextSolution()) {
    counter++;
  }
  solver.EndSearch();
  t.Stop();

  LOG(INFO) << "test time : " << t.GetInUsec() << " micro seconds";
  LOG(INFO) << "Found " << counter << " solutions";
  return counter;
}
}  // namespace operations_research

int main(int argc, char** argv) {
  google::ParseCommandLineFlags(&argc, &argv, true);
  CHECK_EQ(operations_research::TestGcc(FLAGS_vsize,
                                        FLAGS_csize,
                                        FLAGS_slack,
                                        FLAGS_seed,
                                        false),
           operations_research::TestGcc(FLAGS_vsize,
                                        FLAGS_csize,
                                        FLAGS_slack,
                                        FLAGS_seed,
                                        true));
  return 0;
}
<|endoftext|>


<commit_before>// $Id$
/*
 * Example macro to run the HLT Conformal mapping tracker embedded into
 * AliRoot reconstruction. The reconstruction is done from the TPC raw
 * data.
 *
 * Usage:
 *

 *   aliroot -b -q rec-hlt-tpc.C | tee rec-hlt-tpc.log
 *   aliroot -b -q rec-hlt-tpc.C'("./","decoder All")' | tee rec-hlt-tpc.log
 *

 *
 * The macro asumes raw data to be available in the rawx folders, either
 * simulated or real data. A different input can be specified as parameter
 *

 *   aliroot -b -q rec-hlt-tpc.C'("input.root")'
 *

 *
 * The ClusterFinder uses the offline altro decoder v3 by default. The former
 * CF components can be selected by means of the second parameter:
 *    - decoder, uses TPCClusterFinderDecoder. This is default.
 *    - packed, uses TPCClusterFinderPacked
 *
 * Also in the second parameter you can set which output you would like to have:
 *    - ESD, gives you an ESD file. This is default.
 *    - TrackHistogram, will run the TrackHistogram component, and give
 *      root files with histograms.
 *    - TrackDump, dumps the track struct to a text file.
 *    - ClusterHisto, gives you histograms of the cluster.
 *    - ClusterDump, dumps the cluster struct to text flie.
 *    - All, gives you all 3 output.
 *
 * In the first section, an analysis chain is defined. The scale of the
 * chain can be defined by choosing the range of sectors and partitions.
 *
 * The reconstruction is steered by the AliReconstruction object in the
 * usual way.
 *
 * @ingroup alihlt_tpc
 * @author Matthias.Richter@ift.uib.no
 */
void rec_hlt_tpc(const char* input="./", char* opt="decoder ESD")
{

  if(!gSystem->AccessPathName("galice.root")){
    cerr << "please delete the galice.root or run at different place." << endl;
    return;
  }

  if (!input) {
    cerr << "please specify input or run without arguments" << endl;
    return;
  }

  ///////////////////////////////////////////////////////////////////////////////////////////////////
  //
  // init the HLT system in order to define the analysis chain below
  //
  AliHLTSystem* gHLT=AliHLTPluginBase::GetInstance();

  ///////////////////////////////////////////////////////////////////////////////////////////////////
  //
  // Setting up which output to give
  //
  int clusterFinderType=0; // 0 = v3; 1 = decoder; 2 = packed (offline v1)
  bool bUseCA=true;   // use the CA tracker and merger
  TString option="libAliHLTUtil.so libAliHLTRCU.so libAliHLTTPC.so loglevel=0x7c chains=";
  Bool_t esdout=kFALSE, dumpout=kFALSE, histout=kFALSE, chout=kFALSE, cdout=kFALSE;
  TString allArgs=opt;
  TString argument;
  TObjArray* pTokens=allArgs.Tokenize(" ");
  if (pTokens) {
    for (int i=0; i<pTokens->GetEntries(); i++) {
      argument=((TObjString*)pTokens->At(i))->GetString();
      if (argument.IsNull()) continue;

      if (argument.Contains("-statistics=")) {
	argument.ReplaceAll("-statistics=", "");
	if (argument.Contains("root")) {
	  if (option.Length()>0) option+=",";
	  option+="statroot";
	}
	if (argument.Contains("raw")) {
	  if (option.Length()>0) option+=",";
	  option+="statraw";
	}
	continue;
      }
      if (argument.CompareTo("ca", TString::kIgnoreCase)==0) {
	bUseCA=true;
	continue;
      }
      if (argument.CompareTo("cm", TString::kIgnoreCase)==0) {
	bUseCA=false;
	continue;
      }
      if (argument.CompareTo("decoder",TString::kIgnoreCase)==0) {
	clusterFinderType = 1;
	continue;
      }
      if (argument.CompareTo("packed",TString::kIgnoreCase)==0) {
	clusterFinderType = 2;
	continue;
      }
      if (argument.CompareTo("trackhistogram",TString::kIgnoreCase)==0) {
	histout = kTRUE;
	if (option.Length()>0) option+=",";
	option+="histFile";
	continue;
      }
      if (argument.CompareTo("trackdump",TString::kIgnoreCase)==0) {
	dumpout = kTRUE;
	if (option.Length()>0) option+=",";
	option+="dump";
	continue;
      }
      if (argument.CompareTo("esd",TString::kIgnoreCase)==0) {
	esdout = kTRUE;
	if (option.Length()>0) option+=",";
	option+="esd-converter";
	continue;
      }
      if (argument.CompareTo("esdwrite",TString::kIgnoreCase)==0) {
	esdout = kTRUE;
	if (option.Length()>0) option+=",";
	option+="esdfile";
	continue;
      }
      if (argument.CompareTo("clusterdump",TString::kIgnoreCase)==0) {
	cdout = kTRUE;
	if (option.Length()>0) option+=",";
	option+="cdump";
	continue;
      }
      if (argument.CompareTo("clusterhisto",TString::kIgnoreCase)==0) {
	chout = kTRUE;
	if (option.Length()>0) option+=",";
	option+="chhisto";
	continue;
      }
      if (argument.CompareTo("all",TString::kIgnoreCase)==0) {
	histout = kTRUE;
	dumpout = kTRUE;
	esdout = kTRUE;
	chout = kTRUE;
	cdout = kTRUE;
	if (option.Length()>0) option+=",";
	option+="esd-converter,histFile,dump,cdump,chhisto";
	continue;
      }
      else {
	break;
      }
    }
  }
  if (!histout && !dumpout && !esdout && !chout && !cdout) {
    cout << "you need to specify an output option, on or more out of: ESD, TrackHistogram, TrackDump, ClusterHisto, ClusterDump" << endl;
    return;
  }
  if ((option.Contains("statroot") || option.Contains("statraw")) && !esdout) {
    cout << "!!!!!!!! Warning: HLT statistics are only collected for output type ESD !!!!!!!!" << endl;
  }

  ///////////////////////////////////////////////////////////////////////////////////////////////////
  //
  // define the analysis chain to be run
  //
  int iMinSlice=0;
  int iMaxSlice=35;
  int iMinPart=0;
  int iMaxPart=5;
  TString writerInput;
  TString mergerInput;
  TString histoInput;
  TString histogramHandlerInputClusterFinder;
  TString cdumpInput;
  for (int slice=iMinSlice; slice<=iMaxSlice; slice++) {
    TString trackerInput;
    for (int part=iMinPart; part<=iMaxPart; part++) {
      TString arg, publisher, cf;
      TString clusterHistoOutput;
      // raw data publisher components
      int ddlno=768;
      if (part>1) ddlno+=72+4*slice+(part-2);
      else ddlno+=2*slice+part;
      arg.Form("-minid %d -datatype 'DDL_RAW ' 'TPC '  -dataspec 0x%02x%02x%02x%02x -verbose", ddlno, slice, slice, part, part);
      publisher.Form("DP_%02d_%d", slice, part);
      AliHLTConfiguration pubconf(publisher.Data(), "AliRawReaderPublisher", NULL , arg.Data());

      // cluster finder components
      cf.Form("CF_%02d_%d", slice, part);
      if (clusterFinderType==1) {
	AliHLTConfiguration cfconf(cf.Data(), "TPCClusterFinderDecoder", publisher.Data(), "-timebins 1001");
      } else if (clusterFinderType==2) {
	AliHLTConfiguration cfconf(cf.Data(), "TPCClusterFinderPacked", publisher.Data(), "-timebins 1001 -sorted");
      } else {
	AliHLTConfiguration cfconf(cf.Data(), "TPCClusterFinder32bit", publisher.Data(), "-timebins 1001");
      }
      if (trackerInput.Length()>0) trackerInput+=" ";
      trackerInput+=cf;
      if (writerInput.Length()>0) writerInput+=" ";
      writerInput+=cf;
      if (histoInput.Length()>0) histoInput+=" ";
      histoInput+=cf;
      if (cdumpInput.Length()>0) cdumpInput+=" ";
      cdumpInput+=cf;

      if(chout){
	clusterHistoOutput.Form("CH_%02d_%d", slice, part);
	AliHLTConfiguration cfconf(clusterHistoOutput.Data(), "TPCClusterHisto", cf.Data(), "");
	if (histogramHandlerInputClusterFinder.Length()>0) histogramHandlerInputClusterFinder+=" ";
	histogramHandlerInputClusterFinder+=clusterHistoOutput;
      }
    }
    TString tracker;
    // tracker components
    tracker.Form("TR_%02d", slice);
    if (bUseCA) {
      AliHLTConfiguration trackerconf(tracker.Data(), "TPCCATracker", trackerInput.Data(), "");
    } else {
      AliHLTConfiguration trackerconf(tracker.Data(), "TPCSliceTracker", trackerInput.Data(), "-pp-run");
    }

    if (writerInput.Length()>0) writerInput+=" ";
    writerInput+=tracker;
    if (mergerInput.Length()>0) mergerInput+=" ";
    mergerInput+=tracker;
    //add all slice tracks to histo input
    //if (histoInput.Length()>0) histoInput+=" ";
    //histoInput+=tracker;
  }

  // GlobalMerger component
  if (bUseCA) {
    AliHLTConfiguration mergerconf("globalmerger","TPCCAGlobalMerger",mergerInput.Data(),"");
  } else {
    AliHLTConfiguration mergerconf("globalmerger","TPCGlobalMerger",mergerInput.Data(),"");
  }

  //add all global tracks to histo input
  if (histoInput.Length()>0) histoInput+=" ";
  histoInput+="globalmerger";

  // specify whether to write all blocks separately or merge the tracks
  // and convert to ESD
  bool writeBlocks=false;

  if(esdout){
    if (writeBlocks) {
      // the writer configuration
      AliHLTConfiguration fwconf("esdfile", "FileWriter"   , writerInput.Data(), "-specfmt=_%d -subdir=out_%d -blcknofmt=_0x%x -idfmt=_0x%08x");
    } else {

      // the esd converter configuration
      AliHLTConfiguration esdcconf("esd-converter", "TPCEsdConverter"   , "globalmerger", "");

      // the root file writer configuration
      AliHLTConfiguration sink("esdfile", "EsdCollector"   , "esd-converter", "-directory hlt-tpc-esd");

      // optional component statistics
      AliHLTConfiguration statroot("statroot", "StatisticsCollector"   , "esd-converter", "-file HLT.statistics.root -publish 0");
      AliHLTConfiguration statraw("statraw", "FileWriter"   , "esd-converter", "-datatype COMPSTAT PRIV -datafile HLT.statistics.raw -concatenate-blocks -concatenate-events");
    }
  }
  //Chain with Track Histogram
  if(histout){
    AliHLTConfiguration histoconf("histo","TPCTrackHisto",histoInput.Data(),"");
    AliHLTConfiguration fwconf("histFile", "ROOTFileWriter"   , "histo", "-datafile TrackHisto -concatenate-events -overwrite");
  }
  //Chain with Track Dump
  if(dumpout){
    AliHLTConfiguration dumpconf("dump","TPCTrackDump","globalmerger","-directory TrackDump");
  }
  if(chout){
    AliHLTConfiguration cfconf("HHCF", "TPCHistogramHandler", histogramHandlerInputClusterFinder.Data(), "-use-general");
    AliHLTConfiguration rootFileWriterClusters("chhisto", "ROOTFileWriter", "HHCF" , "-datafile histogramHandlerClusterFinder -concatenate-events -overwrite");
  }
  if(cdout){
    AliHLTConfiguration cdumpconf("cdump","TPCClusterDump",cdumpInput.Data(),"-directory ClusterDump");
  }

  ///////////////////////////////////////////////////////////////////////////////////////////////////
  //
  // Init and run the reconstruction
  // All but HLT reconstructio is switched off
  //
  AliReconstruction rec;
  rec.SetInput(input);
  rec.SetRunVertexFinder(kFALSE);
  rec.SetRunReconstruction("HLT");
  rec.SetLoadAlignFromCDB(0);
  rec.SetRunQA(":");
  rec.SetOption("HLT", option);
  rec.Run();
}
<commit_msg>Bugfix: lowercase b should be upper case B for component id: TPCClusterFinder32Bit<commit_after>// $Id$
/*
 * Example macro to run the HLT Conformal mapping tracker embedded into
 * AliRoot reconstruction. The reconstruction is done from the TPC raw
 * data.
 *
 * Usage:
 *

 *   aliroot -b -q rec-hlt-tpc.C | tee rec-hlt-tpc.log
 *   aliroot -b -q rec-hlt-tpc.C'("./","decoder All")' | tee rec-hlt-tpc.log
 *

 *
 * The macro asumes raw data to be available in the rawx folders, either
 * simulated or real data. A different input can be specified as parameter
 *

 *   aliroot -b -q rec-hlt-tpc.C'("input.root")'
 *

 *
 * The ClusterFinder uses the offline altro decoder v3 by default. The former
 * CF components can be selected by means of the second parameter:
 *    - decoder, uses TPCClusterFinderDecoder. This is default.
 *    - packed, uses TPCClusterFinderPacked
 *
 * Also in the second parameter you can set which output you would like to have:
 *    - ESD, gives you an ESD file. This is default.
 *    - TrackHistogram, will run the TrackHistogram component, and give
 *      root files with histograms.
 *    - TrackDump, dumps the track struct to a text file.
 *    - ClusterHisto, gives you histograms of the cluster.
 *    - ClusterDump, dumps the cluster struct to text flie.
 *    - All, gives you all 3 output.
 *
 * In the first section, an analysis chain is defined. The scale of the
 * chain can be defined by choosing the range of sectors and partitions.
 *
 * The reconstruction is steered by the AliReconstruction object in the
 * usual way.
 *
 * @ingroup alihlt_tpc
 * @author Matthias.Richter@ift.uib.no
 */
void rec_hlt_tpc(const char* input="./", char* opt="decoder ESD")
{

  if(!gSystem->AccessPathName("galice.root")){
    cerr << "please delete the galice.root or run at different place." << endl;
    return;
  }

  if (!input) {
    cerr << "please specify input or run without arguments" << endl;
    return;
  }

  ///////////////////////////////////////////////////////////////////////////////////////////////////
  //
  // init the HLT system in order to define the analysis chain below
  //
  AliHLTSystem* gHLT=AliHLTPluginBase::GetInstance();

  ///////////////////////////////////////////////////////////////////////////////////////////////////
  //
  // Setting up which output to give
  //
  int clusterFinderType=0; // 0 = v3; 1 = decoder; 2 = packed (offline v1)
  bool bUseCA=true;   // use the CA tracker and merger
  TString option="libAliHLTUtil.so libAliHLTRCU.so libAliHLTTPC.so loglevel=0x7c chains=";
  Bool_t esdout=kFALSE, dumpout=kFALSE, histout=kFALSE, chout=kFALSE, cdout=kFALSE;
  TString allArgs=opt;
  TString argument;
  TObjArray* pTokens=allArgs.Tokenize(" ");
  if (pTokens) {
    for (int i=0; i<pTokens->GetEntries(); i++) {
      argument=((TObjString*)pTokens->At(i))->GetString();
      if (argument.IsNull()) continue;

      if (argument.Contains("-statistics=")) {
	argument.ReplaceAll("-statistics=", "");
	if (argument.Contains("root")) {
	  if (option.Length()>0) option+=",";
	  option+="statroot";
	}
	if (argument.Contains("raw")) {
	  if (option.Length()>0) option+=",";
	  option+="statraw";
	}
	continue;
      }
      if (argument.CompareTo("ca", TString::kIgnoreCase)==0) {
	bUseCA=true;
	continue;
      }
      if (argument.CompareTo("cm", TString::kIgnoreCase)==0) {
	bUseCA=false;
	continue;
      }
      if (argument.CompareTo("decoder",TString::kIgnoreCase)==0) {
	clusterFinderType = 1;
	continue;
      }
      if (argument.CompareTo("packed",TString::kIgnoreCase)==0) {
	clusterFinderType = 2;
	continue;
      }
      if (argument.CompareTo("trackhistogram",TString::kIgnoreCase)==0) {
	histout = kTRUE;
	if (option.Length()>0) option+=",";
	option+="histFile";
	continue;
      }
      if (argument.CompareTo("trackdump",TString::kIgnoreCase)==0) {
	dumpout = kTRUE;
	if (option.Length()>0) option+=",";
	option+="dump";
	continue;
      }
      if (argument.CompareTo("esd",TString::kIgnoreCase)==0) {
	esdout = kTRUE;
	if (option.Length()>0) option+=",";
	option+="esd-converter";
	continue;
      }
      if (argument.CompareTo("esdwrite",TString::kIgnoreCase)==0) {
	esdout = kTRUE;
	if (option.Length()>0) option+=",";
	option+="esdfile";
	continue;
      }
      if (argument.CompareTo("clusterdump",TString::kIgnoreCase)==0) {
	cdout = kTRUE;
	if (option.Length()>0) option+=",";
	option+="cdump";
	continue;
      }
      if (argument.CompareTo("clusterhisto",TString::kIgnoreCase)==0) {
	chout = kTRUE;
	if (option.Length()>0) option+=",";
	option+="chhisto";
	continue;
      }
      if (argument.CompareTo("all",TString::kIgnoreCase)==0) {
	histout = kTRUE;
	dumpout = kTRUE;
	esdout = kTRUE;
	chout = kTRUE;
	cdout = kTRUE;
	if (option.Length()>0) option+=",";
	option+="esd-converter,histFile,dump,cdump,chhisto";
	continue;
      }
      else {
	break;
      }
    }
  }
  if (!histout && !dumpout && !esdout && !chout && !cdout) {
    cout << "you need to specify an output option, on or more out of: ESD, TrackHistogram, TrackDump, ClusterHisto, ClusterDump" << endl;
    return;
  }
  if ((option.Contains("statroot") || option.Contains("statraw")) && !esdout) {
    cout << "!!!!!!!! Warning: HLT statistics are only collected for output type ESD !!!!!!!!" << endl;
  }

  ///////////////////////////////////////////////////////////////////////////////////////////////////
  //
  // define the analysis chain to be run
  //
  int iMinSlice=0;
  int iMaxSlice=35;
  int iMinPart=0;
  int iMaxPart=5;
  TString writerInput;
  TString mergerInput;
  TString histoInput;
  TString histogramHandlerInputClusterFinder;
  TString cdumpInput;
  for (int slice=iMinSlice; slice<=iMaxSlice; slice++) {
    TString trackerInput;
    for (int part=iMinPart; part<=iMaxPart; part++) {
      TString arg, publisher, cf;
      TString clusterHistoOutput;
      // raw data publisher components
      int ddlno=768;
      if (part>1) ddlno+=72+4*slice+(part-2);
      else ddlno+=2*slice+part;
      arg.Form("-minid %d -datatype 'DDL_RAW ' 'TPC '  -dataspec 0x%02x%02x%02x%02x -verbose", ddlno, slice, slice, part, part);
      publisher.Form("DP_%02d_%d", slice, part);
      AliHLTConfiguration pubconf(publisher.Data(), "AliRawReaderPublisher", NULL , arg.Data());

      // cluster finder components
      cf.Form("CF_%02d_%d", slice, part);
      if (clusterFinderType==1) {
	AliHLTConfiguration cfconf(cf.Data(), "TPCClusterFinderDecoder", publisher.Data(), "-timebins 1001");
      } else if (clusterFinderType==2) {
	AliHLTConfiguration cfconf(cf.Data(), "TPCClusterFinderPacked", publisher.Data(), "-timebins 1001 -sorted");
      } else {
	AliHLTConfiguration cfconf(cf.Data(), "TPCClusterFinder32Bit", publisher.Data(), "-timebins 1001");
      }
      if (trackerInput.Length()>0) trackerInput+=" ";
      trackerInput+=cf;
      if (writerInput.Length()>0) writerInput+=" ";
      writerInput+=cf;
      if (histoInput.Length()>0) histoInput+=" ";
      histoInput+=cf;
      if (cdumpInput.Length()>0) cdumpInput+=" ";
      cdumpInput+=cf;

      if(chout){
	clusterHistoOutput.Form("CH_%02d_%d", slice, part);
	AliHLTConfiguration cfconf(clusterHistoOutput.Data(), "TPCClusterHisto", cf.Data(), "");
	if (histogramHandlerInputClusterFinder.Length()>0) histogramHandlerInputClusterFinder+=" ";
	histogramHandlerInputClusterFinder+=clusterHistoOutput;
      }
    }
    TString tracker;
    // tracker components
    tracker.Form("TR_%02d", slice);
    if (bUseCA) {
      AliHLTConfiguration trackerconf(tracker.Data(), "TPCCATracker", trackerInput.Data(), "");
    } else {
      AliHLTConfiguration trackerconf(tracker.Data(), "TPCSliceTracker", trackerInput.Data(), "-pp-run");
    }

    if (writerInput.Length()>0) writerInput+=" ";
    writerInput+=tracker;
    if (mergerInput.Length()>0) mergerInput+=" ";
    mergerInput+=tracker;
    //add all slice tracks to histo input
    //if (histoInput.Length()>0) histoInput+=" ";
    //histoInput+=tracker;
  }

  // GlobalMerger component
  if (bUseCA) {
    AliHLTConfiguration mergerconf("globalmerger","TPCCAGlobalMerger",mergerInput.Data(),"");
  } else {
    AliHLTConfiguration mergerconf("globalmerger","TPCGlobalMerger",mergerInput.Data(),"");
  }

  //add all global tracks to histo input
  if (histoInput.Length()>0) histoInput+=" ";
  histoInput+="globalmerger";

  // specify whether to write all blocks separately or merge the tracks
  // and convert to ESD
  bool writeBlocks=false;

  if(esdout){
    if (writeBlocks) {
      // the writer configuration
      AliHLTConfiguration fwconf("esdfile", "FileWriter"   , writerInput.Data(), "-specfmt=_%d -subdir=out_%d -blcknofmt=_0x%x -idfmt=_0x%08x");
    } else {

      // the esd converter configuration
      AliHLTConfiguration esdcconf("esd-converter", "TPCEsdConverter"   , "globalmerger", "");

      // the root file writer configuration
      AliHLTConfiguration sink("esdfile", "EsdCollector"   , "esd-converter", "-directory hlt-tpc-esd");

      // optional component statistics
      AliHLTConfiguration statroot("statroot", "StatisticsCollector"   , "esd-converter", "-file HLT.statistics.root -publish 0");
      AliHLTConfiguration statraw("statraw", "FileWriter"   , "esd-converter", "-datatype COMPSTAT PRIV -datafile HLT.statistics.raw -concatenate-blocks -concatenate-events");
    }
  }
  //Chain with Track Histogram
  if(histout){
    AliHLTConfiguration histoconf("histo","TPCTrackHisto",histoInput.Data(),"");
    AliHLTConfiguration fwconf("histFile", "ROOTFileWriter"   , "histo", "-datafile TrackHisto -concatenate-events -overwrite");
  }
  //Chain with Track Dump
  if(dumpout){
    AliHLTConfiguration dumpconf("dump","TPCTrackDump","globalmerger","-directory TrackDump");
  }
  if(chout){
    AliHLTConfiguration cfconf("HHCF", "TPCHistogramHandler", histogramHandlerInputClusterFinder.Data(), "-use-general");
    AliHLTConfiguration rootFileWriterClusters("chhisto", "ROOTFileWriter", "HHCF" , "-datafile histogramHandlerClusterFinder -concatenate-events -overwrite");
  }
  if(cdout){
    AliHLTConfiguration cdumpconf("cdump","TPCClusterDump",cdumpInput.Data(),"-directory ClusterDump");
  }

  ///////////////////////////////////////////////////////////////////////////////////////////////////
  //
  // Init and run the reconstruction
  // All but HLT reconstructio is switched off
  //
  AliReconstruction rec;
  rec.SetInput(input);
  rec.SetRunVertexFinder(kFALSE);
  rec.SetRunReconstruction("HLT");
  rec.SetLoadAlignFromCDB(0);
  rec.SetRunQA(":");
  rec.SetOption("HLT", option);
  rec.Run();
}
<|endoftext|>


<commit_before><commit_msg>use offset of 100 instead of negative values to forward return value of AliHLTCreateGRP class (negatives don't work - thanks to Mikolaj)<commit_after><|endoftext|>


<commit_before>//$Id$

// Author: Anders Vestbo <mailto:vestbo@fi.uib.no>
//*-- Copyright &copy ASV

#include <iostream.h>
#include <math.h>
#include "AliL3Logging.h"
#include "AliL3ClustFinderNew.h"
#include "AliL3DigitData.h"
#include "AliL3Transform.h"
#include "AliL3SpacePointData.h"
#include "AliL3MemHandler.h"

//_____________________________________________________________
// AliL3ClustFinderNew
//
// The current cluster finder for HLT
// Based on STAR L3

ClassImp(AliL3ClustFinderNew)

AliL3ClustFinderNew::AliL3ClustFinderNew()
{
  fMatch = 4;
  fThreshold =10;
  fDeconvPad = kTRUE;
  fDeconvTime = kTRUE;
}

AliL3ClustFinderNew::~AliL3ClustFinderNew()
{

}

void AliL3ClustFinderNew::InitSlice(Int_t slice,Int_t patch,Int_t firstrow, Int_t lastrow,Int_t nmaxpoints)
{
  fNClusters = 0;
  fMaxNClusters = nmaxpoints;
  fCurrentSlice = slice;
  fCurrentPatch = patch;
  fFirstRow = firstrow;
  fLastRow = lastrow;
  fDeconvTime = kTRUE;
  fDeconvPad = kTRUE;
}

void AliL3ClustFinderNew::InitSlice(Int_t slice,Int_t patch,Int_t nmaxpoints)
{
  fNClusters = 0;
  fMaxNClusters = nmaxpoints;
  fCurrentSlice = slice;
  fCurrentPatch = patch;
}

void AliL3ClustFinderNew::SetOutputArray(AliL3SpacePointData *pt)
{

  fSpacePointData = pt;
}

void AliL3ClustFinderNew::Read(UInt_t ndigits,AliL3DigitRowData *ptr)
{
  fNDigitRowData = ndigits;
  fDigitRowData = ptr;

}

void AliL3ClustFinderNew::ProcessDigits()
{
  //Loop over rows, and call processrow

  AliL3DigitRowData *tempPt = (AliL3DigitRowData*)fDigitRowData;

  for(Int_t i=fFirstRow; i<=fLastRow; i++)
    {
      fCurrentRow = i;
      ProcessRow(tempPt);
      Byte_t *tmp = (Byte_t*)tempPt;
      Int_t size = sizeof(AliL3DigitRowData) + tempPt->fNDigit*sizeof(AliL3DigitData);
      tmp += size;
      tempPt = (AliL3DigitRowData*)tmp;
    }
  LOG(AliL3Log::kInformational,"AliL3ClustFinderNew::WriteClusters","Space points")
    <<"Cluster finder found "<<fNClusters<<" clusters in slice "<<fCurrentSlice
    <<" patch "<<fCurrentPatch<<ENDLOG;

}

void AliL3ClustFinderNew::ProcessRow(AliL3DigitRowData *tempPt)
{

  UInt_t last_pad = 123456789;

  ClusterData *pad1[2500]; //2 lists for internal memory=2pads
  ClusterData *pad2[2500]; //2 lists for internal memory=2pads
  ClusterData clusterlist[5000]; //Clusterlist

  ClusterData **currentPt; //List of pointers to the current pad
  ClusterData **previousPt; //List of pointers to the previous pad
  currentPt = pad2;
  previousPt = pad1;
  UInt_t n_previous=0,n_current=0,n_total=0;

  //Loop over sequences of this row:
  for(UInt_t bin=0; bin<tempPt->fNDigit; bin++)
    {

      AliL3DigitData *data = tempPt->fDigitData;
      if(data[bin].fPad != last_pad)
	{
	  //This is a new pad

	  //Switch:
	  if(currentPt == pad2)
	    {
	      currentPt = pad1;
	      previousPt = pad2;

	    }
	  else
	    {
	      currentPt = pad2;
	      previousPt = pad1;
	    }
	  n_previous = n_current;
	  n_current = 0;
	  if(bin[data].fPad != last_pad+1)
	    {
	      //this happens if there is a pad with no signal.
	      n_previous = n_current = 0;
	    }
	  last_pad = data[bin].fPad;
	}

      Bool_t new_cluster = kTRUE;

      UInt_t seq_charge=0,seq_average=0;

      UInt_t last_charge=0,last_was_falling=0;
      Int_t new_bin=-1;
      if(fDeconvTime)
	{
	redo: //This is a goto.
	  if(new_bin > -1)
	    {
	      bin = new_bin;
	      new_bin = -1;
	    }

	  last_charge=0;
	  last_was_falling = 0;
	}

      while(1) //Loop over current sequence
	{
	  if(data[bin].fTime >= AliL3Transform::GetNTimeBins())
	    {
	      LOG(AliL3Log::kFatal,"AliL3ClustFinderNew::ProcessRow","Digits")
		<<"Timebin out of range "<<(Int_t)data[bin].fTime<<ENDLOG;
	      break;
	    }

	  //Get the current ADC-value
	  UInt_t charge = data[bin].fCharge;

	  if(fDeconvTime)
	    {
	      //Check if the last pixel in the sequence is smaller than this
	      if(charge > last_charge)
		{
		  if(last_was_falling)
		    {
		      new_bin = bin;
		      break;
		    }
		}
	      else last_was_falling = 1; //last pixel was larger than this
	      last_charge = charge;
	    }

	  //Sum the total charge of this sequence
	  seq_charge += charge;
	  seq_average += data[bin].fTime*charge;

	  //Check where to stop:
	  if(data[bin+1].fPad != data[bin].fPad) //new pad
	    break;
	  if(data[bin+1].fTime != data[bin].fTime+1) //end of sequence
	    break;

	  bin++;
	}//end loop over sequence

      //Calculate mean of sequence:
      Int_t seq_mean=0;
      if(seq_charge)
	seq_mean = seq_average/seq_charge;
      else
	{
	  LOG(AliL3Log::kFatal,"AliL3ClustFinderNew::ProcessRow","Data")
	    <<"Error in data given to the cluster finder"<<ENDLOG;
	  seq_mean = 1;
	  seq_charge = 1;
	}

      //Calculate mean in pad direction:
      Int_t pad_mean = seq_charge*data[bin].fPad;

      //Compare with results on previous pad:
      for(UInt_t p=0; p<n_previous; p++)
	{
	  Int_t difference = seq_mean - previousPt[p]->fMean;
	  if(difference < -fMatch)
	    break;

	  if(difference <= fMatch)//There is a match here!!
	    {

	      ClusterData *local = previousPt[p];
	      if(fDeconvPad)
		{
		  if(seq_charge > local->fLastCharge)
		    {
		      if(local->fChargeFalling)//The previous pad was falling
			{
			  break;//create a new cluster
			}
		    }
		  else
		    local->fChargeFalling = 1;
		  local->fLastCharge = seq_charge;
		}

	      //Don't create a new cluster, because we found a match
	      new_cluster = kFALSE;

	      //Update cluster on current pad with the matching one:
	      //currentPt[n_current] = previousPt[p];

	      local->fTotalCharge += seq_charge;
	      local->fPad += pad_mean;
	      local->fTime += seq_average;
	      local->fMean = seq_mean;
	      local->fFlags++; //means we have more than one pad

	      currentPt[n_current] = local;
	      n_current++;

	      break;
	    }//Checking for match at previous pad
	}//Loop over results on previous pad.

      if(new_cluster)
	{
	  //Start a new cluster. Add it to the clusterlist, and update
	  //the list of pointers to clusters in current pad.
	  //current pad will be previous pad on next pad.

	  //Add to the clusterlist:
	  ClusterData *tmp = &clusterlist[n_total];
	  tmp->fTotalCharge = seq_charge;
	  tmp->fPad = pad_mean;
	  tmp->fTime = seq_average;
	  tmp->fMean = seq_mean;
	  tmp->fFlags = 0;  //flags for 1 pad clusters
	  if(fDeconvPad)
	    {
	      tmp->fChargeFalling = 0;
	      tmp->fLastCharge = seq_charge;
	    }

	  //Update list of pointers to previous pad:
	  currentPt[n_current] = &clusterlist[n_total];
	  n_total++;
	  n_current++;
	}
      if(fDeconvTime)
	if(new_bin >= 0) goto redo;

    }//Loop over digits on this padrow

  WriteClusters(n_total,clusterlist);

}

void AliL3ClustFinderNew::WriteClusters(Int_t n_clusters,ClusterData *list)
{
  Int_t thisrow,thissector;
  UInt_t counter = fNClusters;

  for(int j=0; j<n_clusters; j++)
    {
      if(!list[j].fFlags) continue; //discard 1 pad clusters
      if(list[j].fTotalCharge < fThreshold) continue; //noise cluster
      Float_t xyz[3];

      Float_t fpad=(Float_t)list[j].fPad/(Float_t)list[j].fTotalCharge;
      Float_t ftime=(Float_t)list[j].fTime/(Float_t)list[j].fTotalCharge;
      //printf("padrow %d number of pads %d totalcharge %d\n",fCurrentRow,list[j].fFlags,list[j].fTotalCharge);
      AliL3Transform::Slice2Sector(fCurrentSlice,fCurrentRow,thissector,thisrow);
      AliL3Transform::Raw2Local(xyz,thissector,thisrow,fpad,ftime);
      if(xyz[0]==0) LOG(AliL3Log::kError,"AliL3ClustFinder","Cluster Finder")
	<<AliL3Log::kDec<<"Zero cluster"<<ENDLOG;
      if(fNClusters >= fMaxNClusters)
	{
	  LOG(AliL3Log::kError,"AliL3ClustFinder::WriteClusters","Cluster Finder")
	    <<AliL3Log::kDec<<"Too many clusters"<<ENDLOG;
	  return;
	  }
      fSpacePointData[counter].fCharge = list[j].fTotalCharge;
      fSpacePointData[counter].fX = xyz[0];
      fSpacePointData[counter].fY = xyz[1];
      fSpacePointData[counter].fZ = xyz[2];
      fSpacePointData[counter].fPadRow = fCurrentRow;
      fSpacePointData[counter].fXYErr = fXYErr;
      fSpacePointData[counter].fZErr = fZErr;
      fSpacePointData[counter].fID = counter
	+((fCurrentSlice&0x7f)<<25)+((fCurrentPatch&0x7)<<22);//uli
#ifdef do_mc
      Int_t trackID[3];
      GetTrackID((Int_t)rint(fpad),(Int_t)rint(ftime),trackID);
      //cout<<"padrow "<<fCurrentRow<<" pad "<<(Int_t)rint(fpad)<<" time "<<(Int_t)rint(ftime)<<" Trackid "<<trackID[0]<<endl;
      fSpacePointData[counter].fTrackID[0] = trackID[0];
      fSpacePointData[counter].fTrackID[1] = trackID[1];
      fSpacePointData[counter].fTrackID[2] = trackID[2];
#endif
      fNClusters++;
      counter++;

    }

}

#ifdef do_mc
void AliL3ClustFinderNew::GetTrackID(Int_t pad,Int_t time,Int_t *trackID)
{
  AliL3DigitRowData *rowPt = (AliL3DigitRowData*)fDigitRowData;

  trackID[0]=trackID[1]=trackID[2]=-2;
  //cout<<"Looking for pad "<<pad<<" time "<<time<<endl;
  for(Int_t i=fFirstRow; i<=fLastRow; i++)
    {
      if(rowPt->fRow < (UInt_t)fCurrentRow)
	{
	  AliL3MemHandler::UpdateRowPointer(rowPt);
	  continue;
	}
      AliL3DigitData *digPt = (AliL3DigitData*)rowPt->fDigitData;
      for(UInt_t j=0; j<rowPt->fNDigit; j++)
	{
	  Int_t cpad = digPt[j].fPad;
	  Int_t ctime = digPt[j].fTime;
	  if(cpad != pad) continue;
	  if(ctime != time) continue;
	  //if(cpad != pad && ctime != ctime) continue;
	  //cout<<"Reading row "<<fCurrentRow<<" pad "<<cpad<<" time "<<ctime<<" trackID "<<digPt[j].fTrackID[0]<<endl;
	  trackID[0] = digPt[j].fTrackID[0];
	  trackID[1] = digPt[j].fTrackID[1];
	  trackID[2] = digPt[j].fTrackID[2];
	  break;
	  //cout<<"Reading trackID "<<trackID[0]<<endl;
	}
      break;
    }

}
#endif
<commit_msg>Commented out cout in WriteClusters<commit_after>//$Id$

// Author: Anders Vestbo <mailto:vestbo@fi.uib.no>
//*-- Copyright &copy ASV

#include <iostream.h>
#include <math.h>
#include "AliL3Logging.h"
#include "AliL3ClustFinderNew.h"
#include "AliL3DigitData.h"
#include "AliL3Transform.h"
#include "AliL3SpacePointData.h"
#include "AliL3MemHandler.h"

//_____________________________________________________________
// AliL3ClustFinderNew
//
// The current cluster finder for HLT
// Based on STAR L3

ClassImp(AliL3ClustFinderNew)

AliL3ClustFinderNew::AliL3ClustFinderNew()
{
  fMatch = 4;
  fThreshold =10;
  fDeconvPad = kTRUE;
  fDeconvTime = kTRUE;
}

AliL3ClustFinderNew::~AliL3ClustFinderNew()
{

}

void AliL3ClustFinderNew::InitSlice(Int_t slice,Int_t patch,Int_t firstrow, Int_t lastrow,Int_t nmaxpoints)
{
  fNClusters = 0;
  fMaxNClusters = nmaxpoints;
  fCurrentSlice = slice;
  fCurrentPatch = patch;
  fFirstRow = firstrow;
  fLastRow = lastrow;
  fDeconvTime = kTRUE;
  fDeconvPad = kTRUE;
}

void AliL3ClustFinderNew::InitSlice(Int_t slice,Int_t patch,Int_t nmaxpoints)
{
  fNClusters = 0;
  fMaxNClusters = nmaxpoints;
  fCurrentSlice = slice;
  fCurrentPatch = patch;
}

void AliL3ClustFinderNew::SetOutputArray(AliL3SpacePointData *pt)
{

  fSpacePointData = pt;
}

void AliL3ClustFinderNew::Read(UInt_t ndigits,AliL3DigitRowData *ptr)
{
  fNDigitRowData = ndigits;
  fDigitRowData = ptr;

}

void AliL3ClustFinderNew::ProcessDigits()
{
  //Loop over rows, and call processrow

  AliL3DigitRowData *tempPt = (AliL3DigitRowData*)fDigitRowData;

  for(Int_t i=fFirstRow; i<=fLastRow; i++)
    {
      fCurrentRow = i;
      ProcessRow(tempPt);
      Byte_t *tmp = (Byte_t*)tempPt;
      Int_t size = sizeof(AliL3DigitRowData) + tempPt->fNDigit*sizeof(AliL3DigitData);
      tmp += size;
      tempPt = (AliL3DigitRowData*)tmp;
    }
  LOG(AliL3Log::kInformational,"AliL3ClustFinderNew::WriteClusters","Space points")
    <<"Cluster finder found "<<fNClusters<<" clusters in slice "<<fCurrentSlice
    <<" patch "<<fCurrentPatch<<ENDLOG;
}

void AliL3ClustFinderNew::ProcessRow(AliL3DigitRowData *tempPt)
{

  UInt_t last_pad = 123456789;

  ClusterData *pad1[2500]; //2 lists for internal memory=2pads
  ClusterData *pad2[2500]; //2 lists for internal memory=2pads
  ClusterData clusterlist[5000]; //Clusterlist

  ClusterData **currentPt; //List of pointers to the current pad
  ClusterData **previousPt; //List of pointers to the previous pad
  currentPt = pad2;
  previousPt = pad1;
  UInt_t n_previous=0,n_current=0,n_total=0;

  //Loop over sequences of this row:
  for(UInt_t bin=0; bin<tempPt->fNDigit; bin++)
    {

      AliL3DigitData *data = tempPt->fDigitData;
      if(data[bin].fPad != last_pad)
	{
	  //This is a new pad

	  //Switch:
	  if(currentPt == pad2)
	    {
	      currentPt = pad1;
	      previousPt = pad2;

	    }
	  else
	    {
	      currentPt = pad2;
	      previousPt = pad1;
	    }
	  n_previous = n_current;
	  n_current = 0;
	  if(bin[data].fPad != last_pad+1)
	    {
	      //this happens if there is a pad with no signal.
	      n_previous = n_current = 0;
	    }
	  last_pad = data[bin].fPad;
	}

      Bool_t new_cluster = kTRUE;

      UInt_t seq_charge=0,seq_average=0;

      UInt_t last_charge=0,last_was_falling=0;
      Int_t new_bin=-1;
      if(fDeconvTime)
	{
	redo: //This is a goto.
	  if(new_bin > -1)
	    {
	      bin = new_bin;
	      new_bin = -1;
	    }

	  last_charge=0;
	  last_was_falling = 0;
	}

      while(1) //Loop over current sequence
	{
	  if(data[bin].fTime >= AliL3Transform::GetNTimeBins())
	    {
	      LOG(AliL3Log::kFatal,"AliL3ClustFinderNew::ProcessRow","Digits")
		<<"Timebin out of range "<<(Int_t)data[bin].fTime<<ENDLOG;
	      break;
	    }

	  //Get the current ADC-value
	  UInt_t charge = data[bin].fCharge;

	  if(fDeconvTime)
	    {
	      //Check if the last pixel in the sequence is smaller than this
	      if(charge > last_charge)
		{
		  if(last_was_falling)
		    {
		      new_bin = bin;
		      break;
		    }
		}
	      else last_was_falling = 1; //last pixel was larger than this
	      last_charge = charge;
	    }

	  //Sum the total charge of this sequence
	  seq_charge += charge;
	  seq_average += data[bin].fTime*charge;

	  //Check where to stop:
	  if(data[bin+1].fPad != data[bin].fPad) //new pad
	    break;
	  if(data[bin+1].fTime != data[bin].fTime+1) //end of sequence
	    break;

	  bin++;
	}//end loop over sequence

      //Calculate mean of sequence:
      Int_t seq_mean=0;
      if(seq_charge)
	seq_mean = seq_average/seq_charge;
      else
	{
	  LOG(AliL3Log::kFatal,"AliL3ClustFinderNew::ProcessRow","Data")
	    <<"Error in data given to the cluster finder"<<ENDLOG;
	  seq_mean = 1;
	  seq_charge = 1;
	}

      //Calculate mean in pad direction:
      Int_t pad_mean = seq_charge*data[bin].fPad;

      //Compare with results on previous pad:
      for(UInt_t p=0; p<n_previous; p++)
	{
	  Int_t difference = seq_mean - previousPt[p]->fMean;
	  if(difference < -fMatch)
	    break;

	  if(difference <= fMatch)//There is a match here!!
	    {

	      ClusterData *local = previousPt[p];
	      if(fDeconvPad)
		{
		  if(seq_charge > local->fLastCharge)
		    {
		      if(local->fChargeFalling)//The previous pad was falling
			{
			  break;//create a new cluster
			}
		    }
		  else
		    local->fChargeFalling = 1;
		  local->fLastCharge = seq_charge;
		}

	      //Don't create a new cluster, because we found a match
	      new_cluster = kFALSE;

	      //Update cluster on current pad with the matching one:
	      //currentPt[n_current] = previousPt[p];

	      local->fTotalCharge += seq_charge;
	      local->fPad += pad_mean;
	      local->fTime += seq_average;
	      local->fMean = seq_mean;
	      local->fFlags++; //means we have more than one pad

	      currentPt[n_current] = local;
	      n_current++;

	      break;
	    }//Checking for match at previous pad
	}//Loop over results on previous pad.

      if(new_cluster)
	{
	  //Start a new cluster. Add it to the clusterlist, and update
	  //the list of pointers to clusters in current pad.
	  //current pad will be previous pad on next pad.

	  //Add to the clusterlist:
	  ClusterData *tmp = &clusterlist[n_total];
	  tmp->fTotalCharge = seq_charge;
	  tmp->fPad = pad_mean;
	  tmp->fTime = seq_average;
	  tmp->fMean = seq_mean;
	  tmp->fFlags = 0;  //flags for 1 pad clusters
	  if(fDeconvPad)
	    {
	      tmp->fChargeFalling = 0;
	      tmp->fLastCharge = seq_charge;
	    }

	  //Update list of pointers to previous pad:
	  currentPt[n_current] = &clusterlist[n_total];
	  n_total++;
	  n_current++;
	}
      if(fDeconvTime)
	if(new_bin >= 0) goto redo;

    }//Loop over digits on this padrow

  WriteClusters(n_total,clusterlist);
}

void AliL3ClustFinderNew::WriteClusters(Int_t n_clusters,ClusterData *list)
{
  Int_t thisrow,thissector;
  UInt_t counter = fNClusters;

  for(int j=0; j<n_clusters; j++)
    {
      if(!list[j].fFlags) continue; //discard 1 pad clusters
      if(list[j].fTotalCharge < fThreshold) continue; //noise cluster

      Float_t xyz[3];
      Float_t fpad=(Float_t)list[j].fPad/(Float_t)list[j].fTotalCharge;
      Float_t ftime=(Float_t)list[j].fTime/(Float_t)list[j].fTotalCharge;
      //cout<<"WriteCluster: padrow "<<fCurrentRow<<" pad "<<fpad<<" time "<<ftime<<" charge "<<list[j].fTotalCharge<<endl;

      //printf("padrow %d number of pads %d totalcharge %d\n",fCurrentRow,list[j].fFlags,list[j].fTotalCharge);
      AliL3Transform::Slice2Sector(fCurrentSlice,fCurrentRow,thissector,thisrow);
      AliL3Transform::Raw2Local(xyz,thissector,thisrow,fpad,ftime);
      if(xyz[0]==0) LOG(AliL3Log::kError,"AliL3ClustFinder","Cluster Finder")
	<<AliL3Log::kDec<<"Zero cluster"<<ENDLOG;
      if(fNClusters >= fMaxNClusters)
	{
	  LOG(AliL3Log::kError,"AliL3ClustFinder::WriteClusters","Cluster Finder")
	    <<AliL3Log::kDec<<"Too many clusters"<<ENDLOG;
	  return;
	}
      fSpacePointData[counter].fCharge = list[j].fTotalCharge;
      fSpacePointData[counter].fX = xyz[0];
      fSpacePointData[counter].fY = xyz[1];
      fSpacePointData[counter].fZ = xyz[2];
      fSpacePointData[counter].fPadRow = fCurrentRow;
      fSpacePointData[counter].fXYErr = fXYErr;
      fSpacePointData[counter].fZErr = fZErr;
      fSpacePointData[counter].fID = counter
	+((fCurrentSlice&0x7f)<<25)+((fCurrentPatch&0x7)<<22);//Uli
#ifdef do_mc
      Int_t trackID[3];
      GetTrackID((Int_t)rint(fpad),(Int_t)rint(ftime),trackID);
      //cout<<"padrow "<<fCurrentRow<<" pad "<<(Int_t)rint(fpad)<<" time "<<(Int_t)rint(ftime)<<" Trackid "<<trackID[0]<<endl;
      fSpacePointData[counter].fTrackID[0] = trackID[0];
      fSpacePointData[counter].fTrackID[1] = trackID[1];
      fSpacePointData[counter].fTrackID[2] = trackID[2];
#endif
      fNClusters++;
      counter++;
    }
}

#ifdef do_mc
void AliL3ClustFinderNew::GetTrackID(Int_t pad,Int_t time,Int_t *trackID)
{
  AliL3DigitRowData *rowPt = (AliL3DigitRowData*)fDigitRowData;

  trackID[0]=trackID[1]=trackID[2]=-2;
  //cout<<"Looking for pad "<<pad<<" time "<<time<<endl;
  for(Int_t i=fFirstRow; i<=fLastRow; i++)
    {
      if(rowPt->fRow < (UInt_t)fCurrentRow)
	{
	  AliL3MemHandler::UpdateRowPointer(rowPt);
	  continue;
	}
      AliL3DigitData *digPt = (AliL3DigitData*)rowPt->fDigitData;
      for(UInt_t j=0; j<rowPt->fNDigit; j++)
	{
	  Int_t cpad = digPt[j].fPad;
	  Int_t ctime = digPt[j].fTime;
	  if(cpad != pad) continue;
	  if(ctime != time) continue;
	  //if(cpad != pad && ctime != ctime) continue;
	  //cout<<"Reading row "<<fCurrentRow<<" pad "<<cpad<<" time "<<ctime<<" trackID "<<digPt[j].fTrackID[0]<<endl;
	  trackID[0] = digPt[j].fTrackID[0];
	  trackID[1] = digPt[j].fTrackID[1];
	  trackID[2] = digPt[j].fTrackID[2];
	  break;
	  //cout<<"Reading trackID "<<trackID[0]<<endl;
	}
      break;
    }

}
#endif
<|endoftext|>


<commit_before>//===--- clang-wpa.cpp - clang whole program analyzer ---------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This tool reads a sequence of precompiled AST files, and do various
// cross translation unit analyses.
//
//===----------------------------------------------------------------------===//

#include "clang/Basic/FileManager.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Frontend/ASTUnit.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Index/CallGraph.h"
#include "llvm/ADT/IntrusiveRefCntPtr.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/raw_ostream.h"
using namespace clang;
using namespace idx;

static llvm::cl::list<std::string>
InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input AST files>"));

static llvm::cl::opt<bool>
ViewCallGraph("view-call-graph", llvm::cl::desc("Display the call graph."));

static llvm::cl::opt<std::string>
AnalyzeFunction("analyze-function",
                llvm::cl::desc("Specify the entry function."));

int main(int argc, char **argv) {
  llvm::cl::ParseCommandLineOptions(argc, argv, "clang-wpa");
  FileManager FileMgr;
  std::vector<ASTUnit*> ASTUnits;

  Program Prog;

  if (InputFilenames.empty())
    return 0;

  DiagnosticOptions DiagOpts;
  llvm::IntrusiveRefCntPtr<Diagnostic> Diags
    = CompilerInstance::createDiagnostics(DiagOpts, argc, argv);
  for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
    const std::string &InFile = InputFilenames[i];
    llvm::OwningPtr<ASTUnit> AST(ASTUnit::LoadFromPCHFile(InFile, Diags));
    if (!AST)
      return 1;

    ASTUnits.push_back(AST.take());
  }

  if (ViewCallGraph) {
    llvm::OwningPtr<CallGraph> CG;
    CG.reset(new CallGraph(Prog));

    for (unsigned i = 0, e = ASTUnits.size(); i != e; ++i)
      CG->addTU(ASTUnits[i]->getASTContext());

    CG->ViewCallGraph();
    return 0;
  }

  if (AnalyzeFunction.empty())
    return 0;

  llvm::outs() << "Analyze function: " << AnalyzeFunction << '\n';
  return 0;
}
<commit_msg>Create a ASTUnitTU class to interface ASTUnit to the Indexer.<commit_after>//===--- clang-wpa.cpp - clang whole program analyzer ---------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This tool reads a sequence of precompiled AST files, and do various
// cross translation unit analyses.
//
//===----------------------------------------------------------------------===//

#include "clang/Basic/FileManager.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Frontend/ASTUnit.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Index/CallGraph.h"
#include "clang/Index/Indexer.h"
#include "clang/Index/TranslationUnit.h"
#include "clang/Index/DeclReferenceMap.h"
#include "clang/Index/SelectorMap.h"
#include "llvm/ADT/IntrusiveRefCntPtr.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/raw_ostream.h"
using namespace clang;
using namespace idx;

static llvm::cl::list<std::string>
InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input AST files>"));

static llvm::cl::opt<bool>
ViewCallGraph("view-call-graph", llvm::cl::desc("Display the call graph."));

static llvm::cl::opt<std::string>
AnalyzeFunction("analyze-function",
                llvm::cl::desc("Specify the entry function."));

namespace {
// A thin wrapper over ASTUnit implementing the TranslationUnit interface.
class ASTUnitTU : public TranslationUnit {
  ASTUnit *AST;
  DeclReferenceMap DeclRefMap;
  SelectorMap SelMap;

public:
  ASTUnitTU(ASTUnit *ast)
    : AST(ast), DeclRefMap(AST->getASTContext()), SelMap(AST->getASTContext()) {
  }

  virtual ASTContext &getASTContext() {
    return AST->getASTContext();
  }

  virtual DeclReferenceMap &getDeclReferenceMap() {
    return DeclRefMap;
  }

  virtual SelectorMap &getSelectorMap() {
    return SelMap;
  }
};
}

int main(int argc, char **argv) {
  llvm::cl::ParseCommandLineOptions(argc, argv, "clang-wpa");
  std::vector<ASTUnit*> ASTUnits;

  Program Prog;
  Indexer Idxer(Prog);

  if (InputFilenames.empty())
    return 0;

  DiagnosticOptions DiagOpts;
  llvm::IntrusiveRefCntPtr<Diagnostic> Diags
    = CompilerInstance::createDiagnostics(DiagOpts, argc, argv);
  for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
    const std::string &InFile = InputFilenames[i];
    llvm::OwningPtr<ASTUnit> AST(ASTUnit::LoadFromPCHFile(InFile, Diags));
    if (!AST)
      return 1;

    ASTUnits.push_back(AST.take());
  }

  if (ViewCallGraph) {
    llvm::OwningPtr<CallGraph> CG;
    CG.reset(new CallGraph(Prog));

    for (unsigned i = 0, e = ASTUnits.size(); i != e; ++i)
      CG->addTU(ASTUnits[i]->getASTContext());

    CG->ViewCallGraph();
    return 0;
  }

  if (AnalyzeFunction.empty())
    return 0;

  // Feed all ASTUnits to the Indexer.
  for (unsigned i = 0, e = ASTUnits.size(); i != e; ++i) {
    ASTUnitTU TU(ASTUnits[i]);
    Idxer.IndexAST(&TU);
  }

  return 0;
}
<|endoftext|>


<commit_before>#include <stdio.h>
#include "xbyak/xbyak_util.h"

#define NUM_OF_ARRAY(x) (sizeof(x) / sizeof(x[0]))

struct PopCountTest : public Xbyak::CodeGenerator {
	PopCountTest(int n)
		: Xbyak::CodeGenerator(4096, Xbyak::DontSetProtectRWE)
	{
		mov(eax, n);
		popcnt(eax, eax);
		ret();
	}
};

void putCPUinfo(bool onlyCpuidFeature)
{
	using namespace Xbyak::util;
	Cpu cpu;
	printf("vendor %s\n", cpu.has(Cpu::tINTEL) ? "intel" : "amd");
	static const struct {
		Cpu::Type type;
		const char *str;
	} tbl[] = {
		{ Cpu::tMMX, "mmx" },
		{ Cpu::tMMX2, "mmx2" },
		{ Cpu::tCMOV, "cmov" },
		{ Cpu::tSSE, "sse" },
		{ Cpu::tSSE2, "sse2" },
		{ Cpu::tSSE3, "sse3" },
		{ Cpu::tSSSE3, "ssse3" },
		{ Cpu::tSSE41, "sse41" },
		{ Cpu::tSSE42, "sse42" },
		{ Cpu::tPOPCNT, "popcnt" },
		{ Cpu::t3DN, "3dn" },
		{ Cpu::tE3DN, "e3dn" },
		{ Cpu::tAESNI, "aesni" },
		{ Cpu::tRDTSCP, "rdtscp" },
		{ Cpu::tOSXSAVE, "osxsave(xgetvb)" },
		{ Cpu::tPCLMULQDQ, "pclmulqdq" },
		{ Cpu::tAVX, "avx" },
		{ Cpu::tFMA, "fma" },
		{ Cpu::tAVX2, "avx2" },
		{ Cpu::tBMI1, "bmi1" },
		{ Cpu::tBMI2, "bmi2" },
		{ Cpu::tLZCNT, "lzcnt" },
		{ Cpu::tPREFETCHW, "prefetchw" },
		{ Cpu::tENHANCED_REP, "enh_rep" },
		{ Cpu::tRDRAND, "rdrand" },
		{ Cpu::tADX, "adx" },
		{ Cpu::tRDSEED, "rdseed" },
		{ Cpu::tSMAP, "smap" },
		{ Cpu::tHLE, "hle" },
		{ Cpu::tRTM, "rtm" },
		{ Cpu::tMPX, "mpx" },
		{ Cpu::tSHA, "sha" },
		{ Cpu::tPREFETCHWT1, "prefetchwt1" },
		{ Cpu::tF16C, "f16c" },
		{ Cpu::tMOVBE, "movbe" },
		{ Cpu::tAVX512F, "avx512f" },
		{ Cpu::tAVX512DQ, "avx512dq" },
		{ Cpu::tAVX512IFMA, "avx512_ifma" },
		{ Cpu::tAVX512PF, "avx512pf" },
		{ Cpu::tAVX512ER, "avx512er" },
		{ Cpu::tAVX512CD, "avx512cd" },
		{ Cpu::tAVX512BW, "avx512bw" },
		{ Cpu::tAVX512VL, "avx512vl" },
		{ Cpu::tAVX512VBMI, "avx512_vbmi" },
		{ Cpu::tAVX512_4VNNIW, "avx512_4vnniw" },
		{ Cpu::tAVX512_4FMAPS, "avx512_4fmaps" },

		{ Cpu::tAVX512_VBMI2, "avx512_vbmi2" },
		{ Cpu::tGFNI, "gfni" },
		{ Cpu::tVAES, "vaes" },
		{ Cpu::tVPCLMULQDQ, "vpclmulqdq" },
		{ Cpu::tAVX512_VNNI, "avx512_vnni" },
		{ Cpu::tAVX512_BITALG, "avx512_bitalg" },
		{ Cpu::tAVX512_VPOPCNTDQ, "avx512_vpopcntdq" },
		{ Cpu::tAVX512_BF16, "avx512_bf16" },
		{ Cpu::tAVX512_VP2INTERSECT, "avx512_vp2intersect" },
		{ Cpu::tAMX_TILE, "amx(tile)" },
		{ Cpu::tAMX_INT8, "amx(int8)" },
		{ Cpu::tAMX_BF16, "amx(bf16)" },
		{ Cpu::tAVX_VNNI, "avx_vnni" },
		{ Cpu::tAVX512_FP16, "avx512_fp16" },
		{ Cpu::tWAITPKG, "waitpkg" },
		{ Cpu::tCLFLUSHOPT, "clflushopt" },
		{ Cpu::tCLDEMOTE, "cldemote" },
		{ Cpu::tMOVDIRI, "movdiri" },
		{ Cpu::tMOVDIR64B, "movdir64b" },
		{ Cpu::tCLZERO, "clzero" },
	};
	for (size_t i = 0; i < NUM_OF_ARRAY(tbl); i++) {
		if (cpu.has(tbl[i].type)) printf(" %s", tbl[i].str);
	}
	printf("\n");
	if (onlyCpuidFeature) return;
	if (cpu.has(Cpu::tPOPCNT)) {
		const int n = 0x12345678; // bitcount = 13
		const int ok = 13;
		PopCountTest code(n);
		code.setProtectModeRE();
		int (*f)() = code.getCode<int (*)()>();
		int r = f();
		if (r == ok) {
			puts("popcnt ok");
		} else {
			printf("popcnt ng %d %d\n", r, ok);
		}
		code.setProtectModeRW();
	}
	/*
		                displayFamily displayModel
		Opteron 2376        10            4
		Core2 Duo T7100      6            F
		Core i3-2120T        6           2A
		Core i7-2600         6           2A
		Xeon X5650           6           2C
		Core i7-3517         6           3A
		Core i7-3930K        6           2D
	*/
	cpu.putFamily();
	if (!cpu.has(Cpu::tINTEL)) return;
	for (unsigned int i = 0; i < cpu.getDataCacheLevels(); i++) {
		printf("cache level=%u data cache size=%u cores sharing data cache=%u\n", i, cpu.getDataCacheSize(i), cpu.getCoresSharingDataCache(i));
	}
	printf("SmtLevel =%u\n", cpu.getNumCores(Xbyak::util::SmtLevel));
	printf("CoreLevel=%u\n", cpu.getNumCores(Xbyak::util::CoreLevel));
}

int main(int argc, char *argv[])
{
	bool onlyCpuidFeature = argc == 2 && strcmp(argv[1], "-cpuid") == 0;
	if (!onlyCpuidFeature) {
#ifdef XBYAK32
		puts("32bit");
#else
		puts("64bit");
#endif
	}
	putCPUinfo(onlyCpuidFeature);
}
<commit_msg>[sample] show AMX_FP16/AVX_VNNI_INT8/AVX_NE_CONVERT<commit_after>#include <stdio.h>
#include "xbyak/xbyak_util.h"

#define NUM_OF_ARRAY(x) (sizeof(x) / sizeof(x[0]))

struct PopCountTest : public Xbyak::CodeGenerator {
	PopCountTest(int n)
		: Xbyak::CodeGenerator(4096, Xbyak::DontSetProtectRWE)
	{
		mov(eax, n);
		popcnt(eax, eax);
		ret();
	}
};

void putCPUinfo(bool onlyCpuidFeature)
{
	using namespace Xbyak::util;
	Cpu cpu;
	printf("vendor %s\n", cpu.has(Cpu::tINTEL) ? "intel" : "amd");
	static const struct {
		Cpu::Type type;
		const char *str;
	} tbl[] = {
		{ Cpu::tMMX, "mmx" },
		{ Cpu::tMMX2, "mmx2" },
		{ Cpu::tCMOV, "cmov" },
		{ Cpu::tSSE, "sse" },
		{ Cpu::tSSE2, "sse2" },
		{ Cpu::tSSE3, "sse3" },
		{ Cpu::tSSSE3, "ssse3" },
		{ Cpu::tSSE41, "sse41" },
		{ Cpu::tSSE42, "sse42" },
		{ Cpu::tPOPCNT, "popcnt" },
		{ Cpu::t3DN, "3dn" },
		{ Cpu::tE3DN, "e3dn" },
		{ Cpu::tAESNI, "aesni" },
		{ Cpu::tRDTSCP, "rdtscp" },
		{ Cpu::tOSXSAVE, "osxsave(xgetvb)" },
		{ Cpu::tPCLMULQDQ, "pclmulqdq" },
		{ Cpu::tAVX, "avx" },
		{ Cpu::tFMA, "fma" },
		{ Cpu::tAVX2, "avx2" },
		{ Cpu::tBMI1, "bmi1" },
		{ Cpu::tBMI2, "bmi2" },
		{ Cpu::tLZCNT, "lzcnt" },
		{ Cpu::tPREFETCHW, "prefetchw" },
		{ Cpu::tENHANCED_REP, "enh_rep" },
		{ Cpu::tRDRAND, "rdrand" },
		{ Cpu::tADX, "adx" },
		{ Cpu::tRDSEED, "rdseed" },
		{ Cpu::tSMAP, "smap" },
		{ Cpu::tHLE, "hle" },
		{ Cpu::tRTM, "rtm" },
		{ Cpu::tMPX, "mpx" },
		{ Cpu::tSHA, "sha" },
		{ Cpu::tPREFETCHWT1, "prefetchwt1" },
		{ Cpu::tF16C, "f16c" },
		{ Cpu::tMOVBE, "movbe" },
		{ Cpu::tAVX512F, "avx512f" },
		{ Cpu::tAVX512DQ, "avx512dq" },
		{ Cpu::tAVX512IFMA, "avx512_ifma" },
		{ Cpu::tAVX512PF, "avx512pf" },
		{ Cpu::tAVX512ER, "avx512er" },
		{ Cpu::tAVX512CD, "avx512cd" },
		{ Cpu::tAVX512BW, "avx512bw" },
		{ Cpu::tAVX512VL, "avx512vl" },
		{ Cpu::tAVX512VBMI, "avx512_vbmi" },
		{ Cpu::tAVX512_4VNNIW, "avx512_4vnniw" },
		{ Cpu::tAVX512_4FMAPS, "avx512_4fmaps" },

		{ Cpu::tAVX512_VBMI2, "avx512_vbmi2" },
		{ Cpu::tGFNI, "gfni" },
		{ Cpu::tVAES, "vaes" },
		{ Cpu::tVPCLMULQDQ, "vpclmulqdq" },
		{ Cpu::tAVX512_VNNI, "avx512_vnni" },
		{ Cpu::tAVX512_BITALG, "avx512_bitalg" },
		{ Cpu::tAVX512_VPOPCNTDQ, "avx512_vpopcntdq" },
		{ Cpu::tAVX512_BF16, "avx512_bf16" },
		{ Cpu::tAVX512_VP2INTERSECT, "avx512_vp2intersect" },
		{ Cpu::tAMX_TILE, "amx(tile)" },
		{ Cpu::tAMX_INT8, "amx(int8)" },
		{ Cpu::tAMX_BF16, "amx(bf16)" },
		{ Cpu::tAVX_VNNI, "avx_vnni" },
		{ Cpu::tAVX512_FP16, "avx512_fp16" },
		{ Cpu::tWAITPKG, "waitpkg" },
		{ Cpu::tCLFLUSHOPT, "clflushopt" },
		{ Cpu::tCLDEMOTE, "cldemote" },
		{ Cpu::tMOVDIRI, "movdiri" },
		{ Cpu::tMOVDIR64B, "movdir64b" },
		{ Cpu::tCLZERO, "clzero" },
		{ Cpu::tAMX_FP16, "amx_fp16" },
		{ Cpu::tAVX_VNNI_INT8, "avx_vnni_int8" },
		{ Cpu::tAVX_NE_CONVERT, "avx_ne_convert" },
	};
	for (size_t i = 0; i < NUM_OF_ARRAY(tbl); i++) {
		if (cpu.has(tbl[i].type)) printf(" %s", tbl[i].str);
	}
	printf("\n");
	if (onlyCpuidFeature) return;
	if (cpu.has(Cpu::tPOPCNT)) {
		const int n = 0x12345678; // bitcount = 13
		const int ok = 13;
		PopCountTest code(n);
		code.setProtectModeRE();
		int (*f)() = code.getCode<int (*)()>();
		int r = f();
		if (r == ok) {
			puts("popcnt ok");
		} else {
			printf("popcnt ng %d %d\n", r, ok);
		}
		code.setProtectModeRW();
	}
	/*
		                displayFamily displayModel
		Opteron 2376        10            4
		Core2 Duo T7100      6            F
		Core i3-2120T        6           2A
		Core i7-2600         6           2A
		Xeon X5650           6           2C
		Core i7-3517         6           3A
		Core i7-3930K        6           2D
	*/
	cpu.putFamily();
	if (!cpu.has(Cpu::tINTEL)) return;
	for (unsigned int i = 0; i < cpu.getDataCacheLevels(); i++) {
		printf("cache level=%u data cache size=%u cores sharing data cache=%u\n", i, cpu.getDataCacheSize(i), cpu.getCoresSharingDataCache(i));
	}
	printf("SmtLevel =%u\n", cpu.getNumCores(Xbyak::util::SmtLevel));
	printf("CoreLevel=%u\n", cpu.getNumCores(Xbyak::util::CoreLevel));
}

int main(int argc, char *argv[])
{
	bool onlyCpuidFeature = argc == 2 && strcmp(argv[1], "-cpuid") == 0;
	if (!onlyCpuidFeature) {
#ifdef XBYAK32
		puts("32bit");
#else
		puts("64bit");
#endif
	}
	putCPUinfo(onlyCpuidFeature);
}
<|endoftext|>


<commit_before>//
// Copyright 2013 Jeff Bush
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

#include "Debug.h"
#include "RenderTarget.h"
#include "ParameterInterpolator.h"
#include "Rasterizer.h"
#include "PixelShader.h"
#include "utils.h"

#define COLOR_SHADER 1

const int kMaxTileIndex = (640 / 64) * ((480 / 64) + 1);
int nextTileIndex = 0;

struct Vertex
{
	float coord[3];
	float params[kMaxParams];
};

class ColorShader : public PixelShader
{
public:
	ColorShader(ParameterInterpolator *interp, RenderTarget *target)
		:	PixelShader(interp, target)
	{}

	virtual void shadePixels(const vecf16 inParams[16], vecf16 outParams[16],
		unsigned short mask);
};

void ColorShader::shadePixels(const vecf16 inParams[16], vecf16 outParams[16],
	unsigned short mask)
{
	for (int i = 0; i < 3; i++)
		outParams[i] = inParams[i];
}

class CheckerboardShader : public PixelShader
{
public:
	CheckerboardShader(ParameterInterpolator *interp, RenderTarget *target)
		:	PixelShader(interp, target)
	{}

	virtual void shadePixels(const vecf16 inParams[16], vecf16 outParams[16],
		unsigned short mask);
};

void CheckerboardShader::shadePixels(const vecf16 inParams[16], vecf16 outParams[16],
	unsigned short mask)
{
	veci16 u = ((__builtin_vp_vftoi(inParams[0] * __builtin_vp_makevectorf(65535.0)))
		>> __builtin_vp_makevectori(10)) & __builtin_vp_makevectori(1);
	veci16 v = ((__builtin_vp_vftoi(inParams[1] * __builtin_vp_makevectorf(65535.0)))
		>> __builtin_vp_makevectori(10)) & __builtin_vp_makevectori(1);

	veci16 color = u ^ v;

	outParams[0] = outParams[1] = outParams[2] = __builtin_vp_vitof(color);
}

const int kFbWidth = 640;
const int kFbHeight = 480;

//
// All threads start execution here
//
int main()
{
	Rasterizer rasterizer;
	RenderTarget renderTarget(0x100000, kFbWidth, kFbHeight);
	ParameterInterpolator interp(kFbWidth, kFbHeight);
#if COLOR_SHADER
	ColorShader shader(&interp, &renderTarget);
#else
	CheckerboardShader shader(&interp, &renderTarget);
#endif

	Vertex vertices[3] = {
#if COLOR_SHADER
		{ { 0.3, 0.1, 0.5 }, { 1.0, 0.0, 0.0 } },
		{ { 0.9, 0.5, 0.4 }, { 0.0, 1.0, 0.0 } },
		{ { 0.1, 0.9, 0.3 }, { 0.0, 0.0, 1.0 } },
#else
		{ { 0.3, 0.1, 0.6 }, { 0.0, 0.0 } },
		{ { 0.9, 0.5, 0.4 }, { 0.0, 1.0 } },
		{ { 0.1, 0.9, 0.1 }, { 1.0, 1.0 } },
#endif
	};

	while (nextTileIndex < kMaxTileIndex)
	{
		// Grab the next available tile to begin working on.
		int myTileIndex = __sync_fetch_and_add(&nextTileIndex, 1);
		if (myTileIndex >= kMaxTileIndex)
			break;

		unsigned int tileX, tileY;
		udiv(myTileIndex, 10, tileY, tileX);

		interp.setUpTriangle(
			vertices[0].coord[0], vertices[0].coord[1], vertices[0].coord[2],
			vertices[1].coord[0], vertices[1].coord[1], vertices[1].coord[2],
			vertices[2].coord[0], vertices[2].coord[1], vertices[2].coord[2]);

		for (int param = 0; param < 3; param++)
		{
			interp.setUpParam(param, vertices[0].params[param],
				vertices[1].params[param], vertices[2].params[param]);
		}

		// Fill a 64x64 tile
		rasterizer.rasterizeTriangle(&shader, tileX * 64, tileY * 64,
			(int)(vertices[0].coord[0] * kFbWidth),
			(int)(vertices[0].coord[1] * kFbHeight),
			(int)(vertices[1].coord[0] * kFbWidth),
			(int)(vertices[1].coord[1] * kFbHeight),
			(int)(vertices[2].coord[0] * kFbWidth),
			(int)(vertices[2].coord[1] * kFbHeight));
	}

	return 0;
}

Debug Debug::debug;
<commit_msg>Update to use shared geometry buffer<commit_after>//
// Copyright 2013 Jeff Bush
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

#include "Debug.h"
#include "RenderTarget.h"
#include "ParameterInterpolator.h"
#include "Rasterizer.h"
#include "PixelShader.h"
#include "utils.h"

#define COLOR_SHADER 0

const int kMaxTileIndex = (640 / 64) * ((480 / 64) + 1);
int nextTileIndex = 0;

struct Vertex
{
	float coord[3];
	float params[kMaxParams];
};

class ColorShader : public PixelShader
{
public:
	ColorShader(ParameterInterpolator *interp, RenderTarget *target)
		:	PixelShader(interp, target)
	{}

	virtual void shadePixels(const vecf16 inParams[16], vecf16 outParams[16],
		unsigned short mask);
};

void ColorShader::shadePixels(const vecf16 inParams[16], vecf16 outParams[16],
	unsigned short mask)
{
	for (int i = 0; i < 3; i++)
		outParams[i] = inParams[i];
}

class CheckerboardShader : public PixelShader
{
public:
	CheckerboardShader(ParameterInterpolator *interp, RenderTarget *target)
		:	PixelShader(interp, target)
	{}

	virtual void shadePixels(const vecf16 inParams[16], vecf16 outParams[16],
		unsigned short mask);
};

void CheckerboardShader::shadePixels(const vecf16 inParams[16], vecf16 outParams[16],
	unsigned short mask)
{
	veci16 u = ((__builtin_vp_vftoi(inParams[0] * __builtin_vp_makevectorf(65535.0)))
		>> __builtin_vp_makevectori(10)) & __builtin_vp_makevectori(1);
	veci16 v = ((__builtin_vp_vftoi(inParams[1] * __builtin_vp_makevectorf(65535.0)))
		>> __builtin_vp_makevectori(10)) & __builtin_vp_makevectori(1);

	veci16 color = u ^ v;

	outParams[0] = outParams[1] = outParams[2] = __builtin_vp_vitof(color);
}

const int kFbWidth = 640;
const int kFbHeight = 480;

// Hard-coded for now.  This normally would be generated during the geometry phase...
Vertex gVertices[3] = {
#if COLOR_SHADER
	{ { 0.3, 0.1, 0.5 }, { 1.0, 0.0, 0.0 } },
	{ { 0.9, 0.5, 0.4 }, { 0.0, 1.0, 0.0 } },
	{ { 0.1, 0.9, 0.3 }, { 0.0, 0.0, 1.0 } },
#else
	{ { 0.3, 0.1, 0.6 }, { 0.0, 0.0 } },
	{ { 0.9, 0.5, 0.4 }, { 0.0, 1.0 } },
	{ { 0.1, 0.9, 0.1 }, { 1.0, 1.0 } },
#endif
};

int gNumVertices = 1;

//
// All threads start execution here
//
int main()
{
	Rasterizer rasterizer;
	RenderTarget renderTarget(0x100000, kFbWidth, kFbHeight);
	ParameterInterpolator interp(kFbWidth, kFbHeight);
#if COLOR_SHADER
	ColorShader shader(&interp, &renderTarget);
#else
	CheckerboardShader shader(&interp, &renderTarget);
#endif

	while (nextTileIndex < kMaxTileIndex)
	{
		// Grab the next available tile to begin working on.
		int myTileIndex = __sync_fetch_and_add(&nextTileIndex, 1);
		if (myTileIndex >= kMaxTileIndex)
			break;

		unsigned int tileX, tileY;
		udiv(myTileIndex, 10, tileY, tileX);

		// Cycle through all triangles and attempt to render into this
		// 64x64 tile.
		for (int vidx = 0; vidx < gNumVertices; vidx += 3)
		{
			Vertex *vertex = &gVertices[vidx];

			// XXX could do some trivial rejections here for triangles that
			// obviously aren't in this tile.

			interp.setUpTriangle(
				vertex[0].coord[0], vertex[0].coord[1], vertex[0].coord[2],
				vertex[1].coord[0], vertex[1].coord[1], vertex[1].coord[2],
				vertex[2].coord[0], vertex[2].coord[1], vertex[2].coord[2]);

			for (int param = 0; param < 3; param++)
			{
				interp.setUpParam(param, vertex[0].params[param],
					vertex[1].params[param], vertex[2].params[param]);
			}

			rasterizer.rasterizeTriangle(&shader, tileX * 64, tileY * 64,
				(int)(vertex[0].coord[0] * kFbWidth),
				(int)(vertex[0].coord[1] * kFbHeight),
				(int)(vertex[1].coord[0] * kFbWidth),
				(int)(vertex[1].coord[1] * kFbHeight),
				(int)(vertex[2].coord[0] * kFbWidth),
				(int)(vertex[2].coord[1] * kFbHeight));
		}
	}

	return 0;
}

Debug Debug::debug;
<|endoftext|>