<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.                  *
 **************************************************************************/

//---------------------------------------------------------------------
// Jet finder base class
// manages the search for jets
// Author: jgcn@mda.cinvestav.mx
//---------------------------------------------------------------------

#include <Riostream.h>
#include <TFile.h>
#include "AliGenPythiaEventHeader.h"
#include "AliJetFinder.h"
#include "AliJet.h"
#include "AliJetReader.h"
#include "AliJetReaderHeader.h"
#include "AliJetControlPlots.h"
#include "AliLeading.h"
#include "AliHeader.h"

ClassImp(AliJetFinder)

////////////////////////////////////////////////////////////////////////

AliJetFinder::AliJetFinder()
{
  //
  // Constructor
  //
  fOut = 0;
  fJets = new AliJet();
  fGenJets = new AliJet();
  fLeading = new AliLeading();
  fReader = 0;
  fPlots = 0;
  SetPlotMode(kFALSE);
}

////////////////////////////////////////////////////////////////////////

AliJetFinder::~AliJetFinder()
{
  //
  // destructor
  //

  // here reset and delete jets
  fJets->ClearJets();
  delete fJets;
  fGenJets->ClearJets();
  delete fGenJets;
  // close file
  if (fOut) {
    fOut->Close();
    fOut->Delete();
  }
  delete fOut;
  // reset and delete control plots
  if (fPlots) delete fPlots;
  delete fLeading;
}

////////////////////////////////////////////////////////////////////////

void AliJetFinder::SetOutputFile(const char *name)
{
  // opens output file
  fOut = new TFile(name,"recreate");
}

////////////////////////////////////////////////////////////////////////

void AliJetFinder::PrintJets()
{
//
// Print jet information
  cout << " Jets found with jet algorithm:" << endl;
  fJets->PrintJets();
  cout << " Jets found by pythia:" << endl;
  fGenJets->PrintJets();
}

////////////////////////////////////////////////////////////////////////

void AliJetFinder::SetPlotMode(Bool_t b)
{
// Sets the plotting mode
  fPlotMode=b;
  if (b && !fPlots) fPlots = new AliJetControlPlots();
}

////////////////////////////////////////////////////////////////////////

void AliJetFinder::WriteJetsToFile(Int_t i)
{
// Writes the jets to file
  fOut->cd();
  char hname[30];
  sprintf(hname,"TreeJ%d",i);
  TTree* jetT = new TTree(hname,"AliJet");
  jetT->Branch("FoundJet",&fJets,1000);
  jetT->Branch("GenJet",&fGenJets,1000);
  jetT->Branch("LeadingPart",&fLeading,1000);
  jetT->Fill();
  jetT->Write(hname);
  delete jetT;
}

////////////////////////////////////////////////////////////////////////

void AliJetFinder::WriteRHeaderToFile()
{
  // write reader header
  fOut->cd();
  AliJetReaderHeader *rh = fReader->GetReaderHeader();
  rh->Write();
}

////////////////////////////////////////////////////////////////////////

void AliJetFinder::GetGenJets()
{
// Get the generated jet information from mc header
  fGenJets->SetNinput(1);
  AliHeader* alih = fReader->GetAliHeader();
  if (alih == 0) return;
  AliGenEventHeader * genh = alih->GenEventHeader();
  if (genh == 0) return;
  Int_t nj =((AliGenPythiaEventHeader*)genh)->NTriggerJets();
  Int_t* m = new Int_t[nj];
  Int_t* k = new Int_t[nj];
  for (Int_t i=0; i< nj; i++) {
    Float_t p[4];
    ((AliGenPythiaEventHeader*)genh)->TriggerJet(i,p);
    fGenJets->AddJet(p[0],p[1],p[2],p[3]);
    m[i]=1;
    k[i]=i;
  }
  fGenJets->SetMultiplicities(m);
  fGenJets->SetInJet(k);
}

////////////////////////////////////////////////////////////////////////

void AliJetFinder::Run()
{
  // do some initialization
  Init();

  // connect files
  fReader->OpenInputFiles();

  // write headers
  if (fOut) {
      fOut->cd();
      WriteRHeaderToFile();
      WriteJHeaderToFile();
  }

  // loop over events
  Int_t nFirst,nLast;
  nFirst = fReader->GetReaderHeader()->GetFirstEvent();
  nLast = fReader->GetReaderHeader()->GetLastEvent();
  // loop over events
  for (Int_t i=nFirst;i<nLast;i++) {
      fReader->FillMomentumArray(i);
      fLeading->FindLeading(fReader);
      GetGenJets();
      FindJets();
      if (fOut) WriteJetsToFile(i);
      if (fPlots) fPlots->FillHistos(fJets,fReader);
      fLeading->Reset();
      fGenJets->ClearJets();
      Reset();
  }
  // write out
  if (fPlots) {
      fPlots->Normalize();
      fPlots->PlotHistos();
  }
  if (fOut) {
      fOut->cd();
      fPlots->Write();
      fOut->Close();
  }
}

<commit_msg>Destructor changed (G. Contreras)<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.                  *
 **************************************************************************/

//---------------------------------------------------------------------
// Jet finder base class
// manages the search for jets
// Author: jgcn@mda.cinvestav.mx
//---------------------------------------------------------------------

#include <Riostream.h>
#include <TFile.h>
#include "AliGenPythiaEventHeader.h"
#include "AliJetFinder.h"
#include "AliJet.h"
#include "AliJetReader.h"
#include "AliJetReaderHeader.h"
#include "AliJetControlPlots.h"
#include "AliLeading.h"
#include "AliHeader.h"

ClassImp(AliJetFinder)

////////////////////////////////////////////////////////////////////////

AliJetFinder::AliJetFinder()
{
  //
  // Constructor
  //
  fOut = 0;
  fJets = new AliJet();
  fGenJets = new AliJet();
  fLeading = new AliLeading();
  fReader = 0;
  fPlots = 0;
  SetPlotMode(kFALSE);
}

////////////////////////////////////////////////////////////////////////

AliJetFinder::~AliJetFinder()
{
  //
  // destructor
  //

  // here reset and delete jets
  fJets->ClearJets();
  delete fJets;
  fGenJets->ClearJets();
  delete fGenJets;
  // close file
  if (fOut) {
    fOut->Close();
    fOut->Delete();
  }
  delete fOut;
  // reset and delete control plots
  if (fPlots) delete fPlots;
  // delete fLeading;
}

////////////////////////////////////////////////////////////////////////

void AliJetFinder::SetOutputFile(const char *name)
{
  // opens output file
  fOut = new TFile(name,"recreate");
}

////////////////////////////////////////////////////////////////////////

void AliJetFinder::PrintJets()
{
//
// Print jet information
  cout << " Jets found with jet algorithm:" << endl;
  fJets->PrintJets();
  cout << " Jets found by pythia:" << endl;
  fGenJets->PrintJets();
}

////////////////////////////////////////////////////////////////////////

void AliJetFinder::SetPlotMode(Bool_t b)
{
// Sets the plotting mode
  fPlotMode=b;
  if (b && !fPlots) fPlots = new AliJetControlPlots();
}

////////////////////////////////////////////////////////////////////////

void AliJetFinder::WriteJetsToFile(Int_t i)
{
// Writes the jets to file
  fOut->cd();
  char hname[30];
  sprintf(hname,"TreeJ%d",i);
  TTree* jetT = new TTree(hname,"AliJet");
  jetT->Branch("FoundJet",&fJets,1000);
  jetT->Branch("GenJet",&fGenJets,1000);
  jetT->Branch("LeadingPart",&fLeading,1000);
  jetT->Fill();
  jetT->Write(hname);
  delete jetT;
}

////////////////////////////////////////////////////////////////////////

void AliJetFinder::WriteRHeaderToFile()
{
  // write reader header
  fOut->cd();
  AliJetReaderHeader *rh = fReader->GetReaderHeader();
  rh->Write();
}

////////////////////////////////////////////////////////////////////////

void AliJetFinder::GetGenJets()
{
// Get the generated jet information from mc header
  fGenJets->SetNinput(1);
  AliHeader* alih = fReader->GetAliHeader();
  if (alih == 0) return;
  AliGenEventHeader * genh = alih->GenEventHeader();
  if (genh == 0) return;
  Int_t nj =((AliGenPythiaEventHeader*)genh)->NTriggerJets();
  Int_t* m = new Int_t[nj];
  Int_t* k = new Int_t[nj];
  for (Int_t i=0; i< nj; i++) {
    Float_t p[4];
    ((AliGenPythiaEventHeader*)genh)->TriggerJet(i,p);
    fGenJets->AddJet(p[0],p[1],p[2],p[3]);
    m[i]=1;
    k[i]=i;
  }
  fGenJets->SetMultiplicities(m);
  fGenJets->SetInJet(k);
}

////////////////////////////////////////////////////////////////////////

void AliJetFinder::Run()
{
  // do some initialization
  Init();

  // connect files
  fReader->OpenInputFiles();

  // write headers
  if (fOut) {
      fOut->cd();
      WriteRHeaderToFile();
      WriteJHeaderToFile();
  }

  // loop over events
  Int_t nFirst,nLast;
  nFirst = fReader->GetReaderHeader()->GetFirstEvent();
  nLast = fReader->GetReaderHeader()->GetLastEvent();
  // loop over events
  for (Int_t i=nFirst;i<nLast;i++) {
      fReader->FillMomentumArray(i);
      fLeading->FindLeading(fReader);
      GetGenJets();
      FindJets();
      if (fOut) WriteJetsToFile(i);
      if (fPlots) fPlots->FillHistos(fJets,fReader);
      fLeading->Reset();
      fGenJets->ClearJets();
      Reset();
  }
  // write out
  if (fPlots) {
      fPlots->Normalize();
      fPlots->PlotHistos();
  }
  if (fOut) {
      fOut->cd();
      fPlots->Write();
      fOut->Close();
  }
}

<|endoftext|>


<commit_before>/*********************************************************************
 * Software License Agreement (BSD License)
 *
 *  Copyright (c) 2011, Willow Garage, Inc.
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer in the documentation and/or other materials provided
 *     with the distribution.
 *   * Neither the name of the Willow Garage nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *  POSSIBILITY OF SUCH DAMAGE.
 *********************************************************************/

/* Author Ioan Sucan */

#include "collision_detection_fcl/collision_world.h"
#include <fcl/geometric_shape_to_BVH_model.h>
#include <fcl/traversal_node_bvhs.h>
#include <fcl/simple_setup.h>
#include <fcl/collision_node.h>
#include <ros/console.h>

collision_detection::CollisionWorldFCL::CollisionWorldFCL(void) : CollisionWorld()
{
  fcl::DynamicAABBTreeCollisionManager* m = new fcl::DynamicAABBTreeCollisionManager();
  // m->tree_init_level = 2;
  manager_.reset(m);
}

collision_detection::CollisionWorldFCL::CollisionWorldFCL(const CollisionWorldFCL &other) : CollisionWorld(other)
{
  fcl::DynamicAABBTreeCollisionManager* m = new fcl::DynamicAABBTreeCollisionManager();
  // m->tree_init_level = 2;
  manager_.reset(m);

  fcl_objs_ = other.fcl_objs_;
  for (std::map<std::string, FCLObject>::iterator it = fcl_objs_.begin() ; it != fcl_objs_.end() ; ++it)
    it->second.registerTo(manager_.get());
  // manager_->update();
}

collision_detection::CollisionWorldFCL::~CollisionWorldFCL(void)
{
}

void collision_detection::CollisionWorldFCL::checkRobotCollision(const CollisionRequest &req, CollisionResult &res, const CollisionRobot &robot, const planning_models::KinematicState &state) const
{
  checkRobotCollisionHelper(req, res, robot, state, NULL);
}

void collision_detection::CollisionWorldFCL::checkRobotCollision(const CollisionRequest &req, CollisionResult &res, const CollisionRobot &robot, const planning_models::KinematicState &state, const AllowedCollisionMatrix &acm) const
{
  checkRobotCollisionHelper(req, res, robot, state, &acm);
}

void collision_detection::CollisionWorldFCL::checkRobotCollision(const CollisionRequest &req, CollisionResult &res, const CollisionRobot &robot, const planning_models::KinematicState &state1, const planning_models::KinematicState &state2) const
{
  ROS_ERROR("FCL continuous collision checking not yet implemented");
}

void collision_detection::CollisionWorldFCL::checkRobotCollision(const CollisionRequest &req, CollisionResult &res, const CollisionRobot &robot, const planning_models::KinematicState &state1, const planning_models::KinematicState &state2, const AllowedCollisionMatrix &acm) const
{
  ROS_ERROR("FCL continuous collision checking not yet implemented");
}

void collision_detection::CollisionWorldFCL::checkRobotCollisionHelper(const CollisionRequest &req, CollisionResult &res, const CollisionRobot &robot, const planning_models::KinematicState &state, const AllowedCollisionMatrix *acm) const
{
  const CollisionRobotFCL &robot_fcl = dynamic_cast<const CollisionRobotFCL&>(robot);
  FCLObject fcl_obj;
  robot_fcl.constructFCLObject(state, fcl_obj);

  CollisionData cd(&req, &res, acm);
  cd.enableGroup(robot.getKinematicModel());
  for (std::size_t i = 0 ; !cd.done_ && i < fcl_obj.collision_objects_.size() ; ++i)
    manager_->collide(fcl_obj.collision_objects_[i].get(), &cd, &collisionCallback);

  if (req.distance)
    res.distance = distanceRobotHelper(robot, state, acm);
}

void collision_detection::CollisionWorldFCL::checkWorldCollision(const CollisionRequest &req, CollisionResult &res, const CollisionWorld &other_world) const
{
  checkWorldCollisionHelper(req, res, other_world, NULL);
}

void collision_detection::CollisionWorldFCL::checkWorldCollision(const CollisionRequest &req, CollisionResult &res, const CollisionWorld &other_world, const AllowedCollisionMatrix &acm) const
{
  checkWorldCollisionHelper(req, res, other_world, &acm);
}

void collision_detection::CollisionWorldFCL::checkWorldCollisionHelper(const CollisionRequest &req, CollisionResult &res, const CollisionWorld &other_world, const AllowedCollisionMatrix *acm) const
{
  const CollisionWorldFCL &other_fcl_world = dynamic_cast<const CollisionWorldFCL&>(other_world);
  CollisionData cd(&req, &res, acm);
  manager_->collide(other_fcl_world.manager_.get(), &cd, &collisionCallback);

  if (req.distance)
    res.distance = distanceWorldHelper(other_world, acm);
}

void collision_detection::CollisionWorldFCL::constructFCLObject(const Object *obj, FCLObject &fcl_obj) const
{
  for (std::size_t i = 0 ; i < obj->shapes_.size() ; ++i)
  {
    FCLGeometryConstPtr g = createCollisionGeometry(obj->shapes_[i], obj);
    if (g)
    {
      fcl::CollisionObject *co = new fcl::CollisionObject(g->collision_geometry_,  transform2fcl(obj->shape_poses_[i]));
      fcl_obj.collision_objects_.push_back(boost::shared_ptr<fcl::CollisionObject>(co));
      fcl_obj.collision_geometry_.push_back(g);
    }
  }
}

void collision_detection::CollisionWorldFCL::updateFCLObject(const std::string &id)
{
  // remove FCL objects that correspond to this object
  std::map<std::string, FCLObject>::iterator jt = fcl_objs_.find(id);
  if (jt != fcl_objs_.end())
  {
    jt->second.unregisterFrom(manager_.get());
    jt->second.clear();
  }

  // check to see if we have this object
  std::map<std::string, ObjectPtr>::iterator it = objects_.find(id);
  if (it != objects_.end())
  {
    // construct FCL objects that correspond to this object
    if (jt != fcl_objs_.end())
    {
      constructFCLObject(it->second.get(), jt->second);
      jt->second.registerTo(manager_.get());
    }
    else
    {
      constructFCLObject(it->second.get(), fcl_objs_[id]);
      fcl_objs_[id].registerTo(manager_.get());
    }
  }
  else
  {
    if (jt != fcl_objs_.end())
      fcl_objs_.erase(jt);
  }

  // manager_->update();
}

void collision_detection::CollisionWorldFCL::addToObject(const std::string &id, const std::vector<shapes::ShapeConstPtr> &shapes, const std::vector<Eigen::Affine3d> &poses)
{
  CollisionWorld::addToObject(id, shapes, poses);
  updateFCLObject(id);
}

void collision_detection::CollisionWorldFCL::addToObject(const std::string &id, const shapes::ShapeConstPtr &shape, const Eigen::Affine3d &pose)
{
  CollisionWorld::addToObject(id, shape, pose);
  updateFCLObject(id);
}

bool collision_detection::CollisionWorldFCL::moveShapeInObject(const std::string &id, const shapes::ShapeConstPtr &shape, const Eigen::Affine3d &pose)
{
  if (CollisionWorld::moveShapeInObject(id, shape, pose))
  {
    updateFCLObject(id);
    return true;
  }
  else
    return false;
}

bool collision_detection::CollisionWorldFCL::removeShapeFromObject(const std::string &id, const shapes::ShapeConstPtr &shape)
{
  if (CollisionWorld::removeShapeFromObject(id, shape))
  {
    updateFCLObject(id);
    return true;
  }
  else
    return false;
}

void collision_detection::CollisionWorldFCL::removeObject(const std::string &id)
{
  CollisionWorld::removeObject(id);
  std::map<std::string, FCLObject>::iterator it = fcl_objs_.find(id);
  if (it != fcl_objs_.end())
  {
    it->second.unregisterFrom(manager_.get());
    it->second.clear();
    fcl_objs_.erase(it);
    // manager_->update();
  }
}

void collision_detection::CollisionWorldFCL::clearObjects(void)
{
  CollisionWorld::clearObjects();
  manager_->clear();
  fcl_objs_.clear();
}

double collision_detection::CollisionWorldFCL::distanceRobotHelper(const CollisionRobot &robot, const planning_models::KinematicState &state, const AllowedCollisionMatrix *acm) const
{
  const CollisionRobotFCL& robot_fcl = dynamic_cast<const CollisionRobotFCL&>(robot);
  FCLObject fcl_obj;
  robot_fcl.constructFCLObject(state, fcl_obj);

  CollisionRequest req;
  CollisionResult res;
  CollisionData cd(&req, &res, acm);
  cd.enableGroup(robot.getKinematicModel());

  for(std::size_t i = 0; !cd.done_ && i < fcl_obj.collision_objects_.size(); ++i)
    manager_->distance(fcl_obj.collision_objects_[i].get(), &cd, &distanceCallback);

  return res.distance;
}

double collision_detection::CollisionWorldFCL::distanceRobot(const CollisionRobot &robot, const planning_models::KinematicState &state) const
{
  return distanceRobotHelper(robot, state, NULL);
}

double collision_detection::CollisionWorldFCL::distanceRobot(const CollisionRobot &robot, const planning_models::KinematicState &state, const AllowedCollisionMatrix &acm) const
{
  return distanceRobotHelper(robot, state, &acm);
}

double collision_detection::CollisionWorldFCL::distanceWorld(const CollisionWorld &world) const
{
  return distanceWorldHelper(world, NULL);
}

double collision_detection::CollisionWorldFCL::distanceWorld(const CollisionWorld &world, const AllowedCollisionMatrix &acm) const
{
  return distanceWorldHelper(world, &acm);
}

double collision_detection::CollisionWorldFCL::distanceWorldHelper(const CollisionWorld &other_world, const AllowedCollisionMatrix *acm) const
{
  const CollisionWorldFCL& other_fcl_world = dynamic_cast<const CollisionWorldFCL&>(other_world);
  CollisionRequest req;
  CollisionResult res;
  CollisionData cd(&req, &res, acm);
  manager_->distance(other_fcl_world.manager_.get(), &cd, &distanceCallback);

  return res.distance;
}
<commit_msg>change according to change in fcl's change of file name<commit_after>/*********************************************************************
 * Software License Agreement (BSD License)
 *
 *  Copyright (c) 2011, Willow Garage, Inc.
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer in the documentation and/or other materials provided
 *     with the distribution.
 *   * Neither the name of the Willow Garage nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *  POSSIBILITY OF SUCH DAMAGE.
 *********************************************************************/

/* Author Ioan Sucan */

#include "collision_detection_fcl/collision_world.h"
#include <fcl/geometric_shape_to_BVH_model.h>
#include <fcl/traversal_node_bvhs.h>
#include <fcl/traversal_node_setup.h>
#include <fcl/collision_node.h>
#include <ros/console.h>

collision_detection::CollisionWorldFCL::CollisionWorldFCL(void) : CollisionWorld()
{
  fcl::DynamicAABBTreeCollisionManager* m = new fcl::DynamicAABBTreeCollisionManager();
  // m->tree_init_level = 2;
  manager_.reset(m);
}

collision_detection::CollisionWorldFCL::CollisionWorldFCL(const CollisionWorldFCL &other) : CollisionWorld(other)
{
  fcl::DynamicAABBTreeCollisionManager* m = new fcl::DynamicAABBTreeCollisionManager();
  // m->tree_init_level = 2;
  manager_.reset(m);

  fcl_objs_ = other.fcl_objs_;
  for (std::map<std::string, FCLObject>::iterator it = fcl_objs_.begin() ; it != fcl_objs_.end() ; ++it)
    it->second.registerTo(manager_.get());
  // manager_->update();
}

collision_detection::CollisionWorldFCL::~CollisionWorldFCL(void)
{
}

void collision_detection::CollisionWorldFCL::checkRobotCollision(const CollisionRequest &req, CollisionResult &res, const CollisionRobot &robot, const planning_models::KinematicState &state) const
{
  checkRobotCollisionHelper(req, res, robot, state, NULL);
}

void collision_detection::CollisionWorldFCL::checkRobotCollision(const CollisionRequest &req, CollisionResult &res, const CollisionRobot &robot, const planning_models::KinematicState &state, const AllowedCollisionMatrix &acm) const
{
  checkRobotCollisionHelper(req, res, robot, state, &acm);
}

void collision_detection::CollisionWorldFCL::checkRobotCollision(const CollisionRequest &req, CollisionResult &res, const CollisionRobot &robot, const planning_models::KinematicState &state1, const planning_models::KinematicState &state2) const
{
  ROS_ERROR("FCL continuous collision checking not yet implemented");
}

void collision_detection::CollisionWorldFCL::checkRobotCollision(const CollisionRequest &req, CollisionResult &res, const CollisionRobot &robot, const planning_models::KinematicState &state1, const planning_models::KinematicState &state2, const AllowedCollisionMatrix &acm) const
{
  ROS_ERROR("FCL continuous collision checking not yet implemented");
}

void collision_detection::CollisionWorldFCL::checkRobotCollisionHelper(const CollisionRequest &req, CollisionResult &res, const CollisionRobot &robot, const planning_models::KinematicState &state, const AllowedCollisionMatrix *acm) const
{
  const CollisionRobotFCL &robot_fcl = dynamic_cast<const CollisionRobotFCL&>(robot);
  FCLObject fcl_obj;
  robot_fcl.constructFCLObject(state, fcl_obj);

  CollisionData cd(&req, &res, acm);
  cd.enableGroup(robot.getKinematicModel());
  for (std::size_t i = 0 ; !cd.done_ && i < fcl_obj.collision_objects_.size() ; ++i)
    manager_->collide(fcl_obj.collision_objects_[i].get(), &cd, &collisionCallback);

  if (req.distance)
    res.distance = distanceRobotHelper(robot, state, acm);
}

void collision_detection::CollisionWorldFCL::checkWorldCollision(const CollisionRequest &req, CollisionResult &res, const CollisionWorld &other_world) const
{
  checkWorldCollisionHelper(req, res, other_world, NULL);
}

void collision_detection::CollisionWorldFCL::checkWorldCollision(const CollisionRequest &req, CollisionResult &res, const CollisionWorld &other_world, const AllowedCollisionMatrix &acm) const
{
  checkWorldCollisionHelper(req, res, other_world, &acm);
}

void collision_detection::CollisionWorldFCL::checkWorldCollisionHelper(const CollisionRequest &req, CollisionResult &res, const CollisionWorld &other_world, const AllowedCollisionMatrix *acm) const
{
  const CollisionWorldFCL &other_fcl_world = dynamic_cast<const CollisionWorldFCL&>(other_world);
  CollisionData cd(&req, &res, acm);
  manager_->collide(other_fcl_world.manager_.get(), &cd, &collisionCallback);

  if (req.distance)
    res.distance = distanceWorldHelper(other_world, acm);
}

void collision_detection::CollisionWorldFCL::constructFCLObject(const Object *obj, FCLObject &fcl_obj) const
{
  for (std::size_t i = 0 ; i < obj->shapes_.size() ; ++i)
  {
    FCLGeometryConstPtr g = createCollisionGeometry(obj->shapes_[i], obj);
    if (g)
    {
      fcl::CollisionObject *co = new fcl::CollisionObject(g->collision_geometry_,  transform2fcl(obj->shape_poses_[i]));
      fcl_obj.collision_objects_.push_back(boost::shared_ptr<fcl::CollisionObject>(co));
      fcl_obj.collision_geometry_.push_back(g);
    }
  }
}

void collision_detection::CollisionWorldFCL::updateFCLObject(const std::string &id)
{
  // remove FCL objects that correspond to this object
  std::map<std::string, FCLObject>::iterator jt = fcl_objs_.find(id);
  if (jt != fcl_objs_.end())
  {
    jt->second.unregisterFrom(manager_.get());
    jt->second.clear();
  }

  // check to see if we have this object
  std::map<std::string, ObjectPtr>::iterator it = objects_.find(id);
  if (it != objects_.end())
  {
    // construct FCL objects that correspond to this object
    if (jt != fcl_objs_.end())
    {
      constructFCLObject(it->second.get(), jt->second);
      jt->second.registerTo(manager_.get());
    }
    else
    {
      constructFCLObject(it->second.get(), fcl_objs_[id]);
      fcl_objs_[id].registerTo(manager_.get());
    }
  }
  else
  {
    if (jt != fcl_objs_.end())
      fcl_objs_.erase(jt);
  }

  // manager_->update();
}

void collision_detection::CollisionWorldFCL::addToObject(const std::string &id, const std::vector<shapes::ShapeConstPtr> &shapes, const std::vector<Eigen::Affine3d> &poses)
{
  CollisionWorld::addToObject(id, shapes, poses);
  updateFCLObject(id);
}

void collision_detection::CollisionWorldFCL::addToObject(const std::string &id, const shapes::ShapeConstPtr &shape, const Eigen::Affine3d &pose)
{
  CollisionWorld::addToObject(id, shape, pose);
  updateFCLObject(id);
}

bool collision_detection::CollisionWorldFCL::moveShapeInObject(const std::string &id, const shapes::ShapeConstPtr &shape, const Eigen::Affine3d &pose)
{
  if (CollisionWorld::moveShapeInObject(id, shape, pose))
  {
    updateFCLObject(id);
    return true;
  }
  else
    return false;
}

bool collision_detection::CollisionWorldFCL::removeShapeFromObject(const std::string &id, const shapes::ShapeConstPtr &shape)
{
  if (CollisionWorld::removeShapeFromObject(id, shape))
  {
    updateFCLObject(id);
    return true;
  }
  else
    return false;
}

void collision_detection::CollisionWorldFCL::removeObject(const std::string &id)
{
  CollisionWorld::removeObject(id);
  std::map<std::string, FCLObject>::iterator it = fcl_objs_.find(id);
  if (it != fcl_objs_.end())
  {
    it->second.unregisterFrom(manager_.get());
    it->second.clear();
    fcl_objs_.erase(it);
    // manager_->update();
  }
}

void collision_detection::CollisionWorldFCL::clearObjects(void)
{
  CollisionWorld::clearObjects();
  manager_->clear();
  fcl_objs_.clear();
}

double collision_detection::CollisionWorldFCL::distanceRobotHelper(const CollisionRobot &robot, const planning_models::KinematicState &state, const AllowedCollisionMatrix *acm) const
{
  const CollisionRobotFCL& robot_fcl = dynamic_cast<const CollisionRobotFCL&>(robot);
  FCLObject fcl_obj;
  robot_fcl.constructFCLObject(state, fcl_obj);

  CollisionRequest req;
  CollisionResult res;
  CollisionData cd(&req, &res, acm);
  cd.enableGroup(robot.getKinematicModel());

  for(std::size_t i = 0; !cd.done_ && i < fcl_obj.collision_objects_.size(); ++i)
    manager_->distance(fcl_obj.collision_objects_[i].get(), &cd, &distanceCallback);

  return res.distance;
}

double collision_detection::CollisionWorldFCL::distanceRobot(const CollisionRobot &robot, const planning_models::KinematicState &state) const
{
  return distanceRobotHelper(robot, state, NULL);
}

double collision_detection::CollisionWorldFCL::distanceRobot(const CollisionRobot &robot, const planning_models::KinematicState &state, const AllowedCollisionMatrix &acm) const
{
  return distanceRobotHelper(robot, state, &acm);
}

double collision_detection::CollisionWorldFCL::distanceWorld(const CollisionWorld &world) const
{
  return distanceWorldHelper(world, NULL);
}

double collision_detection::CollisionWorldFCL::distanceWorld(const CollisionWorld &world, const AllowedCollisionMatrix &acm) const
{
  return distanceWorldHelper(world, &acm);
}

double collision_detection::CollisionWorldFCL::distanceWorldHelper(const CollisionWorld &other_world, const AllowedCollisionMatrix *acm) const
{
  const CollisionWorldFCL& other_fcl_world = dynamic_cast<const CollisionWorldFCL&>(other_world);
  CollisionRequest req;
  CollisionResult res;
  CollisionData cd(&req, &res, acm);
  manager_->distance(other_fcl_world.manager_.get(), &cd, &distanceCallback);

  return res.distance;
}
<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- vim:set ts=4 sw=4 sts=4 noet: */
#include "compiler.hh"

#include <cstdlib>
#include <cstdio>
#include <fstream>

#include "compiler/bcc.h"
#include "compiler/sort.h"
#include "compiler/tac.h"
#include "db/driver.hh"
#include "method.hh"

using std::cerr;
using std::endl;

namespace flint {
namespace compiler {

bool Compile(sqlite3 *db, const char *table, Method method, const char *output)
{
	db::Driver tmp(":memory:");
	switch (method) {
	case Method::kAssign:
		if (!method::Assign(db, table, tmp.db()))
			return false;
		break;
	case Method::kEuler:
		if (!method::Euler(db, table, tmp.db()))
			return false;
		break;
	case Method::kEvent:
		if (!method::Event(db, table, tmp.db()))
			return false;
		break;
	case Method::kRk4:
		if (!method::Rk4(db, table, tmp.db()))
			return false;
		break;
	}
	if (!compiler::sort::Sort(tmp.db()))
		return false;
	if (!compiler::tac::Tac(tmp.db()))
		return false;
	std::ofstream ofs(output, std::ios::binary);
	if (!ofs) {
		cerr << "failed to open " << output << endl;
		return false;
	}
	bool r = compiler::bcc::Bcc(tmp.db(), &ofs);
	ofs.close();
	return r;
}

bool GenerateBytecode(sqlite3 *db, const char *output)
{
	if (!compiler::sort::Sort(db))
		return false;
	if (!compiler::tac::Tac(db))
		return false;
	std::ofstream ofs(output, std::ios::binary);
	if (!ofs) {
		cerr << "failed to open " << output << endl;
		return false;
	}
	bool r = compiler::bcc::Bcc(db, &ofs);
	ofs.close();
	return r;
}

}
}
<commit_msg>Replace duplicate code with a function call<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- vim:set ts=4 sw=4 sts=4 noet: */
#include "compiler.hh"

#include <cstdlib>
#include <cstdio>
#include <fstream>

#include "compiler/bcc.h"
#include "compiler/sort.h"
#include "compiler/tac.h"
#include "db/driver.hh"
#include "method.hh"

using std::cerr;
using std::endl;

namespace flint {
namespace compiler {

bool Compile(sqlite3 *db, const char *table, Method method, const char *output)
{
	db::Driver tmp(":memory:");
	switch (method) {
	case Method::kAssign:
		if (!method::Assign(db, table, tmp.db()))
			return false;
		break;
	case Method::kEuler:
		if (!method::Euler(db, table, tmp.db()))
			return false;
		break;
	case Method::kEvent:
		if (!method::Event(db, table, tmp.db()))
			return false;
		break;
	case Method::kRk4:
		if (!method::Rk4(db, table, tmp.db()))
			return false;
		break;
	}
	return GenerateBytecode(tmp.db(), output);
}

bool GenerateBytecode(sqlite3 *db, const char *output)
{
	if (!compiler::sort::Sort(db))
		return false;
	if (!compiler::tac::Tac(db))
		return false;
	std::ofstream ofs(output, std::ios::binary);
	if (!ofs) {
		cerr << "failed to open " << output << endl;
		return false;
	}
	bool r = compiler::bcc::Bcc(db, &ofs);
	ofs.close();
	return r;
}

}
}
<|endoftext|>


<commit_before>//
//  bootstrap.cpp
//  Parse
//
//  Created by Andrew Hunter on 21/05/2011.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#include "bootstrap.h"

#include "Dfa/ndfa_regex.h"
#include "ContextFree/item.h"
#include "Lr/weak_symbols.h"
#include "Lr/ignored_symbols.h"
#include "Lr/lalr_builder.h"

using namespace dfa;
using namespace contextfree;
using namespace lr;
using namespace language;

/// \brief Adds a new terminal item to an NDFA, and to this object
contextfree::item_container bootstrap::add_terminal(dfa::ndfa_regex* ndfa, const std::wstring& name, const std::wstring& regex) {
    // Add to the terminal dictionary
    int termIdentifier = m_Terminals.symbol_for_name(name);

    if (termIdentifier == -1) {
        termIdentifier = m_Terminals.add_symbol(name);
    }

    // Add to the DFA
    ndfa->add_regex(0, regex, termIdentifier);

    // Return a new container
    return item_container(new terminal(termIdentifier), true);
}

/// \brief Creates the lexer for the language
dfa::ndfa* bootstrap::create_dfa() {
    // Create the NDFA (which we'll eventually turn into the lexer)
    ndfa_regex* languageNdfa = new ndfa_regex();

    // The weak keywords
    t.language          = add_terminal(languageNdfa, L"language", L"language");
    t.grammar           = add_terminal(languageNdfa, L"grammar", L"grammar");
    t.lexersymbols      = add_terminal(languageNdfa, L"lexer-symbols", L"lexer-symbols");
    t.lexer             = add_terminal(languageNdfa, L"lexer", L"lexer");
    t.weaklexer         = add_terminal(languageNdfa, L"weaklexer", L"weaklexer");
    t.ignore            = add_terminal(languageNdfa, L"ignore", L"ignore");
    t.keywords          = add_terminal(languageNdfa, L"keywords", L"keywords");

    // Single character elements (these are also weak)
	t.equals            = add_terminal(languageNdfa, L"'='", L"\\=");
    t.question          = add_terminal(languageNdfa, L"'?'", L"\\?");
    t.plus              = add_terminal(languageNdfa, L"'+'", L"\\+");
    t.star              = add_terminal(languageNdfa, L"'*'", L"\\*");
    t.colon             = add_terminal(languageNdfa, L"':'", L"\\:");
    t.openparen         = add_terminal(languageNdfa, L"'('", L"\\(");
    t.closeparen        = add_terminal(languageNdfa, L"')'", L"\\)");
    t.opencurly         = add_terminal(languageNdfa, L"'{'", L"\\{");
    t.closecurly        = add_terminal(languageNdfa, L"'}'", L"\\}");
    t.dot               = add_terminal(languageNdfa, L"'.'", L"\\.");
    t.pipe              = add_terminal(languageNdfa, L"'|'", L"\\|");

    // The lexical constructs
    t.identifier        = add_terminal(languageNdfa, L"identifier", L"[A-Za-z\\-][A-Za-z\\-0-9]*");
    t.nonterminal       = add_terminal(languageNdfa, L"nonterminal", L"\\<[A-Za-z\\-][A-Za-z\\-0-9]*\\>");
    t.regex             = add_terminal(languageNdfa, L"regex", L"/([^/]|(\\\\/))*/");
    t.string            = add_terminal(languageNdfa, L"string", L"\"([^\"]|(\\\"))*\"");
    t.character         = add_terminal(languageNdfa, L"character", L"'(.|(\\.))'");

    // Ignored elements
    t.newline           = add_terminal(languageNdfa, L"newline", L"[\n\r]");
    t.whitespace        = add_terminal(languageNdfa, L"whitespace", L"[ ]");
    t.comment           = add_terminal(languageNdfa, L"comment", L"//[^\n\r]*");

    // Build into a DFA
    ndfa* uniqueSyms = languageNdfa->to_ndfa_with_unique_symbols();
    delete languageNdfa;

    ndfa* result = uniqueSyms->to_dfa();
    delete uniqueSyms;

    return result;
}

/// \brief Creates the grammar for the language
contextfree::grammar* bootstrap::create_grammar() {
    // Create a new grammar
    grammar* result = new grammar();

    // Generate nonterminals
    nt.parser_language          = result->get_nonterminal(L"Parser-Language");
    nt.toplevel_block           = result->get_nonterminal(L"TopLevel-Block");
    nt.language_block           = result->get_nonterminal(L"Language-Block");
    nt.language_inherits        = result->get_nonterminal(L"Language-Inherits");
    nt.language_definition      = result->get_nonterminal(L"Language-Definition");
    nt.lexer_symbols_definition = result->get_nonterminal(L"Lexer-Symbols-Definition");
    nt.lexer_definition         = result->get_nonterminal(L"Lexer-Definition");
    nt.ignore_definition        = result->get_nonterminal(L"Ignore-Definition");
    nt.keywords_definition      = result->get_nonterminal(L"Keywords-Definition");
    nt.keyword_definition       = result->get_nonterminal(L"Keyword-Definition");
    nt.weak_symbols_definition  = result->get_nonterminal(L"Weak-Symbols-Definition");
    nt.lexeme_definition        = result->get_nonterminal(L"Lexeme-Definition");
    nt.grammar_definition       = result->get_nonterminal(L"Grammar-Definition");
    nt.nonterminal_definition   = result->get_nonterminal(L"Nonterminal-Definition");
    nt.production               = result->get_nonterminal(L"Production");
    nt.ebnf_item                = result->get_nonterminal(L"Ebnf-Item");
    nt.simple_ebnf_item         = result->get_nonterminal(L"Simple-Ebnf-Item");
    nt.nonterminal              = result->get_nonterminal(L"Nonterminal");
    nt.terminal                 = result->get_nonterminal(L"Terminal");
    nt.basic_terminal           = result->get_nonterminal(L"Basic-Terminal");

    // Generate productions
    ebnf_repeating_optional listToplevel;
    (*listToplevel.get_rule()) << nt.toplevel_block;
    ((*result) += L"Parser-Language") << listToplevel;

    // Top level block (language)
    ((*result) += L"TopLevel-Block") << nt.language_block;

    // Language block ('language x (: y) { ... }
    ebnf_optional           optionalLanguageInherits;
    ebnf_repeating_optional listLanguageDefinition;
    (*optionalLanguageInherits.get_rule()) << nt.language_inherits;
    (*listLanguageDefinition.get_rule()) << nt.language_definition;
    ((*result) += L"Language-Block") << t.language << t.identifier << optionalLanguageInherits << t.opencurly << listLanguageDefinition << t.closecurly;

    ((*result) += L"Language-Inherits") << t.colon << t.identifier;

    // Types of definition within a language block
    ((*result) += L"Language-Definition") << nt.lexer_symbols_definition;
    ((*result) += L"Language-Definition") << nt.lexer_definition;
    ((*result) += L"Language-Definition") << nt.ignore_definition;
    ((*result) += L"Language-Definition") << nt.weak_symbols_definition;
    ((*result) += L"Language-Definition") << nt.keywords_definition;
    ((*result) += L"Language-Definition") << nt.grammar_definition;

    // Some simple definitions
    ebnf_repeating_optional lexemeList;
    ebnf_repeating_optional keywordDefinitionList;
    ebnf_repeating_optional lexemeOrIdentifierList;
    ebnf_alternate          lexemeOrIdentifier;

    (*lexemeList.get_rule()) << nt.lexeme_definition;
    (*lexemeOrIdentifier.get_rule()) << nt.lexeme_definition;
    (*lexemeOrIdentifier.add_rule()) << t.identifier;
    (*lexemeOrIdentifierList.get_rule()) << lexemeOrIdentifier;
    (*keywordDefinitionList.get_rule()) << nt.keyword_definition;

    ((*result) += L"Lexer-Symbols-Definition") << t.lexersymbols << t.opencurly << lexemeList << t.closecurly;
    ((*result) += L"Lexer-Definition") << t.lexer << t.opencurly << lexemeList << t.closecurly;
    ((*result) += L"Ignore-Definition") << t.ignore << t.opencurly << lexemeOrIdentifierList << t.closecurly;
    ((*result) += L"Keywords-Definition") << t.keywords << t.opencurly << keywordDefinitionList << t.closecurly;
    ((*result) += L"Keyword-Definition") << t.identifier;
    ((*result) += L"Keyword-Definition") << t.identifier << t.equals << t.string;
    ((*result) += L"Keyword-Definition") << t.identifier << t.equals << t.character;
    ((*result) += L"Weak-Symbols-Definition") << t.weaklexer << t.opencurly << lexemeList << t.closecurly;
    ((*result) += L"Lexeme-Definition") << t.identifier << t.equals << t.regex;
    ((*result) += L"Lexeme-Definition") << t.identifier << t.equals << t.identifier << t.dot << t.identifier;

    // Definitions for a grammar
    ebnf_repeating_optional nonterminalDefinitionList;
    ebnf_repeating_optional orProductionList;
    ebnf_repeating_optional ebnfItemList;
    ebnf_repeating_optional simpleEbnfItemList;

    (*nonterminalDefinitionList.get_rule()) << nt.nonterminal_definition;
    (*orProductionList.get_rule()) << t.pipe << nt.production;
    (*ebnfItemList.get_rule()) << nt.ebnf_item;
    (*simpleEbnfItemList.get_rule()) << nt.simple_ebnf_item;

    ((*result) += L"Grammar-Definition") << t.grammar << t.opencurly << nonterminalDefinitionList << t.closecurly;

    ((*result) += L"Nonterminal-Definition") << t.nonterminal << t.equals << nt.production << orProductionList;
    // (Not supporting the inheritance forms of these in the bootstrap language)

    // Productions
    ((*result) += L"Production") << simpleEbnfItemList;

    ((*result) += L"Ebnf-Item") << nt.simple_ebnf_item;
    ((*result) += L"Ebnf-Item") << nt.simple_ebnf_item << t.pipe << nt.simple_ebnf_item;

    ((*result) += L"Simple-Ebnf-Item") << nt.nonterminal;
    ((*result) += L"Simple-Ebnf-Item") << nt.terminal;
    ((*result) += L"Simple-Ebnf-Item") << nt.simple_ebnf_item << t.star;
    ((*result) += L"Simple-Ebnf-Item") << nt.simple_ebnf_item << t.plus;
    ((*result) += L"Simple-Ebnf-Item") << nt.simple_ebnf_item << t.question;
    ((*result) += L"Simple-Ebnf-Item") << t.openparen << ebnfItemList << t.closeparen;

    ((*result) += L"Nonterminal") << t.nonterminal;

    ((*result) += L"Terminal") << nt.basic_terminal;
    ((*result) += L"Basic-Terminal") << t.identifier;
    ((*result) += L"Basic-Terminal") << t.string;
    ((*result) += L"Basic-Terminal") << t.character;

    // Return the new grammar
    return result;
}

/// \brief Constructs the bootstrap language
bootstrap::bootstrap() {
    // Create the DFA for this language
    ndfa* dfa = create_dfa();

    // Create the grammar for this language
    m_Grammar = create_grammar();

    // Set up the list of 'weak symbols'
    weak_symbols weak;

    // All of the keywords are weak
    item_set weaklings;

    weaklings.insert(t.language);
    weaklings.insert(t.grammar);
    weaklings.insert(t.lexersymbols);
    weaklings.insert(t.lexer);
    weaklings.insert(t.ignore);
    weaklings.insert(t.keywords);

    weak.add_symbols(*dfa, weaklings, m_Terminals);

    // Set up the list of ignored symbols
    ignored_symbols ignore;

    ignore.add_item(t.newline);
    ignore.add_item(t.whitespace);
    ignore.add_item(t.comment);

    // Create the lexer for this language
    m_Lexer = new dfa::lexer(*dfa);

    // No longer need the DFA at this point
    delete dfa;

    // Build the parser
    m_Builder = new lalr_builder(*m_Grammar, m_Terminals);

    m_Builder->add_rewriter(weak);
    m_Builder->add_rewriter(ignore);

    m_Builder->add_initial_state(nt.parser_language);

    // Finish up the parser
    m_Builder->complete_parser();

    // TODO: log information about shift/reduce and reduce/reduce conflicts

    // Turn into the finished parser
    m_Parser = new ast_parser(*m_Builder);
}

/// \brief Destructor
bootstrap::~bootstrap() {
    delete m_Lexer;
    delete m_Grammar;
    delete m_Builder;
    delete m_Parser;
}
<commit_msg>Commented out the items that are causing the problem, looks like a regex bug, probably to do with the '|' operator. Could also be a DFA bug when generating the NDFA that results from using this symbol.<commit_after>//
//  bootstrap.cpp
//  Parse
//
//  Created by Andrew Hunter on 21/05/2011.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#include "bootstrap.h"

#include "Dfa/ndfa_regex.h"
#include "ContextFree/item.h"
#include "Lr/weak_symbols.h"
#include "Lr/ignored_symbols.h"
#include "Lr/lalr_builder.h"

using namespace dfa;
using namespace contextfree;
using namespace lr;
using namespace language;

/// \brief Adds a new terminal item to an NDFA, and to this object
contextfree::item_container bootstrap::add_terminal(dfa::ndfa_regex* ndfa, const std::wstring& name, const std::wstring& regex) {
    // Add to the terminal dictionary
    int termIdentifier = m_Terminals.symbol_for_name(name);

    if (termIdentifier == -1) {
        termIdentifier = m_Terminals.add_symbol(name);
    }

    // Add to the DFA
    ndfa->add_regex(0, regex, termIdentifier);

    // Return a new container
    return item_container(new terminal(termIdentifier), true);
}

/// \brief Creates the lexer for the language
dfa::ndfa* bootstrap::create_dfa() {
    // Create the NDFA (which we'll eventually turn into the lexer)
    ndfa_regex* languageNdfa = new ndfa_regex();

    // The weak keywords
    t.language          = add_terminal(languageNdfa, L"language", L"language");
    t.grammar           = add_terminal(languageNdfa, L"grammar", L"grammar");
    t.lexersymbols      = add_terminal(languageNdfa, L"lexer-symbols", L"lexer-symbols");
    t.lexer             = add_terminal(languageNdfa, L"lexer", L"lexer");
    t.weaklexer         = add_terminal(languageNdfa, L"weaklexer", L"weaklexer");
    t.ignore            = add_terminal(languageNdfa, L"ignore", L"ignore");
    t.keywords          = add_terminal(languageNdfa, L"keywords", L"keywords");

    // Single character elements (these are also weak)
	t.equals            = add_terminal(languageNdfa, L"'='", L"\\=");
    t.question          = add_terminal(languageNdfa, L"'?'", L"\\?");
    t.plus              = add_terminal(languageNdfa, L"'+'", L"\\+");
    t.star              = add_terminal(languageNdfa, L"'*'", L"\\*");
    t.colon             = add_terminal(languageNdfa, L"':'", L"\\:");
    t.openparen         = add_terminal(languageNdfa, L"'('", L"\\(");
    t.closeparen        = add_terminal(languageNdfa, L"')'", L"\\)");
    t.opencurly         = add_terminal(languageNdfa, L"'{'", L"\\{");
    t.closecurly        = add_terminal(languageNdfa, L"'}'", L"\\}");
    t.dot               = add_terminal(languageNdfa, L"'.'", L"\\.");
    t.pipe              = add_terminal(languageNdfa, L"'|'", L"\\|");

    // The lexical constructs
    t.identifier        = add_terminal(languageNdfa, L"identifier", L"[A-Za-z\\-][A-Za-z\\-0-9]*");
    t.nonterminal       = add_terminal(languageNdfa, L"nonterminal", L"\\<[A-Za-z\\-][A-Za-z\\-0-9]*\\>");
    //t.regex             = add_terminal(languageNdfa, L"regex", L"/([^/]|(\\\\/))*/");
    //t.string            = add_terminal(languageNdfa, L"string", L"\"([^\"]|(\\\"))*\"");
    //t.character         = add_terminal(languageNdfa, L"character", L"'(.|(\\.))'");

    // Ignored elements
    t.newline           = add_terminal(languageNdfa, L"newline", L"[\n\r]");
    t.whitespace        = add_terminal(languageNdfa, L"whitespace", L"[ ]");
    t.comment           = add_terminal(languageNdfa, L"comment", L"//[^\n\r]*");

    // Build into a DFA
    ndfa* uniqueSyms = languageNdfa->to_ndfa_with_unique_symbols();
    delete languageNdfa;

    ndfa* result = uniqueSyms->to_dfa();
    delete uniqueSyms;

    return result;
}

/// \brief Creates the grammar for the language
contextfree::grammar* bootstrap::create_grammar() {
    // Create a new grammar
    grammar* result = new grammar();

    // Generate nonterminals
    nt.parser_language          = result->get_nonterminal(L"Parser-Language");
    nt.toplevel_block           = result->get_nonterminal(L"TopLevel-Block");
    nt.language_block           = result->get_nonterminal(L"Language-Block");
    nt.language_inherits        = result->get_nonterminal(L"Language-Inherits");
    nt.language_definition      = result->get_nonterminal(L"Language-Definition");
    nt.lexer_symbols_definition = result->get_nonterminal(L"Lexer-Symbols-Definition");
    nt.lexer_definition         = result->get_nonterminal(L"Lexer-Definition");
    nt.ignore_definition        = result->get_nonterminal(L"Ignore-Definition");
    nt.keywords_definition      = result->get_nonterminal(L"Keywords-Definition");
    nt.keyword_definition       = result->get_nonterminal(L"Keyword-Definition");
    nt.weak_symbols_definition  = result->get_nonterminal(L"Weak-Symbols-Definition");
    nt.lexeme_definition        = result->get_nonterminal(L"Lexeme-Definition");
    nt.grammar_definition       = result->get_nonterminal(L"Grammar-Definition");
    nt.nonterminal_definition   = result->get_nonterminal(L"Nonterminal-Definition");
    nt.production               = result->get_nonterminal(L"Production");
    nt.ebnf_item                = result->get_nonterminal(L"Ebnf-Item");
    nt.simple_ebnf_item         = result->get_nonterminal(L"Simple-Ebnf-Item");
    nt.nonterminal              = result->get_nonterminal(L"Nonterminal");
    nt.terminal                 = result->get_nonterminal(L"Terminal");
    nt.basic_terminal           = result->get_nonterminal(L"Basic-Terminal");

    // Generate productions
    ebnf_repeating_optional listToplevel;
    (*listToplevel.get_rule()) << nt.toplevel_block;
    ((*result) += L"Parser-Language") << listToplevel;

    // Top level block (language)
    ((*result) += L"TopLevel-Block") << nt.language_block;

    // Language block ('language x (: y) { ... }
    ebnf_optional           optionalLanguageInherits;
    ebnf_repeating_optional listLanguageDefinition;
    (*optionalLanguageInherits.get_rule()) << nt.language_inherits;
    (*listLanguageDefinition.get_rule()) << nt.language_definition;
    ((*result) += L"Language-Block") << t.language << t.identifier << optionalLanguageInherits << t.opencurly << listLanguageDefinition << t.closecurly;

    ((*result) += L"Language-Inherits") << t.colon << t.identifier;

    // Types of definition within a language block
    ((*result) += L"Language-Definition") << nt.lexer_symbols_definition;
    ((*result) += L"Language-Definition") << nt.lexer_definition;
    ((*result) += L"Language-Definition") << nt.ignore_definition;
    ((*result) += L"Language-Definition") << nt.weak_symbols_definition;
    ((*result) += L"Language-Definition") << nt.keywords_definition;
    ((*result) += L"Language-Definition") << nt.grammar_definition;

    // Some simple definitions
    ebnf_repeating_optional lexemeList;
    ebnf_repeating_optional keywordDefinitionList;
    ebnf_repeating_optional lexemeOrIdentifierList;
    ebnf_alternate          lexemeOrIdentifier;

    (*lexemeList.get_rule()) << nt.lexeme_definition;
    (*lexemeOrIdentifier.get_rule()) << nt.lexeme_definition;
    (*lexemeOrIdentifier.add_rule()) << t.identifier;
    (*lexemeOrIdentifierList.get_rule()) << lexemeOrIdentifier;
    (*keywordDefinitionList.get_rule()) << nt.keyword_definition;

    ((*result) += L"Lexer-Symbols-Definition") << t.lexersymbols << t.opencurly << lexemeList << t.closecurly;
    ((*result) += L"Lexer-Definition") << t.lexer << t.opencurly << lexemeList << t.closecurly;
    ((*result) += L"Ignore-Definition") << t.ignore << t.opencurly << lexemeOrIdentifierList << t.closecurly;
    ((*result) += L"Keywords-Definition") << t.keywords << t.opencurly << keywordDefinitionList << t.closecurly;
    ((*result) += L"Keyword-Definition") << t.identifier;
    ((*result) += L"Keyword-Definition") << t.identifier << t.equals << t.string;
    ((*result) += L"Keyword-Definition") << t.identifier << t.equals << t.character;
    ((*result) += L"Weak-Symbols-Definition") << t.weaklexer << t.opencurly << lexemeList << t.closecurly;
    ((*result) += L"Lexeme-Definition") << t.identifier << t.equals << t.regex;
    ((*result) += L"Lexeme-Definition") << t.identifier << t.equals << t.identifier << t.dot << t.identifier;

    // Definitions for a grammar
    ebnf_repeating_optional nonterminalDefinitionList;
    ebnf_repeating_optional orProductionList;
    ebnf_repeating_optional ebnfItemList;
    ebnf_repeating_optional simpleEbnfItemList;

    (*nonterminalDefinitionList.get_rule()) << nt.nonterminal_definition;
    (*orProductionList.get_rule()) << t.pipe << nt.production;
    (*ebnfItemList.get_rule()) << nt.ebnf_item;
    (*simpleEbnfItemList.get_rule()) << nt.simple_ebnf_item;

    ((*result) += L"Grammar-Definition") << t.grammar << t.opencurly << nonterminalDefinitionList << t.closecurly;

    ((*result) += L"Nonterminal-Definition") << t.nonterminal << t.equals << nt.production << orProductionList;
    // (Not supporting the inheritance forms of these in the bootstrap language)

    // Productions
    ((*result) += L"Production") << simpleEbnfItemList;

    ((*result) += L"Ebnf-Item") << nt.simple_ebnf_item;
    ((*result) += L"Ebnf-Item") << nt.simple_ebnf_item << t.pipe << nt.simple_ebnf_item;

    ((*result) += L"Simple-Ebnf-Item") << nt.nonterminal;
    ((*result) += L"Simple-Ebnf-Item") << nt.terminal;
    ((*result) += L"Simple-Ebnf-Item") << nt.simple_ebnf_item << t.star;
    ((*result) += L"Simple-Ebnf-Item") << nt.simple_ebnf_item << t.plus;
    ((*result) += L"Simple-Ebnf-Item") << nt.simple_ebnf_item << t.question;
    ((*result) += L"Simple-Ebnf-Item") << t.openparen << ebnfItemList << t.closeparen;

    ((*result) += L"Nonterminal") << t.nonterminal;

    ((*result) += L"Terminal") << nt.basic_terminal;
    ((*result) += L"Basic-Terminal") << t.identifier;
    ((*result) += L"Basic-Terminal") << t.string;
    ((*result) += L"Basic-Terminal") << t.character;

    // Return the new grammar
    return result;
}

/// \brief Constructs the bootstrap language
bootstrap::bootstrap() {
    // Create the DFA for this language
    ndfa* dfa = create_dfa();

    // Create the grammar for this language
    m_Grammar = create_grammar();

    // Set up the list of 'weak symbols'
    weak_symbols weak;

    // All of the keywords are weak
    item_set weaklings;

    weaklings.insert(t.language);
    weaklings.insert(t.grammar);
    weaklings.insert(t.lexersymbols);
    weaklings.insert(t.lexer);
    weaklings.insert(t.ignore);
    weaklings.insert(t.keywords);

    weak.add_symbols(*dfa, weaklings, m_Terminals);

    // Set up the list of ignored symbols
    ignored_symbols ignore;

    ignore.add_item(t.newline);
    ignore.add_item(t.whitespace);
    ignore.add_item(t.comment);

    // Create the lexer for this language
    m_Lexer = new dfa::lexer(*dfa);

    // No longer need the DFA at this point
    delete dfa;

    // Build the parser
    m_Builder = new lalr_builder(*m_Grammar, m_Terminals);

    m_Builder->add_rewriter(weak);
    m_Builder->add_rewriter(ignore);

    m_Builder->add_initial_state(nt.parser_language);

    // Finish up the parser
    m_Builder->complete_parser();

    // TODO: log information about shift/reduce and reduce/reduce conflicts

    // Turn into the finished parser
    m_Parser = new ast_parser(*m_Builder);
}

/// \brief Destructor
bootstrap::~bootstrap() {
    delete m_Lexer;
    delete m_Grammar;
    delete m_Builder;
    delete m_Parser;
}
<|endoftext|>


<commit_before>#ifndef _TCURASTERIZATIONVERIFIER_HPP
#define _TCURASTERIZATIONVERIFIER_HPP
/*-------------------------------------------------------------------------
 * drawElements Quality Program Tester Core
 * ----------------------------------------
 *
 * Copyright 2014 The Android Open Source Project
 *
 * 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.
 *
 *//*!
 * \file
 * \brief Rasterization verifier utils.
 *//*--------------------------------------------------------------------*/

#include "tcuDefs.hpp"
#include "tcuTestLog.hpp"
#include "tcuSurface.hpp"
#include "deMath.h"

#include <vector>

namespace tcu
{

enum CoverageType
{
	COVERAGE_FULL = 0,		// !< primitive fully covers the queried area
	COVERAGE_PARTIAL,		// !< primitive coverage is either partial, or could be full, partial or none depending on rounding and/or fill rules
	COVERAGE_NONE,			// !< primitive does not cover area at all

	COVERAGE_LAST
};

enum VerificationMode
{
	VERIFICATIONMODE_STRICT = 0,	// !< do not allow even a single bad pixel
	VERIFICATIONMODE_WEAK,			// !< allow some bad pixels
	VERIFICATIONMODE_WEAKER,		// !< allow more bad pixels
	VERIFICATIONMODE_SMOOTH,		// !< allow no missing pixels

	VERIFICATIONMODE_LAST
};

enum LineInterpolationMethod
{
	LINEINTERPOLATION_STRICTLY_CORRECT = 0,	// !< line interpolation matches the specification
	LINEINTERPOLATION_PROJECTED,			// !< line interpolation weights are otherwise correct, but they are projected onto major axis
	LINEINTERPOLATION_INCORRECT				// !< line interpolation is incorrect
};

struct TriangleSceneSpec
{
	struct SceneTriangle
	{
		tcu::Vec4	positions[3];
		tcu::Vec4	colors[3];
		bool		sharedEdge[3]; // !< is the edge i -> i+1 shared with another scene triangle
	};

	std::vector<SceneTriangle> triangles;
};

struct LineSceneSpec
{
	LineSceneSpec()
		: isStrip(false)
		, isSmooth(false)
		, stippleEnable(false)
		, verificationMode(VERIFICATIONMODE_STRICT)
	{}

	struct SceneLine
	{
		tcu::Vec4	positions[2];
		tcu::Vec4	colors[2];
	};

	std::vector<SceneLine>	lines;
	float					lineWidth;
	bool					isStrip;
	bool					isSmooth;
	bool					stippleEnable;
	deUint32				stippleFactor;
	deUint16				stipplePattern;
	VerificationMode		verificationMode;
};

struct PointSceneSpec
{
	struct ScenePoint
	{
		tcu::Vec4	position;
		tcu::Vec4	color;
		float		pointSize;
	};

	std::vector<ScenePoint> points;
};

struct RasterizationArguments
{
	int numSamples;
	int subpixelBits;
	int redBits;
	int greenBits;
	int blueBits;
};

struct VerifyTriangleGroupRasterizationLogStash
{
	std::vector<std::string>	messages;
	int							missingPixels;
	int							unexpectedPixels;
	tcu::Surface				errorMask;
	bool						result;
};

struct VerifyTriangleGroupInterpolationLogStash
{
	std::vector<std::string>	messages;
	int							invalidPixels;
	tcu::Surface				errorMask;
	bool						success;
};

/*--------------------------------------------------------------------*//*!
 * \brief Calculates triangle coverage at given pixel
 * Calculates the coverage of a triangle given by three vertices. The
 * triangle should not be z-clipped. If multisample is false, the pixel
 * center is compared against the triangle. If multisample is true, the
 * whole pixel area is compared.
 *//*--------------------------------------------------------------------*/
CoverageType calculateTriangleCoverage (const tcu::Vec4& p0, const tcu::Vec4& p1, const tcu::Vec4& p2, const tcu::IVec2& pixel, const tcu::IVec2& viewportSize, int subpixelBits, bool multisample);

/*--------------------------------------------------------------------*//*!
 * \brief Verify triangle rasterization result
 * Verifies pixels in the surface are rasterized within the bounds given
 * by RasterizationArguments. Triangles should not be z-clipped.
 *
 * Triangle colors are not used. The triangle is expected to be white.
 * If logStash is not NULL the results are not logged, but copied to stash.
 *
 * Returns false if invalid rasterization is found.
 *//*--------------------------------------------------------------------*/
bool verifyTriangleGroupRasterization (const tcu::Surface& surface, const TriangleSceneSpec& scene, const RasterizationArguments& args, tcu::TestLog& log, VerificationMode mode = VERIFICATIONMODE_STRICT, VerifyTriangleGroupRasterizationLogStash* logStash = DE_NULL, const bool vulkanLinesTest = false);

/*--------------------------------------------------------------------*//*!
 * \brief Verify line rasterization result
 * Verifies pixels in the surface are rasterized within the bounds given
 * by RasterizationArguments. Lines should not be z-clipped.
 *
 * Line colors are not used. The line is expected to be white.
 *
 * Returns false if invalid rasterization is found.
 *//*--------------------------------------------------------------------*/
bool verifyLineGroupRasterization (const tcu::Surface& surface, const LineSceneSpec& scene, const RasterizationArguments& args, tcu::TestLog& log);

/*--------------------------------------------------------------------*//*!
 * \brief Verify clipped line rasterization result
 * Verifies pixels in the surface are rasterized within the bounds given
 * by RasterizationArguments and by clipping the lines with a (-1, -1), (1, 1)
 * square. Lines should not be z-clipped.
 *
 * Line colors are not used. The line is expected to be white. Lines are
 * rasterized as two triangles.
 *
 * Returns false if invalid rasterization is found.
 *//*--------------------------------------------------------------------*/
bool verifyClippedTriangulatedLineGroupRasterization (const tcu::Surface& surface, const LineSceneSpec& scene, const RasterizationArguments& args, tcu::TestLog& log);

/*--------------------------------------------------------------------*//*!
 * \brief Verify line rasterization result both clipped and non-clipped
 *
 * For details please see verifyLineGroupRasterization and
 * verifyClippedTriangulatedLineGroupRasterization
 *
 * Returns false if both rasterizations are invalid.
 *//*--------------------------------------------------------------------*/
bool verifyRelaxedLineGroupRasterization (const tcu::Surface& surface, const LineSceneSpec& scene, const RasterizationArguments& args, tcu::TestLog& log, const bool vulkanLinesTest = false, const bool strict = true);

/*--------------------------------------------------------------------*//*!
 * \brief Verify point rasterization result
 * Verifies points in the surface are rasterized within the bounds given
 * by RasterizationArguments. Points should not be z-clipped.
 *
 * Point colors are not used. The point is expected to be white.
 *
 * Returns false if invalid rasterization is found.
 *//*--------------------------------------------------------------------*/
bool verifyPointGroupRasterization (const tcu::Surface& surface, const PointSceneSpec& scene, const RasterizationArguments& args, tcu::TestLog& log);

/*--------------------------------------------------------------------*//*!
 * \brief Verify triangle color interpolation is valid
 * Verifies the color of a fragments of a colored triangle is in the
 * valid range. Triangles should not be z-clipped.
 *
 * The background is expected to be black.
 *
 * Returns false if invalid rasterization interpolation is found.
 *//*--------------------------------------------------------------------*/
bool verifyTriangleGroupInterpolation (const tcu::Surface& surface, const TriangleSceneSpec& scene, const RasterizationArguments& args, tcu::TestLog& log);

/*--------------------------------------------------------------------*//*!
 * \brief Verify line color interpolation is valid
 * Verifies the color of a fragments of a colored line is in the
 * valid range. Lines should not be z-clipped.
 *
 * The background is expected to be black.
 *
 * Returns the detected interpolation method of the input image.
 *//*--------------------------------------------------------------------*/
LineInterpolationMethod verifyLineGroupInterpolation (const tcu::Surface& surface, const LineSceneSpec& scene, const RasterizationArguments& args, tcu::TestLog& log);

/*--------------------------------------------------------------------*//*!
 * \brief Verify line color interpolation is valid
 * Verifies the color of a fragments of a colored line is in the
 * valid range. Lines should not be z-clipped.
 *
 * The background is expected to be black. The lines are rasterized
 * as two triangles.
 *
 * Returns false if invalid rasterization interpolation is found.
 *//*--------------------------------------------------------------------*/
bool verifyTriangulatedLineGroupInterpolation (const tcu::Surface& surface, const LineSceneSpec& scene, const RasterizationArguments& args, tcu::TestLog& log, const bool strictMode = true, const bool allowBresenhamForNonStrictLines = false);

} // tcu

#endif // _TCURASTERIZATIONVERIFIER_HPP
<commit_msg>Fix for potentially uninitialized variables<commit_after>#ifndef _TCURASTERIZATIONVERIFIER_HPP
#define _TCURASTERIZATIONVERIFIER_HPP
/*-------------------------------------------------------------------------
 * drawElements Quality Program Tester Core
 * ----------------------------------------
 *
 * Copyright 2014 The Android Open Source Project
 *
 * 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.
 *
 *//*!
 * \file
 * \brief Rasterization verifier utils.
 *//*--------------------------------------------------------------------*/

#include "tcuDefs.hpp"
#include "tcuTestLog.hpp"
#include "tcuSurface.hpp"
#include "deMath.h"

#include <vector>

namespace tcu
{

enum CoverageType
{
	COVERAGE_FULL = 0,		// !< primitive fully covers the queried area
	COVERAGE_PARTIAL,		// !< primitive coverage is either partial, or could be full, partial or none depending on rounding and/or fill rules
	COVERAGE_NONE,			// !< primitive does not cover area at all

	COVERAGE_LAST
};

enum VerificationMode
{
	VERIFICATIONMODE_STRICT = 0,	// !< do not allow even a single bad pixel
	VERIFICATIONMODE_WEAK,			// !< allow some bad pixels
	VERIFICATIONMODE_WEAKER,		// !< allow more bad pixels
	VERIFICATIONMODE_SMOOTH,		// !< allow no missing pixels

	VERIFICATIONMODE_LAST
};

enum LineInterpolationMethod
{
	LINEINTERPOLATION_STRICTLY_CORRECT = 0,	// !< line interpolation matches the specification
	LINEINTERPOLATION_PROJECTED,			// !< line interpolation weights are otherwise correct, but they are projected onto major axis
	LINEINTERPOLATION_INCORRECT				// !< line interpolation is incorrect
};

struct TriangleSceneSpec
{
	struct SceneTriangle
	{
		tcu::Vec4	positions[3];
		tcu::Vec4	colors[3];
		bool		sharedEdge[3]; // !< is the edge i -> i+1 shared with another scene triangle
		SceneTriangle()
		{
			// Other members are initialized in Vector constructor
			for (int i = 0; i < 3; i++)
				sharedEdge[i] = false;
		}
	};

	std::vector<SceneTriangle> triangles;
};

struct LineSceneSpec
{
	LineSceneSpec()
		: isStrip(false)
		, isSmooth(false)
		, stippleEnable(false)
		, verificationMode(VERIFICATIONMODE_STRICT)
	{}

	struct SceneLine
	{
		tcu::Vec4	positions[2];
		tcu::Vec4	colors[2];
	};

	std::vector<SceneLine>	lines;
	float					lineWidth;
	bool					isStrip;
	bool					isSmooth;
	bool					stippleEnable;
	deUint32				stippleFactor;
	deUint16				stipplePattern;
	VerificationMode		verificationMode;
};

struct PointSceneSpec
{
	struct ScenePoint
	{
		tcu::Vec4	position;
		tcu::Vec4	color;
		float		pointSize;
	};

	std::vector<ScenePoint> points;
};

struct RasterizationArguments
{
	int numSamples;
	int subpixelBits;
	int redBits;
	int greenBits;
	int blueBits;
};

struct VerifyTriangleGroupRasterizationLogStash
{
	std::vector<std::string>	messages;
	int							missingPixels;
	int							unexpectedPixels;
	tcu::Surface				errorMask;
	bool						result;
};

struct VerifyTriangleGroupInterpolationLogStash
{
	std::vector<std::string>	messages;
	int							invalidPixels;
	tcu::Surface				errorMask;
	bool						success;
};

/*--------------------------------------------------------------------*//*!
 * \brief Calculates triangle coverage at given pixel
 * Calculates the coverage of a triangle given by three vertices. The
 * triangle should not be z-clipped. If multisample is false, the pixel
 * center is compared against the triangle. If multisample is true, the
 * whole pixel area is compared.
 *//*--------------------------------------------------------------------*/
CoverageType calculateTriangleCoverage (const tcu::Vec4& p0, const tcu::Vec4& p1, const tcu::Vec4& p2, const tcu::IVec2& pixel, const tcu::IVec2& viewportSize, int subpixelBits, bool multisample);

/*--------------------------------------------------------------------*//*!
 * \brief Verify triangle rasterization result
 * Verifies pixels in the surface are rasterized within the bounds given
 * by RasterizationArguments. Triangles should not be z-clipped.
 *
 * Triangle colors are not used. The triangle is expected to be white.
 * If logStash is not NULL the results are not logged, but copied to stash.
 *
 * Returns false if invalid rasterization is found.
 *//*--------------------------------------------------------------------*/
bool verifyTriangleGroupRasterization (const tcu::Surface& surface, const TriangleSceneSpec& scene, const RasterizationArguments& args, tcu::TestLog& log, VerificationMode mode = VERIFICATIONMODE_STRICT, VerifyTriangleGroupRasterizationLogStash* logStash = DE_NULL, const bool vulkanLinesTest = false);

/*--------------------------------------------------------------------*//*!
 * \brief Verify line rasterization result
 * Verifies pixels in the surface are rasterized within the bounds given
 * by RasterizationArguments. Lines should not be z-clipped.
 *
 * Line colors are not used. The line is expected to be white.
 *
 * Returns false if invalid rasterization is found.
 *//*--------------------------------------------------------------------*/
bool verifyLineGroupRasterization (const tcu::Surface& surface, const LineSceneSpec& scene, const RasterizationArguments& args, tcu::TestLog& log);

/*--------------------------------------------------------------------*//*!
 * \brief Verify clipped line rasterization result
 * Verifies pixels in the surface are rasterized within the bounds given
 * by RasterizationArguments and by clipping the lines with a (-1, -1), (1, 1)
 * square. Lines should not be z-clipped.
 *
 * Line colors are not used. The line is expected to be white. Lines are
 * rasterized as two triangles.
 *
 * Returns false if invalid rasterization is found.
 *//*--------------------------------------------------------------------*/
bool verifyClippedTriangulatedLineGroupRasterization (const tcu::Surface& surface, const LineSceneSpec& scene, const RasterizationArguments& args, tcu::TestLog& log);

/*--------------------------------------------------------------------*//*!
 * \brief Verify line rasterization result both clipped and non-clipped
 *
 * For details please see verifyLineGroupRasterization and
 * verifyClippedTriangulatedLineGroupRasterization
 *
 * Returns false if both rasterizations are invalid.
 *//*--------------------------------------------------------------------*/
bool verifyRelaxedLineGroupRasterization (const tcu::Surface& surface, const LineSceneSpec& scene, const RasterizationArguments& args, tcu::TestLog& log, const bool vulkanLinesTest = false, const bool strict = true);

/*--------------------------------------------------------------------*//*!
 * \brief Verify point rasterization result
 * Verifies points in the surface are rasterized within the bounds given
 * by RasterizationArguments. Points should not be z-clipped.
 *
 * Point colors are not used. The point is expected to be white.
 *
 * Returns false if invalid rasterization is found.
 *//*--------------------------------------------------------------------*/
bool verifyPointGroupRasterization (const tcu::Surface& surface, const PointSceneSpec& scene, const RasterizationArguments& args, tcu::TestLog& log);

/*--------------------------------------------------------------------*//*!
 * \brief Verify triangle color interpolation is valid
 * Verifies the color of a fragments of a colored triangle is in the
 * valid range. Triangles should not be z-clipped.
 *
 * The background is expected to be black.
 *
 * Returns false if invalid rasterization interpolation is found.
 *//*--------------------------------------------------------------------*/
bool verifyTriangleGroupInterpolation (const tcu::Surface& surface, const TriangleSceneSpec& scene, const RasterizationArguments& args, tcu::TestLog& log);

/*--------------------------------------------------------------------*//*!
 * \brief Verify line color interpolation is valid
 * Verifies the color of a fragments of a colored line is in the
 * valid range. Lines should not be z-clipped.
 *
 * The background is expected to be black.
 *
 * Returns the detected interpolation method of the input image.
 *//*--------------------------------------------------------------------*/
LineInterpolationMethod verifyLineGroupInterpolation (const tcu::Surface& surface, const LineSceneSpec& scene, const RasterizationArguments& args, tcu::TestLog& log);

/*--------------------------------------------------------------------*//*!
 * \brief Verify line color interpolation is valid
 * Verifies the color of a fragments of a colored line is in the
 * valid range. Lines should not be z-clipped.
 *
 * The background is expected to be black. The lines are rasterized
 * as two triangles.
 *
 * Returns false if invalid rasterization interpolation is found.
 *//*--------------------------------------------------------------------*/
bool verifyTriangulatedLineGroupInterpolation (const tcu::Surface& surface, const LineSceneSpec& scene, const RasterizationArguments& args, tcu::TestLog& log, const bool strictMode = true, const bool allowBresenhamForNonStrictLines = false);

} // tcu

#endif // _TCURASTERIZATIONVERIFIER_HPP
<|endoftext|>


<commit_before>#include "phantommaterial.h"

namespace TMC {

PhantomMaterial::PhantomMaterial() {
    this->setAlpha(0.15);
}

}
<commit_msg>Tuned PhantomMaterial.<commit_after>#include "phantommaterial.h"

namespace TMC {

PhantomMaterial::PhantomMaterial() {
    this->setAlpha(0.35);
}

}
<|endoftext|>